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 | <repo_name>emilyhorsman/nightshades-react<file_sep>/app/actions/Errors.jsx
export function dismissError(id) {
return {
type: 'DISMISS_ERROR',
id
}
}
<file_sep>/app/actions/Units.jsx
import { fetchAPI } from './'
export function fetchUnits() {
return {
type: 'UNITS',
promise: fetchAPI('/units')
}
}
export function markComplete(uuid) {
const body = new Blob([JSON.stringify({
data: {
type: 'unit',
id: uuid,
attributes: {
completed: true
}
}
})], { type: 'application/json' })
return {
type: 'MARK_COMPLETE',
uuid: uuid,
promise: fetchAPI('/units/' + uuid, { body: body, method: 'PATCH' })
}
}
export function cancelOngoing() {
return {
type: 'CANCEL_ONGOING',
promise: fetchAPI('/units', { method: 'DELETE' })
}
}
<file_sep>/app/components/TagsList/index.jsx
import React from 'react'
function TagsList({ tags }) {
return (
<div>Tags: {tags.join(', ')}</div>
)
}
export default TagsList
<file_sep>/app/containers/UserContainer.jsx
import React, { Component } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as actions from '../actions/User'
import { api } from '../actions'
import CurrentUnitContainer from './CurrentUnitContainer'
import HistoryContainer from './HistoryContainer'
import NewUnitContainer from './NewUnitContainer'
import UnitsListContainer from './UnitsListContainer'
import ActionDashboard from '../components/ActionDashboard'
import Header from '../components/Header'
import Loader from '../components/Loader'
import SignIn from '../components/SignIn'
import User from '../components/User'
class UserContainer extends Component {
constructor(props) {
super(props)
this.onLogout = props.actions.logout.bind(this)
this.signInWithTwitter = this.signIn.bind(this, 'twitter')
this.signInWithFacebook = this.signIn.bind(this, 'facebook')
}
componentDidMount() {
this.interval = setInterval(this.props.actions.tick.bind(this), 1000)
this.props.actions.fetchMe()
}
componentWillUnmount() {
clearInterval(this.interval)
}
signIn(provider) {
const url = api('/auth/' + provider + '?login=start&postMessage=true')
let authWindow = window.open(url, 'SignIn', 'width=600,height=600,resizable=yes')
const onCompletion = (ev) => {
if (ev.data == 'COMPLETE') {
authWindow.close()
this.props.actions.fetchMe()
window.removeEventListener('message', onCompletion, true)
}
}
window.addEventListener('message', onCompletion, true)
}
render() {
const { authenticated, name, loading } = this.props
if (loading) {
return <Loader active={loading} />
}
if (authenticated) {
return (
<div>
<Header>
<User
name={name}
onLogout={this.onLogout}
/>
</Header>
<main>
<ActionDashboard>
<HistoryContainer className="-desktop" />
<CurrentUnitContainer />
<NewUnitContainer />
</ActionDashboard>
<UnitsListContainer />
</main>
</div>
)
}
return (
<SignIn
facebook={this.signInWithFacebook}
twitter={this.signInWithTwitter}
/>
)
}
}
const mapStateToProps = (state) => {
return {
authenticated: state.UserDomain.authenticated,
name: state.UserDomain.name,
loading: state.UserDomain.fetching
}
}
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(actions, dispatch)
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserContainer)
<file_sep>/app/components/Timer/index.jsx
import React from 'react'
import Moment from 'moment'
import CircleProgressVector from '../CircleProgressVector'
import './styles.scss'
function fmt(num) {
if (num <= 9) {
return `0${Math.max(0, num)}`
} else {
return Math.max(0, num)
}
}
function Timer({ delta, radius, path, ticking }) {
const duration = Moment.duration(delta)
const minutes = fmt(duration.minutes())
const seconds = fmt(duration.seconds())
let display = `${minutes}:${seconds}`
if (duration.hours() > 0) {
display = `0${duration.hours()}:${display}`
}
let label
if (ticking) {
label = <div className="label">time remaining</div>
}
return (
<div className="timer">
{label}
<time>{display}</time>
<CircleProgressVector path={path} radius={radius} />
</div>
)
}
Timer.defaultProps = {
radius: 50
}
export default Timer
<file_sep>/app/components/UnitForm/index.jsx
import React, { PropTypes } from 'react'
import TagsInput from 'react-tagsinput'
import Moment from 'moment'
import './styles.scss'
const formatExpiry = (time) => time.format('hh:mm:ss A')
function tagsInputRenderLayout (tagComponents, inputComponent) {
return (
<span>
{inputComponent}
{tagComponents}
</span>
)
}
function UnitForm({
meta,
model,
disabled,
handleSubmit,
handleTagsChange,
handleTimeChange,
handleDescriptionChange
}) {
const tagInputProps = {
id: 'tags'
}
const { delta } = meta
const { description, tags } = model
return (
<div className="unit-form">
<form onSubmit={handleSubmit}>
<label htmlFor="tags">Tags</label>
<TagsInput
addKeys={[9, 13, 188]}
value={tags}
onChange={handleTagsChange}
renderLayout={tagsInputRenderLayout}
inputProps={tagInputProps}
/>
<label htmlFor="description">Description</label>
<textarea
value={description}
onChange={handleDescriptionChange}
name="description"
id="description"
placeholder="What are we doing this time?"
rows="2"
/>
<label htmlFor="time">Length (minutes)</label>
<label htmlFor="timeSlider" className="sr-only">Time Slider</label>
<div className="group">
<div className="-left">
<input
type="number"
id="time"
value={delta / 60}
onChange={handleTimeChange}
/>
</div>
<div className="-right">
<input
type="range"
id="timeSlider"
value={delta / 60}
onChange={handleTimeChange}
min={2}
max={120}
/>
</div>
</div>
<button className="-green" disabled={disabled}>Start Timer</button>
</form>
</div>
)
}
UnitForm.propTypes = {
disabled: PropTypes.bool.isRequired,
handleSubmit: PropTypes.func.isRequired,
handleTagsChange: PropTypes.func.isRequired,
handleTimeChange: PropTypes.func.isRequired,
handleDescriptionChange: PropTypes.func.isRequired
}
export default UnitForm
<file_sep>/app/components/CircleProgressVector/index.jsx
import React from 'react'
import './styles.scss'
function CircleProgressVector({ radius, path }) {
const viewBox = `0 0 ${radius * 2} ${radius * 2}`
const transform = `translate(${radius}, ${radius})`
return (
<svg className="progress" role="presentation" viewBox={viewBox}>
<circle cx={radius} cy={radius} r={radius - 0.2} />
<path className="timer-path" d={path} transform={transform} />
<circle className="subtraction" cx={radius} cy={radius} r={radius - 5} />
</svg>
)
}
export default CircleProgressVector
<file_sep>/README.md
# nightshades
[](https://codeclimate.com/github/emilyhorsman/nightshades-react)
<file_sep>/app/components/Error/index.jsx
import React, { PropTypes } from 'react'
function Error({ message, onDismiss }) {
return (
<div>
<p>{message}</p>
<button onClick={onDismiss}>Dismiss</button>
</div>
)
}
Error.propTypes = {
message: PropTypes.string.isRequired,
onDismiss: PropTypes.func.isRequired
}
export default Error
<file_sep>/app/containers/UnitContainer.jsx
import React, { Component } from 'react'
import Unit from '../components/Unit'
import { isOngoing } from '../reducers/helpers'
class UnitContainer extends Component {
componentWillReceiveProps(nextProps) {
// Let's check if it's time to tell the server that this unit is complete.
if (nextProps.fetching) {
return
}
if (!isOngoing(nextProps)) {
return
}
if (nextProps.meta.delta <= -100) {
this.props.markComplete()
}
}
render() {
const { meta, model } = this.props
return (
<li className="unit">
<Unit
{...model}
{...meta}
expired={!isOngoing(this.props)}
/>
</li>
)
}
}
export default UnitContainer
<file_sep>/webpack.config.js
var webpack = require('webpack');
var merge = require('webpack-merge');
var TARGET = process.env.npm_lifecycle_event;
process.env.BABEL_ENV = TARGET;
var common = {
entry: __dirname + '/app/index.jsx',
output: {
path: __dirname + '/build',
filename: 'bundle.js'
},
resolve: {
extensions: ['', '.js', '.jsx', '.json', '.scss']
},
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel'],
include: __dirname + '/app'
},
{
test: /\.scss$/,
loader: 'style!css!sass',
include: __dirname + '/app'
},
{
test: /\.css$/,
loader: 'style!css',
include: __dirname + '/app'
}
]
},
plugins: [
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
})
]
};
if (TARGET === 'build') {
module.exports = merge(common, {
plugins: [
new webpack.DefinePlugin({
'process.env': { 'NODE_ENV': JSON.stringify('production') }
})
]
});
}
if (TARGET === 'start') {
module.exports = merge(common, {
devtool: 'eval-source-map',
devServer: {
/* --hot --inline in package.json */
contentBase: __dirname + '/build',
progress: true,
host: '0.0.0.0'
}
});
}
<file_sep>/app/actions/NewUnit.jsx
import { fetchAPI } from './'
export function change(attributes) {
return {
type: 'NEW_UNIT_CHANGE',
attributes: attributes
}
}
export function newUnit(attributes) {
const body = new Blob([JSON.stringify({
data: {
type: 'unit',
attributes: {
description: attributes.model.description,
delta: attributes.meta.delta,
tags: attributes.model.tags.join(',')
}
}
})], { type: 'application/json' })
return {
type: 'NEW_UNIT',
promise: fetchAPI('/units', { body: body, method: 'POST' })
}
}
<file_sep>/app/containers/CurrentUnitContainer.jsx
import React, { Component } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as actions from '../actions/Units'
import { isOngoing } from '../reducers/helpers'
import TimerContainer from './TimerContainer'
import Timer from '../components/Timer'
class CurrentUnitContainer extends Component {
render() {
const { actions, currentUnit, newUnit } = this.props
let timer
if (currentUnit.length > 0) {
timer = <TimerContainer {...currentUnit[0]} />
} else {
timer = <Timer delta={newUnit.meta.delta * 1000} ticking={false} />
}
return (
<div className="current-unit-container">
{timer}
<button
className="-red"
disabled={currentUnit.length === 0}
onClick={actions.cancelOngoing}
>Cancel Timer</button>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
currentUnit: state.UnitsDomain.units.filter(isOngoing),
newUnit: state.NewUnitDomain.unit
}
}
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(actions, dispatch)
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(CurrentUnitContainer)
<file_sep>/app/reducers/UserReducer.jsx
const initialState = {
'fetching': false,
'authenticated': false,
'name': ''
}
const UserReducer = (state = initialState, action) => {
switch (action.type) {
case 'ME_FETCHING':
return {
...state,
fetching: true
}
case 'ME_ERROR':
return {
...state,
fetching: false
}
case 'ME_SUCCESS':
if (action.data.type !== 'user') {
return {
...state,
fetching: false
}
}
return {
fetching: false,
authenticated: true,
name: action.data.attributes.name
}
case 'LOGOUT_FETCHING':
return {
...state,
fetching: true
}
case 'LOGOUT_SUCCESS':
return initialState
default:
return state
}
}
export default UserReducer
<file_sep>/app/components/Loader/index.jsx
import React, { PropTypes } from 'react'
import './styles.scss'
function Loader({ active }) {
if (!active) {
return <div></div>
}
return (
<div className="loader">
<div></div>
<div></div>
<div></div>
</div>
)
}
Loader.propTypes = {
active: PropTypes.bool.isRequired
}
export default Loader
<file_sep>/app/reducers/helpers.jsx
import Moment from 'moment'
export function isOngoing({ meta, model }) {
if (model.completed) {
return false
}
const t = model.expiryTime.clone()
t.add(meta.expiryThreshold, 'seconds')
return Moment() < t
}
<file_sep>/app/containers/App.jsx
import React, { Component } from 'react'
import ErrorsListContainer from './ErrorsListContainer'
import UserContainer from './UserContainer'
import '../assets/styles.scss'
export default class App extends Component {
render() {
return(
<div>
<section>
<ErrorsListContainer />
</section>
<UserContainer />
</div>
)
}
}
<file_sep>/app/reducers/UnitsReducer.jsx
import Moment from 'moment'
import { isOngoing } from './helpers'
const initialState = {
fetching: false,
units: []
}
const UnitsReducer = (state = initialState, action) => {
switch (action.type) {
case 'CANCEL_ONGOING_FETCHING':
case 'UNITS_FETCHING':
return {
...state,
fetching: true
}
case 'UNITS_SUCCESS':
return {
...state,
fetching: false,
units: action.data
}
case 'CANCEL_ONGOING_ERROR':
case 'UNITS_ERROR':
case 'MARK_COMPLETE_ERROR':
return {
...state,
fetching: false
}
case 'MARK_COMPLETE_FETCHING':
return {
...state,
units: state.units.map(unit => {
if (unit.uuid !== action.uuid) {
return unit
}
return {
...unit,
fetching: true
}
})
}
case 'MARK_COMPLETE_SUCCESS':
return {
...state,
units: state.units.map(unit => {
if (unit.uuid !== action.uuid) {
return unit
}
return {
...unit,
model: {
...unit.model,
completed: action.data.model.completed
}
}
})
}
case 'NEW_UNIT_SUCCESS':
return {
...state,
units: [action.data].concat(state.units)
}
case 'CANCEL_ONGOING_SUCCESS':
return {
...state,
fetching: false,
units: state.units.filter(unit => !isOngoing(unit))
}
case 'TICK':
return {
...state,
units: state.units.map(unit => {
if (!isOngoing(unit)) {
return unit
}
return {
...unit,
meta: {
...unit.meta,
delta: unit.meta.delta - 1000
}
}
})
}
default:
return state
}
}
export default UnitsReducer
<file_sep>/app/containers/TimerContainer.jsx
import React, { Component } from 'react'
import Moment from 'moment'
import Timer from '../components/Timer'
class TimerContainer extends Component {
constructor(props) {
super(props)
this.state = {
duration: props.model.expiryTime.diff(props.model.startTime),
interval: null,
path: ''
}
}
componentDidMount() {
this.setState({
...this.state,
delta: this.props.meta.delta,
interval: setInterval(this.tick.bind(this), 100)
})
}
componentWillUnmount() {
clearInterval(this.state.interval)
}
tick() {
const { radius, model } = this.props
const { delta, duration } = this.state
// Ensure α ≥ 0.001 to prevent initial flickering.
const angle = Math.min(
Math.max(
(1 - (delta / duration)) * Math.PI * 2,
0.001
),
Math.PI * 2 - 0.001
)
const x = Math.sin(angle) * radius
const y = Math.cos(angle) * -radius
const arc = Number(angle > Math.PI)
const rot = 0
const dir = 1
const r = radius
const path = `M 0 0 V -${r} A ${r} ${r} ${rot} ${arc} ${dir} ${x} ${y} Z`
this.setState({
...this.state,
delta: this.state.delta - 100,
path: path
})
}
render() {
return (
<div className="timer-container">
<Timer
delta={this.props.meta.delta}
path={this.state.path}
ticking={true}
/>
</div>
)
}
}
TimerContainer.defaultProps = {
radius: 50
}
export default TimerContainer
<file_sep>/app/components/ActionDashboard/index.jsx
import React from 'react'
import './styles.scss'
function ActionDashboard({ children }) {
let lastSectionID = 0
return (
<div className="action-dashboard">
{children.map(child =>
<section
key={++lastSectionID}
{...child.props}
>{child}</section>
)}
</div>
)
}
export default ActionDashboard
<file_sep>/app/reducers/NewUnitReducer.jsx
import Moment from 'moment'
import { isOngoing } from './helpers'
function timeRange(delta) {
return {
startTime: Moment(),
expiryTime: Moment().add(delta, 'seconds')
}
}
const initialState = {
fetching: false,
disabled: false,
unit: {
model: {
description: '',
tags: [],
...timeRange(1500)
},
meta: {
delta: 1500,
}
}
}
const NewUnitReducer = (state = initialState, action) => {
switch (action.type) {
case 'NEW_UNIT_CHANGE':
return {
...state,
unit: {
...state.unit,
model: {
...state.unit.model,
...action.attributes.model
},
meta: {
...state.unit.meta,
...action.attributes.meta
}
}
}
case 'TICK':
return {
...state,
unit: {
...state.unit,
model: {
...state.unit.model,
...timeRange(state.unit.meta.delta)
}
}
}
case 'NEW_UNIT_FETCHING':
return {
...state,
fetching: true,
disabled: true
}
case 'NEW_UNIT_ERROR':
return {
...state,
fetching: false,
disabled: false
}
case 'NEW_UNIT_SUCCESS':
return {
...state,
fetching: false,
unit: {
...state.unit,
model: {
...state.unit.model,
description: ''
}
}
}
case 'CANCEL_ONGOING_SUCCESS':
case 'MARK_COMPLETE_SUCCESS':
return {
...state,
disabled: false
}
case 'UNITS_SUCCESS':
// Disable new unit submission if there is a currently ongoing unit.
if (!action.data.find(isOngoing)) {
return state
}
return {
...state,
disabled: true
}
default:
return state
}
}
export default NewUnitReducer
| a857b081949d36cf11ecb15c17f325fa2b246a00 | [
"JavaScript",
"Markdown"
] | 21 | JavaScript | emilyhorsman/nightshades-react | 5ab751a92bd2844dc83e1d85a079e1d9452d5e57 | 507ae5aa821f730c148d781278feb0f34bd69c9b |
refs/heads/master | <file_sep>using UnityEngine;
using System.Collections;
using Flux;
public class FSpineTrack : FTransformTrack
{
public override void UpdateEventsEditor(int frame, float time)
{
base.UpdateEventsEditor(frame, time);
if (Sequence.IsPlayingForward)
{
var e = GetEventAfter(frame) as FSpineEvent;
if(e == null)return;
e.OnEditorUpdateEvent(time - e.StartTime);
}
else
{
var e = GetEventBefore(frame) as FSpineEvent;
if (e == null) return;
e.OnEditorUpdateEvent(time - e.StartTime);
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using Flux;
using Spine.Unity;
using Assets.WTWDT.Scripts;
[FEvent("Spine/Play Animation", typeof(FSpineTrack))]
public class FSpineEvent : FEvent
{
[HideInInspector]
[SerializeField]
private SkeletonAnimation _animation;
[SerializeField]
private string _animName;
[SerializeField]
private bool _loop;
[SerializeField]
private bool _stopWhenExited;
protected override void SetDefaultValues()
{
base.SetDefaultValues();
}
protected override void OnInit()
{
if (!_animation)
{
_animation = Owner.gameObject.GetComponent<SkeletonAnimation>();
}
_spineTrack = (FSpineTrack)_track;
base.OnInit();
}
private bool _wasInteractive = false;
protected override void OnTrigger(float timeSinceTrigger)
{
if (Owner.gameObject.GetComponent<MeshRenderer>())
{
Owner.gameObject.GetComponent<MeshRenderer>().enabled = true;
}
if(Owner.gameObject.GetComponent<InteractableCharacter>())
{
_wasInteractive = Owner.gameObject.GetComponent<InteractableCharacter>().enabled;
Owner.gameObject.GetComponent<InteractableCharacter>().enabled = false;
}
_delta = 0;
_animation.skeleton.FlipX = false;
_animation.Initialize(false);
_animation.state.SetAnimation(0, _animName, _loop);
base.OnTrigger(timeSinceTrigger);
}
public void OnEditorUpdateEvent(float time)
{
if (_animation == null || _animation.state == null) return;
var track = _animation.state.GetCurrent(0);
if (track == null) return;
track.Time = time;
_animation.Update(0);
}
protected override void OnFinish()
{
if (Owner.gameObject.GetComponent<InteractableCharacter>())
{
Owner.gameObject.GetComponent<InteractableCharacter>().enabled = _wasInteractive;
}
if (_stopWhenExited)
{
_animation.state.ClearTracks();
}
base.OnFinish();
}
protected override void OnUpdateEvent(float timeSinceTrigger)
{
base.OnUpdateEvent(timeSinceTrigger);
}
private float _delta = 0;
private FSpineTrack _spineTrack;
}
<file_sep># Flux-Spine
Extend the Unity3D Asset "Flux" to support Spine Animations both in the editor and at run-time.
# Requirements
1 - Flux Unity3D Asset https://www.assetstore.unity3d.com/en/#!/content/18440
2 - Spine Unity3D runtime https://github.com/EsotericSoftware/spine-runtimes/tree/master/spine-unity
# How to use
Add the "spine-flux" folder to your Assets root once you have installed a version of Flux and Spine.
You will need to use the Spine "Skeleton utility" http://esotericsoftware.com/spine-unity#SkeletonUtility-and-SpineUnity-Modules to convert the Spine bones untiy a Unity heirachy so that the controller can track changes inside editor mode.
Finally you can use the "Spine/Play Animation" event inside a Flux timeline to control your Spine characters.
| cfdd35a9e6f942e1862eb72cc8a86e2f1b9cb6fb | [
"Markdown",
"C#"
] | 3 | C# | guerrillacontra/Flux-Spine | 963f386ff55b53bea42b748f952c8d61af7d8c82 | 5c292c3405994684b1788789660c0a690278ceff |
refs/heads/master | <repo_name>Benoti/Hover-Css-functions<file_sep>/hover_array.php
<?php
$array = array(
'version' => '2.0.0',
'prefix' => 'hvr-',
'hoverclass' => array (
'transition' => array(
'grow' => 'Grow', 'shrink' => 'Shrink', 'pulse' => 'Pulse', 'pulse-grow' => 'Pulse grow', 'pulse-shrink' => 'Pulse Shrink', 'push' => 'Push', 'pop' => 'Pop', 'bounce-in' => 'Bounce in',
'bounce-out' => 'Bounce out', 'rotate' => 'Rotate', 'grow-rotate' => 'Grow rotate', 'float' => 'Float', 'sink' => 'Sink', 'bob' => 'Bob', 'bob-float' => 'Bob float', 'hang' => 'Hang',
'hang-sink' => 'Hang sink', 'skew' => 'Skew', 'skew-forward' => 'Skew forward', 'skew-backward' => 'Skew backward', 'wobble-vertical' => 'Wobble vertical', 'wobble-horizontal' => 'Wobble horizontal',
'wobble-to-bottom-right' => 'Wobble to bottom right', 'wobble-to-top-right' => 'Wobble to top right', 'wobble-top' => 'Wobble top', 'wobble-bottom' => 'Wobble bottom',
'wobble-skew' => 'Wobble skew', 'buzz' => 'Buzz', 'buzz-out' => 'Buzz out', 'wobble-to-bottom-left' => 'Wooble to bottom left', 'wobble-to-top-left' => 'Wobble to top left'
),
'background' => array(
'fade' => 'Fade', 'sweep-to-right' => 'Sweep to right', 'sweep-to-left' => 'Sweep to left', 'sweep-to-bottom' => 'Sweep to bottom', 'sweep-to-top' => 'Sweep to top', 'bounce-to-right' => 'Bounce to right',
'bounce-to-left' => 'Bounce to left', 'bounce-to-bottom' => 'Bounce to bottom', 'bounce-to-top' => 'Bounce to top', 'radial-out' => 'Radial out', 'radial-in' => 'Radial in', 'rectangle-in' => 'Rectangle in',
'rectangle-out' => 'Rectangle out', 'shutter-in-horizontal' => 'Shutter in horizontal', 'shutter-out-horizontal' => 'Shutter out horizontal', 'shutter-in-vertical' => 'Shutter in vertical',
'shutter-out-vertical' => 'Shutter out vertical'
),
'border' => array(
'border-fade' => 'Border fade', 'hollow' => 'Hollow', 'trim' => 'Trim', 'ripple-out' => 'Ripple out', 'ripple-in' => 'Ripple in', 'outline-out' => 'Outline out', 'outline-in' => 'Outline in',
'round-corners' => 'Round corners', 'underline-from-left' => 'Underline from left', 'underline-from-center' => 'Underline from center', 'underline-from-right' => 'Underline from right',
'overline-from-left' => 'Overline from left', 'overline-from-center' => 'Overline from center', 'overline-from-right' => 'Overline from right', 'reveal' => 'Reveal', 'underline-reveal' => 'Underline reveal',
'overline-reveal' => 'Overline reveal'
),
'shadow-glow' => array(
'glow' => 'Glow', 'shadow' => 'Shadow', 'grow-shadow' => 'Grow shadow', 'box-shadow-outset' => 'Box shadow outset', 'box-shadow-inset' => 'Box shadow inset', 'float-shadow' => 'Float shadow',
'shadow-radial' => 'Shadow radial'
),
'speech-bubbles' => array(
'bubble-top' => 'Bubble top', 'bubble-right' => 'Bubble right', 'bubble-bottom' => 'Bubble bottom', 'bubble-left' => 'Bubble left', 'bubble-float-top' => 'Bubble float top', 'bubble-float-right' => 'Bubble float right',
'bubble-float-bottom' => 'Bubble float bottom', 'bubble-float-left' => 'Bubble float left'
),
'icons' => array(
'icon-back' => 'Icon back', 'icon-forward' => 'Icon forward', 'icon-down' => 'Icon down', 'icon-up' => 'Icon up', 'icon-spin' => 'Icon spin', 'icon-drop' => 'Icon drop', 'icon-fade' => 'Icon fade',
'icon-float-away' => 'Icon float away', 'icon-sink-away' => 'Icon sink away', 'icon-grow' => 'Icon grow', 'icon-shrink' => 'Icon shrink', 'icon-pulse' => 'Icon pulse',
'icon-pulse-grow' => 'Icon pulse grow', 'icon-pulse-shrink' => 'Icon pulse shrink', 'icon-push' => 'Icon push', 'icon-pop' => 'Icon pop', 'icon-bounce' => 'Icon bounce', 'icon-rotate' => 'Icon rotate',
'icon-grow-rotate' => 'Icon grow rotate', 'icon-float' => 'Icon float', 'icon-sink' => 'Icon sink', 'icon-bob' => 'Icon bob', 'icon-hang' => 'Icon hang', 'icon-hang-sink' => 'Icon hang sink',
'icon-wobble-horizontal' => 'Icon wobble horizontal', 'icon-wobble-vertical' => 'Icon wobble vertical', 'icon-buzz' => 'Icon buzz', 'icon-buzz-out' => 'Icon buzz out'
),
'curls' => array(
'curl-top-left' => 'Curl top left', 'curl-top-right' => 'Curl top right', 'curl-bottom-right' => 'Curl bottom right', 'curl-bottom-left' => 'Curl bottom left'
)
)
);
ob_start();
var_dump($array);
$result = ob_get_clean();
echo "<br><pre>" . $result . "</pre><br>";
?>
| 4519cbc1b80b2bb6e283aea831b2ff8d3053d34f | [
"PHP"
] | 1 | PHP | Benoti/Hover-Css-functions | 57c2fb7968131abf0a052071576ef4a5930819af | c214ffe78f41f49f3088c0fc8f7fe1bb05785b62 |
refs/heads/master | <file_sep>import nflgame
import reverie as rev
import os
import pandas as pd
import tqdm
dir_path = os.path.dirname(os.path.realpath(__file__))
output_directory = os.path.abspath(os.path.join(dir_path, '..', 'data', 'game_data'))
os.makedirs(output_directory, exist_ok=True)
years = list(range(2009, 2020))
for year in tqdm.tqdm(years):
csv_filename = os.path.join(output_directory, f'season{year}.csv')
parquet_filename = os.path.join(output_directory, f'{year}.parquet')
nflgame.combine(nflgame.games(year)).csv(csv_filename)
df = pd.read_csv(csv_filename)
df.to_parquet(parquet_filename)
os.remove(csv_filename)
<file_sep>import reverie as rev
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
output_directory = os.path.abspath(os.path.join(dir_path, '..', 'data', 'ADP'))
print(f'Writing to {output_directory}')
years = range(2007, 2021)
rev.data.populate_historical_adp(output_directory, years)
<file_sep>from pathlib import Path
from setuptools import find_packages, setup
# Read the contents of README file
source_root = Path(".")
with (source_root / "README.md").open(encoding="utf-8") as f:
long_description = f.read()
# Read the requirements
with (source_root / "requirements.txt").open(encoding="utf8") as f:
requirements = f.readlines()
with (source_root / "requirements_dev.txt").open(encoding="utf8") as f:
dev_requirements = f.readlines()
with (source_root / "requirements_test.txt").open(encoding="utf8") as f:
test_requirements = f.readlines()
extras_requires = {"all": requirements + test_requirements + dev_requirements}
setup(
name="reverie",
version="0.0.1",
url="https://github.com/ieaves/reverie",
description="Fantasy football draft utilities ",
author="<NAME>",
author_email="<EMAIL>",
package_data={"reverie": ["py.typed"]},
packages=find_packages("src"),
package_dir={"": "src"},
install_requires=requirements,
include_package_data=True,
extras_require=extras_requires,
tests_require=test_requirements,
python_requires=">=3.8",
long_description=long_description,
long_description_content_type="text/x-rst",
zip_safe=False,
)
<file_sep>from typing import List
from bs4 import BeautifulSoup as BS
import pandas as pd
import requests
import attr
import functools
import os
import tqdm
def split_pos_pos_rank(value):
index = next(i for i, v in enumerate(value) if v.isnumeric())
return value[0:index], value[index:]
def _process_play_team_bye(df):
ts = df['Player Team (Bye)'].str.split()
df['bye'] = ts.apply(lambda x: x[-1].strip('()'))
df['team'] = ts.apply(lambda x: x[-2])
df['player_name'] = ts.apply(lambda x: ' '.join(x[0:-2]))
df.drop(columns=['Player Team (Bye)'], inplace=True)
return df
@attr.s
class FantasyPros:
ADP_URL = attr.ib(default="https://www.fantasypros.com/nfl/adp/ppr-overall.php")
PROJ_URL = attr.ib(default="https://www.fantasypros.com/nfl/projections/{position}.php?week=draft")
def position_projection_url(self, position):
return self.PROJ_URL.format(position=position)
@staticmethod
def request(url: str) -> BS:
res = requests.get(url)
if not res.ok:
raise Exception(f"Request to {url} failed with {res.status_code}")
return BS(res.content, 'html.parser')
@functools.cached_property
def adp_df(self) -> pd.DataFrame:
soup = self.request(self.ADP_URL)
table = soup.find('table', {'id': 'data'})
df = pd.read_html(str(table))[0]
df = _process_play_team_bye(df)
ts = df['POS'].apply(split_pos_pos_rank)
df['position'] = ts.str.get(0)
df['position_rank'] = ts.str.get(1)
df.drop(columns=['POS'], inplace=True)
return df
@functools.cached_property
def projections_df(self) -> pd.DataFrame:
def get_position_df(position: str) -> pd.DataFrame:
soup = self.request(self.position_projection_url(position))
table = soup.find('table', {'id': 'data'})
df = pd.read_html(str(table))[0]
if isinstance(df.columns, pd.core.indexes.multi.MultiIndex):
df.columns = ["_".join(('' if 'Unnamed' in l0 else l0, l1)).lstrip("_") for l0, l1 in df.columns]
df['position'] = position.upper()
return df
# url has positions in lower case
positions = ['rb', 'qb', 'te', 'wr', 'k', 'dst']
df = pd.concat(get_position_df(position) for position in positions)
df['player_name'] = df['Player'].apply(lambda x: ' '.join(x.split()[:-1]))
df.drop(columns=['Player'], inplace=True)
df = df.drop_duplicates()
return df
@attr.s
class HistoricalADP:
BASE_URL = attr.ib("https://fantasyfootballcalculator.com/adp/standard/12-team/all/{year}")
earliest_supported_year = attr.ib(default=2007)
def get_url_for_year(self, year):
return self.BASE_URL.format(year=year)
@staticmethod
def request(url: str) -> BS:
res = requests.get(url)
if not res.ok:
raise Exception(f"Request to {url} failed with {res.status_code}")
return BS(res.content, 'html.parser')
def get_adp_for_year(self, year):
soup = self.request(self.get_url_for_year(year))
table = soup.find("table", {"class": "table adp"})
df = pd.read_html(str(table))[0]
nulls = df.isna().all()
df.drop(columns=nulls[nulls].index.values, inplace=True)
return df
def populate_historical_adp(write_directory: str, years: List[int]) -> None:
ffc_adp = HistoricalADP()
os.makedirs(write_directory, exist_ok=True)
for year in tqdm.tqdm(years):
filename = os.path.join(write_directory, f'{year}.parquet')
df = ffc_adp.get_adp_for_year(year)
df.to_parquet(filename, engine='pyarrow')
<file_sep>bs4
pandas
attrs
requests
lxml
nflgame-redux
pyarrow
tqdm | 18615f8eec57d7c6a24440e812169d5b193b2478 | [
"Python",
"Text"
] | 5 | Python | ieaves/reverie | 738d26cb8892a4861cafae43976435a3904c0bb9 | a5e22b98c3891ba19f44b93b0ddea7f28335293d |
refs/heads/main | <repo_name>UAdenisyu/js-practice-6_food<file_sep>/js/modules/slider.js
function slider({container, slide, nextArrow, prevArrow, totalCounter, currentCounter, wrapper, field}){
function setZero(num){
if (num >= 0 && num < 10){
return '0' + num;
}
else{
return num;
}
}
const d = document;
//slider 1, 2
const sliderSlides = d.querySelectorAll(slide),
sliderMain = d.querySelector(container),
sliderCounterPrevButton = d.querySelector(prevArrow),
sliderCounterNextButton = d.querySelector(nextArrow),
sliderCounterTotalNum = d.querySelector(totalCounter),
sliderCounterCurrentNum = d.querySelector(currentCounter),
sliderWrapper = d.querySelector(wrapper),
sliderField = d.querySelector(field),
width = window.getComputedStyle(sliderWrapper).width;
let slideIndex = 0;
let offset = 0;
const totalSlideAmount = sliderSlides.length;
sliderCounterTotalNum.textContent = `${setZero(totalSlideAmount)}`;
sliderCounterCurrentNum.textContent = `${setZero(slideIndex+1)}`;
sliderField.style.width = 100 * sliderSlides.length + '%';
sliderField.style.display = 'flex';
sliderField.style.transition = '1s all';
sliderWrapper.style.overflow = 'hidden';
sliderSlides.forEach((slide) => {
slide.style.width = width;
});
sliderMain.style.position = 'relative';
//добавление автоматического перелистывания слайдера
let switchInterval,
autoSlidesSwitching = true;//для отключения автоперелистывания поставить false
function resetAutoSwitch(ms = 8000){
if (autoSlidesSwitching == true){
clearInterval(switchInterval);
switchInterval = setInterval(setSlide, ms, slideIndex+1);
}
}
function setSlide(i){
if (i < 0){
slideIndex = sliderSlides.length - 1;
}
else {
if (i >= sliderSlides.length){
slideIndex = 0;
}
else {
slideIndex = i;
}
}
offset = slideIndex * +width.slice(0, -2);
sliderCounterTotalNum.textContent = `${setZero(totalSlideAmount)}`;
sliderCounterCurrentNum.textContent = `${setZero(slideIndex+1)}`;
sliderField.style.transform = `translateX(-${offset}px)`;
//устанавливаем активную точку
sliderIndicators.childNodes.forEach(dot => {
dot.style.opacity = 0.5;
});
sliderIndicators.childNodes[slideIndex].style.opacity = 1;
//сбиваем таймер автоперелистывания
resetAutoSwitch();
}
sliderCounterNextButton.addEventListener('click', () => {
setSlide(slideIndex+1);
});
sliderCounterPrevButton.addEventListener('click', () => {
setSlide(slideIndex-1);
});
//создаём обертку для точек
const sliderIndicators = d.createElement('ol');//ordered list
sliderIndicators.classList.add('slider-indicators');
sliderIndicators.style.cssText = `
position: absolute;
right: 0;
bottom: 10px;
left: 0;
z-index: 15;
display: flex;
justify-content: center;
margin-right: 15%;
margin-left: 15%;
list-style: none;
`;
sliderMain.append(sliderIndicators);
//создаём точечки
for (let i = 0; i < sliderSlides.length; i++) {
const sliderDot = d.createElement('li');
sliderDot.setAttribute('data-slide-to', i);
sliderDot.style.cssText = `
box-sizing: content-box;
flex: 0 1 auto;
width: 30px;
height: 30px;
margin-right: 3px;
margin-left: 3px;
cursor: pointer;
background-color: #fff;
background-clip: padding-box;
border-top: solid transparent;
border-bottom: solid transparent;
border-radius: 15px;
opacity: 0.5;
transition: opacity .6s ease;
`;
sliderIndicators.append(sliderDot);
if (i == 0){
sliderDot.style.opacity = 1;
}
}
sliderIndicators.childNodes.forEach(dot => {
dot.addEventListener('click', () => {
setSlide(+dot.getAttribute('data-slide-to'));
});
});
resetAutoSwitch();
}
export default slider;<file_sep>/js/modules/forms.js
import {postData} from '../services/services';
import {openModal} from '../modules/modal';
function forms(formsSelector, modalDialogSelector, modalSelector){
const d = document;
//forms
const forms = d.querySelectorAll(formsSelector);
const message = {
loading : 'Идёт загрузка, пожалуйста, подождите',
success : 'Данные получены',
failure : 'Что-то пошло не так'
};
function showThankyouModal(message){
const prevModalDialog = d.querySelector('.modal__dialog');
prevModalDialog.classList.add('hide');
prevModalDialog.classList.remove('show');
openModal();//открывает все модальные окна
const thankyouModal = d.createElement('div');
thankyouModal.classList.add(modalDialogSelector);
thankyouModal.innerHTML = `
<div class="modal__content">
<div class="modal__close" data-close>×</div>
<div class="modal__title">${message}</div>
</div>
`;
thankyouModal.classList.add('fade');
d.querySelector().append(thankyouModal);
// проблема при повторном запуске модалки после отправления данных с предыдущей
setTimeout(()=>{
thankyouModal.remove(modalSelector);
prevModalDialog.classList.remove('hide');
prevModalDialog.classList.add('show');
closeModal();
}, 4000);
}
function bingPostData(form){
form.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(form);
const json = JSON.stringify(Object.fromEntries(formData.entries()));
postData('http://localhost:3000/requests', json)
.then(data => {
// console.log(data);
showThankyouModal(message.success);
})
.catch(() => {
showThankyouModal(message.failure);
})
.finally(() => {
form.reset();
});
});
}
forms.forEach(item => {
// console.log(item);
bingPostData(item);
});
}
export default forms;<file_sep>/js/modules/timer.js
function timer(deadLine, timerSelector){
const d = document;
//timer
function getTimeRemaining(endTime){
const t = Date.parse(endTime) - Date.parse(new Date()),//miliseconds differense
days = Math.floor(t / (1000 * 60 * 60 * 24)),
hours = Math.floor(t / (1000 * 60 * 60) % 24),
minutes = Math.floor(t / (1000 * 60) % 60),
seconds = Math.floor((t / 1000) % 60);
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function setZero(num){
if (num >= 0 && num < 10){
return '0' + num;
}
else{
return num;
}
}
//Следующий код не рационален,
//показано использование локальной
//видимости функций и переменных
function setTimer (selector, time) {
const timer = d.querySelector(selector),
days = timer.querySelector('#days'),
hours = timer.querySelector('#hours'),
minutes = timer.querySelector('#minutes'),
seconds = timer.querySelector('#seconds'),
timeInterval = setInterval(updateClock, 1000);
updateClock();
function updateClock() {
const t = getTimeRemaining(time);
days.innerHTML = setZero(t.days);
hours.innerHTML = setZero(t.hours);
minutes.innerHTML = setZero(t.minutes);
seconds.innerHTML = setZero(t.seconds);
if (t.total <= 0) {
clearInterval(timeInterval);
}
}
}
setTimer(timerSelector, deadLine);
}
export default timer; | df8da17d51773eae9ce6fcf3357eca4579a340b8 | [
"JavaScript"
] | 3 | JavaScript | UAdenisyu/js-practice-6_food | 345ad98be3f5bd73e6806eb98e6b2f142499ca98 | ff83ec6ce0cc6561ba8f92bde5af4881361c247c |
refs/heads/master | <file_sep># delhi-university-admissions
this is a program for enrollment in delhi university.
# features
this program enables us to make forms in c++.
<file_sep>#include<bits\stdc++.h>
void main()
{
int a,b,c,d,e,f;
cout<<"this is a program to know are you able to enrol in delhi university \n";
cout<<"enter your marks (in percentage) : ";
cin>>a;
cout<<"\n";
cout<<"enter your age :";
cin>>b;
if((a>=95)&&(b>=18))
{
cout<<"you are eligible to enrol \n";
cout<<"enter your name : ";
cin>>c;
cout<<"\nenter your age :";
cin>>d;
cout<<"\nenter your subject";
cin>>e;
cout<<"\nenter the degree for which you are applying :";
cin>>f;
cout<<"\nCongratulations ! for enrolling in delhi university. You are now eligible to attend the classes";
}
else if(a>100)
{
cout<<"you can not enrol";
}
else
{
cout<<"you are not eligible to enrol";
}
getch();
}
| 2239d216a10abe84b35531394bebabc221fff70b | [
"Markdown",
"C++"
] | 2 | Markdown | shreyans312/delhi-university-admissions | 2fec4bc80410c4bf21f19ff6c0937ddafb04ed30 | 8e4ca74e7e9e548778e782787c117b3602e78b85 |
refs/heads/master | <file_sep># reddit-tree-viz<file_sep>import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import { select, selectAll } from "d3-selection";
import ReactD3Wrapper from "./ReactD3Wrapper";
class App extends Component {
state = {
parentArticle: undefined,
commentData: []
};
componentDidMount() {
const par = this;
fetch(
"http://rockthecatzva.com/reddit-apibounce-php/public/index.php/comments/top/news/year/controversial"
)
.then(function(response) {
if (response.status !== 200) {
console.log(
"Looks like there was a problem. Status Code: " + response.status
);
return;
}
// Examine the text in the response
response.json().then(data => {
console.log(data);
const {
author,
created_utc,
domain,
id,
num_comments,
permalink,
preview,
score,
subreddit_subscribers,
thumbnail,
thumbnail_height,
thumbnail_width,
title,
ups,
upvote_ratio,
url
} = data[0].data.children[0].data;
const parentArticle = {
author,
created_utc,
domain,
id,
num_comments,
permalink,
preview,
score,
subreddit_subscribers,
thumbnail,
thumbnail_height,
thumbnail_width,
title,
ups,
upvote_ratio,
url
};
const recursivelyGetChildren = data => {
return data.map(d => {
const {
body,
title,
upvote_ratio,
ups,
domain,
score,
created,
id,
author,
num_crossposts,
num_comments,
permalink,
url,
subreddit_subscribers,
created_utc
} = d.data;
if (typeof d.data.replies === "object") {
return {
comment: body,
title,
upvote_ratio,
ups,
domain,
score,
created,
id,
author,
num_crossposts,
num_comments,
permalink,
url,
subreddit_subscribers,
created_utc,
replies: recursivelyGetChildren(d.data.replies.data.children)
};
} else {
return {
comment: body,
title,
upvote_ratio,
ups,
domain,
score,
created,
id,
author,
num_crossposts,
num_comments,
permalink,
url,
subreddit_subscribers,
created_utc
};
}
});
};
const commentData = recursivelyGetChildren(data[1].data.children);
par.setState({ parentArticle, commentData });
});
})
.catch(function(err) {
console.log("Fetch Error :-S", err);
});
}
render() {
const { parentArticle } = this.state;
const recursivelyGetReplyCounts = data =>
data.map(d => {
if (d.hasOwnProperty("replies")) {
const r = recursivelyGetReplyCounts(d.replies);
return { count: r.length, children: r };
} else {
return { count: 0 };
}
});
const branchCounts = recursivelyGetReplyCounts(this.state.commentData);
console.log(branchCounts);
console.log(this.state.commentData);
if (this.state.commentData.length > 0) {
let t = this.state.commentData[0];
}
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
{parentArticle !== undefined && (
<div>
<p>{parentArticle.title}</p>
<p>{parentArticle.ups}</p>
<p>
{Date(parentArticle.created_utc).toLocaleString("en-GB", {
timeZone: "UTC"
})}
</p>
<p>{parentArticle.num_comments}</p>
<img src={parentArticle.thumbnail} />
<ReactD3Wrapper chartData={this.state.commentData} />
</div>
)}
</div>
);
}
}
export default App;
| 1558cacdde5eebb3890bad8060f41071238f1433 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | rockthecatzva/reddit-tree-viz | e3b8d6f1ef4a6c851d70c1ee0d3b692b68052393 | 828236f724adea971cbb3b0665f871ce6efaf017 |
refs/heads/master | <repo_name>TheNormieWeeb/oto2lab<file_sep>/tool/lab_insert_sil/xml2lab_mono/utils/xml2lab.sh
#!/bin/bash
# coding: utf-8
# Copyright (c) 2020 oatsu
# wsl run.sh で実行するとPATHが皆無なので登録する
PATH="$HOME/.local/:$PATH"
# pysinsyがSinsyにアクセスできるようにする
LD_LIBRARY_PATH=/usr/local/lib/
# pathに日本語が含まれるとSinsyがエラーを出すので、一時フォルダを使って回避する。
path_temp_dir=$HOME/temp_nnsvs
# このファイルがあるディレクトリ
script_dir=$(cd $(dirname $0); pwd)
# 入出力するフォルダ
path_dir_xml="./musicxml"
path_dir_lab="./lab_input_sinsy"
path_dir_uttlist="./xml2lab_mono/02_uttlist"
path_uttlist="./xml2lab_mono/02_uttlist/utt_list.txt"
path_dir_table="./xml2lab_mono/dic"
# 出力フォルダを作成する
mkdir -p $path_dir_lab
mkdir -p $path_dir_uttlist
# 古いファイルを掃除する
rm -rf $path_temp_dir
rm -f $path_dir_lab/*
rm -f $path_dir_uttlist/*
# 一時フォルダを作る
mkdir $path_temp_dir
# musicxml ファイルをWSLのHOMEに移動させる
python $script_dir/xml2lab.py \
$path_dir_xml \
$path_temp_dir \
$path_dir_lab \
$path_dir_table \
$path_uttlist
# 不要になった一時フォルダを削除
rm -rf $path_temp_dir
<file_sep>/tool/compare_tempo_xml_ust/compare_tempo_xml_ust.py
#! /usr/bin/env python3
# coding: utf-8
# Copyright (c) 2020 oatsu
"""
USTとMusicXMLのテンポが一致するか調べる。
"""
import re
from glob import glob
from os.path import basename, splitext
from utaupy import ust as _ust
def compare_tempo(path_xml, path_ust):
"""
MusicXMLとUSTを読み取って、BPMを比較する。
"""
# MusicXMLのテンポ情報を取得
try:
with open(path_xml, 'r', encoding='utf-8') as f_xml:
s = f_xml.read()
except UnicodeDecodeError:
with open(path_xml, 'r', encoding='sjis') as f_xml:
s = f_xml.read()
tempo_xml = re.findall(r'<sound tempo=".+"/>', s)
# 次の行はデバッグ用出力
# print(tempo_xml)
tempo_xml = tempo_xml[0].split('"')[1]
print(' tempo_xml:', tempo_xml)
# USTのテンポ情報を取得
tempo_ust = _ust.load(path_ust).tempo
print(' tempo_ust:', tempo_ust)
if int(tempo_xml) != int(tempo_ust):
# print('\n_人人人人人人人人人人人人人人人人人人人人人人人人_')
# print('>[ERROR] MusicXML と UST のテンポが一致しません。<')
# print(' ̄Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^ ̄\n')
return False
return True
def main():
"""
PATHを指定して全体の処理をする。
"""
# 歌唱データベースのフォルダを指定
singing_database_dir = input('singing_database_dir: ').strip('"')
# 対象ファイルをリストで取得
xml_files = glob(f'{singing_database_dir}/**/*.*xml', recursive=True)
ust_files = glob(f'{singing_database_dir}/**/*.ust', recursive=True)
xml_files.sort()
ust_files.sort()
# ファイル数が一致するかチェック
assert len(xml_files) == len(
ust_files), f'MusicXMLファイル数({len(xml_files)})とUSTファイル数({len(ust_files)})が一致しません。'
# テンポ情報を比較
l = []
for path_xml, path_ust in zip(xml_files, ust_files):
print(' ---------------------------------------')
print(' path_xml:', path_xml)
print(' path_ust:', path_ust)
if not compare_tempo(path_xml, path_ust):
l.append(splitext(basename(path_xml))[0])
print(' ---------------------------------------')
# ファイル出力
s = '\n'.join(l)
with open('result.txt', 'w') as f:
f.write(s)
# 標準出力
print('\n[テンポが一致しなかった曲]')
print(s)
# ファイル出力
print('\nテンポが一致しなかった曲のリストを result.txt に出力しました。')
if __name__ == '__main__':
main()
input('Press Enter to exit.')
<file_sep>/dic/README.md
# table
ローマ字かな変換表とか、エイリアス種識別用テキストファイルとか。
## ファイルの説明
### kana2romaji_sjis_sinsy.table
- Sinsy 準拠の かな→ローマ字変換表
### kana2romaji_sjis.table
- kana2romaji_sjis_sinsy を拡張して、母音無声化に対応したもの。
- 無声化したものはカタカナを用い、ローマ字では大文字にする。
- カ: k A, シ: s I などを追加している。
### kana2romaji_sjis_for_oto2lab.table
- oto2lab 用の かな→ローマ字変換表
- kana2romaji_sjis を oto2lab 用に拡張したもの。
- R: pau, pau: pau, 息: br, br: br, sil: sil を追加している。
### romaji2kana_sjis_sinsy.table
- Sinsy 準拠の ローマ字→かな変換表
### romaji2kana_sjis.table
- romaji2kana_sjis_sinsy を拡張して、母音無声化に対応したもの。
- 無声化したものはカタカナを用い、ローマ字では大文字にする。
- kA: カ, sI: シ などを追加している。
<file_sep>/tool/generate_label_from_xml/README.md
# generate_label_from_xml
musicxml から 音素ラベルとフルコンテキストラベルを生成する。
## 動作環境
- Windows 10 2004
- WSL2 (Ubuntu-20.04 LTS)
- WSL1でもOK
- たぶん Debian でもOK
- Sinsy と Pysinsy のセットアップを済ませておくこと。
## 使い方
1. WSL を起動
2. oto2lab のリポジトリを複製 `git clone https://github.com/oatsu-gh/oto2lab`
3. Pysinsy にパスを通すために `export LD_LIBRARY_PATH=/usr/local/lib`
4. 変換するスクリプトを起動 `python3 oto2lab/tool/generate_label/from_xml/generate_label_from_xml.py`
5. musicxml があるフォルダのパスを入力(Window形式のパスでOK)
6. musicxml があるフォルダに 音素ラベル lab と フルコンテキストラベル full が生成される。
## 同梱ファイル
### generate_label_from_xml.py
musicxmlから音素ラベルとフルコンテキストラベルを出力する。
### generate_label_from_xml_(wrongformat).py
musicxmlから音素ラベルとフルコンテキストラベルを出力する。フォーマット間違ってて、改行含んでない。
<file_sep>/sample/README.md
# sample
デバッグ用のUSTとWAVが入ってるよ
- 大きな古時計1
- 単純な単独音UST
- 「お」「お」「き」「な」「の」「っ」「ぽ」「の」
- 大きな古時計1-2
- 「お」「お」「き」「な」**「のっ」**「ぽ」「の」
<file_sep>/tool/mono2fakefull/mono2fakefull.py
#!/usr/bin/env python3
# Copyright (c) 2020 oatsu
"""モノラベルだけからフルラベルを生成する。
NNSVSで話し声を学習してみたい。
"""
from glob import glob
from os.path import basename, isdir, join
from typing import List
import utaupy as up
from tqdm import tqdm
from utaupy.hts import Note, Song, Syllable
def monolabel_to_full_phonemes(mono_label: up.label.Label, hts_conf: dict) -> List[up.hts.Phoneme]:
"""音素をCVで区切って音節のリストにする
mono_label: モノラベル
hts_conf: 母音などの判定をするやつ
"""
# 音素の分類
vowels = hts_conf['VOWELS']
pauses = hts_conf['PAUSES']
silences = hts_conf['SILENCES']
breaks = hts_conf['BREAKS']
# フルラベル用の音素に変換する。
full_phonemes = []
for mono_phoneme in mono_label:
full_phoneme = up.hts.Phoneme()
full_phoneme.start = mono_phoneme.start
full_phoneme.end = mono_phoneme.end
full_phoneme.identity = mono_phoneme.symbol
full_phonemes.append(full_phoneme)
# p1を埋める
for phoneme in full_phonemes:
phoneme_identity = phoneme.identity
if phoneme_identity == 'xx':
phoneme.language_independent_identity = 'xx'
elif phoneme_identity in vowels:
phoneme.language_independent_identity = 'v'
elif phoneme_identity in pauses:
phoneme.language_independent_identity = 'p'
elif phoneme_identity in silences:
phoneme.language_independent_identity = 's'
elif phoneme_identity in breaks:
phoneme.language_independent_identity = 'b'
else:
phoneme.language_independent_identity = 'c'
return full_phonemes
def full_phonemes_to_syllables(full_phonemes: List[up.hts.Phoneme]) -> List[up.hts.Syllable]:
"""フルラベル用のPhonemeを音節ごとに区切る。
後ろから作っていくと多分うまくいく。
"""
syllable = Syllable()
syllable.append(full_phonemes[-1])
# 音節のリストを作る
l_syllables = [syllable]
full_phonemes_reversed = list(reversed(full_phonemes))
for i, phoneme in enumerate(full_phonemes_reversed[1:], 1):
# 休符と息継ぎと促音
if phoneme.is_rest() or phoneme.is_break():
syllable = Syllable()
l_syllables.append(syllable)
syllable.append(phoneme)
# 母音
elif phoneme.is_vowel():
# 母音の次が息継ぎか促音のときは、同じ音節にする。
if full_phonemes[i - 1].is_break():
syllable.append(phoneme)
# 母音の次が息継ぎか促音でないときは、音節を切り替える。
else:
syllable = Syllable()
l_syllables.append(syllable)
syllable.append(phoneme)
# 子音
else:
syllable.append(phoneme)
# 音節と音素の順序を逆転させて、発声順に直す
for syllable in l_syllables:
syllable.data.reverse()
l_syllables.reverse()
return l_syllables
def syllables_to_notes(syllables: List[Syllable]) -> List[Note]:
"""
音節のリストをノートのリストにする。
日本語しか想定してないので1ノート1音節。
"""
l_notes = []
for syllable in syllables:
note = Note()
note.append(syllable)
l_notes.append(note)
return l_notes
def notes_to_song(notes: List[Note]) -> Song:
"""ノート(Note)のリストをSongオブジェクトにする。
"""
song = Song()
song.data = notes
return song
def monolabel_to_song(mono_label: up.label.Label, hts_conf) -> Song:
"""
モノラベル用のオブジェクトをフルラベル用のSongオブジェクトにする。
"""
full_phonemes = monolabel_to_full_phonemes(mono_label, hts_conf)
syllables = full_phonemes_to_syllables(full_phonemes)
notes = syllables_to_notes(syllables)
song = notes_to_song(notes)
song._fill_phoneme_contexts(hts_conf)
song._fill_syllable_contexts()
# 休符からの距離(フレーズ内で何番目か)
song._fill_e18_e19()
# e6 を埋める。
for note in song:
note.number_of_syllables = len(note)
# フレーズ数
song._fill_j3()
return song
def monolabel_file_to_fulllabel_file(path_mono_lab_in, path_full_lab_out, path_hts_conf):
# TODO: ここのconfはtableじゃないようにする
hts_conf = up.table.load(path_hts_conf)
mono_label = up.label.load(path_mono_lab_in)
song = monolabel_to_song(mono_label, hts_conf)
song.write(path_full_lab_out)
def main():
"""
ファイルを指定して変換
"""
path_mono = input('path_mono: ')
path_conf = input('path_conf: ')
path_out_dir = 'out'
if isdir(path_mono):
mono_label_files = glob(f'{path_mono}/*.lab')
else:
mono_label_files = [path_mono]
assert path_mono.strip('"').endswith('.lab')
for path_mono in mono_label_files:
path_full = join(path_out_dir, basename(path_mono))
monolabel_file_to_fulllabel_file(path_mono, path_full, path_conf)
up.utils.hts2json(path_full, path_full.replace('.lab', '.json'))
if __name__ == '__main__':
main()
<file_sep>/tool/generate_label_from_xml/generate_label_from_xml.py
#! /usr/bin/env python3
# coding: utf-8
"""
Sinsy をつかって musicxml から
音素ラベル と フルコンテキストラベルを生成するツール。
"""
from glob import glob
from pprint import pprint
import pysinsy
def generate_label(path_xml):
"""
xml を読み取って
音素ラベルとフルコンテキストラベルを生成する。
"""
sinsy = pysinsy.sinsy.Sinsy()
# Set language to Japanese
assert sinsy.setLanguages("j", "/usr/local/lib/sinsy/dic")
assert sinsy.loadScoreFromMusicXML(path_xml)
is_mono = True
labels = sinsy.createLabelData(is_mono, 1, 1).getData()
s = '\n'.join(labels)
with open(path_xml.replace('.musicxml', '_sinsy.lab').replace('.xml', '_sinsy.lab'), 'w') as f:
f.write(s)
is_mono = False
labels = sinsy.createLabelData(is_mono, 1, 1).getData()
s = '\n'.join(labels)
with open(path_xml.replace('.musicxml', '.full').replace('.xml', '.full'), 'w') as f:
f.write(s)
sinsy.clearScore()
def main():
"""
入力ファイルのパスを取得して、変換にかける。
"""
p = input('musicxmlがあるフォルダのPATHを入力してね (WindowsのPATHでもOK)\n>>> ').strip('"')
p = p.replace('C:\\', '/mnt/c/').replace('D:\\', '/mnt/d/').replace('E:\\', '/mnt/e/')
p = p.replace('\\', '/')
xmlfiles = glob(f'{p}/**/*.musicxml', recursive=True)
xmlfiles += glob(f'{p}/**/*.xml', recursive=True)
pprint(xmlfiles)
for path_xml in xmlfiles:
print(f' label generating: {path_xml}')
generate_label(path_xml)
print(f' label generated : {path_xml}')
print('complete')
if __name__ == '__main__':
main()
<file_sep>/tool/lab_check_invalid_time.py
#! /usr/bin/env python3
# coding: utf-8
# Copyright (c) oatsu
"""
発声区間がマイナス値なラベルがないか検査
"""
from glob import glob
from pprint import pprint
import utaupy as up
def main():
path_lab_dir = input('path_lab_dir: ')
l_path_lab = glob(f'{path_lab_dir}/**/*.lab', recursive=True)
pprint(l_path_lab)
for path_lab in l_path_lab:
print(path_lab)
label = up.label.load(path_lab)
label.check_invalid_time()
if __name__ == '__main__':
main()
input('Press Enter to exit.')
<file_sep>/tool/lab_insert_sil/lab_insert_sil.py
#! /usr/bin/env python3
# coding: utf-8
# Copyright (c) 2020 oatsu
"""
lab_set_start_sil の強化版。Sinsyで生成したLABを参照して、oto2labなどで生成したLABにsilを挿入する。
# 使い方
1. sinsyが生成したLABを lab_input_sinsy に入れる。ファイル名は {songname}_sinsy.lab または {musicname}.lab としておく。
2. oto2labが生成したLABを lab_input_oto2lab に入れる。ファイル名は {songname}.lab としておく。
3. lab_insert_sil を起動して実行。
"""
from copy import deepcopy
from glob import glob
from os.path import basename
import utaupy
PATH_SINSY_LABEL_DIR = 'lab_input_sinsy'
PATH_OTO2LAB_LABEL_DIR = 'lab_input_oto2lab'
PATH_OUTPUT_LABEL_DIR = 'lab_output'
def check_label_diff_for_debug(labobj_oto2lab, labobj_sinsy):
"""
デバッグ用に音素数を数える
1つ違うとき・・・前奏または後奏のsilが一致しない
2つ違うとき・・・前奏と構想の両方、または間奏のsilが一致しない
"""
oto2lab_sil = [phoneme for phoneme in labobj_oto2lab if phoneme.symbol == 'sil']
sinsy_sil = [phoneme for phoneme in labobj_sinsy if phoneme.symbol == 'sil']
oto2lab_pau = [phoneme for phoneme in labobj_oto2lab if phoneme.symbol == 'pau']
sinsy_pau = [phoneme for phoneme in labobj_sinsy if phoneme.symbol == 'pau']
oto2lab_br = [phoneme for phoneme in labobj_oto2lab if phoneme.symbol == 'br']
sinsy_br = [phoneme for phoneme in labobj_sinsy if phoneme.symbol == 'br']
oto2lab_cl = [phoneme for phoneme in labobj_oto2lab if phoneme.symbol == 'cl']
sinsy_cl = [phoneme for phoneme in labobj_sinsy if phoneme.symbol == 'cl']
oto2lab_w = [phoneme for phoneme in labobj_oto2lab if phoneme.symbol == 'w']
sinsy_w = [phoneme for phoneme in labobj_sinsy if phoneme.symbol == 'w']
print(' oto2labのラベルの音素数 :', len(labobj_oto2lab))
print(' Sinsy のラベルの音素数 :', len(labobj_sinsy))
print(' oto2labのラベル中のpauの数:', len(oto2lab_pau))
print(' Sinsy のラベル中のpauの数:', len(sinsy_pau))
print(' oto2labのラベル中のsilの数:', len(oto2lab_sil))
print(' Sinsy のラベル中のsilの数:', len(sinsy_sil))
print(' oto2labのラベル中のbrの数 :', len(oto2lab_br))
print(' Sinsy のラベル中のbrの数 :', len(sinsy_br))
print(' oto2labのラベル中のclの数 :', len(oto2lab_cl))
print(' Sinsy のラベル中のclの数 :', len(sinsy_cl))
print(' oto2labのラベル中のwの数 :', len(oto2lab_w))
print(' Sinsy のラベル中のwの数 :', len(sinsy_w))
assert len(oto2lab_br) == len(sinsy_br), 'br の個数が一致しません。'
assert len(oto2lab_w) == len(sinsy_w), 'w の個数が一致しません。'
assert len(labobj_oto2lab) - len(oto2lab_pau) - len(oto2lab_sil) \
== len(labobj_sinsy) - len(sinsy_pau) - len(sinsy_sil), \
'pau, sil 以外の音素で登録ミスが存在するようです。'
def compare_all_phonemes(labobj_oto2lab, labobj_sinsy):
"""
すべての音素が一致するかチェックする。
"""
len_labobj_oto2lab = len(labobj_oto2lab)
len_labobj_sinsy = len(labobj_sinsy)
assert len_labobj_oto2lab == len_labobj_sinsy, \
f'音素数が一致しません。出力するLABの音素数: {len_labobj_oto2lab}, Sinsyの音素数 {len_labobj_sinsy}'
oto2lab_all_phonemes = [phoneme.symbol for phoneme in labobj_oto2lab]
sinsy_all_phonemes = [phoneme.symbol for phoneme in labobj_sinsy]
for i, (ph_oto2lab, ph_sinsy) in enumerate(zip(oto2lab_all_phonemes, sinsy_all_phonemes)):
assert ph_oto2lab == ph_sinsy, \
f'{i+1} 行目付近の音素が一致しません。oto2labの音素: {ph_oto2lab}, Sinsyの音素: {ph_sinsy}'
def check_start_end_match(labobj):
end = 0
for phoneme in labobj:
start = phoneme.start
assert end == start
end = phoneme.end
def delete_pau_and_sil(labobj):
"""
pauとsilを全部消す
"""
labobj.data = [phoneme for phoneme in labobj if phoneme.symbol not in ('pau', 'sil')]
def insert_pau_and_sil(labobj_oto2lab, labobj_sinsy):
"""
pauとsilを入れる。それ以外の音素は完璧に一致している前提とする。
"""
for i, phoneme_sinsy in enumerate(labobj_sinsy):
if phoneme_sinsy.symbol in ('pau', 'sil'):
labobj_oto2lab.insert(i, deepcopy(phoneme_sinsy))
def restore_pau_time(labobj_oto2lab):
"""
一度削除されたことによってpauの開始時刻と終了時刻が崩れているため、
前後の音符の音素の終了時刻と開始時刻から、本来の値を復元する。
"""
rest_symbols = ('pau', 'sil')
for i, current_phoneme in enumerate(labobj_oto2lab[1:], 1):
if current_phoneme.symbol == 'pau':
previous_phoneme = labobj_oto2lab[i - 1]
if previous_phoneme.symbol not in rest_symbols:
current_phoneme.start = previous_phoneme.end
for i, current_phoneme in enumerate(labobj_oto2lab[:-1]):
if current_phoneme.symbol == 'pau':
next_phoneme = labobj_oto2lab[i + 1]
if next_phoneme.symbol not in rest_symbols:
current_phoneme.end = next_phoneme.start
def main_wrap(path_lab_oto2lab, path_lab_sinsy, path_lab_out):
"""
間奏の処理とか前奏の処理とかクラスオブジェクト化とかをまとめて実行する。
path_lab_oto2lab: oto2lab で作ったLABファイルのパス
path_lab_sinsy : Sinsy で作ったLABファイルのパス
path_lab_out : 処理結果の出力パス
"""
# 前処理
labobj_oto2lab = utaupy.label.load(path_lab_oto2lab)
labobj_sinsy = utaupy.label.load(path_lab_sinsy)
print(' 処理前-------------------------')
check_label_diff_for_debug(labobj_oto2lab, labobj_sinsy)
# oto2labのラベルのsilを全部消す
delete_pau_and_sil(labobj_oto2lab)
# oto2labのラベルとSinsyのラベルを比較してsilを挿入する
insert_pau_and_sil(labobj_oto2lab, labobj_sinsy)
# pauが失った時間情報を復元する
restore_pau_time(labobj_oto2lab)
print(' 処理後-------------------------')
check_label_diff_for_debug(labobj_oto2lab, labobj_sinsy)
labobj_oto2lab.check_invalid_time(threshold=5)
# ファイル出力
labobj_oto2lab.write(path_lab_out)
compare_all_phonemes(labobj_oto2lab, labobj_sinsy)
check_start_end_match(labobj_oto2lab)
def main():
"""
PATHを指定して全体の処理をする。
"""
path_sinsy_label_dir = PATH_SINSY_LABEL_DIR
path_oto2lab_label_dir = PATH_OTO2LAB_LABEL_DIR
path_output_label_dir = PATH_OUTPUT_LABEL_DIR
# LABファイルを取得
sinsy_labels = glob(f'{path_sinsy_label_dir}/*.lab')
oto2lab_labels = glob(f'{path_sinsy_label_dir}/*.lab')
len_sinsy_labels = len(sinsy_labels)
len_oto2lab_labels = len(oto2lab_labels)
print('len_sinsy_labels :', len_sinsy_labels)
print('len_oto2lab_labels:', len_sinsy_labels)
assert len_sinsy_labels == len_oto2lab_labels, 'sinsyのラベルファイル数とoto2labのラベルファイル数が一致しません。'
# 書き換えを始める。
for path_lab_sinsy in sinsy_labels:
print('--------------------------------------------------')
songname = basename(path_lab_sinsy).replace('_sinsy.lab', '').replace('.lab', '')
path_lab_oto2lab = f'{path_oto2lab_label_dir}/{songname}.lab'
print('path_lab_oto2lab:', path_lab_oto2lab)
print('path_lab_sinsy :', path_lab_sinsy)
path_lab_out = f'{path_output_label_dir}/{songname}.lab'
main_wrap(path_lab_oto2lab, path_lab_sinsy, path_lab_out)
if __name__ == '__main__':
main()
<file_sep>/tool/mono2fakefull/requirements.txt
utaupy>=1.11.3
tqdm<file_sep>/README_English.md
# oto2lab
A software which can convert UST to INI (for setParam), INI to LAB.
Using this software, you can to phoneme-labeling of song wav files.
THE BELOW IS TRANSLATED TEXT FROM JAPANESE README USING "[MiraiTransrate](https://miraitranslate.com/trial/)".
## Purpose
To make singing DB by utilizing existing software (setParam) and know-how (Otoining) around UTAU, and of UTAU-users.
## Notes
- Please note that the script name may change with the upgrade.
## Development Environment
- Windows 10
- Python 3.8
## Procedure (Entire)
The specification has changed after v2.0.0.
1. Sing to make a WAV file.
2. Make UST of the song.
3. Match the timing of WAV to UST.
4. Convert UST to INI with **oto2lab**.
5. Edit the INI with **setParam** and save it.
6. Convert to LAB with **oto2lab**.
7. Finished
## Procedure (Details)
### Phonome-labeling with SetParam
For the purpose of label conversion, it is used differently from the original sound setting of UTAU.
Set the following.
- **Offset**: Not used
- **Overlap** : Consonant start
- **Preutterance** : Vowel start
- **Consonant** : Not used (the boundary between the second and third notes only when composed of three phonemes)
- **Cutoff** : Not used
### How to use this tool
1. Double-click oto2lab.exe to launch.
2. Select mode according to display. (_NOTE: So sorry, CLI text is only in Japanese._)
3. Drag and drop the file you want to process to the displayed screen.
4. Next to the file you want to process is the converted file.
<file_sep>/tool/lab_insert_sil/requirements.txt
utaupy==1.8
<file_sep>/tool/mono2fakefull/README.md
# mono2fakefull
モノラベルからなんちゃってフルラベルを生成するツール
## 用途
- NNSVSで話し声を学習してみたい。
- 話し声の音声で生成したacousticモデルを歌声用の土台にしたい。
## 仕様
### 生成されるコンテキスト
- 発声開始時刻と発声終了時刻
- 現在の音素の分類(p1)
- 現在や前後の音素記号(p2, p3, p4, p5, p6)
- 現在の音素の、音節内での位置(p12, p13)
- 現在の音素の、母音からの距離(p14, p15)※子音のみ
- 音節の、ノート内音素数(a1, b1, c1)
- 音節の、ノート内での位置(a2, a3, b2, b3, c2, c3)
- ノート内音節数(d6, e6, f6)
- ノートの、フレーズ内での位置(e18, e19)
- 曲中のフレーズ数(j3)<file_sep>/README.md
# oto2lab
setParamで歌唱ラベリングするための、UST→INI→LAB 変換ソフト。
## 目的
UTAUにおける既存インフラとノウハウの流用で、歌唱DBの充実を図る。
## 開発環境
- Windows 10
- Python 3.8
## 手順(全体)
1. 歌って WAV ファイルにする。
2. UST を作る。
3. WAV の歌い出しタイミングをUSTに揃える。
4. oto2lab で UST を INI に変換する。
5. INI を setParam で編集して保存する。
6. oto2lab で LAB に変換する。
7. 完成
## oto2lab 利用作手順
### SetParamでのパラメータ設定
ラベル変換目的のため、UTAUの原音設定とは違う使い方をします。
以下のように設定してください。
<u>**※v2.0.0から仕様が変わりました。**</u>
- 左ブランク : 不使用
- オーバーラップ : **子音** 開始位置(1音素の場合は不使用)
- 先行発声 : **母音** 開始位置(3音素の場合は2音素目開始位置)
- 子音部固定範囲 : 不使用(3音素の場合のみ、3音素目開始位置)
- 右ブランク : 不使用
### 本ツールの使い方
1. oto2lab.exe または oto2labGUI.exe をダブルクリックして起動
1. 表示に従ってモード選択
1. 表示されている画面に処理したいファイルをドラッグ&ドロップ
1. 処理したいファイルの隣に変換後のファイルができます。
### モード一覧
1. ust → ini
2. ini → lab
3. lab → ini(点検用)
4. svp → ini
5. iniファイルのエイリアス置換(かな→ローマ字)(CLI実行時のみ選択可能)
6. lab → ini(再編集用)(CLI実行時のみ選択可能)
---
© 2021 oatsu, Haruqa
© 2001-2021 Python Software Foundation
<file_sep>/tool/split_lab_and_wav/README.md
# split_wav_and_lab
休符でフルコンテキストラベルと音声ファイルを分割する。
## 分割パターン
### sil-pau(前奏)
何もしない
### pau-pau
pau と pau の境界で分割する。
### pau-sil-pau
sil と pau の境界で分割する。
### pau-sil-sil-pau
sil と sil の境界で分割する。
### pau-sil-sil-sil-sil-pau
sil と sil の境界で分割し、単独となったsilの部分は破棄する。
### pau-sil(後奏)
何もしない
## 処理手順
1. モノラベルの数値をフルラベルに転写する。
2. フルラベル中の休符連続を検出する。
3. フルラベルを分割する。このとき、sil のみのラベル(前奏を除く)は破棄する。
4. <file_sep>/tool/join_mono_label_files/join_mono_label_files.py
#!/usr/bin/env python3
# coding: utf-8
"""
複数のモノラベルを結合する。
前のファイルの終了時刻を次のファイルの開始時刻にする。
"""
from glob import glob
import utaupy as up
def main():
"""
複数のファイルをドラッグアンドドロップで指定?して結合したい。
フォルダ内でいいかなあ
"""
path_dir_in = input('path_dir_in: ').strip('"')
labfiles = glob('path_dir_in/*.lab').sorted()
label_objects = [up.label.load(path) for path in path_dir_in]
new_label = up.label.Label()
new_label += label_objects[0]
for i, label in enumerate(label_objects[1:], 1):
# オフセット設定するメソッドが欲しいと思った。
# t_start = label.global_start
offset = label[i-1][-1].end
print(f'{i}\toffset[100ns]: {offset}')
for phoneme in label:
phoneme.start += offset
phoneme.end += offset
new_label += label
if __name__ == '__main__':
main()
<file_sep>/tool/ust2shiroindex/audacitylabel2lab.py
#! /usr/bin/env python3
# coding: utf-8
# Copyright (c) 2020 oatsu
"""
txt (Audacityのラベル) -> lab (歌唱DBモノフォンラベル) の変換
読み取って、時間単位と区切り文字変えて保存するだけ。
"""
import os
from glob import glob
from pprint import pprint
import utaupy as up
def audacitylabelfile2labfile(path_audacitylabel_in:str, path_lab_out:str):
"""
txt (Audacityのラベル) -> lab (歌唱DBモノフォンラベル)
単一ファイルを変換
"""
label = up.label.load(path_audacitylabel_in, time_unit='s')
# ファイル出力
label.write(path_lab_out, time_unit='100ns')
def main():
"""
フォルダを指定して処理
"""
path_in = input('Input Audacity label txt path (file or dir)\n>>> ').strip('"')
if os.path.isdir(path_in):
txt_files = glob('{}/*.{}'.format(path_in, 'txt'))
else:
if not path_in.endswith('.txt'):
raise ValueError('txt ではないファイルが入力されました。終了します。')
txt_files = [path_in]
print('\n処理対象ファイル')
pprint(txt_files)
print('\n始めます')
for path_txt in txt_files:
print(' processing:', path_txt)
path_lab = path_txt.replace('.txt', '.lab')
audacitylabelfile2labfile(path_txt, path_lab)
print('終わりました')
if __name__ == '__main__':
print('---Audacity用ラベルを歌唱DB用ラベルにするツール(20210202)---')
main()
print('Press Enter to exit')
<file_sep>/tool/ust2shiroindex/README.md
# ust2shiroindex
複数のustファイルから、[SHIRO](https://github.com/Sleepwalking/SHIRO) 用の Index file(txt)を生成します。
## 用途
歌唱データベース用の音素アライメント自動化に使えるかもしれない。
1. 歌う。
2. USTファイルを作る。
3. 本ツールを使ってSHIRO用のTXTファイルを生成する。
4. SHIROを使って自動音素アライメントを行う。Audacity用のラベルファイルが生成される。
5. Audacity用のラベルファイルを、audacitylabel2lab とかを使って、歌唱データベース用のLABファイルに変換する。
<file_sep>/tool/force_otoini_cutoff_negative/requirements.txt
utaupy==1.11
pydub
<file_sep>/gui_wxformbuilder/MyProject1MyFrame1.py
"""Subclass of MyFrame1, which is generated by wxFormBuilder."""
import wx
import oto2lab_gui
# Implementing MyFrame1
class MyProject1MyFrame1( oto2lab_gui.MyFrame1 ):
def __init__( self, parent ):
oto2lab_gui.MyFrame1.__init__( self, parent )
# Handlers for MyFrame1 events.
def m_dirPicker1OnDirChanged( self, event ):
# TODO: Implement m_dirPicker1OnDirChanged
pass
def m_modeSelect1OnRadioBox( self, event ):
# TODO: Implement m_modeSelect1OnRadioBox
pass
def m_displayConsole1OnCheckBox( self, event ):
# TODO: Implement m_displayConsole1OnCheckBox
pass
def m_convertButton1OnButtonClick( self, event ):
# TODO: Implement m_convertButton1OnButtonClick
pass
def m_filePicker1OnFileChanged( self, event ):
# TODO: Implement m_filePicker1OnFileChanged
pass
def m_modeSelect2OnRadioBox( self, event ):
# TODO: Implement m_modeSelect2OnRadioBox
pass
def m_displayConsole2OnCheckBox( self, event ):
# TODO: Implement m_displayConsole2OnCheckBox
pass
def m_convertButton2OnButtonClick( self, event ):
# TODO: Implement m_convertButton2OnButtonClick
pass
<file_sep>/tool/generate_random_ust/generate_random_ust.py
#! /usr/bin/env python3
# coding: utf-8
# Copyright (c) oatsu
"""
音程と歌詞がランダムなUSTを生成するツール
"""
import json
import random
from os import makedirs
from pprint import pprint
import utaupy as up
# from copy import deepcopy
PATH_CONFIG = 'generate_random_ust_config.json'
def generate_random_ustobj(d_config):
"""
設定ファイルをもとに utaupy.ust.Ust オブジェクトをつくる
"""
l_for_ust = []
# バージョン情報用の空ノートを追加
l_for_ust.append(up.ust.Note(tag='[#VERSION]'))
# プロジェクト設定のノートを追加
ust_setting = up.ust.Note(tag='[#SETTING]')
ust_setting.set_by_key('Mode2', 'True')
try:
ust_setting.set_by_key('VoiceDir', d_config['voicedir'])
except KeyError:
ust_setting.set_by_key('VoiceDir', r'%VOICE%uta')
try:
ust_setting.set_by_key('Tool1', d_config['tool1'])
ust_setting.set_by_key('Tool2', d_config['tool2'])
except KeyError:
ust_setting.set_by_key('Tool1', 'wavtool.exe')
ust_setting.set_by_key('Tool2', 'resampler.exe')
ust_setting.set_by_key('Mode2', 'True')
l_for_ust.append(ust_setting)
# ノートを一括で生成
notes = [up.ust.Note(tag=f'[#{i}]') for i in range(d_config['ust_length'] - 1)]
for note in notes:
note.lyric = random.choice(d_config['aliases'])
note.length = random.choice(d_config['note_length'])
note.notenum = random.randrange(d_config['min_notenum'], d_config['max_notenum'])
# 休符は長めにする
if note.lyric == 'R':
note.length *= 2
# 最初は全休符にする
notes[0].lyric = 'R'
notes[0].length = 1920
# 最後は休符にする
notes[-1].lyric = 'R'
# リストに結合
l_for_ust += notes
# TRACKEND を追加
l_for_ust.append(up.ust.Note(tag='[#TRACKEND]'))
# Ustオブジェクトにする
ust = up.ust.Ust()
ust.values = l_for_ust
# BPMをセット
ust.tempo = random.choice(d_config['bpm'])
return ust
def join_rest_note(ust):
"""
休符を結合する
"""
counter = 0
for i, note in enumerate(ust.notes[1:]):
# print(f'\n join_rest_note: {note}')
if (ust.notes[i].lyric == 'っ') and (note.lyric == 'っ'):
note.lyric = 'R'
# print(" join_rest_note: 'っ'→'っ' を検出したので後者の 'っ' を休符にしました。")
elif (ust.notes[i].lyric == 'R') and (note.lyric == 'っ'):
note.lyric = 'R'
# print(" join_rest_note: 'R'→'っ' を検出したので後者の 'っ' を休符にしました。")
if (ust.notes[i].lyric == 'R') and (note.lyric == 'R'):
ust.notes[i].tag = '[#DELETE]' # [#DELETE]にする
note.length += ust.notes[i].length
counter += 1
# print(" join_rest_note: 'R'→'R' を検出したので休符を結合しました。")
# print(f' join_rest_note: {note}')
# print(f' 休符を {counter}回 結合しました。')
def join_cl_note(ust):
"""
促音「っ」を前の歌詞に結合する。
"""
counter = 0
for i, note in enumerate(ust.notes[1:]):
if note.lyric == 'っ':
# print(ust.notes[i])
# print(note)
ust.notes[i].length += note.length
ust.notes[i].lyric += note.lyric
note.tag = '[#DELETE]' # [#DELETE]にする
counter += 1
# print(ust.notes[i])
# print(note)
# print(f' 促音を {counter}回 結合しました。')
def main():
"""
ファイル入出力を担当
"""
# 設定ファイルを読み取る
print('PATH_CONFIG:', PATH_CONFIG)
try:
with open(PATH_CONFIG, mode='r', encoding='utf-8') as f_json:
d_config = json.load(f_json)
except UnicodeDecodeError:
with open(PATH_CONFIG, mode='r', encoding='shift-jis') as f_json:
d_config = json.load(f_json)
pprint(d_config, compact=True)
print()
# 出力フォルダをつくる
makedirs('out/ust_for_wav_and_lab', exist_ok=True)
makedirs('out/ust_for_midi_and_musicxml', exist_ok=True)
# Ustオブジェクトを生成して保存する
for i in range(d_config['file_number']):
path_ust_for_wav_and_lab = f'out/ust_for_wav_and_lab/random_{i}.ust'
path_ust_for_midi_and_musicxml = f'out/ust_for_midi_and_musicxml/random_{i}.ust'
# print('-----------------------------------------------------------')
print(f'generating UST: path_ust_for_wav_and_lab : {path_ust_for_wav_and_lab}')
print(f' path_ust_for_midi_and_musicxml: {path_ust_for_midi_and_musicxml}')
ust = generate_random_ustobj(d_config)
# 連続する休符を結合
join_rest_note(ust)
# WAV生成用のUSTを出力
ust.write(path_ust_for_wav_and_lab)
# 促音を前のノートに結合
join_cl_note(ust)
# MIDI, MusicXML, LAB 生成用のUSTを出力
ust.write(path_ust_for_midi_and_musicxml)
# print('-----------------------------------------------------------')
if __name__ == '__main__':
main()
input('Press Enter to exit.')
<file_sep>/gui_wxformbuilder/MyProject1MyFrame1Child.py
#! /usr/bin/env python3
# coding: utf-8
# Copyright (c) oatsu
"""
プロジェクトを変更しても処理内容を上書きされないようにする
"""
from MyProject1MyFrame1 import MyProject1MyFrame1
class MyProject1MyFrame1Child(MyProject1MyFrame1):
"""
wxformbuilder が生成する MyProject1MyFrame1 をいじるためのクラス
"""
def m_convertButton2OnButtonClick(self, event):
"""
右の変換ボタンをクリックしたときの動作
"""
self.m_convertButton2.SetLabel('pressed')
<file_sep>/tool/force_otoini_cutoff_negative/README.md
# force_otoini_cutoff_negative
UTAUの原音設定ファイルの右ブランクの値を負にする。上書きされるので注意。
## 使い方
1. oto.ini ファイルを force_otoini_cutoff_negative.py にD&D する。
2. 処理が終わると oto.ini ファイルが上書きされる。<file_sep>/requirements.txt
utaupy>=1.12.1
<file_sep>/tool/compare_tempo_xml_ust/README.md
# compare_tempo_xml_ust
歌唱データベース内のMusicXMLとUSTのテンポ情報を比較して、一致していない場合に修正を促す。
## 動作環境
- Windows 10 2004
- Python 3.9
- utaupy 1.8
- WSLは不要
## 使い方
1. PowerShell上で `Python compare_tempo_xml_ust.py`
2. MusicXMLやUSTが入っているフォルダを指定(再帰的に取得できます)
3. PowerShell上での出力を読んで不整合を探す
## TODO(開発)
- いずれ改造してログファイル出力したい
- 順に表示するだけでなく不一致を一覧にしたい<file_sep>/tool/ust_double_or_halve_bpm.py
#! /usr/bin/env python3
# coding: utf-8
# Copyright (c) oatsu
"""
ピッチを変えずにUSTのテンポを倍にしたり半分にしたりする。
エンベロープがどうなるかは知らん。
"""
import os
import utaupy
def double_tempo_ust(ust):
"""
ピッチそのままでUSTのテンポを倍にする
"""
ust.tempo *= 2
notes = ust.notes
for note in notes:
note.length *= 2
def halve_tempo_ust(ust):
"""
ピッチそのままでUSTのテンポを倍にする
"""
ust.tempo /= 2
notes = ust.notes
for note in notes:
note.length /= 2
def main():
"""
機能選択とファイル入出力
"""
path_ust_in = input('USTファイルのパスを入力してください\n>>> ').strip('"')
ust = utaupy.ust.load(path_ust_in)
print('どちらの機能を使いますか?( 1 / 2 )')
print('1) ピッチを保って BPMを2倍にする')
print('2) ピッチを保って BPMを半分にする')
mode = input()
# 機能の分岐
if mode in ['1', '1']:
double_tempo_ust(ust)
elif mode in ['2', '2']:
halve_tempo_ust(ust)
# 実行ファイルの隣に出力
path_ust_out = os.path.basename(path_ust_in)
ust.write(f'{path_ust_out}')
if __name__ == '__main__':
main()
input('Press Enter to exit.')
<file_sep>/tool/force_otoini_cutoff_negative/force_otoini_cutoff_negative.py
#!/usr/bin/env python3
# Copyright (c) 2020 oatsu
"""
oto.iniの右ブランクを負の値に強制する。
"""
from sys import argv
from os.path import dirname, join
from pydub import AudioSegment
import utaupy as up
def force_otoinifile_cutoff_negative(path_otoini_in, path_otoini_out):
"""
指定されたoto.iniを読んで、右ブランクが正の値なときはwavファイルの長さを調べて負にする。
"""
otoini = up.otoini.load(path_otoini_in)
voice_dir = dirname(path_otoini_in)
if not all([oto.cutoff <= 0 for oto in otoini]):
for oto in otoini:
path_wav = join(voice_dir, oto.filename)
sound = AudioSegment.from_file(path_wav, 'wav')
duration_ms = 1000 * sound.duration_seconds
absolute_cutoff_position = duration_ms - oto.cutoff
oto.cutoff = -(absolute_cutoff_position - oto.offset)
otoini.write(path_otoini_out)
def main(path_otoini):
"""
もとのファイルを上書き修正する。
"""
force_otoinifile_cutoff_negative(path_otoini, path_otoini)
if __name__ == '__main__':
if len(argv) == 1:
main(input('path_otoini: '))
else:
main(argv[1])
<file_sep>/tool/phoneme_duration_quartile/phoneme_duration_quartile.py
#!/usr/bin/env python3
# Copyright (c) 2020 oatsu
"""
音素の長さの分布を調査する。
指定したフォルダ内にあるモノラベルファイルをすべて取得して、csvか何かにして出力する。
とりあえず、
音素,duration
だけの大きいcsvを作ってExcelで処理させてみる?
"""
from glob import glob
from statistics import median, mode
from typing import Dict
import pandas as pd
import utaupy
# from typing import List
def load_mono_label_files(path_dir):
"""
モノラベルを一括で読み取る
"""
lab_files = glob(f'{path_dir}/**/*.lab', recursive=True)
label_objects = [utaupy.label.load(path_lab) for path_lab in lab_files]
return label_objects
def export_phoneme_duration_csv(label_objects, path_csv_out):
"""
音素記号,duration
のみのCSV出力
"""
lines = []
for label in label_objects:
line = '\n'.join([f'{phoneme.symbol},{phoneme.duration // 10000}' for phoneme in label])
lines.append(line)
s = '\n'.join(lines)
with open(path_csv_out, 'w', encoding='utf-8') as f:
f.write(s)
def phoneme_duration_dict(label_objects) -> dict:
"""
音素:[duration, duration]
な辞書にする
"""
d: Dict[str, list] = {}
for label in label_objects:
for phoneme in label:
if phoneme.symbol in d:
d[phoneme.symbol].append(round(phoneme.duration / 10000))
else:
d[phoneme.symbol] = [round(phoneme.duration / 10000)]
for key, value in d.items():
d[key] = sorted(value)
return d
def export_discribed_data_txt(label_objects, path_out):
"""
{音素: durationの最頻値}
な辞書にする
"""
d: Dict[str, list] = {}
for label in label_objects:
for phoneme in label:
if phoneme.symbol in d:
d[phoneme.symbol].append(phoneme.duration)
else:
d[phoneme.symbol] = [phoneme.duration]
s = ''
for k, v in d.items():
s += '-----------------------------------\n'
s += f'{k}\n'
df = pd.DataFrame(v)
s += str(df.describe())
s += '\n'
with open(path_out, 'w', encoding='utf-8')as f:
f.write(s)
def export_phoneme_median_json(label_objects, path_json_out):
"""
{音素: durationの最頻値}
な辞書にする
"""
d: Dict[str, list] = {}
for label in label_objects:
for phoneme in label:
if phoneme.symbol in d:
d[phoneme.symbol].append(round(phoneme.duration))
else:
d[phoneme.symbol] = [round(phoneme.duration)]
d_median = {key: round(median(value) / 50000) * 5 for key, value in d.items()}
with open(path_json_out, 'w', encoding='utf-8')as f:
f.write(str(d_median).replace('\'', '"'))
def main():
path_dir = input('path_dir: ').strip('"')
label_objects = load_mono_label_files(path_dir)
# export_phoneme_duration_csv(label_objects, 'result_all_durations.csv')
export_phoneme_median_json(label_objects, 'result_median.json')
# export_discribed_data_txt(label_objects, 'result_discribed.txt')
if __name__ == '__main__':
main()
<file_sep>/tool/generate_random_ust/README.md
# generate_random_ust
音程と歌詞がランダムなUSTを生成する。最後は必ず休符になるようにする。
## 使い方
- 使える歌詞(単独音)の一覧を読み取る
- R も書いておく
- 同じ歌詞を重ねてもOK
- 音程の範囲を設定する
- 最低音の鍵盤番号
- 最高音の鍵盤番号
- BPMを設定する
- 途中で変化してもたぶんOK
- USTの長さ(ノート数)を設定する
- ノート長を設定する
- 同じノート長を重ねて出現回数を調整する
- 出力するファイル数を設定する
## generate_random_ust_config.json に書く内容
- 必須パラメーター
- aliases (list of str)
- max_notenum (int)
- min_notenum (int)
- bpm (list of int, or list of float)
- ust_length (int)
- BPM120の場合1800程度が上限(wavが100MBを超えるため)
- BPM240の場合3600程度
- UTAUの仕様で9999が上限
- note_length (list of int)
- file_number (int)
- 任意パラメーター
- voicedir (str)
- tool1 (str)
- tool2 (str)
<file_sep>/tool/join_mono_label_files/README.md
# join_mono_label_files
複数のモノラベルファイルを連結する。
## 用途
wavを分割してラベリングした後に結合し直したい
## 使い方
フォルダを指定するとそのフォルダ内にあるラベルを結合する。
## TODO
oto.iniを分割するスクリプトがないと目的を達成できなそう。
<file_sep>/tool/lab_detect_restrest/lab_detect_restrest.py
#! /usr/bin/env python3
# coding: utf-8
# Copyright (c) 2020 oatsu
"""
休符音素の連続を検知する。
"""
import utaupy as up
from glob import glob
def check_label(path_lab:str) -> list:
"""
utaupy.label.Label オブジェクト内の休符連続を検査
"""
label = up.label.load(path_lab)
l_outer = []
rest_phoneme = ('pau', 'sil')
previous_phoneme = label[0]
for phoneme in label[1:]:
if (previous_phoneme.symbol in rest_phoneme) and (phoneme.symbol in rest_phoneme):
l_inner = [previous_phoneme, phoneme]
l_outer.append('\t'.join((str(lab) for lab in l_inner)))
print('休符音素連続を検出しました。')
print(previous_phoneme)
print(phoneme)
print('--------------------------------------------')
previous_phoneme = phoneme
return l_outer
def main():
path_dir_lab = input('path_dir_lab: ').strip('"')
lab_files = glob(f'{path_dir_lab}/**/*.lab', recursive=True)
total_result = []
for path_lab in lab_files:
print(path_lab)
result = check_label(path_lab)
if len(result) != 0:
total_result.append(f'\n{path_lab}')
total_result.append('\n'.join(result))
str_total_result = '\n'.join(total_result)
with open('result.txt', 'w', encoding='utf-8') as f:
f.write(str_total_result)
if __name__ == '__main__':
main()
<file_sep>/gui_wxformbuilder/main.py
#! /usr/bin/env python3
# coding: utf-8
# Copyright (c) oatsu
"""
wxPythonの動作チェック
"""
# import os
# import sys
import wx
from MyProject1MyFrame1Child import MyProject1MyFrame1Child
if __name__ == '__main__':
app = wx.App(False)
frame = MyProject1MyFrame1Child(None)
frame.Show(True)
app.MainLoop()
<file_sep>/tool/lab_insert_sil/README.md
# lab_insert_sil
lab_set_start_sil の強化版。Sinsyで生成したLABを参照して、oto2labなどで生成したLABにsilやpauを挿入する。
## 開発環境
- Windos 10 2004
- Python 3.9
### 使用ライブラリ
- utaupy 1.8
## 設計
1. oto2labで生成したLABファイルと、Sinsyで生成したLABファイルを読み取る。
2. oto2labで生成したLABの sil と pau をすべて削除する。
3. Sinsyで生成したLABの sil と pau をすべて oto2lab のLABに挿入する。
4. oto2labのLABの pau の時間データがずれるので、復元する。
5. 修正されたoto2labのLABをファイル出力する。
## 使い方
好きなほうを選んでください。
### 使い方①
1. Sinsyが生成したLABを **lab_input_sinsy** に入れる。ファイル名は **{songname}\_sinsy.lab** または **{musicname}.lab** としておく。
1. oto2labが生成したLABを **lab_input_oto2lab** に入れる。ファイル名は **{songname}.lab** としておく。
1. **lab_insert_sil** を起動して実行。
1. **lab_output** に出力される。
## 使い方②
1. WSLにNNSVSの環境を作っておく。
2. MusicXMLを **musicxml** に入れる。ファイル名は **{songname}.musicxml**としておく。
3. oto2labが生成したLABを **lab_input_oto2lab** に入れる。ファイル名は **{songname}.lab** としておく。
4. PowerShell から **xml2lab_and_insert_sil.bat** を実行。
5. lab_output に出力される。途中でエラーが出ると止まるのでPowerShellの画面をチェックしてください。<file_sep>/oto2lab.py
#! /usr/bin/env python3
# Copyright 2021 oatsu
"""
setParam での音声ラベリング支援ツールです。
ファイル形式を変換できます。
・ust → ini
・svp → ini
・ini → lab
・lab → ini
"""
import argparse
import os
# import re
# import sys
from datetime import datetime
from glob import glob
# from pathlib import Path
from pprint import pprint
from shutil import copy2
import utaupy as up
DEBUG_MODE = False
PATH_TABLE = './dic/kana2phonemes_utf8_for_oto2lab.table'
def backup_io(path_file, outdirname):
"""
ファイル名に時刻を組み込んでバックアップ
入出力ファイル向け。
"""
basename, ext = os.path.splitext(os.path.basename(path_file))
now = datetime.now().strftime('%Y%m%d_%H%M%S')
copy2(path_file, f'backup/{outdirname}/{basename}__{now}{ext}')
def split_cl_note_of_ust(ust):
"""
Ustオブジェクト中のNoteのうち、促音を含むノートを半分に割る。
「かっ」→「か」「っ」
促音のみのノートはそのままにすることに注意。
"""
new_notes = []
for note in ust.notes:
lyric = note.lyric
if ('っ' in lyric) and (lyric != 'っ'):
# もとのノートを半分にして、促音を削ってリストに追加
half_length = round(note.length / 2)
note.lyric = lyric.strip('っ')
note.length = half_length
new_notes.append(note)
# もう半分の長さの促音のノートをリストに追加
note_cl = up.ust.Note()
note_cl.lyric = 'っ'
note_cl.length = half_length
# 分割した2つのノートをリストに追加
new_notes.append(note_cl)
else:
new_notes.append(note)
# ノートを上書き
ust.notes = new_notes
ust.reload_tempo()
def ustfile_to_inifile(path:str, path_tablefile:str, mode='romaji_cv'):
"""
USTファイルをINIファイルに変換
"""
allowed_modes = ['mono', 'romaji_cv']
if mode not in allowed_modes:
raise ValueError('argument \'mode\' must be in {}'.format(allowed_modes))
# かな→ローマ字変換テーブルを読み取り
d_table = up.table.load(path_tablefile) # kana-romaji table
# ファイルを指定した場合
if os.path.isfile(path):
l = [path]
outdir = os.path.dirname(path)
# フォルダを指定した場合
else:
l = glob('{}/*.{}'.format(path, 'ust'))
outdir = path
print('\n処理対象ファイル---------')
pprint(l)
print('-------------------------\n')
# USTファイルをINIファイルに変換して保存する処理
for path_ustfile in l:
print('converting UST to INI :', path_ustfile) # 'outdir/name.ini'
backup_io(path_ustfile, 'in')
basename = os.path.basename(path_ustfile) # 'name.ust'
name_wav = basename.replace('.ust', '.wav') # 'name.wav'
# 出力するINIファイルのパス
path_inifile = '{}/{}'.format(outdir, basename.replace('.ust', '.ini'))
# UST を読み取り
ust = up.ust.load(path_ustfile)
# 休符で終わってない場合はエラー終了
if ust.notes[-1].lyric not in ('R', 'pau', 'sil'):
raise ValueError(f'USTファイルの最後は必ず休符にしてください。対象ファイル: {path_ustfile}')
# 促音を含むノートを分割
split_cl_note_of_ust(ust)
# 変換
otoini = up.convert.ust2otoini(ust, name_wav, d_table, mode=mode, debug=DEBUG_MODE)
otoini.write(path_inifile)
backup_io(path_inifile, 'out')
print('converted UST to INI :', path_inifile)
def inifile_to_labfile(path_dir_in, mode='auto'):
"""
oto->lab 変換を単独ファイルに実行
"""
# ファイルを指定した場合
if os.path.isfile(path_dir_in):
l = [path_dir_in]
outdir = os.path.dirname(path_dir_in)
# フォルダを指定した場合
else:
l = glob('{}/*.{}'.format(path_dir_in, 'ini'))
outdir = path_dir_in
print('\n処理対象ファイル---------')
pprint(l)
print('-------------------------\n')
# ファイル変換処理
for path_inifile in l:
print('converting INI to LAB :', path_inifile)
backup_io(path_inifile, 'in')
basename = os.path.basename(path_inifile)
path_labfile = '{}/{}'.format(outdir, basename.replace('.ini', '.lab'))
# INI を読み取り
otoini = up.otoini.load(path_inifile)
# 変換
lab = up.convert.otoini2label(otoini, mode=mode, debug=DEBUG_MODE)
# LAB を書き出し
lab.write(path_labfile)
backup_io(path_labfile, 'out')
print('converted INI to LAB :', path_labfile)
def labfile_to_inifile(path):
"""
lab->ini 変換
"""
if os.path.isfile(path):
l = [path]
else:
l = glob('{}/**/*.{}'.format(path, 'lab'), recursive=True)
# ファイル変換処理
print('\n処理対象ファイル---------')
pprint(l)
print('-------------------------\n')
for path_labfile in l:
# 各種pathの設定
basename = os.path.basename(path_labfile)
path_inifile = os.path.splitext(path_labfile)[0] + '_review.ini'
name_wav = basename.replace('.lab', '.wav')
# 変換開始
print('converting LAB to INI :', path_labfile)
backup_io(path_labfile, 'in')
label = up.label.load(path_labfile)
otoini = up.convert.label2otoini(label, name_wav)
otoini.write(path_inifile)
backup_io(path_inifile, 'out')
print('converted LAB to INI :', path_inifile)
def inifile_kana2romaji(path_input, path_tablefile):
"""
複数のiniファイルの平仮名エイリアスをローマ字にする
"""
if os.path.isdir(path_input):
l = glob('{}/*.{}'.format(path_input, 'ini'))
else:
l = [path_input]
# かな→ローマ字変換テーブル
d_table = up.table.load(path_tablefile)
# ファイル変換処理
print('\n処理対象ファイル---------')
pprint(l)
print('-------------------------\n')
for path_ini in l:
backup_io(path_ini, 'in')
otoini = up.otoini.load(path_ini)
for oto in otoini:
try:
oto.alias = ' '.join(d_table[oto.alias])
except KeyError as err:
print('[WARNING] KeyError in oto2lab.inifile_kana2ramaji')
print(' 詳細:', err)
print(path_ini)
otoini.write(path_ini)
backup_io(path_ini, 'out')
def svpfile_to_inifile(path, path_tablefile, mode='romaji_cv'):
"""
SVPファイルをINIファイルに変換する。
Ustオブジェクトを中間フォーマットにする。
"""
allowed_modes = ['mono', 'romaji_cv']
if mode not in allowed_modes:
raise ValueError('argument \'mode\' must be in {}'.format(allowed_modes))
# かな→ローマ字変換テーブル
d_table = up.table.load(path_tablefile)
# ファイルを指定した場合
if os.path.isfile(path):
l = [path]
outdir = os.path.dirname(path)
# フォルダを指定した場合
else:
l = glob('{}/*.{}'.format(path, 'svp'))
outdir = path
print('\n処理対象ファイル---------')
pprint(l)
print('-------------------------\n')
for path_svpfile in l:
print('converting SVP to INI :', path_svpfile) # 'outdir/<name>.ini'
# 入力ファイルをバックアップ
backup_io(path_svpfile, 'in')
# 出力パスを決める
basename = os.path.basename(path_svpfile) # '<name>.ust'
name_wav = basename.replace('.svp', '.wav') # '<name>.wav'
path_inifile = '{}/{}'.format(outdir, basename.replace('.svp', '.ini'))
# SvpをUstに変換
svp = up.svp.load(path_svpfile)
ust = up.convert.svp2ust(svp, debug=DEBUG_MODE)
# 促音を含むノートを分割
split_cl_note_of_ust(ust)
# UstをOtoIniに変換してファイル出力
otoini = up.convert.ust2otoini(ust, name_wav, d_table, mode=mode, debug=DEBUG_MODE)
otoini.write(path_inifile)
# 出力ファイルをバックアップ
backup_io(path_inifile, 'out')
print('converted SVP to INI :', path_inifile)
def labfile_to_inifile_revise(path):
"""
lab->ini 変換
"""
if os.path.isfile(path):
l = [path]
else:
l = glob('{}/**/*.{}'.format(path, 'lab'), recursive=True)
# ファイル変換処理
print('\n処理対象ファイル---------')
pprint(l)
print('-------------------------\n')
for path_labfile in l:
# 各種pathの設定
basename = os.path.basename(path_labfile)
path_inifile = os.path.splitext(path_labfile)[0] + '_revise.ini'
name_wav = basename.replace('.lab', '.wav')
# 変換開始
print('converting LAB to INI :', path_labfile)
backup_io(path_labfile, 'in')
label = up.label.load(path_labfile)
otoini = up.convert.label2otoini(label, name_wav)
for oto in otoini:
oto.offset -= 100
oto.overlap = 0
oto.preutterance += 100
oto.consonant += 100
oto.cutoff2 += 100
otoini.write(path_inifile)
backup_io(path_inifile, 'out')
print('converted LAB to INI :', path_inifile)
def main_cli():
"""
全体の処理を実行
"""
path_tablefile = PATH_TABLE
print('実行内容を数字で選択してください。')
print('1 ... UST -> INI の変換')
print('2 ... INI -> LAB の変換')
print('3 ... LAB -> INI の変換(点検用)')
print('4 ... SVP -> INI の変換')
print('5 ... INI ファイルのエイリアス置換(かな -> ローマ字)')
print('6 ... LAB -> INI の変換(再編集用)')
mode = input('>>> ')
print('処理対象ファイルまたはフォルダを指定してください。')
path = input('>>> ').strip(r'"')
# ustファイルを変換
if mode in ['1', '1']:
ustfile_to_inifile(path, path_tablefile)
# iniファイルを変換
elif mode in ['2', '2']:
inifile_to_labfile(path, mode='auto')
# labファイルをiniファイルに変換
elif mode in ['3', '3']:
labfile_to_inifile(path)
# svpファイルをiniファイルに変換(ustオブジェクト経由)
elif mode in ['4', '4']:
svpfile_to_inifile(path, path_tablefile)
elif mode in ['5', '5']:
# iniファイルをひらがなCV→romaCV変換
inifile_kana2romaji(path, path_tablefile)
elif mode in ['6', '6']:
# labファイルを再編集用のモノフォンiniファイルに変換
labfile_to_inifile_revise(path)
else:
# 想定外のモードが指定されたとき
print('1 から 5 で選んでください。\n')
main_cli()
def main_gui(path, mode):
"""
oto2lab_gui.exe から呼び出されたときの処理
"""
path_tablefile = PATH_TABLE
path = path.strip(r'"')
if mode == '1':
# ustファイルを変換
ustfile_to_inifile(path, path_tablefile)
elif mode == '2':
# iniファイルを変換
inifile_to_labfile(path)
elif mode == '3':
# labファイルをiniファイルに変換
labfile_to_inifile(path)
elif mode == '4':
# svpファイルをiniファイルに変換(ustオブジェクト経由)
svpfile_to_inifile(path, path_tablefile)
elif mode is None:
print('mode番号が設定されてないみたい。')
if __name__ == '__main__':
print('_____ξ・ヮ・) < oto2lab v2.3.0 ________')
print('Copyright (c) 2021 oatsu')
print('Copyright (c) 2021 Haruqa')
print('Copyright (c) 2001-2021 Python Software Foundation\n')
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', help='入力ファイルかフォルダ input path\t(file or dir)')
parser.add_argument('-m', '--mode', help='モード選択 mode selection\t(1~5)')
parser.add_argument('--table', help='変換テーブルのパス table path\t(file)')
parser.add_argument('--debug', help='デバッグモード debug flag\t(bool)', action='store_true')
parser.add_argument('--gui', help='executed by oto2labGUI\t(bool)', action='store_true')
parser.add_argument('--kana', help='日本語のINIエイリアスの時に有効にしてね\t(bool)', action='store_true')
args = parser.parse_args()
DEBUG_MODE = args.debug
if not args.table is None:
PATH_TABLE = args.table
# バックアップ用のフォルダを生成
os.makedirs('backup/in', exist_ok=True)
os.makedirs('backup/out', exist_ok=True)
if args.gui is False:
if DEBUG_MODE:
print('args:', args)
main_cli()
input('Press Enter to exit.')
else:
# NOTE: GUI呼び出しでデバッグモードにすると実行失敗することが判明。
# args は 扱えるがprintしようとすると落ちる。
# args をつかうのやめてもなんか落ちる。標準出力が多いせいか。
main_gui(path=args.input, mode=args.mode)
<file_sep>/tool/detect_paupau/detect_paupau.py
#! /usr/bin/env python3
# coding: utf-8
# Copyright (c) 2020 oatsu
"""
モノフォンラベルの休符連続を検出する。Sinsy準拠に改変されていることが条件。
"""
from glob import glob
import utaupy as up
from tqdm import tqdm
def load_all_labels(path_dir):
"""
対象のラベルを一気にロードする。
"""
all_paths = glob(f'{path_dir}/**/*.lab', recursive=True)
labels = [up.label.load(path) for path in all_paths]
return labels
def detect_paupau(label):
"""
pau-pau, sil-sil, pau-sil, sil-pau の並びを検出する。
"""
pau_and_sil = ('pau', 'sil')
pau_pau = 0
pau_sil = 0
sil_sil = 0
sil_pau = 0
for i, phoneme in enumerate(label[:-1]):
current_symbol = phoneme.symbol
next_symbol = label[i + 1].symbol
if not (current_symbol in pau_and_sil and next_symbol in pau_and_sil):
continue
if current_symbol == 'pau' and next_symbol == 'pau':
pau_pau += 1
elif current_symbol == 'pau' and next_symbol == 'sil':
pau_sil += 1
elif current_symbol == 'sil' and next_symbol == 'sil':
sil_sil += 1
elif current_symbol == 'sil' and next_symbol == 'pau':
sil_pau += 1
else:
print('は?')
return pau_pau, pau_sil, sil_sil, sil_pau
def main():
path_dir = input('path_dir: ').strip('"')
labels = load_all_labels(path_dir)
pau_pau, pau_sil, sil_sil, sil_pau = (0, 0, 0, 0)
for label in tqdm(labels):
l = detect_paupau(label)
pau_pau += l[0]
pau_sil += l[1]
sil_sil += l[2]
sil_pau += l[3]
s = f'pau_pau: {pau_pau}\npau_sil: {pau_sil}\nsil_sil: {sil_sil}\nsil_pau: {sil_pau}\n'
print(s)
with open('result.txt', mode='w', encoding='utf-8') as f:
f.write(s)
if __name__ == '__main__':
main()
<file_sep>/tool/lab_convert_time_unit/README.md
# lab_convert_time_unit
東北きりたん歌唱DBの音素ラベルフォーマットと、HTS mono phone label のフォーマットを相互変換するツール
## 使い方
1. ダブルクリックして起動
2. lab ファイルがあるフォルダを指定
3. 実行
4. 元のファイルは、変換対象フォルダ内の old_日付 フォルダにバックアップされます。<file_sep>/gui_wxformbuilder/oto2lab_gui.py
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Oct 26 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################
import wx
import wx.xrc
###########################################################################
## Class MyFrame1
###########################################################################
class MyFrame1 ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"oto2lab (wxPython GUI version)", pos = wx.DefaultPosition, size = wx.Size( 720,460 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHints( wx.Size( 640,460 ), wx.Size( 1200,640 ) )
self.SetForegroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOWTEXT ) )
self.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOW ) )
bSizer1 = wx.BoxSizer( wx.VERTICAL )
self.m_staticText7 = wx.StaticText( self, wx.ID_ANY, u"\n1. 変換したいファイル または 変換したいファイルがあるフォルダ を指定してください。\n2. 「変換する」 のボタンを押してください。\n", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_staticText7.Wrap( -1 )
self.m_staticText7.SetForegroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOWTEXT ) )
bSizer1.Add( self.m_staticText7, 0, wx.ALL, 5 )
bSizer2 = wx.BoxSizer( wx.HORIZONTAL )
sbSizer2 = wx.StaticBoxSizer( wx.StaticBox( self, wx.ID_ANY, u"フォルダ指定で変換" ), wx.VERTICAL )
self.m_dirPicker1 = wx.DirPickerCtrl( sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, u"変換したいファイルがあるフォルダを指定", wx.DefaultPosition, wx.Size( -1,-1 ), wx.DIRP_DEFAULT_STYLE|wx.DIRP_DIR_MUST_EXIST )
self.m_dirPicker1.SetForegroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOW ) )
self.m_dirPicker1.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOW ) )
sbSizer2.Add( self.m_dirPicker1, 0, wx.ALL|wx.EXPAND, 5 )
m_modeSelect1Choices = [ u"ini to lab", u"lab to ini", u"ust to ini" ]
self.m_modeSelect1 = wx.RadioBox( sbSizer2.GetStaticBox(), wx.ID_ANY, u"機能選択", wx.DefaultPosition, wx.DefaultSize, m_modeSelect1Choices, 3, wx.RA_SPECIFY_ROWS )
self.m_modeSelect1.SetSelection( 0 )
self.m_modeSelect1.SetFont( wx.Font( wx.NORMAL_FONT.GetPointSize(), wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, wx.EmptyString ) )
self.m_modeSelect1.SetForegroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOWTEXT ) )
self.m_modeSelect1.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOW ) )
sbSizer2.Add( self.m_modeSelect1, 0, wx.ALL|wx.EXPAND, 5 )
self.m_displayConsole1 = wx.CheckBox( sbSizer2.GetStaticBox(), wx.ID_ANY, u"コマンドライン出力を表示", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_displayConsole1.SetForegroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOWTEXT ) )
self.m_displayConsole1.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOW ) )
sbSizer2.Add( self.m_displayConsole1, 0, wx.ALL, 5 )
sbSizer2.Add( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_convertButton1 = wx.Button( sbSizer2.GetStaticBox(), wx.ID_ANY, u"変換する", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_convertButton1.SetFont( wx.Font( 9, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, "MS Pゴシック" ) )
self.m_convertButton1.SetForegroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_BTNTEXT ) )
self.m_convertButton1.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_3DLIGHT ) )
sbSizer2.Add( self.m_convertButton1, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
self.m_gauge1 = wx.Gauge( sbSizer2.GetStaticBox(), wx.ID_ANY, 100, wx.DefaultPosition, wx.DefaultSize, wx.GA_HORIZONTAL )
self.m_gauge1.SetValue( 0 )
self.m_gauge1.SetForegroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOW ) )
sbSizer2.Add( self.m_gauge1, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
bSizer2.Add( sbSizer2, 1, wx.ALL|wx.EXPAND, 5 )
sbSizer3 = wx.StaticBoxSizer( wx.StaticBox( self, wx.ID_ANY, u"ファイル指定で変換" ), wx.VERTICAL )
self.m_filePicker1 = wx.FilePickerCtrl( sbSizer3.GetStaticBox(), wx.ID_ANY, wx.EmptyString, u"入力ファイル選択", u"*.ust, *.ini, *.lab, *.svp", wx.DefaultPosition, wx.Size( -1,-1 ), wx.FLP_DEFAULT_STYLE|wx.FLP_FILE_MUST_EXIST )
self.m_filePicker1.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOW ) )
sbSizer3.Add( self.m_filePicker1, 0, wx.ALL|wx.EXPAND, 5 )
m_modeSelect2Choices = [ u"ini to lab", u"lab to ini", u"ust to ini", u"svp to ini" ]
self.m_modeSelect2 = wx.RadioBox( sbSizer3.GetStaticBox(), wx.ID_ANY, u"機能選択", wx.DefaultPosition, wx.DefaultSize, m_modeSelect2Choices, 4, wx.RA_SPECIFY_ROWS )
self.m_modeSelect2.SetSelection( 0 )
sbSizer3.Add( self.m_modeSelect2, 0, wx.ALL|wx.EXPAND, 5 )
self.m_displayConsole2 = wx.CheckBox( sbSizer3.GetStaticBox(), wx.ID_ANY, u"コマンドライン出力を表示", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_displayConsole2.SetForegroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOWTEXT ) )
sbSizer3.Add( self.m_displayConsole2, 0, wx.ALL, 5 )
sbSizer3.Add( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_convertButton2 = wx.Button( sbSizer3.GetStaticBox(), wx.ID_ANY, u"変換する", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_convertButton2.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_3DLIGHT ) )
sbSizer3.Add( self.m_convertButton2, 0, wx.ALL, 5 )
self.m_gauge2 = wx.Gauge( sbSizer3.GetStaticBox(), wx.ID_ANY, 100, wx.DefaultPosition, wx.DefaultSize, wx.GA_HORIZONTAL )
self.m_gauge2.SetValue( 0 )
sbSizer3.Add( self.m_gauge2, 0, wx.ALL, 5 )
bSizer2.Add( sbSizer3, 1, wx.EXPAND|wx.ALL, 5 )
bSizer1.Add( bSizer2, 1, wx.EXPAND, 5 )
self.m_staticText8 = wx.StaticText( self, wx.ID_ANY, u"\n© 2020 oatsu\n© 1998-2005 <NAME>, <NAME> et al\n© 2001-2020 Python Software Foundation", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_staticText8.Wrap( -1 )
self.m_staticText8.SetForegroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_GRAYTEXT ) )
self.m_staticText8.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOW ) )
bSizer1.Add( self.m_staticText8, 0, wx.ALL|wx.ALIGN_RIGHT, 5 )
self.SetSizer( bSizer1 )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.m_dirPicker1.Bind( wx.EVT_DIRPICKER_CHANGED, self.m_dirPicker1OnDirChanged )
self.m_modeSelect1.Bind( wx.EVT_RADIOBOX, self.m_modeSelect1OnRadioBox )
self.m_displayConsole1.Bind( wx.EVT_CHECKBOX, self.m_displayConsole1OnCheckBox )
self.m_convertButton1.Bind( wx.EVT_BUTTON, self.m_convertButton1OnButtonClick )
self.m_filePicker1.Bind( wx.EVT_FILEPICKER_CHANGED, self.m_filePicker1OnFileChanged )
self.m_modeSelect2.Bind( wx.EVT_RADIOBOX, self.m_modeSelect2OnRadioBox )
self.m_displayConsole2.Bind( wx.EVT_CHECKBOX, self.m_displayConsole2OnCheckBox )
self.m_convertButton2.Bind( wx.EVT_BUTTON, self.m_convertButton2OnButtonClick )
def __del__( self ):
pass
# Virtual event handlers, overide them in your derived class
def m_dirPicker1OnDirChanged( self, event ):
event.Skip()
def m_modeSelect1OnRadioBox( self, event ):
event.Skip()
def m_displayConsole1OnCheckBox( self, event ):
event.Skip()
def m_convertButton1OnButtonClick( self, event ):
event.Skip()
def m_filePicker1OnFileChanged( self, event ):
event.Skip()
def m_modeSelect2OnRadioBox( self, event ):
event.Skip()
def m_displayConsole2OnCheckBox( self, event ):
event.Skip()
def m_convertButton2OnButtonClick( self, event ):
event.Skip()
| 61dfc531fc5ee178587364bd073431917faeb029 | [
"Markdown",
"Python",
"Text",
"Shell"
] | 37 | Shell | TheNormieWeeb/oto2lab | 1afb3bdcf114365c39b5811b39b42f1d31b2a8e4 | 518cb1bddf2e913810204560d6eff074cb0033d6 |
refs/heads/master | <repo_name>tjf/hdmi-matrix-controller<file_sep>/hdmi_matrix_controller_test.py
"""Unit tests for HdmiMatrixController."""
# pylint: disable=missing-docstring,invalid-name,too-many-public-methods,protected-access
import logging
import unittest
import serial
import hdmi_matrix_controller
VALID_PORT = 1
INVALID_PORT = 0
VALID_EDID = hdmi_matrix_controller.EDID_1080I_20
INVALID_EDID = 0
logging.disable(logging.CRITICAL)
class FakeSerialDevice(object):
def __init__(self):
self.last_write = ''
self.response = ''
self._enable_write_exception = False
self._enable_read_exception = False
def set_response(self, response):
self.response = response
def enable_write_exception(self):
self._enable_write_exception = True
def enable_read_exception(self):
self._enable_read_exception = True
def write(self, data):
if self._enable_write_exception:
raise serial.SerialException()
self.last_write = data
def read(self, _):
if self._enable_read_exception:
raise serial.SerialException()
return self.response
class HdmiMatrixControllerTest(unittest.TestCase):
def setUp(self):
self.fake_serial_device = FakeSerialDevice()
self.controller = hdmi_matrix_controller.HdmiMatrixController(
self.fake_serial_device)
@staticmethod
def _cmd_code(cmd):
return [ord(x) for x in cmd[2:4]]
@staticmethod
def _data(cmd):
return [ord(x) for x in cmd[4:-1]]
def _validate_sent_cmd(self, cmd, cmd_code, arg1=None, arg2=None):
self.assertEqual(hdmi_matrix_controller._CMD_LENGTH, len(cmd))
self.assertEqual(cmd_code, self._cmd_code(cmd))
if arg1 is not None:
self.assertEqual(arg1, self._data(cmd)[0])
if arg2 is not None:
self.assertEqual(arg2, self._data(cmd)[2])
def test_change_port_success(self):
self.controller.change_port(VALID_PORT, VALID_PORT)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_CHANGE_PORT,
VALID_PORT, VALID_PORT)
def test_change_port_invalid_input_port(self):
with self.assertRaises(ValueError):
self.controller.change_port(INVALID_PORT, VALID_PORT)
def test_change_port_invalid_output_port(self):
with self.assertRaises(ValueError):
self.controller.change_port(VALID_PORT, INVALID_PORT)
def test_query_port_success(self):
expected_port = 1
fake_response = hdmi_matrix_controller.HdmiMatrixController._generate_cmd(
hdmi_matrix_controller._CMD_QUERY_PORT, VALID_PORT, expected_port)
self.fake_serial_device.set_response(fake_response)
result = self.controller.query_port(VALID_PORT)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_QUERY_PORT,
VALID_PORT)
self.assertEqual(expected_port, result)
def test_query_port_invalid_port(self):
with self.assertRaises(ValueError):
self.controller.query_port(INVALID_PORT)
def test_set_edid_success(self):
self.controller.set_edid(VALID_PORT, VALID_EDID)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_SET_EDID,
VALID_PORT, VALID_PORT)
def test_set_edid_invalid_port(self):
with self.assertRaises(ValueError):
self.controller.set_edid(INVALID_PORT, VALID_EDID)
def test_set_edid_invalid_value(self):
with self.assertRaises(ValueError):
self.controller.set_edid(VALID_PORT, INVALID_EDID)
def test_set_edid_to_all_success(self):
self.controller.set_edid_to_all(VALID_EDID)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_SET_EDID_TO_ALL,
VALID_PORT)
def test_set_edid_to_all_invalid_value(self):
with self.assertRaises(ValueError):
self.controller.set_edid_to_all(INVALID_EDID)
def test_copy_edid_success(self):
self.controller.copy_edid(VALID_PORT, VALID_PORT)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_COPY_EDID,
VALID_PORT, VALID_PORT)
def test_copy_edid_invalid_output_port(self):
with self.assertRaises(ValueError):
self.controller.copy_edid(INVALID_PORT, VALID_PORT)
def test_copy_edid_invalid_input_port(self):
with self.assertRaises(ValueError):
self.controller.copy_edid(VALID_PORT, INVALID_PORT)
def test_copy_edid_to_all_success(self):
self.controller.copy_edid_to_all(VALID_PORT)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_COPY_EDID_TO_ALL,
VALID_PORT)
def test_copy_edid_to_all_invalid_port(self):
with self.assertRaises(ValueError):
self.controller.copy_edid_to_all(INVALID_PORT)
def test_query_hdp_success(self):
fake_response = hdmi_matrix_controller.HdmiMatrixController._generate_cmd(
hdmi_matrix_controller._CMD_QUERY_HDP, VALID_PORT, 0)
self.fake_serial_device.set_response(fake_response)
result = self.controller.query_hdp(VALID_PORT)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_QUERY_HDP,
VALID_PORT)
self.assertTrue(result)
fake_response = hdmi_matrix_controller.HdmiMatrixController._generate_cmd(
hdmi_matrix_controller._CMD_QUERY_HDP, VALID_PORT, 0xff)
self.fake_serial_device.set_response(fake_response)
result = self.controller.query_hdp(VALID_PORT)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_QUERY_HDP,
VALID_PORT)
self.assertFalse(result)
def test_query_hdp_invalid_port(self):
with self.assertRaises(ValueError):
self.controller.query_hdp(INVALID_PORT)
def test_query_status_success(self):
fake_response = hdmi_matrix_controller.HdmiMatrixController._generate_cmd(
hdmi_matrix_controller._CMD_QUERY_STATUS, VALID_PORT, 0)
self.fake_serial_device.set_response(fake_response)
result = self.controller.query_status(VALID_PORT)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_QUERY_STATUS,
VALID_PORT)
self.assertFalse(result)
fake_response = hdmi_matrix_controller.HdmiMatrixController._generate_cmd(
hdmi_matrix_controller._CMD_QUERY_STATUS, VALID_PORT, 0xff)
self.fake_serial_device.set_response(fake_response)
result = self.controller.query_status(VALID_PORT)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_QUERY_STATUS,
VALID_PORT)
self.assertTrue(result)
def test_query_status_invalid_port(self):
with self.assertRaises(ValueError):
self.controller.query_status(INVALID_PORT)
def test_set_beep_success(self):
self.controller.set_beep(True)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_SET_BEEP,
hdmi_matrix_controller._BEEP_ON)
self.controller.set_beep(False)
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_SET_BEEP,
hdmi_matrix_controller._BEEP_OFF)
def test_query_beep_success(self):
fake_response = hdmi_matrix_controller.HdmiMatrixController._generate_cmd(
hdmi_matrix_controller._CMD_QUERY_BEEP, 0, 0)
self.fake_serial_device.set_response(fake_response)
result = self.controller.query_beep()
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_QUERY_BEEP)
self.assertTrue(result)
fake_response = hdmi_matrix_controller.HdmiMatrixController._generate_cmd(
hdmi_matrix_controller._CMD_QUERY_BEEP, 0, 0xff)
self.fake_serial_device.set_response(fake_response)
result = self.controller.query_beep()
cmd = self.fake_serial_device.last_write
self._validate_sent_cmd(cmd, hdmi_matrix_controller._CMD_QUERY_BEEP)
self.assertFalse(result)
def test_send_cmd_error(self):
self.fake_serial_device.enable_write_exception()
with self.assertRaises(hdmi_matrix_controller.HdmiMatrixControllerException):
self.controller.query_beep()
def test_receive_response_error(self):
self.fake_serial_device.enable_read_exception()
with self.assertRaises(hdmi_matrix_controller.HdmiMatrixControllerException):
self.controller.query_beep()
def test_receive_response_wrong_length(self):
fake_response = hdmi_matrix_controller.HdmiMatrixController._generate_cmd(
hdmi_matrix_controller._CMD_QUERY_BEEP + [0], 0, 0)
self.fake_serial_device.set_response(fake_response)
with self.assertRaises(hdmi_matrix_controller.HdmiMatrixControllerException):
self.controller.query_beep()
def test_receive_response_wrong_checksum(self):
fake_response = hdmi_matrix_controller.HdmiMatrixController._generate_cmd(
hdmi_matrix_controller._CMD_QUERY_BEEP, 0, 0)
# Modify checksum
fake_response = fake_response[:-1] + '\x00'
self.fake_serial_device.set_response(fake_response)
with self.assertRaises(hdmi_matrix_controller.HdmiMatrixControllerException):
self.controller.query_beep()
if __name__ == '__main__':
unittest.main()
<file_sep>/README.md
[](https://travis-ci.org/seanwatson/hdmi-matrix-controller)
[](https://coveralls.io/github/seanwatson/hdmi-matrix-controller?branch=master)
Python implementation of the Monoprice Blackbird HDMI Matrix Controller serial protocol.
[Protocol spec](https://www.lindy.co.uk/downloads/1459947591Command_codes_for_LINDY_38152.pdf)
Example usage:
import serial
import hdmi_matrix_controller
BAUD_RATE = 19200
TIMEOUT = 1
serial_dev = serial.Serial('/dev/ttyUSB0', BAUD_RATE, TIMEOUT)
controller = hdmi_matrix_controller.HdmiMatrixController(serial_dev)
controller.set_beep(false)
controller.change_port(1, 2)
<file_sep>/setup.py
from setuptools import setup
setup(
name='HDMI Matrix Controller',
version='0.1',
description='Control an HDMI matrix.',
author='<NAME>',
license='MIT',
py_modules=['hdmi_matrix_controller'],
install_requires=[
'pyserial',
],
zip_safe=False
)
<file_sep>/hdmi_matrix_controller.py
"""Library for controlling an HMDI matrix device over RS232"""
import logging
import serial
# Command constants.
_CMD_HEADER = [0xa5, 0x5b]
_CMD_CODE_LENGTH = 2
_CMD_DATA_LENGTH = 8
_CMD_LENGTH = len(_CMD_HEADER) + _CMD_CODE_LENGTH + _CMD_DATA_LENGTH + 1
_MIN_PORT_NUMBER = 1
_MAX_PORT_NUMBER = 4
# Command codes.
_CMD_CHANGE_PORT = [0x02, 0x03]
_CMD_QUERY_PORT = [0x02, 0x01]
_CMD_SET_EDID = [0x03, 0x02]
_CMD_SET_EDID_TO_ALL = [0x03, 0x01]
_CMD_COPY_EDID = [0x03, 0x04]
_CMD_COPY_EDID_TO_ALL = [0x03, 0x03]
_CMD_QUERY_HDP = [0x01, 0x05]
_CMD_QUERY_STATUS = [0x01, 0x04]
_CMD_SET_BEEP = [0x06, 0x01]
_CMD_QUERY_BEEP = [0x01, 0x0b]
# Values used for representing beep state.
_BEEP_ON = 0x0f
_BEEP_OFF = 0xf0
# Used in calculating checksums.
_CHECKSUM_BASE = 0x100
# EDID values.
EDID_1080I_20 = 1
EDID_1080I_51 = 2
EDID_1080I_71 = 3
EDID_1080P_20 = 4
EDID_1080P_51 = 5
EDID_1080P_71 = 6
EDID_3D_20 = 7
EDID_3D_51 = 8
EDID_3D_71 = 9
EDID_4K2K_20 = 10
EDID_4K2K_51 = 11
EDID_4K2K_71 = 12
EDID_DVI_1024_768 = 13
EDID_DVI_1920_1080 = 14
EDID_DVI_1920_1200 = 15
_MIN_EDID = EDID_1080I_20
_MAX_EDID = EDID_DVI_1920_1200
class HdmiMatrixControllerException(Exception):
"""Exception type thrown for errors receiving data."""
pass
class HdmiMatrixController(object):
"""Controls an HDMI matrix device over RS232."""
def __init__(self, serial_device):
"""Initializer.
Args:
serial_device (obj: serial.Serial): An open serial device.
"""
self._ser = serial_device
@staticmethod
def _generate_cmd(cmd_code, arg1=0, arg2=0):
"""Builds a command out of all the pieces of a command.
Args:
cmd_code (array): The 2 byte command code.
arg1 (int): First argument to the command if used.
arg2 (int): Second argument to the command if used.
Returns:
str: A complete command ready to be sent over serial.
"""
data = [0] * _CMD_DATA_LENGTH
data[0] = arg1
data[2] = arg2
cmd = _CMD_HEADER + cmd_code + data
HdmiMatrixController._append_checksum(cmd)
return ''.join(chr(c) for c in cmd)
@staticmethod
def _append_checksum(cmd):
"""Calculates the checksum and appends it to the command.
Args:
cmd (array): A command buffer without a checksum.
"""
checksum = _CHECKSUM_BASE - sum(cmd)
if checksum < 0:
while checksum < 0:
checksum += 0xff
checksum += 1
cmd.append(checksum)
@staticmethod
def _checksum_valid(response_data):
"""Checks whether the checksum is valid on a response buffer.
Args:
response_buffer (str): A complete response received from the device.
Returns:
bool: True if the checksum is valid, False otherwise.
"""
checksum = _CHECKSUM_BASE - sum(ord(x) for x in response_data[:-1])
if checksum < 0:
while checksum < 0:
checksum += 0xff
checksum += 1
return ord(response_data[-1]) == checksum
@staticmethod
def _check_port(port_number):
"""Checks if a port number is valid.
Args:
port_number (int): The port number to check.
Raises:
ValueError: Port number invalid.
"""
if port_number < _MIN_PORT_NUMBER or port_number > _MAX_PORT_NUMBER:
logging.error('Invalid port number: %d.', port_number)
raise ValueError('Invalid port number.')
@staticmethod
def _check_edid_value(value):
"""Checks if an EDID value is valid.
Args:
value (int): The EDID value to check.
Raises:
ValueError: EDID value invalid.
"""
if value < _MIN_EDID or value > _MAX_EDID:
logging.error('Invalid EDID value: %d.', value)
raise ValueError('Invalid EDID value.')
def change_port(self, input_port, output_port):
"""Changes the input on a given output port.
Args:
input_port (int): The input port number to change to.
output_port (int): The output port number to change.
Raises:
HdmiMatrixControllerException: Error writing to serial.
ValueError: Port number invalid.
"""
self._check_port(input_port)
self._check_port(output_port)
logging.debug('Changing port %d input to %d.', output_port, input_port)
cmd = self._generate_cmd(_CMD_CHANGE_PORT, input_port, output_port)
self._send_cmd(cmd)
def query_port(self, output_port):
"""Queries for the input port being used by a given output port.
Args:
output_port (int): The output port to query.
Returns:
int: The input port number being used.
Raises:
HdmiMatrixControllerException: Serial device error.
ValueError: Port number invalid.
"""
self._check_port(output_port)
logging.debug('Querying input port for %d.', output_port)
cmd = self._generate_cmd(_CMD_QUERY_PORT, output_port)
self._send_cmd(cmd)
response = self._receive_response()
logging.debug('Input port for %d is port %d.', output_port, ord(response[2]))
return ord(response[2])
def set_edid(self, input_port, value):
"""Sets the EDID value for a given input port.
Args:
input_port (int): The input port number to change.
value (int): The EDID value to use on the port.
Raises:
HdmiMatrixControllerException: Error writing to serial.
ValueError: Port number or value invalid.
"""
self._check_port(input_port)
self._check_edid_value(value)
logging.debug('Setting EDID value to %d for port %d.', value, input_port)
cmd = self._generate_cmd(_CMD_SET_EDID, value, input_port)
self._send_cmd(cmd)
def set_edid_to_all(self, value):
"""Sets the EDID for all input ports.
Args:
value (int): The EDID value to use on the ports.
Raises:
HdmiMatrixControllerException: Error writing to serial.
ValueError: EDID value is invalid.
"""
self._check_edid_value(value)
logging.debug('Setting EDID value to %d for all ports.', value)
cmd = self._generate_cmd(_CMD_SET_EDID_TO_ALL, value)
self._send_cmd(cmd)
def copy_edid(self, output_port, input_port):
"""Copies the EDID value from an output port to an input port.
Args:
output_port (int): The output port number to copy from.
input_port (int): The input port number to copy to.
Raises:
HdmiMatrixControllerException: Error writing to serial.
ValueError: Port number invalid.
"""
self._check_port(output_port)
self._check_port(input_port)
logging.debug('Copying EDID from output port %d to input port %d.',
output_port, input_port)
cmd = self._generate_cmd(_CMD_COPY_EDID, output_port, input_port)
self._send_cmd(cmd)
def copy_edid_to_all(self, output_port):
"""Copies the EDID value from an output port to all input ports.
Args:
output_port (int): The output port number to copy from.
Raises:
HdmiMatrixControllerException: Error writing to serial.
ValueError: Port number invalid.
"""
self._check_port(output_port)
logging.debug('Copying EDID from output port %d to all input ports.',
output_port)
cmd = self._generate_cmd(_CMD_COPY_EDID_TO_ALL, output_port)
self._send_cmd(cmd)
def query_hdp(self, output_port):
"""Queries for the HDP state of an output port.
Args:
output_port (int): The output port to query.
Returns:
bool: True if the HPD is high, False if HPD is low.
Raises:
HdmiMatrixControllerException: Serial device error.
ValueError: Port number invalid.
"""
self._check_port(output_port)
logging.debug('Querying HDP for port %d.', output_port)
cmd = self._generate_cmd(_CMD_QUERY_HDP, output_port)
self._send_cmd(cmd)
response = self._receive_response()
logging.debug('HDP for port %d: %s.',
output_port,
'HIGH' if ord(response[2]) == 0 else 'LOW')
return ord(response[2]) == 0
def query_status(self, input_port):
"""Queries if an input port is connected.
Args:
input_port (int): The input port to query.
Returns:
bool: True if the input is connected, False otherwise.
Raises:
HdmiMatrixControllerException: Serial device error.
ValueError: Port number invalid.
"""
self._check_port(input_port)
logging.debug('Querying cable status for port %d.', input_port)
cmd = self._generate_cmd(_CMD_QUERY_STATUS, input_port)
self._send_cmd(cmd)
response = self._receive_response()
logging.debug('Cable status for port %d: %s.',
input_port,
'connected' if ord(response[2]) != 0 else 'not connected')
return ord(response[2]) != 0
def set_beep(self, enable):
"""Enables or disables beeping.
Args:
enable (bool): Set to True to enable beep, False to disable.
Raises:
HdmiMatrixControllerException: Error writing to serial.
"""
logging.debug('Turning beep %s.', 'on' if enable else 'off')
beep_value = _BEEP_ON if enable else _BEEP_OFF
cmd = self._generate_cmd(_CMD_SET_BEEP, beep_value)
self._send_cmd(cmd)
def query_beep(self):
"""Queries for whether the beep is enabled.
Returns:
bool: True if the beep is enabled, False otherwise.
Raises:
HdmiMatrixControllerException: Serial device error.
"""
logging.debug('Querying beep status.')
cmd = self._generate_cmd(_CMD_QUERY_BEEP)
self._send_cmd(cmd)
response = self._receive_response()
logging.debug('Beep is %s.', 'enabled' if ord(response[2]) == 0 else 'disabled')
return ord(response[2]) == 0
def _send_cmd(self, cmd):
"""Sends a complete command over serial.
Args:
cmd (str): Command to send.
Raises:
HdmiMatrixControllerException: Error writing to serial.
"""
try:
logging.debug('Sending cmd: %s.',
' '.join(c.encode('hex') for c in cmd))
self._ser.write(cmd)
except (serial.SerialException, serial.SerialTimeoutException) as exception:
logging.error('Error writing to serial: %s', str(exception))
raise HdmiMatrixControllerException(exception, 'Error writing to serial.')
def _receive_response(self):
"""Reads and validates a response.
Returns:
str: The data section of a response as a string.
Raises:
HdmiMatrixControllerException: Error reading response.
"""
try:
logging.debug('Attempting to read from serial.')
response = self._ser.read(_CMD_LENGTH)
except (serial.SerialException, serial.SerialTimeoutException) as exception:
logging.error('Error reading from serial: %s', str(exception))
raise HdmiMatrixControllerException(exception, 'Error reading from serial')
else:
if len(response) != _CMD_LENGTH or not self._checksum_valid(response):
logging.error('Response was invalid: %s.',
' '.join(c.encode('hex') for c in response))
raise HdmiMatrixControllerException('Did not receive valid response')
logging.debug('Received response: %s.',
' '.join(c.encode('hex') for c in response))
return response[len(_CMD_HEADER) + _CMD_CODE_LENGTH:-1]
| ed4c65202012e1c593f5faa97b7bd090e4f6b6b4 | [
"Markdown",
"Python"
] | 4 | Python | tjf/hdmi-matrix-controller | adaf10780f7a8a22129cdf4ce18559ab04826ef1 | 125dd6212b7d6d576f96cedc2db3580ae9070ecf |
refs/heads/master | <file_sep>//
// MemeTableViewCell.swift
// MemeMe
//
// Created by <NAME> on 4/20/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class MemeTableViewCell: UITableViewCell {
@IBOutlet weak var memeImageView: UIImageView!
@IBOutlet weak var memeLabel: UILabel!
}
<file_sep>//
// MemeCollectionViewController.swift
// MemeMe
//
// Created by <NAME> on 4/20/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
private let reuseIdentifier = "cell"
class MemeCollectionViewController: UICollectionViewController {
var memes: [Meme] {
return (UIApplication.sharedApplication().delegate as! AppDelegate).memes
}
@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
collectionView?.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return memes.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MemeCollectionViewCell
cell.memeImage.image = memes[indexPath.item].memedImage
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("memeDetailSegue", sender: memes[indexPath.item].memedImage)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "memeDetailSegue") {
let memeDetailVC = segue.destinationViewController as! MemeDetailViewController
let meme = sender as! UIImage
memeDetailVC.meme = meme
}
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
}
<file_sep>//
// MemeCollectionViewCell.swift
// MemeMe
//
// Created by <NAME> on 4/20/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class MemeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var memeImage: UIImageView!
}
<file_sep>//
// ViewController.swift
// MemeMe
//
// Created by <NAME> on 4/19/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var cameraButton: UIBarButtonItem!
@IBOutlet weak var albumButton: UIBarButtonItem!
@IBOutlet weak var topTextField: UITextField!
@IBOutlet weak var bottomTextField: UITextField!
@IBOutlet weak var shareButton: UIBarButtonItem!
@IBOutlet weak var topToolbar: UIToolbar!
@IBOutlet weak var bottomToolbar: UIToolbar!
let memeTextAttributes = [
NSStrokeColorAttributeName: UIColor.blackColor(),
NSForegroundColorAttributeName: UIColor.whiteColor(),
NSFontAttributeName: UIFont(name: "Impact", size: 32)!,
NSStrokeWidthAttributeName: -5.0
]
override func viewDidLoad() {
super.viewDidLoad()
shareButton.enabled = false
topTextField.defaultTextAttributes = memeTextAttributes
bottomTextField.defaultTextAttributes = memeTextAttributes
topTextField.textAlignment = NSTextAlignment.Center
bottomTextField.textAlignment = NSTextAlignment.Center
}
override func viewWillAppear(animated: Bool) {
cameraButton.enabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeToKeyboardNotifications()
}
@IBAction func pickAnImage(sender: UIBarButtonItem) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
if sender == cameraButton {
presentImagePicker(imagePicker, sourceType: .Camera)
} else {
presentImagePicker(imagePicker, sourceType: .PhotoLibrary)
}
presentViewController(imagePicker, animated: true, completion: nil)
}
func presentImagePicker(imagePicker: UIImagePickerController, sourceType: UIImagePickerControllerSourceType) {
imagePicker.sourceType = sourceType
}
@IBAction func share(sender: AnyObject) {
let activityViewController = UIActivityViewController(activityItems: [generateMemedImage()], applicationActivities: nil)
presentViewController(activityViewController, animated: true) {
self.save()
}
}
@IBAction func cancel(sender: AnyObject) {
imageView.image = nil
topTextField.text = "TOP"
bottomTextField.text = "BOTTOM"
shareButton.enabled = false
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func textFieldDidBeginEditing(sender: UITextField) {
sender.text = ""
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.image = image
dismissViewControllerAnimated(true, completion: nil)
shareButton.enabled = true
}
}
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
func unsubscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
self.view.frame.origin.y -= getKeyboardHeight(notification)
}
func keyboardWillHide(notification: NSNotification) {
self.view.frame.origin.y = 0
}
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo!
let keyboardSize = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue
if bottomTextField.editing {
return keyboardSize.CGRectValue().height
} else {
return 0
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func save() {
let meme = Meme(topText: topTextField.text!, bottomText: bottomTextField.text!, originalImage: imageView.image!, memedImage: generateMemedImage())
let object = UIApplication.sharedApplication().delegate
let appDelegate = object as! AppDelegate
appDelegate.memes.append(meme)
}
func generateMemedImage() -> UIImage {
topToolbar.hidden = true
bottomToolbar.hidden = true
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.drawViewHierarchyInRect(self.view.frame, afterScreenUpdates: true)
let memedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
topToolbar.hidden = false
bottomToolbar.hidden = false
return memedImage
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
struct Meme {
let topText: String
let bottomText: String
let originalImage: UIImage
let memedImage: UIImage
init(topText: String, bottomText: String, originalImage:UIImage, memedImage:UIImage) {
self.topText = topText
self.bottomText = bottomText
self.originalImage = originalImage
self.memedImage = memedImage
}
}
| cc01b4f01bd92ca360445738fe3231e936fcace8 | [
"Swift"
] | 4 | Swift | williamkurniawan/udacity-meme | de8da2307545d12731b3d9605439c20c1d5a92bc | 6a548853bddf875db984adf5fa4cd4a65a57c8f6 |
refs/heads/master | <repo_name>martin-c91/laratwit<file_sep>/app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Auth;
class UserController extends Controller
{
public function followers(User $user)
{
return $user->followers;
}
public function followings(User $user)
{
return $user->followings;
}
public function followUser(User $user)
{
return Auth::user()->follow($user);
}
public function unFollowUser(User $user)
{
return Auth::user()->unFollow($user);
}
public function getNotFollowingUsers(User $user = null, $limit = 20)
{
if (! $user) {
$user = Auth::user();
}
$followingsIds = $user->followings()->pluck('id');
if(request()->input(['exceptUsers'])) $followingsIds = $followingsIds->concat(request()->input(['exceptUsers']));
return User::whereNotIn('id', $followingsIds)->inRandomOrder()->limit($limit)->get();
}
}
<file_sep>/app/Http/Controllers/TweetController.php
<?php
namespace App\Http\Controllers;
use App\Tweet;
use App\User;
use Auth;
use App\Http\Resources\Tweet as TweetResource;
use Illuminate\Http\Request;
use Validator;
class TweetController extends Controller
{
public function index(User $user = null)
{
if (! $user) {
$user = Auth::user();
$tweetsUrl = route('api.timeline');
} else {
$tweetsUrl = route('api.user.tweets', $user->slug);
}
$user = $user->append('isFollowing');
$currentUser = Auth::user();
return view('home', compact('user','tweetsUrl', 'currentUser'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validated = $request->validate([
'content' => 'required|max:250',
]);
$tweet = Auth::user()->tweets()->create($validated);
if ($tweet->wasRecentlyCreated) {
return response()->json($tweet->load('user'));
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//get single tweet by id
$tweet = Tweet::with('user')->find($id);
return $tweet;
}
public function destroy($id)
{
$tweet = Auth::user()->tweets()->findOrFail($id);
$tweet->delete();
}
public static function getTimelineTweets()
{
$tweets = Auth::user()->getTimeline();
if (request()->wantsJson()) {
return response()->json($tweets);
}
return $tweets;
}
public static function getUserTweets(User $user)
{
//$tweets = Tweet::remember(60)->with('user')->where('user_id', $user->id)->latest()->paginate();
$tweets = Tweet::with('user')
->with('likedByAuth')
->where('user_id', $user->id)
->latest()->paginate()
;
if (request()->wantsJson()) {
return response()->json($tweets);
}
return $tweets;
}
}
<file_sep>/database/seeds/TweetsSeeder.php
<?php
use Illuminate\Database\Seeder;
class TweetsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
protected $twitter_user_name;
public function __construct($twitter_user_name)
{
$this->twitter_user_name = $twitter_user_name;
}
public function run()
{
}
}
<file_sep>/app/Http/Controllers/AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Hash;
use Auth;
class AuthController extends Controller
{
private $client;
public function __construct()
{
$this->client = \Laravel\Passport\Client::where('password_client', 1)->first();
}
function register(Request $request)
{
/**
* Get a validator for an incoming registration request.
*
* @param array $request
* @return \Illuminate\Contracts\Validation\Validator
*/
$valid = validator($request->json()->all(), [
'name' => 'required|string|max:20',
'slug' => 'required|string|max:50|unique:users',
'email' => 'required|string|email|max:255|unique:users',
'description' => 'text|max:255',
'password' => '<PASSWORD>',
]);
if ($valid->fails()) {
$jsonError=response()->json($valid->errors()->all(), 400);
return \Response::json($jsonError);
}
$data = request()->json()->all();
User::create([
'name' => $data['name'],
'slug' => $data['slug'],
'description' => $data['description'],
'email' => $data['email'],
'password' => <PASSWORD>($data['<PASSWORD>']),
]);
$request->request->add([
'grant_type' => 'password',
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'username' => $data['slug'],
'password' => $data['<PASSWORD>'],
'scope' => null,
]);
$token = Request::create(
'oauth/token',
'POST'
);
return \Route::dispatch($token);
}
/**
* @param Request $request
* @return mixed
*/
protected function login(Request $request)
{
$request->request->add([
'grant_type' => 'password',
//passport take in username param thus:
'username' => $request->username,
'password' => $<PASSWORD>,
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'scope' => ''
]);
$proxy = Request::create(
'oauth/token',
'POST'
);
return \Route::dispatch($proxy);
}
/**
* @param Request $request
* @return mixed
*/
protected function refreshToken(Request $request)
{
$request->request->add([
'grant_type' => 'refresh_token',
'refresh_token' => $request->refresh_token,
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'scope' => ''
]);
$proxy = Request::create(
'oauth/token',
'POST'
);
return \Route::dispatch($proxy);
}
public function user(Request $request)
{
return $request->user('api')->append('isFollowing');
}
public function logout(Request $request)
{
$user = Auth::user()->token();
$user->revoke();
return response()->json(["message" => "successfully logged out"]);
}
}
<file_sep>/app/Http/Controllers/LikeController.php
<?php
namespace App\Http\Controllers;
use App\Like;
use App\Tweet;
use App\User;
use Illuminate\Http\Request;
use Auth;
class LikeController extends Controller
{
public function store($id)
{
$result = Auth::user()->likes()->syncWithoutDetaching($id);
if($result['attached']){
$tweet = Tweet::whereId($id)->increment('likes');
return $tweet;
}
}
public function destroy($id)
{
$result = Auth::user()->likes()->detach($id);
if($result){
$tweet = Tweet::whereId($id)->decrement('likes');
return $tweet;
}
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use App\User;
use App\Tweet;
Use App\Http\Controllers\UserController;
Route::get('/healthcheck', function(){
return response('System up', 200)
->header('Content-Type', 'text/plain');
});
Route::get('/', function () {
if (Auth::check()) {
return redirect('timeline');
}
return redirect('login');
});
//test function
Route::get('test/{userid}', function($userId){
$tweets = Tweet::with('user')
->with('likes')
// whereIn allows collections
->where('user_id', $userId)
->latest()
->get();
//$tweets = $tweets->append('liked_by_auth');
return $tweets;
});
Route::get('test1/{tweet_id}', 'LikeController@destroy');
Auth::routes();
Route::get('/timeline', 'TweetController@index')->name('timeline')->middleware('auth');
Route::get('/{user}', 'TweetController@index')->name('user.profile');
//get user followers, followings
Route::get('/{user}/followers', 'UserController@followers')->name('user.followers');
Route::get('/{user}/followings', 'UserController@followings')->name('user.followings');
<file_sep>/app/Http/Controllers/FollowingController.php
<?php
namespace App\Http\Controllers;
use App\Following;
use App\User;
use Illuminate\Http\Request;
use Auth;
class FollowingController extends Controller
{
public function store($id)
{
Auth::user()->followings()->syncWithoutDetaching($id);
return Auth::user()->followings;
}
public function destroy($id)
{
Auth::user()->followings()->detach($id);
return Auth::user()->followings;
}
}
<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
use App\User;
//
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user()->append('isFollowing');
});
Route::get('/test', function (Request $request) {
//return Auth::user()->followings;
return User::find(6)->append('isFollowing');
})->middleware('auth:api');
Route::middleware(['auth:api'])->group(function () {
//timeline actions
Route::get('/timeline', 'TweetController@getTimelineTweets')->name('api.timeline');
Route::post('/timeline/store', 'TweetController@store')->name('api.timeline.store');
Route::delete('/tweet/{id}', 'TweetController@destroy');
//following action
Route::post('/following/{id}', 'FollowingController@store')->name('api.user.follow');
Route::delete('/following/{id}', 'FollowingController@destroy')->name('api.user.unfollow');
//tweet likes action
Route::post('like/{id}', 'LikeController@store');
Route::delete('like/{id}', 'LikeController@destroy');
});
//following list actions
Route::get('/{user}', 'TweetController@getUserTweets')->name('api.user.tweets');
Route::get('/{user}/followings', 'UserController@followings')->name('api.user.followings');
Route::get('/{user}/followers', 'UserController@followers')->name('api.user.followers');
Route::post('{user}/getFeaturedUsers/{limit?}', 'UserController@getNotFollowingUsers');
Route::group(['prefix' => 'auth',], function () {
Route::post('login', 'AuthController@login');
Route::post('register', 'AuthController@register');
Route::group(['middleware' => 'auth:api'], function () {
Route::get('logout', 'AuthController@logout');
Route::get('user', 'AuthController@user');
});
});//test function
//Route::post('test/{user}/{limit?}', 'UserController@getNotFollowingUsers');
//Route::post('test/{user}', function(){
// return 'sdfds';
//});
<file_sep>/app/User.php
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Storage;
use Auth;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Support\Collection;
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
protected $table = 'users';
protected $avatar_folder = 'avatars';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'slug',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
'email',
'updated_at',
'created_at',
];
protected $appends = [
//'IsFollowedByAuth',
'avatar_url',
];
public function getRouteKeyName()
{
return 'slug';
}
public function findForPassport($slug) {
return $this->where('slug', $slug)->first();
}
public function tweets()
{
return $this->hasMany('App\Tweet');
}
public function followers()
{
return $this->belongsToMany('App\User', 'followers', 'user_id', 'follower_id');
}
public function followings()
{
return $this->belongsToMany('App\User', 'followers', 'follower_id', 'user_id');
}
public function likes()
{
return $this->belongsToMany('App\Tweet', 'likes', 'user_id', 'tweet_id')->withTimestamps();
}
/**
* Add follower to current user
*
* @param User $user
* @return Model
*/
public function follow(User $user)
{
$user->followers()->syncWithoutDetaching($this->id);
//event(new UserFollowedAnotherUser($user));
return $user;
}
public function unfollow(User $user)
{
$user->followers()->detach($this->id);
//event(new UserUnFollowedAnotherUser($user));
return $user;
}
/**
* @param User|int $user
* @return bool
*/
public function checkFollowing($user)
{
if ($user instanceof self) {
$user = $user->getKey(); // or $user->id, doesn't matter much.
}
return $this->followings()->where('user_id', $user)->exists();
}
/**
* @param mixed $users
* @return bool
*/
public function checkFollowingAny($users)
{
// we could deal with both collection types the same way tbh, I did it for the example
if ($users instanceof EloquentCollection) {
$users = $users->modelKeys();
}
if ($users instanceof Collection) {
$users = $users->pluck('id'); // or $users->map->id using Higher Order Messages
}
if (! is_array($users)) {
return $this->checkFollowing($users); // default to single value check
}
// whereIn allows collections
return $this->followings()->whereIn('user_id', $users)->exists();
}
public function getIsFollowingAttribute()
{
if(!Auth::user()) return false;
if (Auth::user()->checkFollowing($this->id)) {
return true;
};
return false;
}
/**
* Get the path to the user's avatar.
*
* @param string $slug
* @return string
*/
public function getAvatarAttribute()
{
$avatar_file_path = "{$this->avatar_folder}/$this->avatar_file_name";
return $avatar_file_path;
}
public function getAvatarUrlAttribute()
{
return Storage::url($this->avatar_folder.'/'.$this->avatar_file_name);
}
public function get_and_store_avatar($avatar_origin_url)
{
return Storage::put($this->avatar_folder.'/'.$this->avatar_file_name, file_get_contents($avatar_origin_url), 'public');
}
/**
* @param \App\User $user
* @return $tweets collection
*/
public function getTimeline()
{
// This will do a 'Select id' instead of an uneeded 'Select *'
// and return a collection of ids, instead of a collection of
// models then map it in php, when the following relation isn't loaded yet
$ids = $this->relationLoaded('following')?
$this->followings->pluck('id'):
$this->followings()->pluck('id');
return Tweet::with('user')
->with('likedByAuth')
// whereIn allows collections
->whereIn('user_id', $ids->push($this->id))
->latest()
->paginate();
}
}
<file_sep>/Dockerfile
FROM php:7.3-apache
MAINTAINER <NAME><<EMAIL>>
RUN a2enmod rewrite
RUN docker-php-ext-install pdo pdo_mysql
##todo: install xdebug
RUN apt-get update
RUN apt-get -y install gnupg2 zip unzip
#install composer and node
RUN curl -sS https://getcomposer.org/installer | php && mv composer.phar /usr/local/bin/composer && composer global require hirak/prestissimo --no-plugins --no-scripts
RUN curl -sL https://deb.nodesource.com/setup_11.x | bash - && apt-get install -y nodejs
#
COPY mysite.conf /etc/apache2/sites-enabled/000-default.conf
#COPY php.ini /usr/local/etc/php
# Install dependencies
WORKDIR /app
COPY composer.json composer.json
COPY composer.lock composer.lock
RUN composer install --prefer-dist --no-scripts --no-dev --no-autoloader && rm -rf /root/.composer
# Copy codebase
ADD --chown=www-data:www-data . .
RUN cp .env.example .env
# Finish composer
RUN composer dump-autoload --no-dev --optimize
RUN composer run-script --no-dev post-install-cmd
RUN npm install
RUN npm run production
#HEALTHCHECK CMD curl --fail http://localhost:80/healthcheck || exit 1
EXPOSE 80
<file_sep>/app/Http/Resources/V1/Tweet.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Tweet extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'user_slug' => $this->slug,
'user_full_name' => $this->name,
'created_at' => $this->created_at->toDateString(),
'tweets' => $this->tweet,
];
}
public function with($request){
return [
'version' => '1.0.0',
'author_url' => url('http://martinchea.com')
];
}
}
<file_sep>/tests/Feature/TweetTest.php
<?php
namespace Tests\Feature;
use App\Tweet;
use http\Env\Request;
use PassportTestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class TweetTest extends PassportTestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testUnauthorizedCannotPost()
{
$data = [
'content' => $this->faker->unique()->text(),
];
$response = $this->json('POST', 'api/timeline/store', $data);
$response->assertStatus(401);
$response->assertJson(['message' => "Unauthenticated."]);
}
public function testAuthorizedUserCanPost()
{
$fakeTweet = $this->faker->unique()->text();
$body = [
'content' => $fakeTweet,
];
$response = $this->postJson('api/timeline/store', $body);
//dd(json_decode($response->content())->content);
$response->assertStatus(200);
$this->assertEquals($fakeTweet, json_decode($response->content())->content);
}
public function test_user_can_like_other_post()
{
$tweet = $this->user2->tweets->first();
$response = $this->postJson('api/like/'.$tweet->id);
$response->assertStatus(200);
$tweet_likes = (int) $response->content();
$this->assertGreaterThan(0, $tweet_likes);
}
public function test_user_can_unlike_other_post()
{
$tweet = $this->user2->tweets->first();
$response = $this->deleteJson('api/like/'.$tweet->id);
$response->assertStatus(200);
}
}
<file_sep>/tests/Feature/FollowingTest.php
<?php
namespace Tests\Feature;
use Tests\TestCase;
class followingTest extends \PassportTestCase
{
public function test_user1_and_2_exist()
{
$this->assertInstanceOf('\App\User', $this->user1);
$this->assertInstanceOf('\App\User', $this->user2);
}
/** @test */
public function users_can_follow_each_other()
{
//$this->user1->follow($this->user2);
$response = $this->postJson('api/following/'.$this->user2->id);
$response->assertStatus(200);
$this->assertEquals($this->user2->id, ($this->user1->followings()->where('id', $this->user2->id)->first()->id));
}
/** @test */
public function users_can_un_follow_each_other()
{
//$this->user1->unFollow($this->user2);
$response = $this->deleteJson('api/following/'.$this->user2->id);
$response->assertStatus(200);
$result = $this->user1->followings()->where('id', $this->user2->id)->first();
$this->assertEmpty($result);
}
}
<file_sep>/app/Tweet.php
<?php
namespace App;
use Watson\Rememberable\Rememberable;
use Auth;
class Tweet extends Model
{
protected $fillable = [
'id',
'content',
'user_id',
'json_raw',
];
protected $hidden = [
'json_raw',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function likes()
{
return $this->HasMany('App\Like');
}
public function likedByAuth()
{
return $this->hasOne('App\Like')->where('user_id', auth()->guard('api')->id());
}
}
<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\User;
use App\Tweet;
use Illuminate\Support\Facades\Storage;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
protected $seed_users_origin = [
'katyperry',
'justinbieber',
'BarackObama',
'rihanna',
'taylorswift13',
'ladygaga',
'TheEllenShow',
'Cristiano',
'YouTube',
'jtimberlake',
'Twitter',
'KimKardashian',
'britneyspears',
'ArianaGrande',
'ddlovato',
'selenagomez',
'cnnbrk',
'realDonaldTrump',
'shakira',
'jimmyfallon',
'BillGates',
'JLo',
'BrunoMars',
'narendramodi',
'Oprah',
'nytimes',
'KingJames',
'MileyCyrus',
'CNN',
'NiallOfficial',
'neymarjr',
'instagram',
'BBCBreaking',
'Drake',
'SportsCenter',
'iamsrk',
'KevinHart4real',
'SrBachchan',
'LilTunechi',
'espn',
'wizkhalifa',
'Louis_Tomlinson',
'BeingSalmanKhan',
'Pink',
'LiamPayne',
'Harry_Styles',
'onedirection',
'aliciakeys',
'realmadrid',
'KAKA',
'NASA',
'FCBarcelona',
'ConanOBrien',
'EmmaWatson',
'chrisbrown',
'Adele',
'kanyewest',
'NBA',
'ActuallyNPH',
'zaynmalik',
'pitbull',
'danieltosh',
'akshaykumar',
'KendallJenner',
'PMOIndia',
'khloekardashian',
'sachin_rt',
'KylieJenner',
'imVkohli',
'coldplay',
'NFL',
'deepikapadukone',
'kourtneykardash',
'iHrithik',
'BBCWorld',
'aamir_khan',
'TheEconomist',
'andresiniesta8',
'POTUS',
'MesutOzil1088',
'Eminem',
'HillaryClinton',
'priyankachopra',
'NatGeo',
'AvrilLavigne',
'davidguetta',
'elonmusk',
'ChampionsLeague',
'NICKIMINAJ',
'MariahCarey',
'blakeshelton',
'ricky_martin',
'Google',
'edsheeran',
'arrahman',
'Reuters',
'AlejandroSanz',
'LeoDiCaprio',
'Dr_alqarnee',
'NikkiHaley'
];
protected function get_seed_user()
{
$last_user = User::latest()->first();
$seed_user_json = Twitter::getUsers(['screen_name' => $last_user->slug, 'format' => 'json']);
$seed_user = json_decode($seed_user_json);
return $seed_user;
}
public function run()
{
foreach ($this->seed_users_origin as $seed_user) {
if ($this->seed_user_info($seed_user)) {
$this->seed_user_tweets($seed_user, 30);
}
}
}
protected function seed_user_info($twitter_username)
{
$seed_user_json = Twitter::getUsers(['screen_name' => $twitter_username, 'format' => 'json']);
$seed_user = json_decode($seed_user_json);
$user = new User;
$avatar_origin_url = str_replace('_normal.jpg','_400x400.jpg', $seed_user->profile_image_url);
//if(!storage::exists('avatars/'.$seed_user->screen_name.'.jpg')){
// Storage::put("avatars/$seed_user->screen_name.jpg", file_get_contents($avatar_origin_url));
// echo "$seed_user->screen_name avatar not in storage, put new one in. \n";
//}
$data = [
'name' => $seed_user->name,
'slug' => $seed_user->screen_name,
'email' => $faker = Faker\Factory::create()->email,
'description' => $seed_user->description,
//'json_raw' => $seed_user_json,
'avatar_file_name' => $seed_user->screen_name.".jpg",
//'avatar_origin_url' => str_replace('_normal.jpg','_400x400.jpg', $seed_user->profile_image_url),
'password' => <PASSWORD>'),
];
$new_user = $user->updateOrCreate(['slug' => $twitter_username], $data);
if ($new_user AND $new_user->get_and_store_avatar($avatar_origin_url)) {
return $new_user->slug. "\n";
}
}
protected function seed_user_tweets($twitter_username, $tweets_count = 10)
{
$user = User::where('slug', $twitter_username)->firstOrFail();
$tweets = Twitter::getUserTimeline([
'screen_name' => $user->slug,
'count' => $tweets_count,
//'include_rts' => 0,
'format' => 'json',
]);
$tweets = json_decode($tweets);
foreach ($tweets as $tweet) {
$data = [
//'id' => $tweet->id,
//'json_raw' => json_encode($tweet),
'content' => $tweet->text,
//'user_id' => $user->id,
'created_at' => strtotime($tweet->created_at),
'updated_at' => strtotime($tweet->created_at),
];
$user->tweets()->create($data);
}
}
}
<file_sep>/database/seeds/UserSeeder.php
<?php
use Illuminate\Database\Seeder;
Use App\User;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
protected $twitter_user_name;
public function __construct($twitter_user_name)
{
$this->twitter_user_name = $twitter_user_name;
}
public function run()
{
$seed_user = Twitter::getUsers(['screen_name' => $this->twitter_user_name, 'format' => 'json']);
$seed_user = json_decode($seed_user);
$new_user = User::create([
'name' => $seed_user->name,
'slug' => $seed_user->screen_name,
'description' => $seed_user->description,
'avatar' => $seed_user->profile_image_url,
'password' => <PASSWORD>('<PASSWORD>')
])->get();
if(isset($new_user)) return $new_user;
}
}
<file_sep>/readme.md
This is a clone of Twiter.
todo:
finish readme.
For full working demo:
http://laratwit.martinchea.com
Username: chrisbrown
Pass: <PASSWORD>
Author: <NAME>
<file_sep>/tests/Feature/UserTest.php
<?php
namespace Tests\Feature;
class UserTest extends \PassportTestCase
{
public function testDatabase()
{
$this->assertInstanceOf(\App\User::class, $this->user1);
$this->assertDatabaseHas('users', [
'slug' => $this->user1->slug,
]);
}
public function testApiLogin()
{
$body = [
'username' => $this->user2->slug,
'password' => '<PASSWORD>',
];
$response = $this->json('POST', '/api/auth/login', $body, ['Accept' => 'application/json']);
//$test = \DB::table('oaUTH_PERSONAL_ACCESS_CLIENTS')->GET();
//DD($TEST);
//dd($response->content());
$response->assertStatus(200)->assertJsonStructure([
'token_type',
'expires_in',
'access_token',
'refresh_token',
]);
}
public function testApiLogout()
{
$response = $this->getJson('api/auth/logout');
$response->assertStatus(200);
$response->assertJson(
["message"=>"successfully logged out"]
);
}
}
<file_sep>/tests/TestCase.php
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\User as User;
use Illuminate\Foundation\Testing\WithFaker;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
use RefreshDatabase;
use WithFaker;
public $user1;
public $user2;
protected $baseUrl = 'http://whatever';
protected function setUp()
{
parent::setUp(); // this is important!
//\Artisan::call('migrate');
\Artisan::call('passport:install');
//Artisan::call('db:seed');
$users = factory(\App\User::class, 3)
->create()
->each(function (\App\User $user) {
$user->tweets()->save(factory(\App\Tweet::class)->make());
$user->tweets()->save(factory(\App\Tweet::class)->make());
$user->tweets()->save(factory(\App\Tweet::class)->make());
});
$this->user1 = $users[0];
$this->user2 = $users[1];
$this->user1->follow($users[2]);
//dd($this->user1);
////$this->user1 = \App\User::where('slug', 'justinbieber')->first();
//$this->user2 = \App\User::where('slug', 'katyperry')->first();
//dd($this->user2);
//$this->actingAs($this->user1);
}
public function tearDown()
{
unset($this->user1);
unset($this->user2);
}
}
| d25a94a504a9e4b503ddd9c99913f8cd9d894cad | [
"Markdown",
"Dockerfile",
"PHP"
] | 19 | PHP | martin-c91/laratwit | 07832b8084c08b82f6fd6c5b7e25b58d68c27844 | d623acedcbcdfac3f1a82aad1e3789aacaa51765 |
refs/heads/main | <file_sep>/*
An Insurance company follows following rules to calculate premium.
a.) IF a person’s health is excellent and the person is between 25 and 35 years of age and lives IN a city and is a male THEN the premium is Rs. 4 per thousand and his
policy amount can’t exceed Rs. 2 lakhs.
b.) IF a person satisfies all the above conditions except that the gender is female THEN the premium is Rs. 3 per thousand and her policy amount can’t exceed Rs. 1 lakh.
c.) IF a person’s health is poor and the person is between 25 and 35 years of age and lives IN a village and is a male THEN the premium is Rs. 6 per thousand and his
policy can’t exceed Rs. 10,000.
d.) In all other cases the person is not Insured.
Input person’s health, age, location and gender. According to above conditions display whether person could be Insured or not. IF yes, display premium amount
*/
DECLARE
health VARCHAR(200) := :health;
age INTEGER := :age;
location VARCHAR(200) := :location;
gender VARCHAR(200) := :gender;
policy_amt INTEGER := :policy_amt;
premium INTEGER := 0;
BEGIN
IF ( health = 'excellent'
AND age > 25
AND age < 35
AND location = 'city'
AND gender = 'male'
AND policy_amt < 200000 ) THEN
premium := Trunc(policy_amt / 1000) * 4;
dbms_output.Put_line('Premium is Rs. '
|| premium);
ELSIF ( health = 'excellent'
AND age > 25
AND age < 35
AND location = 'city'
AND gender = 'female'
AND policy_amt < 100000 ) THEN
premium := Trunc(policy_amt / 1000) * 3;
dbms_output.Put_line('Premium is Rs. '
|| premium);
ELSIF ( health = 'poor'
AND age > 25
AND age < 35
AND location = 'village'
AND gender = 'male'
AND policy_amt < 10000 ) THEN
premium := Trunc(policy_amt / 1000) * 6;
dbms_output.Put_line('Premium is Rs. '
|| premium);
ELSE
dbms_output.Put_line('Person is not INsured');
END IF;
END; <file_sep>/*
Input any date with time. Extract time and day from Inputted date. IF time is not between 10 am to 6 pm and day is not weekdays, display the message “Office is closed” ELSE display “Office is Open”.
*/
DECLARE
d TIMESTAMP:=:d;
hh INTEGER;
mm INTEGER;
ss INTEGER;
dy varchar(200);
BEGIN
hh := extract(hour from d);
mm := extract(mINute from d);
ss := extract(second from d);
dy := rtrim(to_char(d,'dy'));
IF hh>=10 and hh<=18 and dy not IN ('sat','sun') THEN
IF hh=18 and (mm!=0 or ss!=0) THEN
dbms_output.put_line('Office is closed');
ELSE
dbms_output.put_line('Office is open');
END IF;
ELSE
dbms_output.put_line('Office is closed.');
END IF;
dbms_output.put_line(hh);
END;
/<file_sep>/*
Input any number and display following patterns. Ex., Inputted number is 5, program
should display 5 lines.
1
2 3
4 5 6
7 8 9 10
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
*/
DECLARE
s INTEGER:=:s;
i INTEGER;
j INTEGER;
temp INTEGER;
BEGIN
temp := 1;
FOR i IN 1..(s-1) LOOP
FOR j IN 1..i LOOP
dbms_output.put(temp||' ');
temp := temp + 1;
END LOOP;
dbms_output.put_line(' ');
END LOOP;
END;
DECLARE
s INTEGER:=:s;
i INTEGER;
j INTEGER;
temp2 boolean;
BEGIN
temp2 := true;
FOR i IN 1..s LOOP
IF MOD(i,2)=0 THEN
temp2 := false;
ELSE
temp2 := true;
END IF;
FOR j IN 1..i LOOP
IF temp2 = true THEN
dbms_output.put(1||' ');
ELSE
dbms_output.put(0||' ');
END IF;
temp2 := NOT temp2;
END LOOP;
dbms_output.put_line(' ');
END LOOP;
END;<file_sep>--Q1 Input any number and display following patterns. Ex., inputted number is 5, program should display 5 lines.
declare
i int:=:i;
s int;
j int;
k int;
begin
s:=1;
for j in 1..i-1 loop
for k in 1..j loop
dbms_output.put(s||' ');
s := s+1;
end loop;
dbms_output.put_line(' ');
end loop;
s:=1;
for j in 1..i loop
s:= MOD(j,2);
for k in 1..j loop
dbms_output.put(s||' ');
s := 1-s;
end loop;
dbms_output.put_line(' ');
end loop;
end;
/
-- Result
--Q2 Input person’s health, age, location and gender. According to above conditions display whether person could be insured or not. If yes, display premium amount.
declare
health varchar(10):=:health;
age int:=:age;
location varchar(20):=:location;
gender varchar(10):=:gender;
amount int:=:amount;
premium int;
begin
premium := 0;
if health='excellent' and age<=35 and age>=25 and location='city' and gender='male' and amount<=200000 then
dbms_output.put_line('YES');
dbms_output.put_line('Premium Amount is '||(amount*4)/1000);
elsif health='excellent' and age<=35 and age>=25 and location='city' and gender='female' and amount<=100000 then
dbms_output.put_line('YES');
dbms_output.put_line('Premium Amount is '||(amount*3)/1000);
elsif health='poor' and age<=35 and age>=25 and location='village' and gender='male' and amount<=10000 then
dbms_output.put_line('YES');
dbms_output.put_line('Premium Amount is '||(amount*6)/1000);
else
dbms_output.put_line('NO Premium');
end if;
end;
/
-- Result
--Q3 Input mode of transport, weight of parcel, delivery is domestic or overseas and delivery to be done same day or not. According to the mentioned rules, display charges.
declare
transport_mode varchar(10):=:transport_mode;
parcel_weight int:=:parcel_weight;
delivery_type varchar(10):=:delivery_type;
same_day varchar(10):=:same_day;
charges int:=0;
extra_charges int:=0;
total_charges int:=0;
begin
if transport_mode = 'air' then
if parcel_weight>50 then
extra_charges:= (parcel_weight-50)*3;
parcel_weight := 50;
end if;
charges := parcel_weight*5;
elsif transport_mode = 'rail' then
if parcel_weight>50 then
extra_charges:= (parcel_weight-50)*3;
parcel_weight :=50;
end if;
charges := parcel_weight*2;
end if;
if same_day = 'yes' then
extra_charges:= extra_charges + 20;
end if;
total_charges:= extra_charges+charges;
if delivery_type = 'overseas' then
total_charges:= total_charges*2;
end if;
dbms_output.put_line('Basic Charge is '||charges||' Extra Charge is '||extra_charges||' Total Charge is '||total_charges)
end;
/
-- Result
--Q4 Input any date with time. Extract time and day from inputted date. If time is not between 10 am to 6 pm and day is not weekdays, display the message “Office is closed” else display “Office is Open”.
DECLARE
d TIMESTAMP:=:d;
hh int;
mm int;
ss int;
dy varchar(200);
BEGIN
hh := extract(hour from d);
mm := extract(minute from d);
ss := extract(second from d);
dy := rtrim(to_char(d,'dy'));
if hh>=10 and hh<=18 and dy not in ('sat','sun') THEN
if hh=18 and (mm!=0 or ss!=0) THEN
dbms_output.PUT_LINE('Office is closed');
else
dbms_output.PUT_LINE('Office is open');
end if;
else
dbms_output.PUT_LINE('Office is closed.');
end if;
dbms_output.PUT_LINE(hh);
END;
/
-- Result
--Q5 Input any number. Display sum of digits of that number.
declare
i integer:=:i;
su integer;
temp integer;
begin
su:=0;
while i<>0 loop
temp:= MOD(i,10);
su := su + temp;
i := trunc(i/10);
end loop;
dbms_output.put_line('Sum of digits is '||su);
end;
/
-- Result
--Q6. Input any number to generate following series.
declare
i int:=:i;
temp int:=0;
j int;
begin
for j in 1..i loop
temp:= j*j;
dbms_output.put(temp||' ');
end loop;
dbms_output.put_line(' ');
end;
/
-- Result
--Q7 Input any string and display whether it is palindrome or not.
declare
str varchar(20):=:str;
f int:=0;
i int:=0;
j int:=0;
begin
j:= length(str);
for i in 1..length(str) loop
if substr(str,i,1)!=substr(str,j-i+1,1) then
dbms_output.put_line('Labad'||i||' '||j);
f := 1;
exit;
end if;
end loop;
if f=1 then
dbms_output.put_line('Not a palindrome');
else
dbms_output.put_line('Palindrome');
end if;
end;
/
-- Result
--Q8 Input any string and display total no. of vowels in that string.
declare
str varchar(20):=:str;
n int:=0;
j int:=0;
begin
for j in 1..length(str) loop
if substr(str,j,1) in ('A','E','I','O','U') or substr(str,j,1) in ('a','e','i','o','u') then
n := n + 1;
end if;
end loop;
dbms_output.put_line('Total number of vowels are '||n);
end;
/
-- Result
--Q9 Input marks of five subjects each out of 50. Display total marks and percentage only if student is passed in all the subjects. Passing marks are 25 out of 50.
declare
marks1 int:=:marks1;
marks2 int:=:marks2;
marks3 int:=:marks3;
marks4 int:=:marks4;
marks5 int:=:marks5;
f int:=0;
tm int:=0;
j int:=0;
begin
tm := marks1 + marks2 + marks3 +marks4 + marks5;
if marks1<25 or marks2<25 or marks3<25 or marks4<25 or marks5<25 then
f:=1;
end if;
if f=0 then
dbms_output.put_line('Percentage is '||((tm/250)*100)||' and Total marks are '||tm);
else
dbms_output.put_line('Fail');
end if;
end;
/
-- Result<file_sep>/*
Input any number to generate following series.
1 4 9 16 25 36 ……
1 2 4 8 16 32 64 ……
*/
DECLARE
n INTEGER:=:n;
i INTEGER;
BEGIN
FOR i IN 1..n LOOP
dbms_output.Put((i*i)||' ');
END LOOP;
dbms_output.put_line(' ');
END;
DECLARE
n INTEGER:=:n;
i INTEGER;
BEGIN
FOR i IN 0..n LOOP
dbms_output.Put(POWER(2,i)||' ');
END LOOP;
dbms_output.put_line(' ');
END;
/<file_sep>declare
name varchar(10):=:name;
gender varchar(10):=:gender;
birthdate date:=:birthdate;
age int;
begin
age:= months_between(sysdate, birthdate)/12;
if (gender='male' and age<=12) then
dbms_output.put_line('Master '||name);
elsif (gender='male' and age>12) then
dbms_output.put_line('Mr '||name);
elsif (gender='female' and age<=12) then
dbms_output.put_line('Baby '||name);
else
dbms_output.put_line('Ms '||name);
end if;
end;
declare
num int:=:num;
root int;
i int;
flag int;
begin
root:= sqrt(num);
flag:= 0;
for i in 2..root loop
if (mod(num,i)=0) then
flag := 1;
exit;
end if;
end loop;
if (flag=0) then
dbms_output.put_line(num||' is prime');
else
dbms_output.put_line(num||' is composite');
dbms_output.put_line('Factors of '||num|| ' are ');
for i in 1..num loop
if mod(num,i)=0 then
dbms_output.put_line(i);
end if;
end loop;
end if;
end;
declare
mail varchar(40):=:mail;
begin
if (mail like '%@%') then
dbms_output.put_line(mail||' is a valid mail id');
else
dbms_output.put_line(mail||' is not a valid mail id');
end if;
end;<file_sep>/*
A postal delivery company delivers parcels by air or rail transport. The price of delivery by air depends upon the weight of the parcel. There is a basic charge of 5 euros per kilo up to 50 kilos. Excess weight over 50 kilos is charged at 3 euros per kilo. Delivery by rail is charged at 3 euros per kilo up to 50 kilos and THEN 2 euros per kilo. There is a special service guaranteeing same day delivery which carries an additional flat rate charge of 20 euros. Any deliveries overseas are charged at double the normal rate. Input mode of transport, weight of parcel, delivery is domestic or overseas and
delivery to be done same day or not. According to the mentioned rules, display charges.
*/
DECLARE
transport varchar(200):=:transport;
weight INTEGER:=:weight;
delivery varchar(200):=:delivery;
isday varchar(200):=:isday;
charge INTEGER:=0;
BEGIN
IF(transport='air') THEN
IF(weight<50) THEN
charge := weight*5;
ELSE
charge := 50*5 + (weight-50)*8;
END IF;
END IF;
IF(transport='rail') THEN
IF(weight<50) THEN
charge := weight*3;
ELSE
charge := 50*3 + (weight-50)*5;
END IF;
END IF;
IF(delivery='overseas') THEN
charge := charge * 2;
END IF;
IF(isday='yes') THEN
charge := charge + 20;
END IF;
dbms_output.put_line('charge is ' || charge);
END;
/<file_sep>/*
Input any number. Display sum of digits of that number.
*/
DECLARE
n INTEGER :=:n;
temp_sum INTEGER;
r INTEGER;
BEGIN
temp_sum := 0;
WHILE n <> 0 LOOP
r := MOD(n, 10);
temp_sum := temp_sum + r;
n := Trunc(n / 10);
END LOOP;
dbms_output.put_line('Sum of digits = '|| temp_sum);
END; <file_sep>-- Q1 Write a procedure to input any number as a parameter. Check whether the number is an Armstrong number or not.
create or replace procedure checkArmstrong(n int) as
s int;
r int;
i int;
temp int;
begin
i := 0;
s := n;
r := 0;
temp := n;
while (temp>0) loop
r := r + power(mod(temp,10),3);
temp := trunc(temp/10);
end loop;
if (r=s) then
dbms_output.put_line(n||' is an Armstong number');
else
dbms_output.put_line(n||' is not an armstong number');
end if;
end;
declare
n int:=:n;
begin
checkArmstrong(n);
end;
/
-- Q2 Write a procedure to input product’s class and purchase amount and display discount along with the payable amount
create or replace procedure companyProfit(class char,purchase int) as
discount int;
payable int;
begin
discount:=0;
if (class='A' and purchase>5000) then
discount := 10;
elsif (class='B' and purchase>8000) then
discount := 5;
elsif (class='C' and purchase>=10000) then
discount := 4;
end if;
payable := purchase - ((purchase*discount)/100);
dbms_output.put_line('Discount is '||discount||'% and Payable amount is '||payable);
end;
declare
class char:=:class;
purchaseAmount int:=:purchaseAmount;
begin
companyProfit(class,purchaseAmount);
end;
/
-- Q3 Write a function to input basic_salary of the employee and return net_salary
create or replace function salary(basic_salary float) return float as
DA float;
HRA float;
MA float;
CLA float;
TA float;
PF float;
PT float;
IT float;
allowance float;
deduction float;
netsalary float;
begin
if (basic_salary>=0 and basic_salary<2000) then
PT := 20.00;
elsif (basic_salary>=2000 and basic_salary<4000) then
PT := 40.00;
elsif (basic_salary>=4000 and basic_salary<6000) then
PT := 60.00;
elsif (basic_salary>=6000) then
PT := 10.00;
end if;
DA := trunc(basic_salary*43/100);
HRA := trunc((basic_salary+DA)*15/100);
MA := 10.00;
CLA := 240.00;
TA := 800.00;
PF := trunc((basic_salary+DA)*12/100);
IT := trunc(basic_salary*10/100);
allowance := DA+HRA+MA+CLA+TA;
deduction := PF+PT+IT;
netsalary := allowance+basic_salary-deduction;
return netsalary;
end;
declare
basic_salary float:=:basic_salary;
temp float;
begin
temp := salary(basic_salary);
dbms_output.put_line('Your net salary is '||temp);
end;
/
-- Q4 Write a function to input person’s age as total no. of days and return age of that person in years, months and days.
create or replace function calculate_age(totaldays int) return varchar as
totalday int;
temp int;
years int;
months int;
days int;
final_age varchar(100);
begin
totalday := totaldays;
temp := mod(totalday,365);
years := trunc(totalday/365);
totalday := temp;
temp := mod(totalday,30);
months := trunc(totalday/30);
totalday := temp;
days := totalday;
final_age := 'Your age must be '||years||' years, '||months||' months and '||days||' days';
return final_age;
end;
declare
days int:=:days;
ans varchar(100);
begin
ans := calculate_age(days);
dbms_output.put_line(ans);
end;
/
-- Q5 Write a procedure to input price of one computer and total no. of computers sold by the salesperson. Calculate and display total bonus, total commission and gross salary.
create or replace procedure calculate(unitprice int, totalsale int) as
totalbonus int;
totalcommission float;
grosssalary float;
begin
grosssalary := 10000;
totalbonus := 500*totalsale;
totalcommission := trunc((unitprice*totalsale)/50);
grosssalary := grosssalary + totalbonus + totalcommission;
dbms_output.put_line('Total Bonus : '||totalbonus);
dbms_output.put_line('Total Commission : '||totalcommission);
dbms_output.put_line('Gross Salary : '||grosssalary);
end;
declare
unitprice int:=:unitprice;
totalsale int:=:totalsale;
begin
calculate(unitprice,totalsale);
end;
/
-- Q6 Write procedure that will retrieve records from the PERSON table and will display person’s name as following four formats. For Ex., if first name is Pooja, middle name is Harshad and last name is Shah then it should be displayed as follows. Based on the gender display Ms. or Mr. before name.
create table person(
first_name varchar(10),
middle_name varchar(10),
last_name varchar(10),
age int,
gender varchar(10)
);
create or replace procedure retrieve_records as
cursor records is select * from person;
name records%rowtype;
begin
for name in records loop
if (name.gender=UPPER('male') or name.gender='male' or name.gender='Male') then
dbms_output.put_line('Mr. '||name.first_name||' '||name.middle_name||' '||name.last_name);
dbms_output.put_line('Mr. '||substr(name.first_name,1,1)||'. '||substr(name.middle_name,1,1)||'. '||name.last_name);
dbms_output.put_line('Mr. '||name.last_name||' '||substr(name.first_name,1,1)||'. '||substr(name.middle_name,1,1)||'.');
dbms_output.put_line('Mr. '||name.last_name||' '||name.first_name||' '||name.middle_name);
else
dbms_output.put_line('Ms. '||name.first_name||' '||name.middle_name||' '||name.last_name);
dbms_output.put_line('Ms. '||substr(name.first_name,1,1)||'. '||substr(name.middle_name,1,1)||'. '||name.last_name);
dbms_output.put_line('Ms. '||name.last_name||' '||substr(name.first_name,1,1)||'. '||substr(name.middle_name,1,1)||'.');
dbms_output.put_line('Ms. '||name.last_name||' '||name.first_name||' '||name.middle_name);
end if;
end loop;
end;
declare
begin
retrieve_records();
end;
/
-- Q7 Write a procedure to display the details of STUDENT and CLASS table.
create table class(
classcode int primary key,
classdesc varchar(10)
);
create table student(
stdno int primary key,
classcode int,
stdname varchar(10),
birthdate date,
admissiondate date,
gender varchar(10),
contact varchar(10),
constraint fk_classcode foreign key (classcode) references class(classcode)
);
insert into class values(100,'ICP');
insert into class values(200,'OOP');
insert into class values(300,'DBMS');
insert into student values(10,100,'abc',to_date('03/07/2020','mm/dd/yyyy'),to_date('03/01/2020','mm/dd/yyyy'),'male',213113);
insert into student values(30,200,'abc',to_date('03/07/2020','mm/dd/yyyy'),to_date('03/01/2020','mm/dd/yyyy'),'male',213113);
insert into student values(40,300,'abc',to_date('03/07/2020','mm/dd/yyyy'),to_date('03/01/2020','mm/dd/yyyy'),'male',213113);
insert into student values(20,100,'xyz',to_date('02/07/2020','mm/dd/yyyy'),to_date('02/01/2020','mm/dd/yyyy'),'male',213111);
insert into student values(50,200,'xyz',to_date('02/07/2020','mm/dd/yyyy'),to_date('02/01/2020','mm/dd/yyyy'),'male',213111);
create or replace procedure display_class as
cursor records is select * from class;
data_val records%rowtype;
begin
open records;
dbms_output.put_line('ClassCode ClassDesc');
loop
fetch records into data_val;
exit when records%notfound;
dbms_output.put_line(data_val.classcode||' '||data_val.classdesc);
end loop;
close records;
end;
create or replace procedure display_student as
cursor records is select * from student;
data_val records%rowtype;
begin
open records;
dbms_output.put_line('Student Table');
dbms_output.put_line('Stdno Classcode Stdname Birthdate AdmissDate Gender Contact ');
loop
fetch records into data_val;
exit when records%notfound;
dbms_output.put_line(data_val.stdno||' '||data_val.classcode||' '||data_val.stdname||' '||data_val.birthdate||' '||data_val.admissiondate||' '||data_val.gender||' '||data_val.contact);
end loop;
close records;
end;
declare
begin
dbms_output.put_line('Class Table');
display_class();
dbms_output.put_line('');
display_student();
end;
/
-- Q8 Create a procedure to display employee name, salary and joining date from the EMPLOYEE table. Also, display total no. of years of experience of each employee from the joining_date field and retirement date of each employee from the birth_date field
create table employee(empno int primary key, empname varchar(10), salary int, jdate date, bdate date);
insert all
into employee values(1,'sagar',50000,to_date('01/01/2012','dd/mm/yyyy'),to_date('01/01/1990','dd/mm/yyyy'))
into employee values(2,'dhaval',70000,to_date('10/10/2005','dd/mm/yyyy'),to_date('01/01/1980','dd/mm/yyyy'))
into employee values(3,'gaurav',80000,to_date('01/09/2000','dd/mm/yyyy'),to_date('05/01/1975','dd/mm/yyyy'))
into employee values(11,'aman',40000,to_date('03/03/2001','dd/mm/yyyy'),to_date('01/05/1980','dd/mm/yyyy'))
into employee values(10,'sagar',50000,to_date('05/09/2015','dd/mm/yyyy'),to_date('02/04/1995','dd/mm/yyyy'))
select * from dual
create or replace procedure emp_details as
cursor c_emp is select * from employee;
record c_emp%rowtype;
expe int;
ret date;
curdate date;
begin
open c_emp;
select sysdate into curdate from dual;
dbms_output.put_line('Emp Name Salary JoinDate Exp RetDate');
loop
fetch c_emp into record;
if c_emp%notfound then
exit;
end if;
ret := add_months(record.bdate,720);
select floor(months_between(curdate,record.jdate) /12) into expe from dual;
dbms_output.put_line(' '||record.empname||' '||record.salary||' '||record.jdate||' '||expe||' '||ret);
end loop;
close c_emp;
end;
declare
begin
emp_details();
end;
/
-- Q9 Create a procedure which will display department wise employee details in ascending order of department name and descending order of employee names within each department as per the following format. Also, display total no of employees in each department and overall total no of employees at the end.
create table depart(deptno int primary key, deptname varchar(10));
create table employee(empno int primary key, deptno int references depart(deptno), empname varchar(10), salary int, jdate date, bdate date);
insert all
into depart values(1,'IT')
into depart values(2,'Sales')
into depart values(3,'RnD')
select * from dual
insert all
into employee values(1,1,'sagar',50000,to_date('01/01/2012','dd/mm/yyyy'),to_date('01/01/1990','dd/mm/yyyy'))
into employee values(2,1,'dhaval',70000,to_date('10/10/2005','dd/mm/yyyy'),to_date('01/01/1980','dd/mm/yyyy'))
into employee values(3,2,'gaurav',80000,to_date('01/09/2000','dd/mm/yyyy'),to_date('05/01/1975','dd/mm/yyyy'))
into employee values(11,2,'aman',40000,to_date('03/03/2001','dd/mm/yyyy'),to_date('01/05/1980','dd/mm/yyyy'))
into employee values(10,3,'sagar',50000,to_date('05/09/2015','dd/mm/yyyy'),to_date('02/04/1995','dd/mm/yyyy'))
into employee values(12,3,'deep',51000,to_date('01/04/2013','dd/mm/yyyy'),to_date('02/08/1993','dd/mm/yyyy'))
select * from dual
create or replace procedure company_details as
emp_dept_id depart.deptno%TYPE;
temp int;
total_emp int;
CURSOR cur_dept IS
SELECT *
FROM depart
ORDER BY deptname;
CURSOR cur_emp IS
SELECT *
FROM employee
WHERE deptno = emp_dept_id
ORDER BY empname desc;
BEGIN
total_emp := 0;
FOR r_dept IN cur_dept
LOOP
emp_dept_id:=r_dept.deptno;
DBMS_OUTPUT.PUT_LINE('----------------------------------');
DBMS_OUTPUT.PUT_LINE('Department Name : '||r_dept.deptname);
DBMS_OUTPUT.PUT_LINE('----------------------------------');
DBMS_OUTPUT.PUT_LINE('EmpNo EmpName Salary BirthDate JoinDate');
FOR r_emp IN cur_emp
LOOP
DBMS_OUTPUT.PUT_LINE(' '||r_emp.empno||' '||r_emp.empname||' '||r_emp.salary||' '||r_emp.bdate||' '||r_emp.jdate);
END LOOP;
select count(*) into temp from employee where employee.deptno=r_dept.deptno;
DBMS_OUTPUT.PUT_LINE('----------------------------------');
DBMS_OUTPUT.PUT_LINE('Total No. of Employees in '||r_dept.deptname||' : '||temp);
DBMS_OUTPUT.PUT_LINE('');
temp:=0;
END LOOP;
select count(*) into total_emp from employee;
DBMS_OUTPUT.PUT_LINE('Total No. of Employees in the company are '||total_emp);
DBMS_OUTPUT.PUT_LINE('');
END;
declare
begin
company_details();
end;
/
-- Q10 Create a procedure to input from date and to date. Display details of bills between these dates as per the following format. Use lineitem, item and sale tables.
create table sale(
saleno int primary key,
saledate date,
saletext char(100)
);
create table item(
itemno int primary key,
itemname char(20),
itemtype char,
itemcolor char(20)
);
create table lineitem(
lineno int,
lineqty int,
lineprice float,
saleno int references sale(saleno),
itemno int references item(itemno),
primary key (saleno,itemno)
);
insert all
into sale values(1,to_date('15-01-1995','dd-mm-yyyy'),'Scruffy Australian-called himself bruce')
into sale values(2,to_date('15-01-1995','dd-mm-yyyy'),'Man. Rather fond of hats')
into sale values(3,to_date('15-01-1995','dd-mm-yyyy'),'Woman. Planning to row atlantic-lengthwise')
into sale values(4,to_date('15-01-1995','dd-mm-yyyy'),'Man. Trip to new york-thinks new york is a jungle')
into sale values(5,to_date('16-01-1995','dd-mm-yyyy'),'Expedition leader for African safari')
select * from dual;
create or replace procedure sale_details(from_date date, to_date date) as
total_price float;
total_bill float;
sale_no sale.saleno%TYPE;
item_no lineitem.itemno%TYPE;
sale_date sale.saledate%TYPE;
cursor cur_saledetail is
select * from sale where saledate = sale_date;
cursor cur_sale is
select distinct(saledate) from sale where saledate between from_date and to_date;
cursor cur_lineitem is
select * from lineitem where saleno = sale_no;
cursor cur_item is
select * from item where itemno = item_no;
begin
for sale_record in cur_sale
loop
sale_date := sale_record.saledate;
DBMS_OUTPUT.PUT_LINE('');
DBMS_OUTPUT.PUT_LINE('');
DBMS_OUTPUT.PUT_LINE('Sale Date: '||sale_record.saledate);
for saledetail_rec in cur_saledetail
loop
total_bill := 0;
sale_no := saledetail_rec.saleno;
DBMS_OUTPUT.PUT_LINE('Sale No: '||saledetail_rec.saleno);
DBMS_OUTPUT.PUT_LINE('SrNo. ItemName Price Quantity Total_Price');
for l_item in cur_lineitem
loop
item_no := l_item.itemno;
for item_det in cur_item
loop
total_price := l_item.lineqty * l_item.lineprice;
total_bill := total_bill + total_price;
DBMS_OUTPUT.PUT_LINE(' '||item_no||' '||item_det.itemname||' '||l_item.lineprice||' '||l_item.lineqty||' '||total_price);
end loop;
end loop;
DBMS_OUTPUT.PUT_LINE('');
DBMS_OUTPUT.PUT_LINE('Total Bill Amount : '||total_bill);
DBMS_OUTPUT.PUT_LINE('');
end loop;
end loop;
end;
declare
from_date date:=:from_date;
to_date date:=:to_date;
begin
sale_details(from_date,to_date);
end;
/
<file_sep># DBMS-SQL-Codes | 0adeb7455119205dab074d5bd47eb8020fbae326 | [
"Markdown",
"SQL"
] | 10 | SQL | NamitS27/DBMS-SQL-Codes | 738a38ac328832041dad7227f74ff80f0a3c9f26 | 2d8d112105abedee02097c6d9c4332722aedacaa |
refs/heads/main | <repo_name>SanjogSamuelSamantaray/projects<file_sep>/javascript/store_kata/src/classes/Person.js
const {states} = require("./Store.js")
class Person {
constructor(name) {
this.name = name;
}
}
class Client extends Person {
constructor(name, membership = false) {
super(name);
this.membership = membership;
this.basket = [];
}
addToBasket = (product) => {
if(Object.prototype.toString.call(product) == "[object Array]"){
product.forEach(product => {
this.basket.push(product);
});
}else{
this.basket.push(product);
console.log(this.basket)
}
}
checkOut = () =>{
let total = 0;
this.basket.forEach(product => {
total += (this.membership ? product.discount !== 0 ? product.price - (product.price * product.discount /100) : product.price : product.price);
})
return total;
}
}
class Employee extends Person {
constructor(name, commission = 0) {
super(name);
this.commission = commission;
}
sellTo = (person, product) => {
if(Object.prototype.toString.call(product) == "[object Array]"){
product.forEach(product => {
if(product.state == states.PHYSICAL){
console.log("PRICE", product.price)
this.commission += product.price * 0.05;
}
person.addToBasket(product);
});
}else{
person.addToBasket(product);
}
if(product.state == states.PHYSICAL){
console.log("PRICE", product.price)
this.commission += product.price * 0.05;
}
return this.commission;
};
}
module.exports = {
Client : Client,
Employee : Employee
}<file_sep>/python/Image_Compression.md
# Image Compressing using K-Clustering
In this project, you will compress image using unsupervised learning algorithm K-clustering in python (Beginner-friendly).
## Solution
Navigate to the ~/python/image_compression/ directory, there, you will find an example of how you can do it.I will also submit some images to try on.
Keep plot_utils.py in same folder in which you will keep your project file.
Submitted by Astha<file_sep>/javascript/stickball/ball.js
class balls{
constructor(){
this.r=5;
this.x=100;
this.y=200;
}
create(){
fill(255,0,0);
noStroke();
ellipse(this.x,this.y,this.r*2,this.r*2);
}
move(this.a,this.b){
this.x+=5*this.a;
this.y+=5*this.b;
}
}<file_sep>/javascript/stickball/stick.js
var speed=10;
class stick{
constructor(){
this.x1=this.x2=width;
this.y1=random(0,height/2-10);
this.y2=random(height/2+10,height);
}
show(){
fill(255,0,0);
rect(this.x1,0,10,this.y1);
rect(this.x2,this.y2,10,height-this.y2);
}
move(){
this.x1-=speed;
this.x2-=speed;
}
check(){
if(((this.x2<(ball.x+ball.r)) && ((this.x2+10)>(ball.x+ball.r)) && (this.y2<(ball.y+ball.r)) && ((ball.y+ball.r)<height))|| ((this.x1<(ball.x+ball.r)) && ((this.x+10)>(ball.x+ball.r)) && (0<(ball.y-ball.r)) && ((ball.y-ball.r)<this.y))){
this.stop();
}
}
stop(){
speed=0;
}
}<file_sep>/javascript/Bubble_Shooter.md
# Build a Bubble Shooter Game
In this project, you will create a basic bubble shooter game using JavaScript!
## Solution
Navigate to the `~/javascript/bubbleshooter/` directory, there, you will find the JavaScript and HTML files required for this!
Submitted by DheerajKumar
<file_sep>/python/ROCK_PAPER_SCISSORS.md
# Build a simple Rock Paper Scissors game
In this project, you will create a game of rock paper scissors in python. (Beginner-friendly)
## Solution
Navigate to the `~/python/rock_paper_scissors/` directory, there, you will find an example of how you can do it.
Submitted by Harowo
<file_sep>/javascript/bubbleshooter/bubble.js
class bubble{
constructor(q,w){
if(q%2==0)
this.x=6*r+(2*w*r);
else
this.x=7*r+(2*w*r);
this.y=(q*r*1.732)+r;
this.col=random([color(0,255,0),color(0,0,255)]);
this.exist=1;//as soon as exist is 0 splice the bubble
}
show(){
if(this.exist==0)
;
else{
push();
fill(this.col);
strokeWeight(1);
stroke(0);
ellipse(this.x,this.y,2*r);
pop();
}
}
spread(l,m,n){
//
if(b[l-1]){
if( b[l-1][m-1]){
if(floor(dist(b[l-1][m-1].x,b[l-1][m-1].y,this.x,this.y))==(2*r-1) && this.col.levels[0]===b[l-1][m-1].col.levels[0] && this.col.levels[1]===b[l-1][m-1].col.levels[1] && this.col.levels[2]===b[l-1][m-1].col.levels[2] ){
b[l-1][m-1].exist=0;
b[l-1][m-1].spread(l-1,m-1);
}
}
if(b[l-1][m]){
if(floor(dist(b[l-1][m].x,b[l-1][m].y,this.x,this.y))==(2*r-1) && this.col.levels[0]===b[l-1][m].col.levels[0] && this.col.levels[1]===b[l-1][m].col.levels[1] && this.col.levels[2]===b[l-1][m].col.levels[2]){
b[l-1][m].exist=0;
b[l-1][m].spread(l-1,m);
}
}
if(b[l-1][m+1]){
if(floor(dist(b[l-1][m+1].x,b[l-1][m+1].y,this.x,this.y))==(2*r-1) && this.col.levels[0]===b[l-1][m+1].col.levels[0] && this.col.levels[1]===b[l-1][m+1].col.levels[1] && this.col.levels[2]===b[l-1][m+1].col.levels[2]){
b[l-1][m+1].exist=0;
b[l-1][m+1].spread(l-1,m+1);
}
}
}
//
}
}
<file_sep>/javascript/CHUCK_NORRIS_JOKES.md
# Chuck Norris Jokes generator
In this project, you will create a basic web app using skeleton and javascript.
## Solution
Navigate to the `~/chuck_norris_jokes/` directory, there, you will find the JavaScript and HTML files required for this!
Submitted by Amrutha26
<file_sep>/python/image_compression/plot_utils.py
import numpy as np
import matplotlib.pyplot as plt
class plot_utils:
def __init__(self, img_data, title, num_pixels=10000, colors=None):
self.img_data = img_data
self.title = title
self.num_pixels = num_pixels
self.colors = colors
def colorSpace(self):
if self.colors is None:
self.colors = self.img_data
rand = np.random.RandomState(42)
index = rand.permutation(self.img_data.shape[0])[:self.num_pixels]
colors = self.colors[index]
R, G, B = self.img_data[index].T
fig, ax = plt.subplots(1, 2, figsize=(12,8))
ax[0].scatter(R, G, color=colors, marker='.')
ax[0].set(xlabel='Red', ylabel='Green', xlim=(0, 1), ylim=(0, 1))
ax[1].scatter(R, B, color=colors, marker='.')
ax[1].set(xlabel='Red', ylabel='Blue', xlim=(0, 1), ylim=(0, 1))
fig.suptitle(self.title, size=20)
<file_sep>/javascript/Stick_Ball.md
# Build a Stick Ball Game
In this project, you will create a basic game of Stick Ball using JavaScript!
## Solution
Navigate to the `~/javascript/stickball/` directory, there, you will find the JavaScript and HTML files required for this!
Submitted by DheerajKumar<file_sep>/javascript/stickball/boosters.js
var bc;
class boosters{
constructor(bc){
this.x=bc;
this.b=1;
}
move(){
this.x-=speed2;
}
life(){
stroke(255,0,0);
fill(255);
rect(this.x-9,196,23,23);
fill(255,0,0);
rect(this.x,200,5,15);
rect(this.x-5,205,15,5);
}
check(){
if(
(
((ball.x+ball.r>=this.x-9) && (ball.x+ball.r<=this.x+14)
)
||
( (ball.x-ball.r>=this.x-9) && (ball.x-ball.r<=this.x+14)
)
)
&& (
((ball.y+ball.r>=196)&&(ball.y+ball.r<=219)
)
||
( (ball.y-ball.r>=196)&&(ball.y-ball.r<=219)
)
)
&& this.b==1
){
life++;
this.b=2;
flag4=1;
}
}
}<file_sep>/python/lms_project_readme.md
LMS(Library Mangement System) is a python based project designed using sqlite db.
The main features include:
1. A student cannot issue more than two copies of the same book
2. A student cannot issue more than two books
3. Admin password checker
4. A proper record log to see which book has been issued to whom
It has two portals:
1. Admin has to create an account(if first time user) and then login. all details of everything will be stored in the db. the admin can:
1. Add/remove books
2. Add/delete students from student list
3. Can see who has taken which book
4. Can update the no. of books available in the Library
2. Librarian can:
1. Issue books
2. Return books
3. Can see which book is taken by which student
4. Can see what books are taken by a particular student
<file_sep>/javascript/MOVIE_SEAT_BOOKING.md
# Build a Movie Seat Booking App
In this project, you will create a basic static movie seat bookin web app using javascript!
## Solution
Navigate to the `~/javascript/movie_seat_booking/` directory, there, you will find the JavaScript and HTML files required for this!
Submitted by Amrutha26<file_sep>/javascript/PING_PONG_GAME.md
# Build a Ping Pong Game
In this project, you will create a basic game of ping pong using JavaScript!
## Solution
Navigate to the `~/javascript/ping_pong_game/` directory, there, you will find the JavaScript and HTML files required for this!
Submitted by arpantaneja
<file_sep>/pull_request_template.md
# (Project Name)
## 🔎 Brief Project Description
(Your Answer)
## 📫 Programming Langauge (and Framework)
(Your Answer)
## 🤷 Other Info?
(Your Answer)
- [x] I have checked and confirm that this is not a duplicate.
- [x] All (if any) links (or content) is appropriate for all viewers.
- [x] I have read the contributing guidelines and followed all of them.
- [x] I have updated the README file and created all other necessary files.
<file_sep>/C++/TEXT_BASED_GAME.md
# Build a Text Based Game
In this project, you will create a basic text based game using C++!
## Solution
Navigate to the `~/C++/textbasedgame/` directory, there, you will find the C++ files required for this!
Submitted by <NAME>
<file_sep>/javascript/STORE_KATA.md
# Store Kata
In this small project you will create a Test Driven Project where you create a store that has a limited number of products to sell.
Customers can purchase goods, Employees can sell stuff to customers and earn commission on this.
# Products
BOOK
VIDEOGAME
BANANA
# Business Rules
- The store currently sells physical books, video-games (online and physical)
- The store has also a optional membership for it's clients
- The membership allows specific discounts for each product sold in the store
- The store will send a 5% commission to the employee that sells a physical product
- The store plans to expand selling also bananas (why not?) and coffee drinks.
You don't have to implement those yet, but keep in mind that new products can be added to the store
# Credits
[<NAME>](http://codekata.com/kata/kata16-business-rules/)
# Solutions & Hints
Work with classes
Work with Enums
Create a few test cases to show that your code is working
<file_sep>/javascript/maze/box.js
var k,l,m,xyz;
var d=0;
var min2=500;var side_size=40;
var q=0;//distance from endpoint loop everytime udated and to check if q<this.dFromEnd
//var side=20;
class boxes{
constructor(k,l){
this.x=k;
this.y=l;
this.visited=0;
this.neigh=[];
this.l12=this.l23=this.l34=this.l41=true;
this.rev;
this.dFromEnd=100;
}
show(){
if(this.l12)
line((this.x+1)*side_size,(this.y+1)*side_size,(this.x+2)*side_size,(this.y+1)*side_size);
if(this.l23)
line((this.x+2)*side_size,(this.y+1)*side_size,(this.x+2)*side_size,(this.y+2)*side_size);
if(this.l34)
line((this.x+2)*side_size,(this.y+2)*side_size,(this.x+1)*side_size,(this.y+2)*side_size);
if(this.l41)
line((this.x+1)*side_size,(this.y+1)*side_size,(this.x+1)*side_size,(this.y+2)*side_size);
if(this.visited==1){
push();
noStroke();
fill(255,0,255,100);
rect((this.x+1)*side_size,(this.y+1)*side_size,side_size,side_size);
pop();
}
}
//to highlight current box
show1(){
push();
noStroke();
fill(0,255,0);
rect((this.x+1)*side_size,(this.y+1)*side_size,side_size,side_size);
pop();
}
//to find the next box
next(){
this.visited=1;
this.neigh=[];
if(this.x>0)
if(b[this.x-1][this.y].visited==0)
this.neigh.push(b[this.x-1][this.y]);
if(this.y>0)
if(b[this.x][this.y-1].visited==0)
this.neigh.push(b[this.x][this.y-1]);
if(this.x<col-1)
if(b[this.x+1][this.y].visited==0)
this.neigh.push(b[this.x+1][this.y]);
if(this.y<row-1)
if(b[this.x][this.y+1].visited==0)
this.neigh.push(b[this.x][this.y+1]);
if(this.neigh.length>0){
this.lucky=random(this.neigh);
this.lucky.rev=curr;
curr=this.lucky;
total++;
if(this.lucky.x<this.x){
this.lucky.l23=false;
this.l41=false;
}
else if(this.lucky.x>this.x){
this.lucky.l41=false;
this.l23=false;
}
else if(this.lucky.y<this.y){
this.lucky.l34=false;
this.l12=false;
}
else if(this.lucky.y>this.y){
this.lucky.l12=false;
this.l34=false;
}
}
else
curr=this.rev;
}
endudate(){
//updates minimum distance from end
if((this.dFromEnd>(end.dFromEnd-1)) && this.dFromEnd!=0)
{this.dFromEnd=end.dFromEnd+1;
}
}
// show2(){
// push();
// noStroke();
// fill(150,150,0);
// rect((this.x+1)*10,(this.y+1)*10,10,10);
// pop();
//
// }
//
next2(){
if(this.y<row-1 && !(this.l34)){
if(b[this.x][this.y+1].dFromEnd===this.dFromEnd-1){
start=b[this.x][this.y+1];
}
}
if(this.y>0 && !(this.l12)){
if(b[this.x][this.y-1].dFromEnd===this.dFromEnd-1){
start=b[this.x][this.y-1];
}
}
if(this.x<col-1 && !(this.l23)){
if(b[this.x+1][this.y].dFromEnd===this.dFromEnd-1 ){
start=b[this.x+1][this.y];
}
}
if(this.x>0 && !(this.l41)){
if(b[this.x-1][this.y].dFromEnd==this.dFromEnd-1){
start=b[this.x-1][this.y];
}
}
}
show2(){
//to highlight cell of the player
push();
noStroke();
fill(255,0,0);
rect((this.x+1)*side_size,(this.y+1)*side_size,side_size,side_size);
pop();
}
}
function backtrack(s,t){
end=b[s][t];
if(end==start){
flag7=1;
}
if(!end.l12){
b[end.x][end.y-1].endudate();
}
if(!end.l23)
b[end.x+1][end.y].endudate();
if(!end.l34)
b[end.x][end.y+1].endudate();
if(!end.l41)
b[end.x-1][end.y].endudate();
}<file_sep>/python/AUTOMATE_A_WEBSITE.md
# Automate a Website
In this project, you will automate tasks based on a website!
## Examples
To find examples of how to do this, navigate to the `~/python/automate_a_website/` directory, there you will find both a PDF and a README, the README contains a warning, and the PDF has examples and how-to's, good luck!
Submitted by Satyajeet-code
<file_sep>/typescript/sqlite-simple-api/api.ts
import { serve } from "https://deno.land/std@0.65.0/http/server.ts";
import { DB } from "https://deno.land/x/sqlite/mod.ts";
const PORT = 8162;
const s = serve({ port: PORT});
const db = new DB("my.db");
db.query(
"CREATE TABLE IF NOT EXISTS jobs (\
id INTEGER PRIMARY KEY AUTOINCREMENT, \
created_at DATETIME, last_updated DATETIME , \
active BOOLEAN, company_id INTEGER, apply_url TEXT, \
job_title CHARACTER(140), details TEXT, pay_range TEXT)"
);
db.query(
"CREATE TABLE IF NOT EXISTS companies (\
id INTEGER PRIMARY KEY AUTOINCREMENT, \
logo_url TEXT, \
name CHARACTER(50), \
description TEXT, \
created_at DATETIME, \
last_updated DATETIME , \
active BOOLEAN)"
);
/* db.query(
"INSERT INTO companies (logo_url, name, description, created_at, last_updated, active) VALUES (?,?,?,?,?,?)",
["adresaURL", "Adastra", "popis firmy", Date.now(), Date.now(), 1]
); */
console.log(`Listening on <http://localhost>:${PORT}/`);
for await (const req of s) {
const params = req.url.split("?");
const bad_request = { body: "Error 400: bad request.", status: 400 };
if (params.length > 2) {
req.respond(bad_request);
continue;
}
const url = params[0];
const search_params = new URLSearchParams(params[1]);
if (url == "/api/v1/jobs") {
let count = 10;
let request_count = search_params.get("count");
if (request_count) {
if (parseInt(request_count) > 100) {
req.respond(bad_request);
continue;
} else {
count = parseInt(request_count);
}
}
const results = [];
for (const [
job_title,
name,
] of db.query(
"SELECT job_title,name \
FROM jobs \
JOIN companies ON company_id = companies.id \
ORDER BY jobs.id DESC \
LIMIT ?",
[count]
)) {
results.push({ company_name: name, job_title: job_title });
}
req.respond({
body: JSON.stringify(results),
status: 200,
});
continue;
}
if (url == "/api/v1/jobs/add") {
let password_valid = false;
const password = "<PASSWORD>";
let request_password = search_params.get("pw");
if (request_password) {
if (request_password == password) {
password_valid = true;
}
}
if (password_valid == false) {
req.respond({
body: "Not Allowed",
status: 405,
});
continue;
}
// validated can add
else {
const apply_url = search_params.get("apply_url");
const job_title = search_params.get("job_title");
const company = search_params.get("company");
const details = search_params.get("details");
const pay_range = search_params.get("pay_range");
let company_id;
// To get the company ID we need to know if from the other table
for (const [id] of db.query("SELECT id FROM companies WHERE name = ?", [
company,
]))
company_id = id;
// companies are added in a different endpoint
if (!company_id) {
req.respond({ body: "Company Name not specified.", status: 400 });
continue;
}
// write into database
db.query(
"INSERT INTO jobs (company_id, apply_url, job_title, details, pay_range,created_at,last_updated,active) VALUES (?,?,?,?,?,?,?,?)",
[company_id, apply_url, job_title, details, pay_range, Date.now(), Date.now(), 1]
);
req.respond({
status: 200,
});
continue;
}
}
}
db.close();
<file_sep>/javascript/PASSWORD_GENERATOR.md
# JavaScript Password Generator
The goal of this project is to randomly generate passwords, if you want to go above and beyond you can add customized settings, or even password copying and generator settings! This project will teach you some basic methods that will be important to many other projects, such as using the `Math` object.
## Hint(s)
<details>
<summary>How to generate a random string.</summary>
It's pretty simple to generate a random string, all you have to do is:
```js
function randomize(length) {
let possible = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!";
let characterArray = possible.split('');
let final = "";
for(let i = 0; i < length; i++){
final+=characterArray[Math.floor(Math.random() * characterArray.length)];
}
return final;
}
/* now you can use randomize(10) and get a random string that is 10 characters long! */
```
</details>
Submitted by [sqwyer](https://github.com/sqwyer)
<file_sep>/javascript/store_kata/checklist.md
STORE HAS PRODUCTS
- BOOKS
- VIDEO GAMES
- VIDEO GAMES ONLINE
- MEMBERSHIP GIVES 5%
LIST OF CLIENTS
- NAME
- MEMBERSHIP
CODE STRUCTURE
class PERSONS, class CLIENT, class EMPLOYEE
class STORE has a list of PRODUCTS
class PRODUCT
<file_sep>/javascript/bubbleshooter/bullet.js
class bullet{
constructor(x){
this.os=createVector(3,0);
this.os2=createVector(3,0);//for tail
this.angle=x;
this.os.rotate(this.angle);
this.os2.rotate(this.angle);
this.vel=createVector(5,0);
this.vel.rotate(this.angle);
}
show(){
stroke(0);
strokeWeight(3); line(width/2+4+this.os.x+s.os.x,height+this.os.y+s.os.y,width/2+4+this.os.x+s.os.x-this.os2.x,height+this.os.y+s.os.y-this.os2.y);
//move
this.os.add(this.vel);
}
}<file_sep>/javascript/Maze_Game.md
# Build a Maze Game
In this project, you will create a basic Maze runner game where you(red square) need to run away from being caught by green square in 60 seconds using JavaScript!
## Solution
Navigate to the `~/javascript/maze/` directory, there, you will find the JavaScript and HTML files required for this!
Submitted by DheerajKumar<file_sep>/python/rock_paper_scissors/rps.py
from random import randint
intro = "to quit press k"
print(intro)
while True: # game will not stop until k is inputted
player = input("rock (r), paper (p), scissors (s): ")
if player not in ("r", "s", "p", "k"): # invalid input
print("pls enter correctly")
elif player == "k": # input to stop game
print("play stopped")
break # ends game
else:
options = ["r", "p", "s"] # r = rock, p = paper, s = scissors
comp = options[randint(0, 2)]
print(player, "vs", comp)
# display results
if (player == "r" and comp == "r") or (player == "p" and comp == "p") or (player == "s" and comp == "s"):
print("Draw")
elif (player == "r" and comp == "p") or (player == "s" and comp == "r") or (player == "p" and comp == "s"):
print("Lose")
elif (player == "p" and comp == "r") or (player == "r" and comp == "s") or (player == "s" and comp == "p"):
print("Win")
<file_sep>/javascript/store_kata/index.js
const {Client, Employee} = require("./src/classes/Person.js")
const {Product, products, states} = require("./src/classes/Store.js")
const Person1 = new Client("Tijs", false)
const Employee1 = new Employee("Kris")
Person1.addToBasket([new Product(products.BOOK, 100, undefined, 50), new Product(products.VIDEOGAME, 100, states.ONLINE, 12)]);
Person1.addToBasket(new Product(products.BOOK, 10));
Person1.checkOut();
Employee1.sellTo(Person1, [new Product(products.BOOK, 100, undefined, 50), new Product(products.VIDEOGAME, 100, states.ONLINE, 12)])
<file_sep>/javascript/2048/2048box.js
//remember non coordinate(array type) type numbering
class box{
constructor(i,j){
this.x=j;
this.y=i;
// this.filled=0;
this.num=0;
}
show(){
fill(255,255,153);
rect(this.x*side+side,this.y*side+side,side,side);
if(this.num!=0){
fill(0);
textSize(40);
text(this.num,(this.x*side)+side+25,(this.y*side)+side+50);
}
}
}<file_sep>/python/automate_a_website/Readme.md
NOTE:
YOU NEED TO HAVE PRIOR PERMISSION OF THE OWNER(S) OR THE DEVELOPER(S) OF THE WEBSITE (OWNER(S) AND DEVELOPER(S) MIGHT BE DIFFERENT INDIVIDUALS OR COMPANIES, INSTITUTIONS, ETC. IN MANY CASES), BEFORE AUTOMATING THEIR WEBSITE OR A LEGAL ACTION CAN BE TAKEN.
<file_sep>/javascript/stickball/game.js
var s=[];
var ball=new balls();
var i;
function setup(){
createCanvas(600,400);
}
function draw(){
background(50,100,150);
s[0]=new stick();
if ((frameCount%50)==0){
s[s.length]=new stick();
}
ball.move();
for(i=0;i<s.length;i++){
s.show();
s.move();
s.check();
if((s[i].x1+10)<0)
s.splice(i,1);
}
}
function keyPressed(){
if (keyCode===37)
ball.move(-1,0);
if (keyCode===39)
ball.move(1,0);
if (keyCode===38)
ball.move(0,-1);
if (keyCode===40)
ball.move(0,1);
}<file_sep>/javascript/store_kata/src/classes/Store.js
const products = {
BOOK: 'Book',
VIDEOGAME: 'Videogame',
BANANA: 'Banana'
}
const states = {
ONLINE: 'Online',
PHYSICAL: 'Physical'
}
class Product {
constructor(name, price = 0, state = states.PHYSICAL, discount = 0) {
this.name = name;
this.state = state;
this.price = price;
this.discount = discount;
}
}
module.exports = {
Product : Product,
products : products,
states : states
}<file_sep>/javascript/bubbleshooter/shotter.js
class shooter{
constructor(){
this.os=createVector(0,-110);
this.angle=PI/2;
}
show(){
noStroke();
fill(50);
ellipse(width/2+5,height,75,75);
stroke(50);
strokeWeight(10);
line(width/2+4,height,width/2+4+this.os.x,height+this.os.y);
}
rotate(q){
this.os.rotate(q*PI/100);
this.angle-=q*PI/100;
}
}<file_sep>/README.md
# A list of awesome project ideas to help you learn!
This is a repository for random projects that would help you learn! You can contribute by creating a pull request and adding whatever project ideas, spelling mistakes, grammar mistakes, etc. that you would like! First, check if there is a directory for projects of that language/framework, if there is, just add a file to that directory, if not, create the file yourself, use \_'s for seperators ('spaces') and have no capital letters! Example: `React Native` => `react_native`! You will also need to add the project under the correct heading (or create a heading) in the `README.md`!
If you want to take things a step further, after adding a breif description of the project idea, you can add hints to creating it, as well as possible solutions! This would help people out with learning a new method, or even just showing someone that something exists in the specific programming language or framework.
# Contributing.
Check out the `CONTRIBUTING.md` file on how you can start contributing to this repo.
## JavaScript projects
### ToDo list
Build a simple todo list web page that allows you to add, remove, and complete todos, [View Project](https://github.com/sqwyer/projects/blob/main/javascript/TODO_LIST.md) - Submitted by sqwyer
### Stone Paper Scissors
Build a simple stone paper scissors (rock paper scissors) game, [View Project](https://github.com/sqwyer/projects/blob/main/javascript/STONE_PAPER_SCISSORS.md) - Submitted by eswarupkumar
### Password Generator
Build a simple password generator with JavaScript, [View Project](https://github.com/sqwyer/projects/blob/main/javascript/PASSWORD_GENERATOR.md) - Submitted by sqwyer
### Ping Pong game
Build a simple ping pong game using JavaScript, [View Project](https://github.com/sqwyer/projects/blob/main/javascript/PING_PONG_GAME.md) - Submitted by arpantaneja
### Bubble Shooter game
Build a simple Bubble Shooter game using JavaScript, [View Project](https://github.com/sqwyer/projects/blob/main/javascript/Bubble_Shooter.md) - Submitted by DheerajKumar
### Stick Ball game
Build a simple Stick Ball game using Javascript, [View Project](https://github.com/sqwyer/projects/blob/main/javascript/Stick_Ball.md) - Submitted by DheerajKumar
### 2048 game
Build a simple 2048 game using Javascript, [View Project](https://github.com/sqwyer/projects/blob/main/javascript/2048_Game.md) - Submitted by Dheeraj
### Maze game
Build a simple Maze game using Javascript, [View Project](https://github.com/sqwyer/projects/blob/main/javascript/Maze_Game.md) - Submitted by Dheeraj
## TypeScript projects
### Deno SQLite
Build a simple API for local SQLite instance in Deno with Typescript [View Project](https://github.com/sqwyer/projects/blob/main/typescript/SQLITE-SIMPLE-API.md) - Submitted by dergyitheron
## Python projects
### Automating Websites
In this project, you will use tools to automate a website using Python, [View Project](https://github.com/sqwyer/projects/blob/main/python/AUTOMATE_A_WEBSITE.md) - Submitted by Satyajeet-code
### Rock Paper Scissors game
In this beginner-friendly project, you will build a simple rock paper scissors game using Python, [View Project](https://github.com/sqwyer/projects/blob/main/python/ROCK_PAPER_SCISSORS.md) - Submitted by Harowo
### Image Compression using K-Clustering
In this beginner-friendly project, you will build a simple page to compress images by selecting no of clusters using Python , [View Project](https://github.com/sqwyer/projects/blob/main/python/Image_Compression.md) - Submitted by Astha
### Library Management System
In this beginner-friendly project, you will get to know how a library portal works. , [View Project](https://github.com/sqwyer/projects/blob/main/python/lms_project_readme.md) - Submitted by Sanjog
## C++ projects
###Text Based game
In this beginner-friendly project, you will build a text based game using C++, [View Project](https://github.com/sqwyer/projects/blob/main/C++/TEXT_BASED_GAME.md) - Submitted by <NAME>
<file_sep>/typescript/SQLITE-SIMPLE-API.md
# SQLite simple API
Goal of this project is to use Deno and Typescript and try to create simplest API for SQLite possible. SQLite is database in file that can sit in the same repository or initialized with the start of the app.
This project is based on my own and on the first iteration of it that is accessible in my profile. You can use it however you want.
## Hint(s)
<details>
<summary>How to get started</summary>
Visit [deno.land](https://deno.land/) to get Deno installed with your prefered way. After that, just create directory, file in it for example `api.ts` where you write your API and you can run it with `deno run api.ts -A` (because deno is really playing with security, -A allows all security measures to be eased, see docs for more detail).
</details>
<details>
<summary>SQLite Library</summary>
Use SQLite library for deno, if you could not find it, try [this link](https://deno.land/x/sqlite@v2.3.0). Import it with `import { DB } from "https://deno.land/x/sqlite/mod.ts";`
</details>
## Solution
Simplest iteration possible of this API with few endpoints for both SELECT and CREATE queries is [here](https://github.com/sqwyer/projects/tree/main/typescript/sqlite-simple-api/).
Submitted by [dergyitheron](https://github.com/dergyitheron)
<file_sep>/CONTRIBUTING.md
# How to get started
Please ensure that your pull request adheres to the following guidelines:
- Fork the repository by clicking the fork button on the top of the page. This will create an instance of that entire repository in your account.
- Once the repository is in your account, clone it to your machine to work with it locally.
To clone, click on the clone button and copy the link.
- Open the terminal and run the command ` git clone [HTTPS ADDRESS] `
- After cloning, enter the cloned directory by running the command `cd [NAME OF REPOSITORY]`
- Create a new branch by running `git checkout -b [Branch Name]`, you can name your branch whatever you want.
- make your neccessary changes then commit your changes to that branch.
- Push your changes to github `git push origin [Branch Name]`
- Go to your repository on GitHub and you’ll see a button “Compare & pull request” and click it. Then create your pull request.
## What should I do before I create my pull request?
- Make sure your contribution is not a duplicate.
- Make sure you have created a file named `YOUR_PROJECT_NAME.md` inside of the `project_langauage` folder! Ex. Todo List - Javascript -> `javascript/TODO_LIST.md`. (Make sure the name of the file is all caps, and that the folder names are all lowercae with underscores seperating spaces)
- Make sure that if you provide a solution it is in the `project_language/project_name/` directorty, please follow the same naming guidelines for the project language directories (lowercase, use \_'s as spaces)
- Update the README to add your project.
**Please note that if all of these are not completed, you will be asked to add them yourself before the PR being merged.**
Happy coding :relaxed:
# License & Attribution
This Project is available under the [MIT License](https://github.com/sqwyer/projects/blob/main/LICENSE)
<file_sep>/javascript/2048_Game.md
# Build a 2048 Game
In this project, you will create a 2048 game using JavaScript!
## Solution
Navigate to the `~/javascript/2048/` directory, there, you will find the JavaScript and HTML files required for this!
Submitted by Dheeraj<file_sep>/javascript/store_kata/README.MD
TO RUN TEST INSTALL JASMINE TESTING FRAMEWORK GLOBALLY
TO RUN TESTS
npx jasmine **/*spec.js
<file_sep>/C++/textbasedgame/textbasedgame.cpp
#include <iostream>
#include <string>
using namespace std;
// A struct to represent one "page" of the game. IE: a page is where
// you print some text, then ask the user for input on what they want
// to do next.
//
// Pages can lead to other pages, like a choose your own adventure book.
//
// Or pages can lead to a "game over"
struct Page
{
string text; // the text displayed to the user when they're on this page
int options; // the number of options available to the user. If <= 0,
// then this indicates the user has no options because
// they died / got a game over.
int nextpage[10]; // The next page to go to depending on which option the user
// selected.
};
/*
THE DATA
Here is where we'll have all of our pages defined. Note we don't really have
any code here... this is just data. We're defining what the game world is...
NOT how the game world works.
(note that the way this is stored is not ideal -- but I'm just trying to show a
conceptual example here)
*/
const Page gamePages[] = {
////////////////////////////////////////////
// Page 0: The start of the game
{
"Welcome to your adventure. Which character would you like?\n" // the flavor text
"(1 for knight, 2 for samurai)\n",
2, // number of options available to user
{1,4} // if they choose option 1, go to page 1
// if they choose option 2, go to page 4
},
////////////////////////////////////////////
// Page 1: Knight selected
{
"You have chosen to become a knight.\n" // flavor text
"Welcome to the land known as Chronia.\n"
"Their is a strangely dressed women. Do you approach her? (1 for y, 2 for n)\n",
2, // 2 options
{2,3} // option 1 -> page 2
// option 2 -> page 3
},
////////////////////////////////////////////
// Page 2: Knight selected, approaching woman
{
"You ask the women who she is and she replies I AM THE GREAT MICHELLINA\n"
"How do I get back home? I DO NOT KNOW BUT IF YOU CAN GUESS IN WHICH HAND I HAVE THE ORB\n"
"I WILL GET YOU BACK HOME. Which hand is it in? (1 for left, 2 for right)\n",
2,
{0,0} // TODO: fill in your options here. I have both options
// going back to page 0
},
////////////////////////////////////////////
// Page 3: Knight selected, not approaching woman
{
"You do not approach her and get your head sliced off by an incoming horseman.\n"
"Game Over. You suck at adventure games.",
0, // 0 options because they got game over
{}
},
////////////////////////////////////////////
// Page 4: Samurai selected
{
"You have chose to become a samurai.\n"
"Welcome to the land know as Remian.\n"
"Their is another samurai charging at you. Do you attack them? (1 for y, 2 for n)\n",
2,
{5,0} // option 1 -> page 5
// option 2 -> (TODO - fill in your next page... I have it going back to the start)
},
////////////////////////////////////////////
// Page 5: Samurai selected, attacking other samurai
{
"The samurai head goes flying off and the horse bucks his body off and runs away scared.\n"
"You search his body and find a key and a map to get back home.\n"
"Do you want to get back home? (1 for y, 2 for n)\n",
2,
{0,0} // TODO - fill in next pages
}
};
/*
THE CODE / LOGIC
Now that we have all the game data set up... the code can use that data to actually drive the game.
*/
// the 'doPage' function will do the logic for the given 'page' parameter.
// It will return the next page that the user will go to, or will return -1
// if the user died / got game over.
int doPage(int page)
{
// Page logic is simple: output the flavor text
cout << gamePages[page].text;
// If the user has no options, they got game over
if(gamePages[page].options <= 0) // no options
return -1; // return -1 to indicate game over
// otherwise, if they did not get game over, get their selection
int selection;
cin >> selection;
// make sure their selection is valid
while( selection < 1 || // invalid selections are less than 1
selection > gamePages[page].options // or are greater than the number of available options
)
{
cout << "That is an invalid selection. Please try again.\n";
cin >> selection;
}
// their selection is valid.... so return the next page number to go to
return gamePages[page].nextpage[ selection-1 ]; // note we have to subtract 1 here
// because our selection ID starts at 1
// but array indexes start at 0
}
/*
MAIN
Since doPage does all the logic, main is very simple. It just keeps calling
doPage until the user gets game over.
*/
int main()
{
int currentPage = 0; // start at page 0
while(currentPage >= 0) // as long as they don't have game over...
{
//... do a page
currentPage = doPage(currentPage);
}
return 0;
}
<file_sep>/javascript/bubbleshooter/main.js
let s,i,j;//shooter
let b=[];//bubble
let r=15;//radius of bubble
let row=11,col=16;
let bull=[];
var k;
function setup(){
s=new shooter();
for(i=0;i<row;i++){
b[i]=[];
for(j=0;j<col-2*i;j++){
b[i][j+i-1]=new bubble(i,j+i-1);
}
}
createCanvas(600,400);
}
function draw(){
background(204,204,255);
s.show();
for(i=0;i<row;i++){
for(j= 0;j<col-2*i;j++){
b[i][j+i-1].show();
for(k=0;k<bull.length;k++){
if(b[i][j+i-1].exist==1 && (dist(b[i][j+i-1].x,b[i][j+i-1].y,width/2+4+bull[k].os.x+s.os.x,height+bull[k].os.y+s.os.y)<r ||
dist(b[i][j+i-1].x,b[i][j+i-1].y,width/2+4+bull[k].os.x+s.os.x-bull[k].os2.x,height+bull[k].os.y+s.os.y-bull[k].os2.y)<r)){
bull.splice(k,1);
b[i][j+i-1].exist=0;
b[i][j+i-1].spread(i,j+i-1);
}
}
}
}
for(i=0;i<bull.length;i++){
bull[i].show();
}
if(keyIsDown(LEFT_ARROW))
s.rotate(-1);
if(keyIsDown(RIGHT_ARROW))
s.rotate(1);
}
function keyPressed(){
if(keyCode==38){
bull[bull.length]=new bullet(s.os.heading());
}
}<file_sep>/javascript/STONE_PAPER_SCISSORS.md
# Stone Paper Scissors
In this project you will create a basic game of stone paper scissors (rock paper scissors)! Stone beats scissors, scissors beats paper, paper beats stone. You should create this project without any external libraries! Good luck.
## Solution
Navigate to the `~/javascript/rstone_paper_scissors` directory in htis repository, there you will see all of the files in the solution!
Submitted by eswarupkumar
<file_sep>/index.md
# A list of super awesome projects!
This repository is maintained by [@Sqwyer](https://github.com/sqwyer)!
## Want to view the list?
I know that it's often hard to get project ideas, wether you want to learn, want to build your resume, or just want to have fun, this repository for you! You can see all of the projects on the GitHub page, [here](https://github.com/sqwyer/projects)!
## Want to contribute?
Do you have a project that you think would be fun and/or useful for others? Great! You should create a pull request on the projects repository and add your project ideas! We take part in Hacktoberfest, so if you ever need to get some PRs in for Hacktoberfest, you can add a project here! Just make sure to read the contributing guidelines before you make your PR!
## License
This project is licensed under the MIT license.
Made with <3
<file_sep>/javascript/FORM_VALIDATOR.md
# Form Validator
In this project, you will create a simple form validator using regex concept in javascript.
## Solution
Navigate to the `~/form_validator/` directory, there, you will find the JavaScript and HTML files required for this!
Submitted by Amrutha26<file_sep>/javascript/stickball/balls.js
class balls{
constructor(){
this.r=10;
this.x=100;
this.y=200;
}
create(){
fill(255,0,0);
noStroke();
ellipse(this.x,this.y,this.r*2,this.r*2);
if(life>0)
this.y+=1;
}
move(a,b){
this.x+=5*a;
this.y+=5*b;
}
}<file_sep>/python/lms_project/lib_mod_db.py
import sqlite3
connect_lib = sqlite3.connect('library.db')
lib = connect_lib.cursor()
lib.execute('CREATE TABLE IF NOT EXISTS recordtolist(sicno INTEGER,bookname TEXT)')
#ISSUE BOOK
def issue_func():
sicno = int(input('\nEnter SIC no.: '))
book_name = input('Enter book name: ')
lib.execute('SELECT bookname FROM recordtolist WHERE sicno = (?)',(sicno,))
compare_bookname_tup = lib.fetchone()
try:
compare_bookname = compare_bookname_tup[0]
except:
compare_bookname = None
if compare_bookname != book_name:
lib.execute('SELECT no_of_book FROM booktolist WHERE name = (?)',(book_name,))
modify_no_books_tup = lib.fetchone()
try:
modify_no_books = modify_no_books_tup[0]
except:
modify_no_books = None
lib.execute('SELECT count FROM studenttolist WHERE sicno = (?)',(sicno,))
count_tup = lib.fetchone()
try:
count = count_tup[0]
except:
count = None
print('\nNo of copies of the book available are:: ',modify_no_books)
print('The student has issued total ',count,' books before')
if count < 2 and modify_no_books != None and modify_no_books != 0 and count != None:
count += 1
modify_no_books -= 1
lib.execute('INSERT INTO recordtolist VALUES(?,?)',(sicno,book_name))
connect_lib.commit()
lib.execute('UPDATE studenttolist SET count = (?) WHERE sicno = (?)',(count,sicno))
connect_lib.commit()
lib.execute('UPDATE booktolist SET no_of_book = (?) WHERE name = (?)',(modify_no_books,book_name))
connect_lib.commit()
print('\nThe book has been succesfully issued')
elif modify_no_books == None or count == None:
print('\nAn error occured because SIC no or book name do not exist. Please try again')
elif modify_no_books == 0:
print('\nNo more copies of the book are left')
elif count >= 2:
print('\nThe student has issued more than 2 books. Cannot issue more')
else:
print('You cannot issue same book more than once')
#RETURN BOOK
def return_func():
sicno = int(input('\nEnter SIC no.: '))
book_name = input('Enter book name: ')
lib.execute('SELECT no_of_book FROM booktolist WHERE name = (?)',(book_name,))
modify_no_books_tup = lib.fetchone()
try:
modify_no_books = modify_no_books_tup[0]
except:
modify_no_books = None
lib.execute('SELECT count FROM studenttolist WHERE sicno = (?)',(sicno,))
count_tup = lib.fetchone()
try:
count = count_tup[0]
except:
count = None
if count > 0 and count != None:
count -= 1
modify_no_books += 1
lib.execute('DELETE FROM recordtolist WHERE bookname = (?) AND sicno = (?)',(book_name,sicno))
connect_lib.commit()
lib.execute('UPDATE studenttolist SET count = (?) WHERE sicno = (?)',(count,sicno))
connect_lib.commit()
lib.execute('UPDATE booktolist SET no_of_book = (?) WHERE name = (?)',(modify_no_books,book_name))
connect_lib.commit()
print('The book has been successfully return')
else:
print('He has not issued any book from library')
#LIST OF BOOKS ISSUED BY A STUDENT
def books_by_student(student_sicno):
print('\nList of Books issued by the student are: ')
lib.execute('SELECT bookname FROM recordtolist WHERE sicno = (?)',(student_sicno,))
bookname_tup = lib.fetchall()
for i in bookname_tup:
print(i[0])
#LIST OF STUDENTS ISSUED A BOOK
def students_fora_book(book_name):
print('\nList of students who took the book are: ')
lib.execute('SELECT sicno FROM recordtolist WHERE bookname = (?)',(book_name,))
sicno_tup = lib.fetchall()
for i in sicno_tup:
lib.execute('SELECT name FROM studenttolist WHERE sicno = (?)',(i[0],))
store_name = lib.fetchone()
print('\nName of the Student: ',store_name[0],'\nSIC no.: ',i[0])
#CHOICE IN LIBRARY
def choice():
while True:
print('\nWelcome to Librarian portal')
choice = input('\nChoices:\n1. Issue a book\n2. Return a book\n3. List of books\n4. List of books issued by a student\n5. List of students who took a book\n6. Back\nEnter your choice: ')
if choice == '1':
issue_func()
elif choice == '2':
return_func()
elif choice == '3':
print('\nList of Books are: ')
lib.execute('SELECT * FROM booktolist')
for row in lib.fetchall():
print('\nBook name: ',row[0],'\nAuthor name: ',row[1],'\nNo. of copies: ',row[3])
elif choice == '4':
sicno = int(input('Enter the SIC no.: '))
books_by_student(sicno)
elif choice == '5':
bname = input('\nName of the book: ')
students_fora_book(bname)
elif choice == '6':
print('Exited Library Module')
break
else:
print('Invalid choice')
#choice()<file_sep>/javascript/HEXCOLOR_GENERATOR.md
# Build a Randox Hexcolor generator
In this project, you will create a basic hexcolor generator using javascript
## Solution
Navigate to the `~/hexcolor_generator/` directory, there, you will find the JavaScript and HTML files required for this!
Submitted by Amrutha26
| 618a0a8537efd0d9dc95042b76618d5b2490c8dc | [
"JavaScript",
"Markdown",
"Python",
"TypeScript",
"C++"
] | 44 | JavaScript | SanjogSamuelSamantaray/projects | dd1e1bb76dce3ad4f5100a83fd6995ce30f29553 | 130bd99db56aeb0a0f7b03ad9e485480f1f9c0d3 |
refs/heads/master | <repo_name>parav01d/re-qui-en<file_sep>/content/2020-02-13-dont-make-me-think.md
---
date: 2020-02-13
title: "Don't Make Me Think: A Common Sense Approach to Web Usability"
cover: "/images/dont-make-me-think.jpg"
categories:
- Books
tags:
- ui
- ux
---
## About the Book
<NAME> knows how to explain the user experience approach in a fun and easy-to-understand way. Everyone who has something to do with the web should take a look, not just the UX Designer. However, some examples are quite out of date. For the experienced experts, I would recommend other books that contain current practical examples and go into more detail.
<file_sep>/content/2020-02-13-machine-learning.md
---
date: 2020-02-13
title: "Machine Learning: The New AI"
cover: "/images/machine-learning.jpg"
categories:
- Books
tags:
- data science
- machine learning
---
## About the Book
The book offers a few pages an overview of the area of machine learning. The various techniques are clearly explained and are followed by examples of their use. The implementation details are not dealt with, the book is quite understandable. I recommend it to everyone who wants to get a quick overview of the application areas of "machine learning".
<file_sep>/content/2020-02-13-command-query.md
---
date: 2020-02-13
title: "Command - Query"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters. Since I am using use cases to encapsulate the business logic I only use commands and queries as data transfer objects with validation rules.
## Example
In this Example we take a look at a create user command. I use the `class-validator` framework to define validation rules for the input information. Later in the use case we can validate this command and create an validation error on failure.
```javascript
export class CreateUserCommand {
@IsNotEmpty()
@IsString()
public readonly name: string;
@IsNotEmpty()
@IsInt()
public readonly age: number;
constructor(payload: { name: string, age: number }) {
this.name = payload.name;
this.age = payload.age;
}
}
```
<br></br>
The following example shows the query variant of this pattern. Because the most queries to our system will follow the same structure we can use an abstract implementation to unify input parameters like pagination or id filter.
```javascript
export class GetUserQuery extends AbstractQuery {
constructor(payload: { id?: string, pagination?: Pagination }) {
this.id = payload.id;
this.pagination = payload.pagination;
super();
}
}
```
<br></br>
The way the information get passed to the Commands and Queries is shown in the [Front Controller Pattern](/front-controller)
<file_sep>/content/2020-12-30-paracry-rules.md
---
date: 2020-12-31
title: "Rules"
cover: "/images/paracry.png"
categories:
- ParaCry
tags:
- paracry
- tabletop
---

<br/>
## Why do we play ParaCry instead of Warcry?
A year ago I started playing WarCry and since I didn't like the two standard warbands, I bought a Start Collecting Box from Maggotkin of Nurgle - Rotbringers. Like all Rotbringers players, I was more than disappointed with the opportunities I had in WarCry. The entire game was completely unbalanced and lacked not only units but also meaningful skills. At the end of 2020 the new Grand Alliance books came out and the new units made many warbands more interesting. However, the abilities "Onslaught" and "Haste" were the only ones played besides the four-in-hand.

With my new game board, the games were now even more boring, as the weaknesses of the individual factions were even more evident. Some factions had what felt like 100 different units and others only 10. To bring everything back into line I decided to develop this game. The individual factions are subdivided again and have skills that are tailored to the individual units. Each faction also has a passive ability that is supposed to better bring out the variety of the subgroup. The Points and Attributes of the Units stay untouched so you can still use your cards and books (2020).
<br/>
## Rules
I really like the simplicity of the WarCry rules so all of them staying untouched, except by the specific units with specific abilities for each subgroup of a fraction.
## Legend
### Unit
❤ Life
🦵Movement
🛡Toughness
### Weapon
📏 Range
🎲 Number of Dices per Attack
💪 Strengt
🩸 Damage ( hit / crit )
### Game
🤾 Disengage
🏃 Move Action
🤼 Attack Action
## Game Development
We play one or two times a week with this rules and change them from time to time. At the beginning the Rules will be changed often because we balance the game by playing it.
## Wishes for Improvement
You can send me your change request via mail at tkunzema[at]gmail[dot]com
If you are familiar with development place your pull request here: https://github.com/parav01d/re-qui-en
<file_sep>/content/2020-02-13-the-tao-of-programming.md
---
date: 2020-02-13
title: "The Tao of Programming"
cover: "/images/the-tao-of-programming.jpg"
categories:
- Books
tags:
- ethic
---
## About the Book
This is the Definitive book to programming humor and realism. Only Hard Core programmers can understand its wisdom.
>The wise programmer is told about the Tao and follows it. The averate programmer is told about the Tao and searches for it. The foolish programmer is told about the Tao and laughs at it.
(chapter 1.4)
<file_sep>/content/2020-11-02-warcry-board.md
---
date: 2020-11-02
title: "Modular Warcry Board"
cover: "/images/warcry.png"
categories:
- Tabletop
tags:
- warcry
- tabletop
---
## Modular Warcry Board
Hello Fellows, I've been building my Warcry Board for half a year now. After showing it on [Reddit](https://www.reddit.com/r/WarCry/comments/jksw50/showcase_modular_warcry_board/?utm_source=share&utm_medium=web2x&context=3), I was asked how it came about and what steps I took. This is the story of deadly pandemics and happy quarantines.
<br></br>
### My Birthday Party

As always, I got a lot of toys for my birthday. This time it was all about Warhammer Age of Sigmar and Warcry. But this time there was that special moment when I got 1 kilogram of printable material. I don't know how much a kilogram is, but at first I assumed it was a lot but the future will teach me better.
<br></br>
### Looking For 3D Printing Files
At first I tried [Ulvheim Szenario](https://www.thingiverse.com/thing:2762318) but after taking a look at the ~500 little bit different parts, I gave up. After a few days of procrastinating I found [Infinite Dimensions Games](https://www.infinitedimensions.ca/). They have some cool [Map Tiles](https://www.infinitedimensions.ca/product/medieval-cobbled-streets/), [Walls](https://www.infinitedimensions.ca/product/medieval-modular-3d-printable-walls/) and [Gantries](https://www.infinitedimensions.ca/product/improvised-defence-gantries/). I thought a combination of these three elements will be a good fundament for a warcry board for competitive gaming ( Catacombs will be released in a half year at this Point).
<br></br>
### Everything Needs A Plan

After spending some time in Keynote putting together a combination of map tiles, walls and gantries with various shapes and colors, the conception phase failed to display the entire project in 3D with visualization software. The Mc Gyver in me was armed with scissors and cardboard within a short time and the individual parts (12 "x 12") could be put together for the first time as a test.
<br></br>
### The Print Job Gift

After we have calculated everything, we have come to 3.5 kilograms of material. But the Lord was gracious and just took it and started printing.
<br></br>
### Painting The Walls

The printed parts are not 100% waterproof, so I primed all parts with [Abaddon Black](https://www.games-workshop.com/en-AU/Base-Abaddon-Black-2019) first. To better prepare the surface for the next layers. I've read a lot about sanding the surfaces with 500 grit sandpaper, however I decided against it because it looks not THAT bad and I am more the player then the painter.
<br></br>

After the primer I applied a layer [Rakarth Flesh](https://www.games-workshop.com/en-AU/Base-Rakarth-Flesh-2019) and painted 50% of the stones with [Bugman's Glow](https://www.games-workshop.com/en-AU/Base-Bugmans-Glow-2019), [Balor Brown](https://www.games-workshop.com/en-AU/Layer-Balor-Brown-2019) and [Zandri Dust](https://www.games-workshop.com/en-AU/Base-Zandri-Dust-2019). I used [Leadbelcher](https://www.games-workshop.com/en-AU/Base-Leadbelcher-2019) for the grille but that should be clear visible. Maybe you ask yourself why I use [Rakarth Flesh](https://www.games-workshop.com/en-AU/Base-Rakarth-Flesh-2019) instead of a more greyish color. On the one hand, the base color becomes very gray after the shade, on the other hand, the flesh color gives a warmer result. In the end, you still play the game at the kitchen / living room table. It should stay cozy there.
<br></br>

A coat or two of [Nuln Oil](https://www.games-workshop.com/en-AU/Shade-Nuln-Oil-2019) later, the wall should look something like this.
<br></br>

Now you can drybrush with [Rakarth Flesh](https://www.games-workshop.com/en-AU/Base-Rakarth-Flesh-2019) again and you will see that the bright colors disappear and a beautiful wall results.
<br></br>

Then a little [Typhus Corrosion](https://www.games-workshop.com/en-AU/Technical-Typhus-Corrosion-2019) with [Ryza Rust](https://www.games-workshop.com/en-AU/Dry-Ryza-Rust-2019) and the wall is ready for use. But keep in mind, there are a hell of a lot of walls.
<br></br>
### Painting The Roof

Here we are again painting the whole surface with [Rakarth Flesh](https://www.games-workshop.com/en-AU/Base-Rakarth-Flesh-2019) after priming everything with [Abaddon Black](https://www.games-workshop.com/en-AU/Base-Abaddon-Black-2019).
<br></br>

Now I painted 5-10% of the stones with [Bugman's Glow](https://www.games-workshop.com/en-AU/Base-Bugmans-Glow-2019), [Balor Brown](https://www.games-workshop.com/en-AU/Layer-Balor-Brown-2019) and [Zandri Dust](https://www.games-workshop.com/en-AU/Base-Zandri-Dust-2019) and a blue and green I don't remember. But for real who cares? Except for the way, I smeared the entire plate with [Nuln Oil](https://www.games-workshop.com/en-AU/Shade-Nuln-Oil-2019).
<br></br>

After adding a lot of sunlight, all I had to do was coat the paths with [Agrax Earthshade](https://www.games-workshop.com/en-AU/Shade-Agrax-Earthshade-2019) and as soon as everything was dry, I went over it with the makeup brush and [Rakarth Flesh](https://www.games-workshop.com/en-AU/Base-Rakarth-Flesh-2019).
<br></br>

So that you can distinguish the panels from the walls at the end, I added a little bit of [Biel-Tan Green](https://www.games-workshop.com/en-AU/Shade-Biel-Tan-Green-2019) and [Coelia Greenshade](https://www.games-workshop.com/en-AU/Shade-Coelia-Greenshade-2019).
Pro Tip: Be careful with the [Coelia Greenshade](https://www.games-workshop.com/en-AU/Shade-Coelia-Greenshade-2019). It looks a little bit unrealistic.
<br></br>
### Painting The Gantries

Ha HA ha! We had some smaller issues printing these little piles of wood. But who cares because this is way more realistic. Not every gantry look the same in real, checkout your city for comparison. No gantries? You should take over the city while it's unprotected.
<br></br>

I forgot to take a series of photos about it, but the whole thing is not as spectacular as it looks. I primed 50% of the woods with [Dryad Bark](https://www.games-workshop.com/en-NZ/Base-Dryad-Bark-2019) and 50% of the woods with [Rhinox Hide](https://www.games-workshop.com/en-NZ/Base-Rhinox-Hide-2019). Please make sure that the first 50% are different then the second 50%, otherwise a part will remain black. Now you brush part of [Mournfang Brown](https://www.games-workshop.com/en-NZ/Base-Mournfang-Brown-2019), part of [Mournfang Brown](https://www.games-workshop.com/en-NZ/Base-Mournfang-Brown-2019) mixed with [Mephiston Red](https://www.games-workshop.com/en-NZ/Base-Mephiston-Red-2019) and part of [Mournfang Brown](https://www.games-workshop.com/en-NZ/Base-Mournfang-Brown-2019) mixed with [Averland Sunset](https://www.games-workshop.com/en-NZ/Base-Averland-Sunset-2019). If I remember correctly I used [Zandri Dust](https://www.games-workshop.com/en-NZ/Base-Zandri-Dust-2019) with a layer of [Ushabti Bone](https://www.games-workshop.com/en-NZ/Layer-Ushabti-Bone-2019) for the Ropes.
<br></br>
### Testing The Board

Honestly, the first game was awesome. We tried not to climb over the wall and to keep the targets shielded by the walls (it was not possible to take a target through a wall). The whole game felt much more balanced and strategic. I would assume the current Catacombs set plays very similarly. One of my friends plays <NAME> and asked me if we might get a few heights. We will see ...
<br></br>
### A Dream About Heights and Lows

At some point I got this picture suggested on Instagram and thought: This is exactly what we need. So I looked on Amazon for hard foam blocks with 6 "to 6" with different heights and found [these ones](https://www.amazon.de/Sculpture-Block-151550-Hartschaumblock-Modellierblock/dp/B01E5WMYO8). There are cheaper alternatives out there and I can recommend trying another one because these are very crumbly.
<br></br>
### PU Foam Boxes From Hell

I'm very bad at drawing straight lines with the hobby knife aka the kitchen knife. That's why I opted for the more expensive variant, in which the boxes already have the finished dimensions. They have three different versions: [flat](https://www.amazon.de/Sculpture-Block-Hartschaumblock-Modellierblock-anfertigen/dp/B00W9WVBUK), [mid](https://www.amazon.de/Sculpture-Block-151550-Hartschaumblock-Modellierblock/dp/B01E5WMYO8), and [height](https://www.amazon.de/Sculpture-Block-151575-Hartschaumblock-Modellierblock/dp/B01E5WMZAG).
<br></br>

I tried a little to see if I could put together enough combinations with the given boxes. It was not that easy because I already printed the roof plates with different street styles.
<br></br>

Look at that! That was about the point where I started wearing a mask. There is no warning sign on the packaging, but after the bridge I felt like I had shortened my life by about 2 years.
<br></br>

I thought it might be a nice idea to freshen up the water with a few highlights. I'm supposed to be right, it was a good idea.
<br></br>

That's not what it looks like: Small PU foam blocks in hibernation. No no, I brushed all of them with a layer of epoxy resin and laid them on different surfaces to dry. A few of these were a good idea and a few others weren't.
<br></br>

I spent several hours removing the cork sheet from the rock-hard foam blocks. Protip at this point: wear a mask! Epoxy resin dust is toxic.
<br></br>

The blocks get really hard, so really hard. That's why I put these little cushions on to not ruin my table. By the way, you will have noticed that I primed all the blocks with [Abaddon Black](https://www.games-workshop.com/en-AU/Base-Abaddon-Black-2019).
<br></br>

Here we are again, this is the part where we painting the walls (again). After the primer I applied a layer [Rakarth Flesh](https://www.games-workshop.com/en-AU/Base-Rakarth-Flesh-2019) and painted 50% of the stones with [Bugman's Glow](https://www.games-workshop.com/en-AU/Base-Bugmans-Glow-2019), [Balor Brown](https://www.games-workshop.com/en-AU/Layer-Balor-Brown-2019) and [Zandri Dust](https://www.games-workshop.com/en-AU/Base-Zandri-Dust-2019). Maybe you ask yourself why I use [Rakarth Flesh](https://www.games-workshop.com/en-AU/Base-Rakarth-Flesh-2019) instead of a more greyish color. On the one hand, the base color becomes very gray after the shade, on the other hand, the flesh color gives a warmer result. In the end, you still play the game at the kitchen / living room table. It should stay cozy there.
<br></br>

Yeah it's okay.
<br></br>

Adding some Details here ...
<br></br>

... and there.
<br></br>
### Epoxy Me A River

After watching [this](https://www.youtube.com/watch?v=2TwpB7sVMn8) video everything was clear. I had to do my part for the corona pandemic and buy a lot of toilet paper. On principle!
<br></br>

I covered three layers of toilet paper with a layer of wood glue diluted with water. With the tip of a thick brush, I carefully pressed the waves out. It's hard to describe, but it comes about when you do it yourself.
<br></br>

This is the result if the first evening. Now everything needs 72h to dry.
<br></br>

When it dries it looks something like this.
<br></br>

Now I've applied a thick coat of [Creed Carmo](https://www.games-workshop.com/en-NZ/Creed-Camo-2019). Be careful it needs some time to dry. Now the edges can be shaded with [Agrax Earthshade](https://www.games-workshop.com/en-NZ/Shade-Agrax-Earthshade-2019) and [Athonian Camoshade](https://www.games-workshop.com/en-NZ/Shade-Athonian-Camoshade-2019).
<br></br>

After priming the copper pipe with Abaddon Black I had to create something again that looks like a copper pipe. A layer of [Balthasar gold](https://www.games-workshop.com/en-NZ/Base-Balthasar-Gold-2019) shaded with [Reikland Fleshshade](https://www.games-workshop.com/en-NZ/Shade-Reikland-Fleshshade-2019) ( no gloss! ). Finally I added some highlights with [Nihilakh Oxide](https://www.games-workshop.com/de-DE/Technical-Nihilakh-Oxide-2019).
<br></br>
### Special Parts

This is a special part that works on its own as a 1 inch plate and is otherwise suitable for raising another block by 1 inch.
<br></br>
# The Result

<br></br>

<br></br>

<br></br>

<br></br>

<br></br>
<file_sep>/content/2020-02-23-magical-triangle.md
---
date: 2020-02-23
title: "Magical Triangle"
cover: "/images/empty-red.png"
categories:
- Management
tags:
- management
links:
- add-book-link-here
---
## About this technique
Did you ever heard about the "Magical Triangle"? As a developer I have nearly 50 every day use principles and patterns in my mind. Each of them are really straight forward like "Dependency-Inversion"-Principle or "Single-Responsibility"-Principle and now I make my first steps in project management and read something like "Magical Triangle". I mean "Magical Triangle" ... is this the way you economically savvy dudes name patterns? To make it short here is what it means:
The Success of the Project depends on the following 3 Parameters:
- time
- money
- quality
and these Parameters should be balanced to avoid:
- delay
- overpay
- poor quality / over engineering
Thats it, not more, not less. For real, if YOU call this "Magical"? You should spend some years in software development and you will understand, this is a very oversimplified pattern without any magic at all. Pffft.. magical .. You know there was a man and he had to debug a app which would crash very rarely. It would only fail on Wednesdays -- in September -- after the 9th. Yes, 362 days of the year, it was fine, and three days out of the year it would crash immediately. The system would format a date as "Wednesday, September 22 2008", but the buffer was one character too short -- so it would only cause a problem when you had a 2 digit DOM on a day with the longest name in the month with the longest name - Finding this Bug is magical.
<file_sep>/content/2020-02-13-the-hacker-ethic.md
---
date: 2020-02-13
title: "The Hacker Ethic: and the Spirit of the Information Age"
cover: "/images/the-hacker-ethic.jpg"
categories:
- Books
tags:
- ethic
---
## About the Book
I mean its the hacker ethic. You should read it.
<file_sep>/content/2020-02-26-stakeholder-monitoring.md
---
date: 2020-02-26
title: "Stakeholder Monitoring"
cover: "/images/empty-red.png"
categories:
- Management
tags:
- management
---
## About this technique
The initial analysis of stakeholders are not enough if you have a bigger group of it. The best way to have an easy overview is to make a chart with to axis.
The first one is the conflict potential and the second one is the influence of the stakeholder on the project. Now you set a marker of each stakeholder on this chart and move them, depending on your email communication and other influences, to their actual position. Now you have an every day overview about the current situation of your stakeholders.
* You should pay the most attention to the stakeholders who are on the top right of your visualization, because they have the greatest influence and potential for conflict.
* Then you should focus on the stakeholders who have a lot of influence but no potential for conflict - they are in the box at the top left.
Stakeholders can be a big win on the one hand, but also a risk for the project on the other. Good stakeholder management is therefore very helpful for project success.
<file_sep>/content/2020-02-11-patterns-of-enterprise-application-architecture.md
---
date: 2020-02-11
title: "Patterns of Enterprise Application Architecture"
cover: "/images/patterns-of-enterprise-application-architecture.jpg"
categories:
- Books
tags:
- clean code
- architecture
---
## About the book
<NAME> has once again written an upcoming classic. In the first part of the book, numerous basic aspects and questions to which software architecture is exposed are discussed and the possible solution compared. I have been looking for such an overview for a long time. In the second part, Fowler uses the pattern form to detail individual aspects, i.e. also to look at the implementation. In contrast to many other Patterns books, the chosen form is not very formal, easy to read and appropriate to the problems.
Some people say that the book by the Gang of Four contains the most important patterns, but this book should be mandatory reading for every engineer of enterprise applications!
<file_sep>/content/2020-03-18-dependency-injection-container.md
---
date: 2020-03-18
title: "Dependency Injection Container"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
### Here is how a code _not_ using DI will roughly work:
- Application needs Foo (e.g. a controller), so:
- Application creates Foo
- Application calls Foo
- Foo needs Bar (e.g. a service), so:
- Foo creates Bar
- Foo calls Bar
- Bar needs Bim (a service, a repository, …), so:
- Bar creates Bim
- Bar does something
### Here is how a code using DI will roughly work:
- Application needs Foo, which needs Bar, which needs Bim, so:
- Application creates Bim
- Application creates Bar and gives it Bim
- Application creates Foo and gives it Bar
- Application calls Foo
- Foo calls Bar
- Bar does something
This is the pattern of Inversion of Control. The control of the dependencies is inverted from one being called to the one calling.
The main advantage: the one at the top of the caller chain is always you. You can control all dependencies and have complete control over how your application works. You can replace a dependency by another (one you made for example).
For example what if Library X uses Logger Y and you want to make it use your logger Z? With dependency injection, you don't have to change the code of Library X.
### Now how does a code using PHP-DI works:
- Application needs Foo so:
- Application gets Foo from the Container, so:
- Container creates Bim
- Container creates Bar and gives it Bim
- Container creates Foo and gives it Bar
- Application calls Foo
- Foo calls Bar
- Bar does something
In short, the container takes away all the work of creating and injecting dependencies.
<br></br>
## Typescript Example
In my Typescript applications I use "inversify" as my recommended dependency injection container. It works straight forward and has a nice documentation.
<br></br>
As a part of my front controller, the routes file contains the root container and provide all controller functions:
```javascript
class Routes {
static TRACKING_TRACK_INTERACTION = "TRACKING_TRACK_INTERACTION";
private container: Container;
private trackingInteractionController: ITrackingInteractionController;
public getRoutes() {
return [
{
path: "/tracking/interaction",
name: Routes.TRACKING_TRACK_INTERACTION,
method: "post",
action: this.trackingInteractionController.trackInteraction.bind(this.trackingInteractionController),
middlewares: [this.fetchCurrentUser.bind(this)],
documentation: {
payload: "TrackInteractionCommand",
resource: null,
resources: null
}
}
];
}
public getContainer(): Container {
return this.container as Container;
}
public setContainer(container: Container) {
this.container = container;
}
public initializeContainer() {
this.container = Container.merge(DependencyInjectionContainer, FrameworkContainer) as Container;
}
public initializeDependencies() {
this.trackingInteractionController = this.container.get<ITrackingInteractionController>(TrackingControllerModule.InteractionController);
}
public async fetchCurrentUser(request: Request, _: Response, next: NextFunction) {
...
next();
}
}
```
<br></br>
In the bootstrapping process of my application I initialise the routes like this (using Express):
```javascript
const app = express();
app.use(cors());
app.use(bodyParser.json());
const routes = new Routes();
routes.initializeContainer();
routes.initializeDependencies();
routes.getRoutes().forEach((route) => {
console.log(`[${route.method.toUpperCase()}]${route.path}`);
if (route.middlewares.length > 0) {
app.use(route.path, ...route.middlewares);
}
app[route.method](route.path, (request: Request, response: Response, next: any) => {
route.action(request, response)
.then(() => next)
.catch((err: any) => next(err));
});
});
```
<br></br>
In my E2E tests I use the "cucumber" library and an instance of my application in their "world"-object, now I can rebind all dependencies in the container for test purposes. In the following example I mock the email and crypto service to prevent sending emails and hashing my passwords etc.:
```javascript
this.appRoutes.initializeContainer();
const appContainer = this.appRoutes.getContainer() as Container;
// rewire dependencies
appContainer.unbind(FrameworkServiceModule.MailService);
appContainer.bind<IMailService>(FrameworkServiceModule.MailService).to(MockEmailService);
appContainer.unbind(FrameworkServiceModule.CryptoService);
appContainer.bind<ICryptoService>(FrameworkServiceModule.CryptoService).to(MockCryptoService);
// setup dependencies for routes
this.appRoutes.setContainer(appContainer);
this.appRoutes.initializeDependencies();
```
<file_sep>/src/components/Footer.js
import React from 'react'
import styles from './Footer.module.scss'
import config from '../../data/SiteConfig'
const Footer = () => (
<footer>
<div className={styles.container}>
<div>
<a
styles={{color: "#fff"}}
href={`https://github.com/${config.userGitHub}`}
target="_blank"
rel="noopener noreferrer"
>
GitHub
</a>
</div>
<div className={styles.copyright}>{config.copyright}</div>
<div className={styles.logo}>
<div className={`${styles.rec } ${ styles.rec1}`} />
<div className={`${styles.rec } ${ styles.rec2}`} />
<div className={`${styles.rec } ${ styles.rec3}`} />
<div className={`${styles.rec } ${ styles.rec4}`} />
<div className={`${styles.rec } ${ styles.rec5}`} />
</div>
</div>
</footer>
)
export default Footer
<file_sep>/content/2020-02-09-clean-code.md
---
date: 2020-02-09
title: "Clean Code: A Handbook of Agile Software Craftsmanship"
cover: "/images/clean-code.jpg"
categories:
- Books
tags:
- clean code
---
## About the book
<NAME>'s Clean Code is, in my opinion, one of the most valuable books for anyone involved in software development. Regardless of whether agile software development or not, everyone should have read Clean Code. No matter whether junior or senior developer.
Especially in today's time of technology madness, where more and more software is being cobbled together "quickly and cheaply", the quality and the manual art of software development often falls by the wayside. If you want to develop software that should be maintainable, expandable and scalable, and should survive a longer period (> 10 years), you will hardly be able to avoid the basic principles described in this book.
<file_sep>/content/2020-03-17-validation.md
---
date: 2020-03-17
title: "Validation"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
There is only one place for validation: The Backend! If you think your frontend validation is enough, you are wrong. Every frontend validation follows a UX/UI concept to improve the usability and prevent unnecessary input failures. Validation from the aspect of security and database compatibility can only be a part of the backend itself.
There are different strategies of information validation in the backend. The two most common strategies are input-validation and model-validation.
Input-validation means, you validate the input information without change or transforming. This is really nice, because you can provide a good validation error object with target and error message.
```javascript
export class CreateImpressionCommand {
@IsNotEmpty()
@IsInt()
public readonly businessId: number;
@IsNotEmpty()
@IsString()
public readonly description: string;
@IsNotEmpty()
public readonly image: Express.Multer.File;
@IsIn(["image/jpeg", "image/png"])
public readonly mimetype: string;
constructor(payload: { businessId: string, description: string, image: Express.Multer.File }) {
this.businessId = parseInt(payload.businessId, 10);
this.description = payload.description;
this.image = payload.image;
this.mimetype = payload.image.mimetype;
}
}
```
The second one is model-validation, in this case you use the input information and hydrate your model. After this you check if your model is valid. The problem in this case is you have no target left which you can provide to the frontend. E.g. The request property <username> get's split in the backend and the first part will be forename and the last part will be surname. The model itself can only send validation errors for forename and surname and not for the username itself.
```javascript
@Entity()
export class Address extends BaseModel {
@IsNotEmpty()
@IsString()
@Column()
addressLineOne: string;
@IsOptional()
@IsString()
@Column({ nullable: true })
addressLineTwo: string;
@IsNotEmpty()
@IsString()
@Column()
city: string;
@IsNotEmpty()
@IsString()
@Column()
zipCode: string;
@IsNotEmpty()
@IsString()
@Column()
country: string;
asJson() {
return {
addressLineOne: this.addressLineOne,
addressLineTwo: this.addressLineTwo,
city: this.city,
zipCode: this.zipCode,
country: this.country,
};
}
}
```
<file_sep>/content/2020-02-26-rtfm.md
---
date: 2020-02-26
title: "Rtfm: Red Team Field Manual"
cover: "/images/rtfm.jpg"
categories:
- Books
tags:
- dev ops
---
## About the Book
Lies on the desk next to the calculator. There is nothing to say about this book but you should read it and try everything out you read and then go deeper to get an understanding of what's going on.
<file_sep>/content/2020-02-24-stakeholder-analysis.md
---
date: 2020-02-24
title: "Stakeholder Analysis"
cover: "/images/empty-red.png"
categories:
- Management
tags:
- management
---
## About this technique
The first step is to identify all stakeholders - ideally immediately after project planning. All individuals participating in the project, formal and informal groupings and the other project environment should be included and directly categorized ("internal / external", "supplier", "competitor", "customer"). In a next step, the identified stakeholders will be analyzed more specifically and evaluated and weighted based on project-specific influencing factors (content-related, organizational, social).
Based on the weightings worked out, a stakeholder map can be developed that visualizes the connection between influence and support (positive vs. negative) with the help of color-coded bubbles of different sizes and positions. In practice, the stakeholder analysis is often only carried out during project planning and subsequently or neglected in the further course of the project. The stakeholder analysis should, however, be continuously and continuously checked in all project phases and modified if necessary, as opinions change and information can be continuously reinterpreted and weighted. In addition, a continuous review enables a correction of initial misjudgments.
To identify all important stakeholders, ask yourself the following key questions:
- What is the goal of the project phase (the project), who draws positive and who negative consequences?
- Who is professionally involved? Who is involved in leadership? Who is involved strategically or in an advisory capacity?
- Who defines rules and framework conditions at which point?
- Who is the contact person for definable trades?
- What delimitable trades are there and what do they cause (e.g. noise, dust, etc.)?
- Which public bodies are involved and which should still be involved?
- Which regulations, laws and specifications have to be observed?
- Who is interested in achieving the project goal?
- Who is interested in the project goal not being achieved?
- Who has to give their approval for strategic decisions? Who has a VETO right?
- Who can make mood for or against the project?
### That's why you should do a stakeholder analysis
#### You can specifically address and convince negative stakeholders.
The output of the stakeholder analysis shows you which people or participants are negative about the project. In the best case, you will not only find out who is negative, but also why this attitude comes about.
With this knowledge, you can specifically refute the arguments or point out positive aspects.
#### You can guess which goals stakeholders are pursuing.
In contrast to nature, which mainly works according to a cause and effect principle, people act according to a personal motive. You can find out why stakeholders act, how you act and thus infer the motives of individuals or groups.
#### Your image improves.
At first glance it reads like a cheap advertising lie. But can be logically substantiated:
By addressing stakeholders in the initial analysis and later reassessment, everyone involved feels taken seriously. A brilliant side effect: Those who feel taken seriously and respected see the project, the process and the project manager with benevolent eyes. The number of negative stakeholders naturally decreases when there is a feeling that fears and expectations are taken seriously.
#### Project marketing measures can be used and planned more precisely.
You know which people or groups have which reservations, reviews or attitudes. In this way you can initiate project marketing measures in a targeted manner. The scattering of fog candles is avoided. Protects the budget and does not make the marketing indicators flash red.
#### Uncover "influencers" and use them for your own purposes.
Does one of the stakeholders have the ability or ability to involve, convince and inspire others through his character or position? Mark this person thick, neon green and blinking. Drag that person to your side. Unthinkable without stakeholder analysis.
<file_sep>/content/2020-02-11-sql-performance-explained.md
---
date: 2020-02-11
title: "SQL Performance Explained: Alles, was Entwickler über SQL-Performance wissen müssen."
cover: "/images/sql-performance-explained.jpeg"
categories:
- Books
tags:
- clean code
- database
---
## About the book
<NAME> gets to the point in a nutshell. The man knows 120% of what he is writing about. Quietly and pointedly, he explains for example that it is not a good idea on the MS SQL server to create a clustered index with more than one indexed column / table. Great: The book is written in really understandable language. You won't find any cryptic or nested sentences. After reading the book, one thing is clear: in the end, only the database developer can provide really good indexes. All others will probably only be able to solder something at certain points. My belief: The book is definitely part of the basic equipment of all database developers. It is definitely one of my best SQL / Databases bookshelves.
<file_sep>/content/2020-02-26-team-building.md
---
date: 2020-02-26
title: "Team Building"
cover: "/images/empty-red.png"
categories:
- Management
tags:
- management
---
## About this technique
In my experience, teams usually form in two ways.
The first way is natural team building without external influence. This is usually done on the basis of sympathy and friendship. Even though it is said in many books that these teams are not as performant as others, I have found that long-term motivation is very high and the level of stress is very low. However, these teams often take on tasks that exceed the capabilities of the individual employees. This often results in a working solution, but this is usually of poor quality. Monitoring the team and their competencies is therefore essential and tasks that are unsuitable for the team should be taken over by people who are temporarily added to the team. This procedure is good for the further training of employees and the willingness to access third-party competencies is much higher if the period is defined.
The second way to form a team is based on the skills and characteristics of the individual employees.
Common personas are:
**The Thinker**
He is quick to grasp relationships, and as a rule he works very precisely. He does not attach great importance to the team, often he does not express his own suggestions, but waits for instructions from above.
**The Teamworker**
He always thinks of the people in the team first. He is characterized by a high degree of group feeling. He always wants a harmonious team.
**The Maker**
He is confident and actively contributes suggestions to the team, but occasionally tends to go it alone. However, it is good for him to convince the other members of his opinion.
<br></br>
A good team should preferably consist of different characters who can work well together. I would not recommend forcing a team to work in a particular constellation.
The reality is of course different. But it definitely helps to characterize the individual members. Various techniques can be used, which I will link here later.
<file_sep>/content/2020-02-09-clean-architecture.md
---
date: 2020-02-09
title: "Clean Architecture: A Craftsman's Guide to Software Structure and Design"
cover: "/images/clean-architecture.jpg"
categories:
- Books
tags:
- clean code
- architecture
---
## About the book
Clean Architecture is basically one idea repeated over and over for 30 chapters. The idea is that the business logic should be self-contained. It should not depend on the database or sockets or frameworks or GUI. It is a really, really good idea, and it is not easy to actually follow. However, the idea could have been explained in a lot less than 300 pages.
At the end there is a 50-pages appendix where <NAME> describes many of the projects he worked on, from the early 1970s to the 1990s. Many of the problems from those projects are interesting case studies that you can learn from - I quite enjoyed reading those stories (somewhat to my own surprise).
<file_sep>/content/2020-03-18-configuration.md
---
date: 2020-03-18
title: "Configuration"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
I highly recommend to use a environment specific configuration for your application. Here is an example how you inject this environment variables in your docker environment (environment section):
```
version: "3"
volumes:
node_modules_thalamus:
node_modules_console:
services:
db_host:
build:
context: ./
dockerfile: ./container/postgres.Dockerfile
ports:
- "5432:5432"
networks:
- backend
thalamus:
build:
context: ./src/thalamus
dockerfile: ../../container/thalamus.Dockerfile
args:
IS_WATCHMODE: "true"
ports:
- "3090:3000"
depends_on:
- db_host
networks:
- backend
volumes:
- ./src/thalamus/:/bindmount:rw
- ./resources/uploads/:/uploads:rw
- node_modules_thalamus:/bindmount/node_modules/:rw
environment:
DB_HOST: db_host
DB_USERNAME: spdbuser
DB_PASSWORD: <PASSWORD>
DB_DATABASE: thalamus
NODE_ENV: docker
SMTP_HOST: mail1.hosting.ntag.de
SMTP_PORT: 587
SMTP_USER: SMTP_USER
SMTP_PASSWORD: <PASSWORD>
console:
build:
context: ./src/provider
dockerfile: ../../container/console.Dockerfile
args:
IS_WATCHMODE: "true"
ports:
- "3086:3000"
depends_on:
- thalamus
networks:
- frontend
volumes:
- ./src/provider/:/bindmount:rw
- node_modules_console:/bindmount/node_modules/:rw
environment:
NODE_ENV: docker
REACT_APP_SP_API_BASEURL: http://localhost:3090
REACT_APP_GOOGLE_API_KEY: GOOGLE_API_SECRET_KEY
networks:
frontend:
backend:
```
Creating a .env.exmaple file can help your developers to make their own configurations. The structure of this file looks like this:
```
## General
BASEURL=http://localhost:3090
UPLOADS_PATH=../uploads
PORT=3000
```
A configuration for an ORM for example can be look like this:
```javascript
export const ORMConfig = {
host: process.env.TYPEORM_HOST,
port: process.env.TYPEORM_PORT as unknown as number,
username: process.env.TYPEORM_USERNAME,
password: <PASSWORD>,
database: process.env.TYPEORM_DATABASE,
type: "postgres",
logging: true,
entities: [
path.resolve(__dirname, "../api/Model/**/*.ts"),
path.resolve(__dirname, "../api/Model/**/*.js"),
],
migrations: [
path.resolve(__dirname, "../database/migration/*.ts"),
path.resolve(__dirname, "../database/migration/*.js"),
path.resolve(__dirname, "../database/seed/*.ts"),
path.resolve(__dirname, "../database/seed/*.js"),
],
subscribers: [],
namingStrategy: new nameingStrategies.SnakeNamingStrategy(),
} as ConnectionOptions;
```
<file_sep>/content/2020-02-23-smart.md
---
date: 2020-02-23
title: "S.M.A.R.T."
cover: "/images/empty-red.png"
categories:
- Management
tags:
- management
---
## About this technique
Defining a task or subtask is not easy at all, because working on a never ending story or a way to hard task can be really demotivating. The acronym "SMART" describes the properties of a good target definition: Specific, Measureable, Achievable, Relevant, Time-bound is the most common resolution of the acronym.
#### S like "Specific" and M like "Measureable"
There is broad agreement that goals must be clear and measurable. This means that they meet the necessary conditions of quality criteria or acceptance criteria. Mere naming expectations or. Requirements are not sufficient to e.g. to be able to check the success of a project.
#### A like "Assignable", "Achievable", "Attainable" or "Ambitious"
The "assignable" used in the original expresses that a goal should be formulated in such a way that a work instruction can easily be derived from it for a specific person (or organizational unit). This is undoubtedly an important property for goals, but it arises as a logical consequence of the other properties: A clearly described, realistic and measurable goal can always be given to someone.
#### R like "Realistic", "Relevant", "Resourced" or "Reasonable"
That a goal is "realistic", i.e. should be reachable is undisputed and should therefore also be included in the SMART formula. However, the reinterpretation of "assignable" to the "achievable" that is mostly used allows other criteria to be assigned to the "R". This is most often the "relevant" property. This expresses that it does not make sense to declare goals or trivialities as the goal.
#### T like "Time-related", "Time-bound" or "Time-based"
The "T" is used uniformly for a time-related criterion. However, since the English word "terminate" does not mean "end with an appointment", but rather "end", a combination of words must be used to express that the formulation of a goal also requires the point in time at which it should be reached.
<file_sep>/content/2020-02-13-drive.md
---
date: 2020-02-13
title: "Drive: The Surprising Truth About What Motivates Us"
cover: "/images/drive.jpeg"
categories:
- Books
tags:
- ethic
---
## About the Book
It is written in an entertaining and exciting way, exercises some systemic criticism of capitalism. I can transfer some of it to my professional, but also private life / recognize things. If you are looking for a book that provides good reasons for an unconditional basic income - this is the right thing.
<file_sep>/content/2020-02-10-front-controller.md
---
date: 2020-02-10
title: "Front Controller"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
The term front controller denotes a design pattern in software technology. A front controller serves as an entry point into a web application.
All requests to the web application are received by the front controller and delegated to a specific controller. To do this, he initializes the router (usually relocated to an external component) and performs general tasks.
## Example
In this example we are taking a look at a *find filtered and paged user* implementation in typescript. The front controller is the most logic-less part of our application. It dispatches the incomming request to a controller function, map the request parameters to an query or command and execute an use-case. Creating error and success responses are also a part of the front controller. In our case we dispatch the `/user get call` to the `userController` and the corresponding `ffapUser` method. To handle access control tasks we register a middleware to load the account from the system who made the request.
<br/><br/>
```javascript
class Routes {
...
public getRoutes() {
return [
{
path: "/user",
name: Routes.FFAP_USER,
method: "get",
action: this.userController.ffapUser,
middlewares: [this.fetchCurrentAccount]
},
...
]
}
}
```
Routes.ts
<br/><br/>
Inside the `UserController` we use a dependency injection container for our use cases. The controller method itself has only 3 tasks:
* mapping the request data to a query or command object
* executing the use case
* creating a success or error response
The `createErrorResponse` function made a response object in predefined structure and depending on the error code ( 404 response looks different to 403 or 401 )
<br/><br/>
```javascript
@injectable()
export class UserController extends AbstractController implements IServiceController {
public constructor(
@inject(UseCaseModule.UseCase)
@named(UseCaseModule.FFAPUserUseCase)
private readonly ffapUserUseCase: FFAPUserUseCase,
) { super(); }
public async ffapUser(request: Request, response: Response): Promise<Response> {
return this.ffapUserUseCase.execute(new FFAPUserQuery({
pagination: { take: request.query.take, page: request.query.page },
}), request.body.currentAccount).then((users) => {
return response.status(STATUS_CODE.SUCCESS).send(
CollectionResponse.builder().setResources(users).build().asJson()
);
}).catch((error: IError) => {
return this.createErrorResponse(response, error);
});
}
}
```
UserController.ts
<br/><br/>
In this example we are using `class-validator` to define validation rules in decorator syntax for the input information. We can use this to validate the input data in the use case later.
<br/><br/>
```javascript
export class FFAPUserQuery {
@IsOptional()
@ValidateNested()
public readonly pagination: Pagination;
constructor( payload: { pagination?: IPaginationPayload }) {
this.pagination = new Pagination(payload.pagination);
}
}
```
FFAPUserQuery.ts
<br/><br/>
I like to use unified response objects for single or collection responses. The response body always include `response` or `responses` for the corresponding model. It's easier to decode on the frontend side. Response objects are easy to enhance later. Maybe you need a XML response as well?! No problem just add a `asXml()` method.
<br/><br/>
```javascript
class CollectionResponse extends AbstractResponse implements IResponse {
...
private resources: any[];
...
asJson() {
return {
resources: this.resources.map((res) => res.asJson())
};
}
}
```
CollectionResponse.ts
<br/><br/>
Okay now you know some fundamentals about the front controller pattern. Use it in your next project and you will see you raise the level of cohesion and separation of concerns.
<file_sep>/content/2020-02-09-implementing-domain-driven-design.md
---
date: 2020-02-09
title: "Implementing Domain-Driven Design"
cover: "/images/implementing-domain-driven-design.jpg"
categories:
- Books
tags:
- clean code
- architecture
---
## About the book
After reading <NAME>' blue DDD book, I got this one and I personally found it's the perfect addition. The numerous and extensive code examples make many of DDD's concepts and patterns much easier to understand than the blue book alone. Without <NAME>'s work, I would never have been able to master my first DDD project.
I can recommend anyone who is serious about developing projects based on the patterns of DDD to deal intensively with this work. In addition to deepening the fundamentals of DDD, the author gives numerous tips on the use of DDD in connection with different architectural styles and shows many examples and demonstrates the use of different technologies. In addition, there are countless implementation notes for each individual pattern.
This book should not be missing in any architect's bookshelf!
<file_sep>/content/2020-02-24-project-brief.md
---
date: 2020-02-24
title: "Project Brief"
cover: "/images/empty-red.png"
categories:
- Management
tags:
- management
---
## About this technique
A project brief provides an overview of the most important project facts. He makes sure that you have to think about different things at the beginning of the project and don't forget anything. The project brief creates a common understanding between the client and the project manager and in later project phases, he helps to remember the original project again.
In general, however, the following project parameters should be included:
- Project description
- project objectives
- project participants
- project deadlines
- project costs
- risks
Usually, a profile is briefly formulated and presented on one page.
And yet a very essential point is missing. The answer to the following questions:
- Why should the project be carried out at all?
- What do we get from it?
- What improvement are we aiming for in the current situation?
Keyword: **project benefits!**
<file_sep>/content/2020-02-13-data-science.md
---
date: 2020-02-13
title: "Data Science"
cover: "/images/data-science.jpg"
categories:
- Books
tags:
- data science
---
## About the Book
The book offers a good introduction to data science. Although there is not much depth, topics such as ethics and privacy are dealt with. It was fun to read the book and because of the format it was good reading on the go.
<file_sep>/content/2020-12-31-paracry-gloomspite-gitz-grots.md
---
date: 2020-12-30
title: "Gloomspite Gitz - Grots"
cover: "/images/paracry.png"
categories:
- ParaCry
tags:
- paracry
- tabletop
---
## Gloomspite Gitz - Grots

### Passiv Ability
For each Grot between your fighter and your target enemy you extend the reach of your attack for 1 inch and these Grots doesn't restrict your sight.
[F]<->[G]<->[G]<->[E]
[F] can attack [E] with 1 inch weapon reach.
### Possible Leaders:
#### [150P] Moonclan Boss ( 16❤ 4🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |4 | 4 | 2/4 |
🎲 🎲 🎲 **Next!** Mark an Enemy, each fighter get's +1 🦵 if his movement ends nearer on this fighter
🎲 🎲 🎲 🎲 **More Grots!** You get an additional Stecha, Stabba or Shoota on a starting point
---
<br/>
#### [175P] Loonboss ( 18❤ 4🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 2" |4 | 4 | 2/4 |
🎲 🎲 🎲 **Exploding Fungi** Select Target in 8" and deal 2🩸and -1🎲 in 3"
🎲 🎲 🎲 🎲 **Buzzing Squigglebees** Grots cannot be attacked or bounded within 12" of a chosen point
---
<br/>
### Possible Fighters:
#### [65P] Shoota ( 8❤ 4🦵 3🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |3 | 3 | 1/2 |
| 🏹 | 3-12" |2 | 3 | 1/3 |
🎲 🎲 **In da Face:** Next Attack +1 🎲 +1 💪
---
<br/>
#### [70P] Stabba ( 8❤ 4🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 2" |2 | 3 | 1/4 |
🎲 🎲 **Throw da Stick:** 2🩸one Target in 6"
---
<br/>
#### [70P] Stecha ( 8❤ 4🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |3 | 3 | 1/3 |
🎲 🎲 **Togetha:** Friendly fighter is within 1" +1 🩸per 🎲
---
<br/>
#### [85P] Sneaky Snuffler ( 15❤ 4🦵 3🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |3 | 3 | 2/4 |
🎲 🎲 **Sneak** 1 Unit within 6 Inch ( ignore depths ) can't attack or bind him ( end of turn )
---
<br/>
#### [45P] Netta ( 8❤ 4🦵 3🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |3 | 3 | 1/2 |
🎲 🎲 🎲 **Barbed Net** Throw a Dice on 2+ target Enemy skip his turn
---
<br/>
#### [45P] Squig Herder ( 8❤ 4🦵 3🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |3 | 3 | 1/2 |
🎲 🎲 🎲 **Go Dat Way!** 1 Squig within 6 Inch ( ignore depths ) +1 🏃
---
<br/>
#### [140P] Cave Squig ( 15❤ 4🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |4 | 5 | 2/4 |
🎲 🎲 🎲 **Eat a Grot** Remove one Grot within 3" from the game: +5 ❤ and +1 🩸
---
<br/>
### Recommended List:
[150P] Moonclan Boss
[65P] Shoota
[65P] Shoota
[70P] Stabba
[70P] Stecha
[85P] Sneaky Snuffler
[85P] Sneaky Snuffler
[45P] Netta
[45P] Netta
[45P] Squig Herder
[140P] <NAME>
[140P] Cave Squig
<file_sep>/content/2020-02-25-systematisches-requirements-engineering.md
---
date: 2020-02-25
title: "Systematisches Requirements Engineering"
cover: "/images/systematisches-requirements-engineering.jpg"
categories:
- Books
tags:
- management
---
## About the book
I will read this book in the next 7 days.
<file_sep>/content/2020-03-18-documentation.md
---
date: 2020-03-18
title: "Documentation"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
Maintaining an API Documentation can be very hard, so I recommend to generate dynamic parts of the documentation with scripts. This needs some experience in software craftsmanship, because the structure of the project can be avoid this. I will show you one hacky method which helps me creating a api documentation generation script in one day.
<br></br>
In my typescript projects I use the "class-validator" library to validate my input data. With decorators I can define rules for all different input values:
```javascript
export class CreateImpressionCommand {
@IsNotEmpty()
@IsInt()
public readonly businessId: number;
@IsNotEmpty()
@IsString()
public readonly description: string;
@IsNotEmpty()
public readonly image: Express.Multer.File;
@IsIn(["image/jpeg", "image/png"])
public readonly mimetype: string;
constructor(payload: { businessId: string, description: string, image: Express.Multer.File }) {
this.businessId = parseInt(payload.businessId, 10);
this.description = payload.description;
this.image = payload.image;
this.mimetype = payload.image.mimetype;
}
}
```
<br></br>
In my documentation generation script I bootstrap my application and initialise the dependency injection container with presets:
```javascript
const appRouteLoader = new AppRoutes();
appRouteLoader.initializeContainer();
appRouteLoader.initializeDependencies();
```
<br></br>
The "class-validator" library stores all rules with the corresponding objects in an MetaStorage object. This can be used to read all rules in JSON format:
```javascript
const metadata = get(getFromContainer(MetadataStorage), "validationMetadatas");
const schemas = validationMetadatasToSchemas(metadata);
```
<br></br>
The last step is dereferencing the JSON schema to get all rules for nested objects:
```javascript
dereference(s).then((dereferencedSchemas) => {
...
}
```
<br></br>
Using this approach and some file system writes later we get an api request documentation like this:
>## [PATCH] /activity/showcase/:activityShowcaseId
>#### Payload
>```javascript
>{
> "activityShowcaseId": {
> "type": "string",
> "minLength": 1
> },
> "name": {
> "minLength": 1,
> "type": "string"
> },
> "description": {
> "minLength": 1,
> "type": "string"
> },
> "categoryIds": {
> "minLength": 1,
> "type": "array",
> "items": {
> "type": "integer"
> }
> }
>}
>
>Required: ["activityShowcaseId"]
>```
<file_sep>/content/2020-02-13-rxjs-in-action.md
---
date: 2020-02-13
title: "RxJS in Action"
cover: "/images/rxjs-in-action.jpg"
categories:
- Books
tags:
- javascript
---
## About the Book
All examples in this book are outdated. This makes it not easy for beginners to reproduce the solutions. I recommend using rx marble websites to learn all operators. You can read it, of cause but there are too many books out there to waste your time.
<file_sep>/content/2020-02-27-domain-event.md
---
date: 2020-02-27
title: "Domain Event"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
To reduce noise in our business logic and notify external systems we trigger fire and forget events. Let's take a look at this use case:
```javascript
injectable();
export class UpdateUserUseCase extends AbstractUseCase implements IUseCase {
public static DOMAIN_EVENT_NAME: string = "UpdateUserEvent";
public constructor(
@inject(FrameworkServiceModule.EventService) protected eventService: IEventService,
@inject(RepositoryModule.UserRepository) protected userRepository: IUserRepository,
@inject(HydrationModule.UserHydrator) protected userHydrator: IUserHydrator,
) {
super();
}
public async execute(command: UpdateUserCommand, currentUser: User): Promise<User> {
this.checkAuthentication(currentUser);
await this.validate(command);
const hydratedUser = await this.userHydrator.hydrate(currentUser, command);
const persistedUser = await this.userRepository.save(hydratedUser);
this.fireDomainEvent({ name: UpdateUserUseCase.DOMAIN_EVENT_NAME, account: currentUser, payload: command, target: currentUser });
return persistedUser;
}
}
```
In this case we:
* get an command with the corresponding user input
* validate the input data
* update the current user with the input information
* persist it.
In most systems there are logging services to create an history to make changes comprehensible. This is really easy in our case, because the underlaying implementation uses the node event emitter and it's easy to subscribe to it. It's possible to connect for example Rabbit MQ with our event emitter to unify the event structure and make it accessible for external systems.
<br></br>
Here is an example for a notification listener:
```javascript
@injectable()
class UserListener {
constructor(
@inject(FrameworkServiceModule.EventService) private readonly eventService: IEventService,
@inject(FrameworkServiceModule.TranslationService) protected translationService: ITranslationService,
@inject(ServiceModule.NotificationService) private readonly notificationService: INotificationService,
) {
this.eventService.addEventListener(UpdateUserUseCase.DOMAIN_EVENT_NAME, this.notify, this);
}
public unsubscribe() {
this.eventService.removeEventListener(UpdateUserUseCase.DOMAIN_EVENT_NAME, this.notify, this);
}
private async notify({target: payload}: {target: IEventPayload<UpdateUserCommand, User>}) {
return this.notificationService.sendSlackNotification(
this.translationService.translate(BOT_USER_UPDATED, { name: payload.target.name }),
config.slack.SLACK_APP_CHANNEL
);
}
}
```
<br></br>
If you have no idea how to develop an easy event service here is an example with "eventbusjs"
```javascript
import EventBus from "eventbusjs";
...
@injectable()
export class EventService implements IEventService {
public dispatch<Payload, Model>(name: string, payload: IEventPayload<Payload, Model>): void {
EventBus.dispatch(name, payload);
}
public addEventListener(name: string, func: (event: any) => void, reference: object): void {
EventBus.addEventListener(name, func, reference);
}
public removeEventListener(name: string, func: (event: any) => void, reference: object): void {
EventBus.removeEventListener(name, func, reference);
}
public getEvents(): string {
return EventBus.getEvents();
}
}
```
<file_sep>/content/2021-01-01-paracry-gloomspite-gitz-squighopper.md
---
date: 2020-01-01
title: "Gloomspite Gitz - Squig Hopper"
cover: "/images/paracry.png"
categories:
- ParaCry
tags:
- paracry
- tabletop
---
## Gloomspite Gitz - Squig Hopper

### Passiv Ability
1200P: More Squig Hoppers - More Boing Boing!
### Possible Leaders:
#### [275P] Loongboss on Giant Cave Squig ( 26❤ 8🦵 5🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 2" |4 | 5 | 2/5 |
🎲 🎲 🎲 **BOING!** 3🩸 within 3" on next 🏃-end
🎲 🎲 🎲 🎲 **BADUM!** Move in one direction until an obstacle occur.
---
<br/>
#### [250P] Squig Hopper Boss ( 22❤ 10🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |5 | 5 | 2/4 |
🎲 🎲 🎲 **Fasta** +1 🏃
🎲 🎲 🎲 🎲 **Thiz One** +2🩸next 🤼
---
<br/>
#### [265P] Bounder Boss ( 24❤ 8🦵 5🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 2" |4 | 5 | 2/5 |
🎲 🎲 **Stay Away!** Bind all to Combat within 2"
🎲 🎲 🎲 🎲 **Lances of the Bounderz** All Friendly Fighters within 6" 🤼
---
<br/>
### Possible Fighters:
#### [200P] Squig Hopper ( 16❤ 10🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |4 | 5 | 2/4 |
🎲 🎲 🎲 **Boing! Boing! Boing!:** 1/2 🎲🩸on next 🏃-end within 1"
---
<br/>
#### [220P] Boingrot Bounder ( 18❤ 8🦵 5🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 2" |3 | 5 | 2/5 |
🎲 🎲 **Stay Away!** Bind one to Combat within 2"
---
<br/>
### Recommended List:
[275P] Loongboss on Giant Cave Squig
[220P] Boingrot Bounder
[220P] Boingrot Bounder
[220P] Boingrot Bounder
[220P] Boingrot Bounder
<file_sep>/content/2020-03-20-access-control-list.md
---
date: 2020-03-20
title: "Access Control List"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
Implementing an access control list can be a very difficult challenge. In the most cases we find a RBAC (Role Based Access Control) or ABAC (Attribute Based AccessControl) implementation when we come into an existing project. But when you start a new project and some requirements are unclear, I can recommend starting with this approach:
### Creating a resource based access control with user/resource hierarchy
We start building a permission model which represent standard (CRUD) actions at the beginning:
```javascript
export enum PermissionType {
ALLOWED_TO_CREATE = "ALLOWED_TO_CREATE",
ALLOWED_TO_READ = "ALLOWED_TO_READ",
ALLOWED_TO_UPDATE = "ALLOWED_TO_UPDATE",
ALLOWED_TO_DELETE = "ALLOWED_TO_DELETE",
}
@Entity()
export class Permission extends BaseModel {
@Column({
type: "enum",
enum: PermissionType,
unique: true,
})
type: PermissionType;
@ManyToMany(() => Role, (role) => role.permissions)
roles: Role[];
}
```
You should seed your database with one instance of each.
<br></br>
At the second step we build a role model to group some permissions together:
```javascript
export enum RoleType {
CREATOR = "CREATOR",
EDITOR = "EDITOR",
VISITOR = "VISITOR"
}
@Entity()
export class Role extends BaseModel {
@Column({
type: "enum",
enum: RoleType,
unique: true,
})
type: RoleType;
@ManyToMany(() => Permission)
@JoinTable()
permissions: Permission[];
}
```
<br></br>
A role definition will help you taking an overview about your ACL and easy introduce new developers.
```javascript
export default {
[RoleType.CREATOR]: [
PermissionType.ALLOWED_TO_CREATE,
PermissionType.ALLOWED_TO_UPDATE,
PermissionType.ALLOWED_TO_FIND,
PermissionType.ALLOWED_TO_DELETE,
PermissionType.ALLOWED_TO_INVITE,
],
[RoleType.EDITOR]: [
PermissionType.ALLOWED_TO_FIND,
PermissionType.ALLOWED_TO_UPDATE,
],
[RoleType.VISITOR]: [
PermissionType.ALLOWED_TO_FIND,
]
};
```
<br></br>
Okay now we need to bring our resource together with the roles and permissions. We call this: taking responsibility.
```javascript
export enum ResponsibilityType {
COMPANY = "COMPANY",
BUSINESS = "BUSINESS"
}
@Entity()
export class Responsibility extends BaseModel {
@ManyToOne(() => User, (user) => user.responsibilities)
user: User;
@Column({
type: "enum",
enum: ResponsibilityType,
})
type: ResponsibilityType;
@Column()
targetId: number;
@ManyToMany(() => Role)
@JoinTable()
roles: Role[];
}
```
<br></br>
Starting with this project a user can create a company, which means he is the creator of the company.
User -> Responsibility -> COMPANY
-> CREATOR Role -> CRUD Permission
Now this user invite another user to the project to maintain the created company.
User -> Responsibility -> COMPANY
-> EDITOR Role -> RU Permission
All callcenter agents needs access to the company data to inform clients:
User -> Responsibility -> COMPANY
-> VISITOR Role -> R Permission
Okay you see this works really great based on single user invites and single user-resource responsibility handling.
<br></br>
#### Why this approach fails
It's very common not to invite someone to maintain one resource, in the most cases users will be a part of an hierarchy based on company structures. Or the underlaying model structure depends on permission inheritance.
For example: You own a company
User -> Responsibility -> COMPANY
-> CREATOR Role -> CRUD Permission
For all Businesses of this company you inherit the company rules:
User -> Responsibility -> BUSINESS
-> CREATOR Role -> CRUD Permission
... I will finish this post later ...
<file_sep>/content/2020-02-13-domain-driven-design-reference.md
---
date: 2020-02-13
title: "Domain-driven Design Referenz: Definitionen & Muster"
cover: "/images/domain-driven-design-reference.jpg"
categories:
- Books
tags:
- architecture
- clean code
---
## About the Book
The domain-driven design reference provides an overview of the basic patterns for domain-driven design. Domain-driven design is an approach to the architecture and design of software projects that is consistently based on the technical requirements. For not even 5 Bucks this Book is the best investment in the world.
<file_sep>/content/2020-02-12-use-case.md
---
date: 2020-02-12
title: "Use Case"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
> These use cases orchestrate the flow of data to and from the entities, and direct those entities to use their Critical Business Rules to achieve the goals of the use case.
[Clean Architecture: A Craftsman's Guide to Software Structure and Design](/clean-architecture-a-craftsmans-guide-to-software-structure-and-design)
<br/><br/>
The use case encapsulate a procedure described by his behaviour. In the case of behaviour driven development we define e2e tests like this:
```
GIVEN A user called "John" which is authorized to get user information
AND A user called "Smith"
WHEN The user called "John" gets user information
THEN The Response contain "Smith"
```
The when task describe the main functionality of the use case and the then block contains the functional requirements. Each use case can be executed and have a deterministic behaviour. In my applications I encapsulate:
* Access Control
* Validation
* Hydration
* Repository
* Service
from the use case to make them lightweight and easy to understand. A dependency injection container will help you to make the use cases easy to unit test and will help you to exchange dependencies in e2e tests.
## Example
In this example we take a look at a find filtered and paged user implementation. The whole use case encapsulate the business logic. To make it better readable and separate concerns we use services and repositories. The external event helps us to register logging services and notify external services with an message queue.
```javascript
injectable();
export class FFAPUserUseCase extends AbstractUseCase implements IUseCase {
public static DOMAIN_EVENT_NAME: string = "UserFoundFilteredAndPagedEvent";
public constructor(
@inject(FrameworkServiceModule.EventService) protected userAccessControl: IUserAccessControl,
@inject(FrameworkServiceModule.EventService) protected eventService : IEventService,
@inject(RepositoryModule.UserRepository) protected userRepository : IUserRepository,
) {
super();
}
public async execute(query: FFAPUserQuery, currentAccount: Account): Promise<User[]> {
this.checkAuthentication(currentAccount);
this.validate(query);
this.userAccessControl.allowedToGetUser(currentAccount)
const { pagination } = query;
const users = await this.userRepository.get({ pagination });
this.eventService.fireDomainEvent({ name: FFAPUserUseCase.DOMAIN_EVENT_NAME, account: currentAccount, payload: query, target: users });
return users;
}
}
```
You see, 8 lines of code cover the following points:
* The Account which made the request is authenticated
* The Request Data encapsulated in an query DTO is valid
* The Account which made the request is allowed to make this operation
* The requested Data is fetched from the Database
* External Services are notified about this operation
<file_sep>/content/2020-02-15-dependency-injection.md
---
date: 2020-02-15
title: "Dependency Injection"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
Dependency Injection is a technique of object oriented programming whereby one object supplies the dependencies of another object. Two principles are followed in this pattern. The first one is `separation of concerns` of construction and use of objects and the second one is `inversion of control`, because a client who wants to call some services should not have to know how to construct those services. Instead, the client delegates the responsibility of providing its services to external code.
In general we distinguish four different parts:
* the `service object` to be used
* the `client object` that is depending on the service
* the `interfaces` that define how the client may use the service
* the `injector`, which is responsible for constructing the services and injecting them into the client
<br/><br/>
## Example without dependency injection
```javascript
class Service implements IService {
...
}
```
```javascript
class Client implements IClient {
service: IService;
constructor() {
super();
this.service = new Service();
}
}
```
You see there are no explicit injector because the client class becomes the injector itself creating the service in its own constructor. If you see this, you should talk with your technical lead about this problem, because you will get in trouble in the future.
<br/><br/>
## Problems that occur with this implementation
When unit testing a method of the client object which is using the service instance created by the constructor, you will get trouble mocking the service. Because in unit tests you should test the functionality of the method and not the implementation of the service.
```javascript
class Client implements IClient {
service: IService;
constructor() {
super();
this.service = new Service();
}
public methodToTest(x: number, y: number): number {
return this.service.dontTestMe(x) + this.service.dontTestMe(y)
}
}
```
```javascript
const client = new Client();
const result = client.methodToTest(1,2);
expect(result).toBe(3);
```
The significance of the test is reduced because the test fails even if the service implementation is faulty. In more complex implementations this problem can be
<br/><br/>
## Example with dependency injection (Constructor injection)
```javascript
class Client implements IClient {
service: IService;
constructor(service: Service) {
super();
this.service = service;
}
public methodToTest(x: number, y: number): number {
return this.service.dontTestMe(x) + this.service.dontTestMe(y)
}
}
```
```javascript
class MockService {
public dontTestMe(x: number): number {
return x;
}
}
const mockService = new MockService();
const client = new Client(mockService);
const result = client.methodToTest(1,2);
expect(result).toBe(3);
```
This solution is more elegant, but it shifts the problem of the constructor call to the upper level. So at the application entry point we will have a large amount of constructor calls.
<br/><br/>
## Example with dependency injection (Setter injection)
```javascript
class Client implements IClient {
service?: IService;
constructor() {
super();
}
set service(service:IService) {
this.service = service;
}
public methodToTest(x: number, y: number): number {
if(!this.service) {
throw Error("Invalid Parameter: service must not be null")
}
return this.service.dontTestMe(x) + this.service.dontTestMe(y)
}
}
```
```javascript
class MockService {
public dontTestMe(x: number): number {
return x;
}
}
const mockService = new MockService();
const client = new Client();
client.service = mockService;
const result = client.methodToTest(1,2);
expect(result).toBe(3);
```
This offers flexibility, but if there is more than one dependency to be injected, it is difficult for the client to ensure that all dependencies are injected before the client could be provided for use.
<br/><br/>
## Example with dependency injection (Static Factory Method)
```javascript
class Client implements IClient {
service?: IService;
constructor(service: IService) {
super();
this.service = service;
}
public methodToTest(x: number, y: number): number {
return this.service.dontTestMe(x) + this.service.dontTestMe(y)
}
}
```
```javascript
class Injector implements IInjector {
static create() {
const service = new Service();
const client = new Client(service);
return client;
}
}
```
```javascript
// the create function is static so there is no way to change it for test purposes.
// so the dontTestMe() function gets called without change or replacement.
const client = Injector.create();
const result = client.methodToTest(1,2);
expect(result).toBe(3);
```
The use of this generation pattern amounts to subclassing. There must be a separate class that can accommodate the class method for generation. But sometimes its helpful to create an instance from different inputs. For example, a `Color.createFromRGB()` method can create a color object from RGB values, and a `Color.createFromHSV()` method can create a color object from HSV values.
Long Story Short: There are several ways to create an object. Obvious the worst way is to use a constructor call in another one. For real, you will lost all your fame if you do it.
The `Gang of Four` (<NAME>, <NAME>, <NAME> and <NAME>) defined 5 patterns to create an object:
* Factory method
* Abstract Factory
* Singleton
* Builder
* Prototype
These are enough and you should understand these patterns before writing your next line of code.
<file_sep>/content/2020-02-11-mystical-man-month.md
---
date: 2020-02-11
title: "The Mythical Man-Month. Essays on Software Engineering"
cover: "/images/mystical-man-month.jpg"
categories:
- Books
tags:
- agile
- management
---
## About the book
The book deals with the typical problems in large IT development projects. The facts are pointedly presented, and you can quickly recognize yourself or your boss in the explanations. The author also writes about his own mistakes and what he has learned from them. In addition, solution strategies are presented, which of course are already being implemented today (after more than 30 years). Nevertheless, reading this classic is recommended, not to forget your own experiences.
The chapters are short and entertaining. As a result, the book is also suitable for distracting yourself for 10 minutes and reflecting on your own approach.
I recommend the book to everyone who works in IT development.
<file_sep>/content/2020-02-23-project-structure-plan.md
---
date: 2020-02-23
title: "Work Breakdown Structure"
cover: "/images/empty-red.png"
categories:
- Management
tags:
- management
---
## About this technique
A project is divided into subtasks and work packages as part of the structuring. Subtasks are elements that have to be subdivided further, work packages are elements that are at the lowest level in the WBS and are not subdivided further there. Work packages contain the operations that are required for the further planning stages.
Three methods have been established for creating project structure plans:
#### Top-down approach
The deductive way leads from the whole to the detail, the PSP is formed by dismantling from the project to the work packages.
Name the project
Selection of the appropriate orientation method for the second level
Breakdown of the overall project into sub-projects or sub-tasks
List of tasks or structural elements of the second level
Selection of the appropriate orientation method for each element of the second level
Further disassembly until work packages are available
This procedure is often chosen if experience with similar projects is already available or the content of the project to be planned is largely known.
#### Bottom-up approach
The inductive path leads from the detail to the whole, the PSP is formed by putting together from the activity to the project.
Collection of tasks to be carried out in the project
Analysis of relationships with the question of what is part of what
Structure and composition to a tree structure
Control of completeness and uniqueness of all tasks
This process is suitable for projects with a high degree of innovation.
#### Yo-Yo technique
In the countercurrent process, deductive and inductive steps are carried out alternately in order to use the strengths of both processes. In order to use this method sensibly, however, it should not be used for a too small section of the project.
<br></br>
In order to ensure that no tasks have been forgotten and that no tasks occur more than once, the following rules should be observed:
Uniqueness: The structural elements of a level must be completely different in terms of content.
Completeness: The total content of the elements belonging to a parent element must match the content of the parent element.
<file_sep>/content/2020-02-24-reactive-programming-swift.md
---
date: 2020-02-24
title: "Reactive Programming with Swift"
cover: "/images/reactive-programming-swift.jpg"
categories:
- Books
tags:
- reactive
---
## About the Book
Be careful this book is not about RxSwift, it's more about general reactive design patterns and examples are in Reactive Cocoa. The examples are old and not really good, this sucks because the whole book is full of it. Don't waste your time, skip this book.
<file_sep>/content/2020-02-11-react.md
---
date: 2020-02-11
title: "React: Die praktische Einführung in React, React Router und Redux"
cover: "/images/react.jpg"
categories:
- Books
tags:
- clean code
- react
- frontend
---
## About the book
The authors did an excellent job introducing React. All important concepts that are required to create complete React applications are presented using a sample application (a service for online surveys), which also deals with topics that go beyond the core functionality of React, such as the connection of a REST API Servers and the flux architecture. The latest technologies are used throughout, especially the ES2015 language features (which are explained separately in the appendix). Everything is well structured and clearly presented, without unnecessary ballast, but without any noteworthy gaps. This book is exactly the React introduction that I wanted.
<file_sep>/content/2020-03-17-repository.md
---
date: 2020-03-17
title: "Repository"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
To encapsulate database access and access to external resources we use repositories. There are several ORM-Implementations which supports a base repository to inherit from. In the most cases it makes sense to write a repository for each root aggregate. Creating a repository for each model will end in a big mess, trust me.
This is an example of the repository implementation of TypeORM:
```javascript
...
let allPhotos = await photoRepository.find();
console.log("All photos from the db: ", allPhotos);
let firstPhoto = await photoRepository.findOne(1);
console.log("First photo from the db: ", firstPhoto);
let meAndBearsPhoto = await photoRepository.findOne({ name: "Me and Bears" });
console.log("Me and Bears photo from the db: ", meAndBearsPhoto);
let photoToUpdate = await photoRepository.findOne(1);
photoToUpdate.name = "Me, my friends and polar bears";
await photoRepository.save(photoToUpdate);
...
```
Providing an interface to get an empty model will helps you to mock all the database specific dependencies in your unit tests (preventing constructor calls):
```javascript
export class UserRepository extends BaseRepository<User> implements IUserRepository {
public getEmptyUserModel(): User {
return new User();
}
}
```
<file_sep>/content/2021-01-02-paracry-gloomspite-gobbapalooza.md
---
date: 2020-01-02
title: "Gloomspite Gitz - Gobbapalooza"
cover: "/images/paracry.png"
categories:
- ParaCry
tags:
- paracry
- tabletop
---
## Gloomspite Gitz - Gobbapalooza

### Passiv Ability
Shaman: For each hit flip a coin on head it misses.
### Possible Leaders:
#### [175P] Funguid Cave-Shaman ( 18❤ 4🦵 3🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |3 | 4 | 1/4 |
| ☄ | 3-7" |2 | 3 | 3/6 |
🎲 🎲 🎲 **Know Wotz**
🎲 🎲 🎲 🎲
---
<br/>
### Possible Fighters:
#### [85] Boggleye ( 12❤ 4🦵 3🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 2" |3 | 3 | 1/4 |
🎲 🎲 **Mesmerise:** Within 12 Inch, no opponent unit can be activated next.
🎲 🎲 ****
---
<br/>
#### [85] Scaremonger ( 16❤ 4🦵 3🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |4 | 3 | 1/4 |
🎲 🎲 **Bogeyman** Within 12 Inch, you make a 🤾with each Opponent.
🎲 🎲 ****
---
<br/>
#### [85] Shroomancer ( 12❤ 4🦵 3🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 2" |3 | 3 | 1/4 |
🎲 🎲 **Fungoid Cloud:** Within 12 Inch, reduce all opponent 🗡🎲 to 1
🎲 🎲 ****
---
<br/>
#### [85] Brewgit ( 12❤ 4🦵 3🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |4 | 3 | 1/3 |
🎲 🎲 **Loonshine Portion:** Within 12 Inch, re-roll 1 🗡🎲 per 🤼 ( friend and opponent )
🎲 🎲 ****
---
<br/>
#### [85] Spiker ( 12❤ 4🦵 3🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 2" |3 | 3 | 1/4 |
🎲 🎲 **Poison Brewer** Within 12 Inch, reduce 1🩸from all opponent hits ( damage can be 0 ).
🎲 🎲 ****
---
<br/>
#### [190] Rockgut Troggoth ( 28❤ 4🦵 5🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |3 | 5 | 2/5 |
🎲 🎲 **Troggoth Regrowth:** 🎲❤
---
<br/>
### Recommended List:
[175P] Funguid Cave-Shaman
[85] Scaremonger
[85] Shroomancer
[85] Boggleye
[85] Spiker
[85] Brewgit
[190] Rockgut Troggoth
[190] Rockgut Troggoth
<file_sep>/content/2020-02-11-api-design.md
---
date: 2020-02-11
title: "API-Design: Praxishandbuch für Java- und Webservice-Entwickler"
cover: "/images/api-design.jpeg"
categories:
- Books
tags:
- clean code
- architecture
---
## About the book
Still one of the best German-language books in this field for me. I read the entire book on my 2 week trip through Italy. In general, you could say that the book is aimed at beginners rather than advanced developers. In many startups I would like the developers to have had a look here.
<file_sep>/content/2020-02-23-project-plan.md
---
date: 2020-02-23
title: "Project Plan"
cover: "/images/empty-red.png"
categories:
- Management
tags:
- management
---
## About this technique
According to the Project Management Body of Knowledge (PMBOK), a project plan is: "...a formal, approved document used to guide both project execution and project control. The primary uses of the project plan are to document planning assumptions and decisions, facilitate communication among project stakeholders, and document approved scope, cost, and schedule baselines. A project plan may be summarised or detailed."
The project plan typically covers topics used in the project execution system and includes the following main aspects:
- Scope management
- Requirements management
- Schedule management
- Financial management
- Quality management
- Resource management
- Stakeholder management – New from PMBOK 5
- Communications management
- Project change management
- Risk management
The easiest way to start is creating a table with 5 columns. The first one is the enumeration of tasks, the second one the name of the task, third fourth and fifth is duration start and end date of the task. To make these information more readable, you can create a Gantt-Diagram which presents the duration in the form of bars on a timeline.
Today there are different strategies in agile software development management frameworks like SCRUM or KANBAN to archive good predictions for task durations and risks. In general is worth to make 3 or 4 milestones to archive the goal. It's a WIN-WIN situation for you and for the team, because it's really motivating archiving a goal and make a party or something else, on the other hand you can evaluate failures way faster.
<file_sep>/content/2020-02-13-the-devils-dictionary.md
---
date: 2020-02-13
title: "The Devil's Dp Dictionary"
cover: "/images/the-devils-dictionary.jpg"
categories:
- Books
tags:
- fun
---
## About the Book
This book is older then me, but most of the "funny things" inside it are totally actual. Good book for the toilet of the local IT department.
<file_sep>/content/2020-02-09-domain-driven-design.md
---
date: 2020-02-09
title: "Domain-Driven Design: Tackling Complexity in the Heart of Software"
cover: "/images/domain-driven-design.jpg"
categories:
- Books
tags:
- clean code
- architecture
---
## About the book
Highly recommended for junior developers on their way to become a master programmer. Topics like ubiquitous language, model, domain object lifecycle, core domain definition and useful patterns are well defined inside the book. The second part of the book seems a little bit confusing, but <NAME> save this part with useful DDD-Patterns. But be careful, you won't understand this book 100% the first time you read it. But after 5 to 10 years of software craftsmanship you will understand, this book is really useful if you wanna write large scalable applications without loosing control after 2 years.
<file_sep>/content/2020-02-24-project-management-erfolg.md
---
date: 2020-02-24
title: "Project Management - Führung mit Erfolg"
cover: "/images/project-management.jpg"
categories:
- Books
tags:
- management
---
## About the Book
Basically, every professional activity should be divided into projects. As soon as you understand this point, you can be successful in my view, even if the work only really starts. From my point of view, you learn to manage these projects very well here in the book. It provides all the foundation for managing projects and the key factors of the projects. Definitely worth a recommendation for beginners.
<file_sep>/content/2020-02-26-risk-management.md
---
date: 2020-02-26
title: "Risk Management"
cover: "/images/empty-red.png"
categories:
- Management
tags:
- management
---
## About this technique
In every project there are problems and risks that are foreseeable from the first second. These risks should be summarized in a document and given the chance of occurrence based on the assessment in the team. It is advisable to describe the problem in as much detail as possible and, if necessary, to file an emergency plan. Risks that cause a very high probability but little damage are not as explosive as risks that can cause a lot of damage.
If there are risks that are very likely and can cause great damage, then it is worthwhile to set up an emergency team that can respond to precisely this problem. Or create an issue for each sprint which tries to prevent this risk.
It is worthwhile to sensitize the team to errors and risks so that in an emergency it does not generate demotivation, but rather deals with the situation in a calm manner.
<file_sep>/content/2020-02-13-reactive-design-patterns.md
---
date: 2020-02-13
title: "Reactive Design Patterns"
cover: "/images/reactive-design-patterns.jpg"
categories:
- Books
tags:
- data science
- machine learning
---
## About the Book
Exactly the book you should read starting with reactive extensions. It's all about structures and patterns used by scaleable reactive applications. Most interesting part for me was the fault tolerance and recovery patterns and some flow control strategies. There are only 300 pages so buy this book and take you a weekend.
<file_sep>/content/2020-02-11-refactoring.md
---
date: 2020-02-11
title: "Refactoring: Improving the Design of Existing Code"
cover: "/images/refactoring.jpg"
categories:
- Books
tags:
- clean code
---
## About the book
Read it! Read it again! Become a senior developer. This is one of these books every developer should read before writing another line of code. There is no way around it, buy it, read it, and read it again.
<file_sep>/content/2020-03-18-definitions.md
---
date: 2020-03-18
title: "Definitions"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
I recommend to collect all constants and definitions of your project in one folder. This makes it really easy for your mates to find them, change them or get an overview about your project.
For example you can make a role/permission definition file to describe your role system:
```javascript
export default {
[RoleType.CREATOR]: [
PermissionType.ALLOWED_TO_CREATE,
PermissionType.ALLOWED_TO_UPDATE,
PermissionType.ALLOWED_TO_FIND,
PermissionType.ALLOWED_TO_DELETE,
PermissionType.ALLOWED_TO_INVITE,
],
[RoleType.EDITOR]: [
PermissionType.ALLOWED_TO_FIND,
PermissionType.ALLOWED_TO_UPDATE,
],
[RoleType.VISITOR]: [
PermissionType.ALLOWED_TO_FIND,
]
};
```
As a fresh developer of this project, its really easy to understand this role system without seeing the underlying implementation.
<file_sep>/content/2020-02-24-swift-3-functional-programming.md
---
date: 2020-02-24
title: "Swift 3 Functional Programming"
cover: "/images/functional-programming-swift.jpg"
categories:
- Books
tags:
- swift
---
## About the Book
The book starts with functional programming concepts, the basics of Swift 3, and essential concepts such as functions, closures, optionals, enumerations, immutability, and generics in detail with coding examples.
Furthermore, this book introduces more advanced topics such as function composition, monads, functors, applicative functors, memoization, lenses, algebraic data types, functional data structures, functional reactive programming (FRP), protocol-oriented programming (POP) and mixing object-oriented programming (OOP) with functional programming (FP) paradigms.
Long Story Short: Read it and enjoy the swift programming language.
<file_sep>/content/2020-02-25-builder.md
---
date: 2020-02-25
title: "Builder Pattern"
cover: "/images/empty.png"
categories:
- Development
tags:
- clean code
- architecture
---
## About the Pattern
This is one of my favourite creational patterns. Combined with a static factory method and a fluent interface it brings readability and useability to the next level.
Take a look at this beauty
```javascript
export default class Business implements IBusiness {
private readonly _id: string;
private readonly _name: string;
private readonly _description: string;
private readonly _createdAt: Date;
static builder(): BusinessBuilder {
return new BusinessBuilder();
}
constructor(data: IBusiness) {
this._id = data.id;
this._name = data.name;
this._description = data.description;
this._createdAt = data.createdAt;
}
get id(): string {
return this._id;
}
get name(): string {
return this._name;
}
get description(): string {
return this._description;
}
get createdAt(): Date {
return this._createdAt;
}
}
```
and the corresponding builder:
```javascript
export default class BusinessBuilder {
private id?: string;
private name?: string;
private description?: string;
private createdAt?: Date;
setId(id: string): BusinessBuilder {
this.id = id;
return this;
}
setName(name: string): BusinessBuilder {
this.name = name;
return this;
}
setDescription(description: string): BusinessBuilder {
this.description = description;
return this;
}
setCreatedAt(timestamp: string): BusinessBuilder {
this.createdAt = new Date(timestamp);
return this;
}
build(): Business {
return new Business({
id: this.id,
name: this.name,
description: this.description,
createdAt: this.createdAt,
});
}
}
```
Finally the usage:
```javascript
const business = Business.builder()
.setId("1")
.setName("Oh my Business")
.setDescription("Lorem ipsum dolor sit amet.")
.build()
```
<br></br>
If you have multiple nested objects you can provide their builders in the setter methods as higher order function. You know what I mean? Let's take a look:
```javascript
export default class Business implements IBusiness {
private readonly _id: string;
private readonly _name: string;
private readonly _description: string;
private readonly _address: Address;
private readonly _location: Location;
private readonly _createdAt: Date;
static builder(): BusinessBuilder {
return new BusinessBuilder();
}
constructor(data: IBusiness) {
this._id = data.id;
this._name = data.name;
this._description = data.description;
this._address = data.address;
this._location = data.location;
this._createdAt = data.createdAt;
}
get id(): string {
return this._id;
}
get name(): string {
return this._name;
}
get description(): string {
return this._description;
}
get address(): Address {
return this._address;
}
get location(): Location {
return this._location;
}
get createdAt(): Date {
return this._createdAt;
}
}
```
and the corresponding builder:
```javascript
export default class BusinessBuilder {
private id?: string;
private name?: string;
private description?: string;
private address?: Address;
private location?: Location;
private createdAt?: Date;
setId(id: string): BusinessBuilder {
this.id = id;
return this;
}
setName(name: string): BusinessBuilder {
this.name = name;
return this;
}
setDescription(description: string): BusinessBuilder {
this.description = description;
return this;
}
setAddress(callback: (builder: AddressBuilder) => Address): BusinessBuilder {
this.address = callback(Address.builder());
return this;
}
setLocation(callback: (builder: LocationBuilder) => Location): BusinessBuilder {
this.location = callback(Location.builder());
return this;
}
setCreatedAt(timestamp: string): BusinessBuilder {
this.createdAt = new Date(timestamp);
return this;
}
build(): Business {
return new Business({
id: this.id,
name: this.name,
description: this.description,
address: this.address,
location: this.location,
createdAt: this.createdAt,
});
}
}
```
Finally the usage:
```javascript
const business = Business.builder()
.setId("1")
.setName("<NAME> Business")
.setDescription("Lorem ipsum dolor sit amet.")
.setAddress(
(addressBuilder) => addressBuilder
.setStreet("St Marks Ave")
.setZipCode("12 32 B")
.setCity("New York")
.setCountry("USA")
.build();
)
.setLocation(
(locationBuilder) => locationBuilder
.setLongitude("73.927128")
.setLatitude("40.673959")
.build()
)
.build()
```
With this technique you have a nice auto suggestion in your IDE and a really small amount of import statements.
You should understand this pattern before writing your next line of code.
<file_sep>/content/2021-01-03-paracry-mon-rotbringers.md
---
date: 2020-01-02
title: "Maggotkin of Nurgle - Rotbringers"
cover: "/images/paracry.png"
categories:
- ParaCry
tags:
- paracry
- tabletop
---
## Maggotkin of Nurgle - Rotbringers

### Passiv Ability
End of turn each Unit gets 4🩸
### Possible Leaders:
#### [205P] Lord of Plagues ( 32❤ 3🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |3 | 5 | 3/5 |
🎲 🎲 🎲 **** -4🩸
🎲 🎲 🎲 🎲 **** -4🩸
#### [210P] Lord of Blights ( 32❤ 3🦵 5🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |3 | 4 | 2/5 |
🎲 🎲 🎲 **** -4🩸
🎲 🎲 🎲 🎲 **** -4🩸
---
<br/>
#### [290P] Lord of Afflictions ( 42❤ 6🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 2" |4 | 4 | 3/5 |
🎲 🎲 🎲 **** -4🩸
🎲 🎲 🎲 🎲 **** -4🩸
---
<br/>
#### [190P] Blightlord ( 30❤ 3🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |4 | 4 | 2/5 |
🎲 🎲 🎲 **** -4🩸
🎲 🎲 🎲 🎲 **** -4🩸
---
<br/>
#### [165P] Rotbringer Sorcerer ( 22❤ 3🦵 3🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 2" |3 | 3 | 1/4 |
| ☄ | 3"-7" |2 | 3 | 3/6 |
🎲 🎲 🎲 **** -4🩸
🎲 🎲 🎲 🎲 **** -4🩸
---
<br/>
#### [195P] Harbinger of Decay ( 25❤ 6🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 2" |3 | 4 | 2/4 |
🎲 🎲 🎲 **** -4🩸
🎲 🎲 🎲 🎲 **** -4🩸
---
<br/>
### Possible Fighters:
#### [135] Putrid Blightking with Blighted Weapon ( 25❤ 4🦵 4🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |3 | 4 | 2/4 |
🎲 🎲 **** -4🩸
---
<br/>
### Possible Fighters:
#### [145] Putrid Blightking with Filth-Encrusted Shield ( 25❤ 4🦵 5🛡)

| | 📏 |🎲 | 💪 | 🩸|
| - |:-:|:-:| :--:| -:|
| 🗡| 1" |3 | 4 | 2/4 |
🎲 🎲 **** -4🩸
---
<br/>
### Recommended List:
<file_sep>/README.md
## paravoid re-qui-en blog
| 10e060df3c4b80a542994d2d3bc0e5de3792726f | [
"Markdown",
"JavaScript"
] | 55 | Markdown | parav01d/re-qui-en | ee5cf5853694706f263a964e97e18f366b8d8c18 | 79aa024d93a71d895743119ad8de0b5b5aff5f65 |
refs/heads/master | <file_sep>listPopupTemplates = function(x, row_index = TRUE) {
nms = colnames(x)
id_crd = nms == "Feature ID"
id_val = !id_crd
out = data.frame(matrix(ncol = ncol(x), nrow = nrow(x)))
colnames(out) = nms
if (any(id_crd)) {
out[, id_crd] = brewPopupCoords(nms[id_crd], x[, id_crd])
}
out[, id_val] = matrix(
brewPopupRow(
which(id_val)
, nms[id_val]
, t(x[, id_val])
, row_index
)
, ncol = sum(id_val)
, byrow = TRUE
)
# args = c(out, sep = "")
out = do.call(paste0, out)
# as.character(vsub("<%=pop%>", out, createTemplate(), perl = TRUE))
sprintf(createTemplate(), out)
# vapply(out, gsub, "chracter", x = createTemplate()
# , pattern = "<%=pop%>", USE.NAMES = FALSE)
}
vsub = Vectorize(gsub)
brewPopupCoords = function(colname, value) {
ind_string = "<td></td>"
# col_string = paste0("<th>", colname, "</th>")
# val_string = paste0("<td>", value, " </td>")
# out_string = paste0("<tr class='coord'>", ind_string, col_string, val_string, "</tr>")
col_string = sprintf("<th><b>%s </b></th>", colname)
val_string = sprintf("<td>%s </td>", value)
out_string = sprintf("<tr class='coord'>%s%s%s</tr>", ind_string, col_string, val_string)
return(out_string)
}
brewPopupRow = function(index, colname, value, row_index = TRUE) {
# ind_string = if (row_index) {
# paste0("<td>", index - 1, "</td>")
# } else {
# "<td></td>"
# }
# col_string = paste0("<th>", colname, " </th>")
# val_string = paste0("<td>", value, " </td>")
#
# out_string = paste0("<tr>", ind_string, col_string, val_string, "</tr>")
ind_string = if (row_index) {
sprintf("<td>%s</td>", index - 1)
} else {
"<td></td>"
}
# col_string = sprintf("<td><b>%s </b></td>", colname)
# val_string = sprintf("<td align='right'>%s </td>", value)
col_string = sprintf("<th>%s </th>", colname)
val_string = sprintf("<td>%s </td>", value)
# row_class = "<tr>%s%s%s</tr>"
out_string = sprintf("<tr>%s%s%s</tr>", ind_string, col_string, val_string)
return(out_string)
}
createTemplate = function() {
"<div class='scrollableContainer'><table class='popup scrollable' id='popup'>%s</table></div>"
}
# createTemplate = function() {
# gsub("\\n", ""
# , "<html>
# <head>
# <link rel='stylesheet' type='text/css' href='lib/popup/popup.css'>
# </head>
#
# <body>
#
# <div class='scrollableContainer'>
# <table class='popup scrollable' id='popup'>
#
# %s
#
# </table>
# </div>
# </body>
# </html>
# ")
# }
<file_sep>#' Create HTML strings for popups
#'
#' @description
#' Create HTML strings for \code{popup} tables used as input for
#' \code{mapview} or \code{leaflet}.
#' This optionally allows the user to include only a subset of feature attributes.
#'
#' @param x A \code{Spatial*} object.
#' @param zcol \code{numeric} or \code{character} vector indicating the columns
#' included in the output popup table. If missing, all columns are displayed.
#' @param row.numbers \code{logical} whether to include row numbers in the popup table.
#' @param feature.id \code{logical} whether to add 'Feature ID' entry to popup table.
#'
#' @return
#' A \code{list} of HTML strings required to create feature popup tables.
#'
#' @examples
#' library(leaflet)
#'
#' leaflet() %>% addTiles() %>% addCircleMarkers(data = breweries91)
#' leaflet() %>%
#' addTiles() %>%
#' addCircleMarkers(data = breweries91,
#' popup = popupTable(breweries91))
#' leaflet() %>%
#' addTiles() %>%
#' addCircleMarkers(data = breweries91,
#' popup = popupTable(breweries91,
#' zcol = c("brewery", "zipcode", "village"),
#' feature.id = FALSE,
#' row.numbers = FALSE))
#'
#' @export popupTable
#' @name popupTable
#' @rdname popup
popupTable = function(x, zcol, row.numbers = TRUE, feature.id = TRUE) {
if (inherits(x, "sfc")) return(NULL)
brewPopupTable(x, zcol, row.numbers = row.numbers, feature.id = feature.id)
}
# create popup table of attributes
brewPopupTable = function(x,
zcol,
width = 300,
height = 300,
row.numbers = TRUE,
feature.id = TRUE) {
if (inherits(x, "Spatial")) x = x@data
if (inherits(x, "sf")) x = as.data.frame(x)
if (!missing(zcol)) x = x[, zcol, drop = FALSE]
# ensure utf-8 for column names (column content is handled on C++ side)
colnames(x) = enc2utf8(colnames(x))
if (inherits(x, "SpatialPoints")) {
mat = NULL
} else {
sf_col = attr(x, "sf_column")
# data.frame with 1 column
if (ncol(x) == 1 && !is.null(sf_col) && names(x) == sf_col) {
mat = as.matrix(class(x[, 1])[1])
} else if (ncol(x) == 1) {
mat = matrix(as.character(x[, 1]))
# data.frame with multiple columns
} else {
# check for list columns, if found format it
ids = which(sapply(x, is.list))
if (any(ids)) {
# nms = attr(ids, "names")[ids]
x[, ids] = sapply(sapply(x, class)[ids], "[[", 1) #format(x[, ids])
# #
# # for (i in nms) {
# # x[[i]] = format(x[[i]])
# }
}
# data to character matrix
mat = as.matrix(x)
attr(mat, "dimnames") = NULL
if (!inherits(mat[1], "character")) {
mat[1, 1] = as.character(mat[1, 1])
}
}
colnames(mat) = names(x)
# if (nrow(x) == 1) mat = t(mat)
}
if (feature.id) {
fid = rownames(x)
mat = cbind("Feature ID" = fid, mat)
}
## create list with row-specific html code
lst_html = listPopupTemplates(mat, row_index = row.numbers)
attr(lst_html, "popup") = "leafpop"
return(lst_html)
}
| 8d37f505838f75e3806718db02363046593b3889 | [
"R"
] | 2 | R | git-ashish/leafpop | 659a8b8d4b5a6e93dcbc781de0d142e0f5f42291 | 5e6edec4c7bc5f33233542969919b8bd678b450d |
refs/heads/master | <file_sep>var app=angular.module('navbar',['ngMaterial']);
app.run(function( $mdSidenav,$rootScope){
$rootScope.open= function(){
$mdSidenav("right").toggle()
.then(function () {
console.log("open")
});
}
$rootScope.close=function(){
$mdSidenav("right").toggle()
.then(function () {
console.log("open")
});
}
})
<file_sep>'use strict';
const gulp = require('gulp'),
jshint = require('gulp-jshint'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
cleancss = require('gulp-clean-css'),
pump = require('pump'),
rev = require('gulp-rev'),
replace = require('gulp-replace'),
revReplace = require('gulp-rev-replace'),
fs = require('fs');
const watchFiles =['app/*.js','template/*/*.ctrl.js','app_modules/*/*.ctrl.js'];
gulp.task('bundle:cssmin', () => {
gulp.src([
//css file path
'css/*.style.css',
])
.pipe(concat('bundle.css'))
.pipe(cleancss({compatibility: 'ie8', processImport: false}))
.pipe(gulp.dest('dist/css/'));
});
/*
minify external Js files for admin-end
*/
gulp.task('bundle:uglify', (cb) => {
pump([
gulp.src([
//application folder
"app/evn.js",
"app/config.js",
"app/theme.js",
"app/app.js",
"app/services.js",
"app/directive.js",
//controller
"template/*/*.ctrl.js",
"app_modules/*/*.ctrl.js",
"app_modules/*/*/*.ctrl.js"
]),
concat('bundle.js'),
uglify({output:{beautify: false, max_line_len:50000}}),
gulp.dest('dist/js/')
],cb);
});
gulp.task('default', [
'bundle:uglify',
'bundle:cssmin',
'watch'
], function() {
console.log("gulp all tasks finished");
});
//build all task
// Production binaries
gulp.task('deleteOldFiles', () => {
});
gulp.task('revision:css', () => {
fs.unlink('index.html', function(err, success){
console.log(err);
console.log(success);
});
fs.unlink('dist/rev-manifest.json', function(err, success){
console.log(err);
console.log(success);
});
setTimeout(function(){
gulp.src([
'dist/css/*.css'
], {base: 'dist/css'})
.pipe(rev())
.pipe(gulp.dest('dist/')) //stote hash css file on location dist/css/
.pipe(rev.manifest('rev-manifest.json', {
base: 'dist/', //store rev-manifest.json file on location /dist/
merge: true // merge with the existing manifest if one exists,
}))
.pipe(gulp.dest('dist/css/'))
},1000);
});
let opt = {
distFolder: 'dist/',
srcFolder: ''
}
gulp.task("build", ["deleteOldFiles","revision:css"], () => {
var manifest = gulp.src(opt.distFolder + "rev-manifest.json");
// Read from a source that remains unchanged, so the replacement values can always be found.
// return
// gulp.src("index.template.html")
// .pipe(revReplace({manifest: manifest}))
// .pipe(fs.write('index.html')) //create new file
// .pipe(gulp.dest(''));
setTimeout(function(){
return gulp.src("index.template.html")
.pipe(revReplace({manifest: manifest}))
.pipe(concat('index.html')) //create new file
.pipe(gulp.dest(''));
},1500);
});
/*
gulp watch automatically build files when changes are done js or css
*/
gulp.task('watch',function(){
gulp.watch('css/*.style.css', ['bundle:cssmin'],
function() {
console.log("gulp all tasks finished1");
});
gulp.watch(watchFiles,
['bundle:uglify'],
function() {
console.log("gulp all tasks finished2");
});
})
<file_sep>//http://stackoverflow.com/questions/35216601/angular-url-removing-using-express-to-route-request
app.get(/^((?!\/(api)).)*$/, function (req, res) {
res.render('index');
});
<file_sep># temp
sidernavbar
concat('site.min.js'),
uglify({output:{beautify: false, max_line_len:60000}}),
gulp.dest('./public/js')
<file_sep> 'use strict';
/*
Singletons – Each component dependent on a service gets a reference to the
single instance generated by the service factory
*/
angular.module('appraiser')
//bx slider
.directive('bxSlider',['$timeout',function($timeout){
return {
restrict: 'E',
scope:{
data:'=' ,
config:'='
},
template:[
'<div class="bx-slider">',
'<div class="bx-slider-loader" layout="column" layout-align="center center">',
'<md-progress-circular md-diameter="30" md-mode="indeterminate"></md-progress-circular>',
'</div>',
'<ul class="owl-carousel" style="visibility:hidden">',
'<li ng-repeat="item in data">{{item}}</li>',
'</ul></div>'].join(''),
link: function(scope, ele,attr){
scope.sliderConfig = scope.$eval(scope.config) || {};
scope.$watch('data', function(data){
if(data){
scope.initSlider(scope.sliderConfig);
}
});
scope.initSlider = function(config){
$timeout(function(){
ele.find('.bx-slider-loader').fadeOut();
ele.find('.owl-carousel').bxSlider(config);
ele.find('.owl-carousel').css({'visibility':'visible'});
},10);
};
}
};
}]);
| 8e57b45ff50c71841895fc72e1669b9dc624fc9e | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | mahendralife/temp | 7e1c15287b26d98162fd43ff4ae40099dc86571c | 6984213e634029456d513a2a2d81f876b460c294 |
refs/heads/master | <repo_name>Achway/wikijourney_website<file_sep>/README.md
# wikijourney_website
Codes for Wiki Journey's website, an Androïd application made for tourism.
<file_sep>/team.php
<?php
include("./include/haut.php");
?>
<h1><?php echo _TEAM_TITLE; ?></h1>
<h2><?php echo _TEAM_WHO_R_WE; ?></h2>
<p>
<img src="./images/design/centrale_logo.jpg" alt="Centrale Lille" style="float: right; width: 60px; padding-left: 30px;"/>
<?php echo _TEAM_QUICKDESC; ?>
</p>
<h2>Trombinoscope</h2>
<table id="trombi">
<tr>
<td class="tcol1"><img src="./images/trombi/Arn.jpg" alt="Photo" /></td>
<td class="tcol2"><span class="trombiNom"><NAME></span><br/><span class="trombiFonc">Chef de Projet<br/>Développement Web</span></td>
<td class="tcol3">J'ai rejoins le projet WikiJourney car je suis vraiment intéressé par la programmation et le développement informatique. Ce projet est pour moi l'occasion de mettre mes compétences de programmation au profit d'un réel projet, qui de plus se place dans le cadre du logiciel libre.</td>
</tr>
<tr>
<td class="tcol1"><img src="./images/trombi/Arz.jpg" alt="Photo" /></td>
<td class="tcol2"><span class="trombiNom"><NAME></span><br/><span class="trombiFonc">Serveur<br/>Développement Web</span></td>
<td class="tcol3">Je suis dans ce groupe projet de par ma passion pour l'informatique; mon domaine de prédilection est l'administration de serveurs sous Linux et le développement en C, mais néanmoins capable de coder en utilisant des technologies web. En outre, le développement du tourisme dans les pays émergents ainsi que l'explosion des nouvelles technologies est un terreau fertile pour l'innovation dans ce domaine, assez peu exploré jusqu'à maintenant.</td>
</tr>
<tr>
<td class="tcol1"><img src="./images/trombi/Gau.jpg" alt="Photo" /></td>
<td class="tcol2"><span class="trombiNom"><NAME></span><br/><span class="trombiFonc">Développement Java<br/>Développement Serveur</span></td>
<td class="tcol3">Le projet Wikijourney m'a attiré à la fois par à sa dominante informatique (développement Web et Android), et par son côté communautaire. En effet, je suis depuis longtemps un adepte des logiciels libres, et j'aimerais contribuer à mon tour au monde du Libre en participant à un projet novateur, liant tourisme et informatique, deux domaines rarement combinés.</td>
</tr>
<tr>
<td class="tcol1"><img src="./images/trombi/Hat.jpg" alt="Photo" /></td>
<td class="tcol2"><span class="trombiNom"><NAME></span><br/><span class="trombiFonc">Trésorier - Partenariats<br/>Développement Java</span></td>
<td class="tcol3">Interessé par l'informatique et l'aide à la décision, j'ai rejoint le projet WikiJourney pour m'initier à ces sujets et participer à un projet libre qui m'offrira sans doute une expérience unique et fort profitable.</td>
</tr>
<tr>
<td class="tcol1"><img src="./images/trombi/Hub.jpg" alt="Photo" /></td>
<td class="tcol2"><span class="trombiNom"><NAME></span><br/><span class="trombiFonc">Partenariats<br/>Développement Web</span></td>
<td class="tcol3">Après des années d’une formation très généraliste, je souhaitais m’intégrer à un projet concret, avec une forte emphase sur les NTIC. WikiJourney apparaissait alors comme Le projet à rejoindre pour développer mes compétences, d’autant plus qu’il répond à une problématique me touchant vraiment en tant qu’étudiant : donner un accès rapide à une information de qualité à des personnes cherchant à explorer le monde, et les guider dans leurs découvertes.</td>
</tr>
<tr>
<td class="tcol1"><img src="./images/trombi/Mae.jpg" alt="Photo" /></td>
<td class="tcol2"><span class="trombiNom"><NAME></span><br/><span class="trombiFonc">Partenariats<br/>Développement Java</span></td>
<td class="tcol3">Depuis toujours intéressée par l’informatique, j’ai rejoint WikiJourney pour développer mes connaissances et surtout participer à un projet au concept primordial. Visitant de nouvelles villes plusieurs fois par an, j’ai pu remarquer que les guides touristiques ne sont pas toujours pratiques. Les informations sont librement disponibles sur internet, mais pas facilement accessibles aux touristes.</td>
</tr>
<tr>
<td class="tcol1"><img src="./images/trombi/Wan.jpg" alt="Photo" /></td>
<td class="tcol2"><span class="trombiNom"><NAME></span><br/><span class="trombiFonc">Développement Java</span></td>
<td class="tcol3">Je connais bien les langages C et C++, et j'ai appris les langages CSS et HTML en autodidacte. Je m'intéresse à ce projet parce que c'est une bonne idée de combiner les cartes numériques avec les informations fournies par Wikipédia. De plus, le projet correspond bien à mes compétences. </td>
</tr>
</table>
<?php
include("./include/bas.php");
?><file_sep>/include/haut.php
<?php
if(isset($_COOKIE['lg']))
{
if($_COOKIE['lg'] == 'en')
include("./lg/en.php");
else if($_COOKIE['lg'] == 'fr')
include("./lg/fr.php");
else //Not normal
{
include("./lg/en.php");
setcookie("lg","en"); //Redefine cookie
}
}
else
{
include("./lg/fr.php");
setcookie("lg","fr"); //Define cookie
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo _TITLE; ?></title>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" type="text/css" title="Design" href="design.css" />
<link rel="Shortcut icon" href="./images/design/favicon.ico" />
</head>
<body>
<div id="banniere">
<table>
<tr>
<td><img id="logoban" src="<?php echo _SRC_IMAGE_LOGO; ?>" alt="Logo" /></td>
<td><p id="languagesBox">
<a href="action.php?lg=en">English</a><br/>
<a href="action.php?lg=fr">Français</a>
</p>
</td>
</tr>
</table>
<div id="menu">
<table id="liste_menu.php" style="border-collapse: separate;" >
<tr>
<td id="lien_index.php"><a href="index.php"><?php echo _INDEX ;?></a></td>
<td id="lien_team.php"><a href="team.php"><?php echo _TEAM ;?></a></td>
<td id="lien_about.php"><a href="about.php"><?php echo _ABOUT ;?></a></td>
<td id="lien_contact.php"><a href="technical.php"><?php echo _TECHNICAL ;?></a></td>
</tr>
</table>
</div>
<?php
//Colorating the active page
$nomPage = $_SERVER['PHP_SELF'];
$reg = '#^(.+[\\\/])*([^\\\/]+)$#';
$nomPage = preg_replace($reg, '$2', $nomPage);
?>
<script type="text/javascript">
document.getElementById("lien_" + "<?php echo $nomPage; ?>").style.cssText = "background-color: rgb(137,160,173);";
</script>
</div>
<div id="corps"><file_sep>/map.php
<?php
include("./include/haut_map.php");
error_reporting(E_ALL);
/* Obtain current user latitude/longitude */
if(isset($_POST['name'])) {
$name = $_POST['name'];
$osm_array_json = file_get_contents("http://nominatim.openstreetmap.org/search?q=" . urlencode($name) . "&format=json");
$osm_array = json_decode($osm_array_json, true);
$user_latitude = $osm_array[0]["lat"];
$user_longitude = $osm_array[0]["lon"];
}
else {
$user_latitude= $_POST[0];
$user_longitude= $_POST[1];
}
/* Returns a $poi_id_array_clean array with a list of wikidata pages ID within a $range km range from user location */
$range = 1;
$poi_id_array_json = file_get_contents("http://wdq.wmflabs.org/api?q=around[625,$user_latitude,$user_longitude,$range]");
$poi_id_array = json_decode($poi_id_array_json, true);
$poi_id_array_clean = $poi_id_array["items"];
$nb_poi = count($poi_id_array_clean);
$poi_array["nb_poi"] = $nb_poi;
/* stocks latitude, longitude, name and description of every POI located by ↑ in $poi_array */
for($i = 0; $i < max($nb_poi, 10); $i++) {
$temp_geoloc_array_json = file_get_contents("http://www.wikidata.org/w/api.php?action=wbgetclaims&format=json&entity=Q" . $poi_id_array_clean["$i"] . "&property=P625");
$temp_geoloc_array = json_decode($temp_geoloc_array_json, true);
$temp_latitude = $temp_geoloc_array["claims"]["P625"][0]["mainsnak"]["datavalue"]["value"]["latitude"];
$temp_longitude = $temp_geoloc_array["claims"]["P625"][0]["mainsnak"]["datavalue"]["value"]["longitude"];
$temp_description_array_json = file_get_contents("http://www.wikidata.org/w/api.php?action=wbgetentities&format=json&ids=Q" . $poi_id_array_clean["$i"] . "&props=labels&languages=fr");
$temp_description_array = json_decode($temp_description_array_json, true);
$name = $temp_description_array["entities"]["Q" . $poi_id_array_clean["$i"]]["labels"]["fr"]["value"];
$temp_sitelink_array_json = file_get_contents("http://www.wikidata.org/w/api.php?action=wbgetentities&ids=Q" . $poi_id_array_clean["$i"] . "&sitefilter=frwiki&props=sitelinks/urls&format=json");
$temp_sitelink_array = json_decode($temp_sitelink_array_json, true);
$temp_sitelink = $temp_sitelink_array["entities"]["Q" . $poi_id_array_clean["$i"]]["sitelinks"]["frwiki"]["url"];
$poi_array[$i]["latitude"] = $temp_latitude;
$poi_array[$i]["longitude"] = $temp_longitude;
$poi_array[$i]["name"] = $name;
$poi_array[$i]["sitelink"] = $temp_sitelink;
}
$poi_array_json_encoded = json_encode((array)$poi_array);
?>
<div id="map" class="map"></div>
<script>
var poi_array = new Array();
poi_array = <?php echo($poi_array_json_encoded); ?>;
user_latitude = <?php echo($user_latitude); ?>;
user_longitude = <?php echo($user_longitude); ?>;
L.mapbox.accessToken = '<KEY>';
var map = L.mapbox.map('map', 'polochon-street.kpogic18')
/* place the first marker with 50% opacity to distinguish it */
//var marker = L.marker([user_latitude, user_longitude], {opacity:0.5, color: '#fa0'}).addTo(map);
var marker = L.marker([user_latitude, user_longitude], { icon: L.mapbox.marker.icon({
'marker-size': 'large',
'marker-symbol': 'pitch',
'marker-color': '#fa0'
})}).addTo(map);
//Cf liste complète des symboles : https://www.mapbox.com/maki/
marker.bindPopup("Vous êtes ici !").openPopup();
/* place wiki POI */
for(i = 0; i < Math.max(poi_array.nb_poi, 10); ++i) {
var popup_content = new Array();
if(poi_array[i].sitelink != null)
popup_content = poi_array[i].name + "<br /> <p><a target=\"_blank\" href=\"http:" + poi_array[i].sitelink + "\">Lien wikipédia</a> <br /> <a href=\"http://perdu.com\">[+]</a></p>";
else
popup_content = poi_array[i].name + "<br /> <a href=\"http://perdu.com\">[+]</a></p>";
var marker = L.marker([poi_array[i].latitude, poi_array[i].longitude]).addTo(map);
marker.bindPopup(popup_content).openPopup();
}
map.setView([user_latitude, user_longitude], 15);
</script>
<?php
include("./include/bas.php");
?>
<file_sep>/lg/en.php
<?php
//========================================================//
//===============> LANGAGE FILE : ENGLISH <===============//
//========================================================//
//===================> Global Content <===================//
//===> General
define("_TITLE", "Wiki Journey - Revisitez le tourisme.");
define("_SRC_IMAGE_LOGO", "./images/design/logo_and_catchphrase/en.png");
//===> Top
define("_INDEX", "Index");
define("_TEAM", "Team");
define("_ABOUT", "About");
define("_TECHNICAL", "Technical Informations");
//===> Bottom
define("_OUR_PARTNERS", "Our partners");
define("_NO_PARTNERS_LOL", "No partners for the moment. If interested in a partnership, contact us !");
//========================> Pages <========================//
//===> index.php
define("_WELCOME_TITLE", "Welcome!");
define("_BUTTON_POI_AROUND","Find Point Of Interest around me!");
define("_ADRESS_LOOK_UP", "Or enter an adress to look up!");
//===> team.php
define("_TEAM_TITLE", "Our Team!");
define("_TEAM_WHO_R_WE", "Who are we?");
define("_TEAM_QUICKDESC", "We're a team of seven students from the Ecole Centrale de Lille, a graduate school in Lille in the north of France. We
have to create a multidisciplinary project in two years, that's how we started to work together on WikiJourney. This project
is really important for us, that's why we will make everything we could to achieve it.");
//===> about.php
define("_ABOUT_TITLE", "Tell me more about WikiJourney");
define("_ABOUT_TEXT"," <p>It's a student project, which was made to connect a user and Wikimedia content, linked by its position in a city.<br/>
We are trying to release a mobile app which will recommend to tourists some points of interest to visit. Adjust your settings, chose a path, and let's go!
</p>
<h2>Why an application?</h2>
<p>
Because it's the more portative way, and the simplest when we talk about tourism. When you're walking in a city, you'd rather take a quick look at your phone than using your laptop, aren't you?
<br/>It will also be possible to prepare ones trip before, on a computer. Data will be viewable thanks to an offline mode.
</p>
<h2>WanderWiki is back! </h2>
<p>
You already knew about <a href=\"http://wiki-geolocalisation.wix.com/\">WanderWiki</a>? Great! WikiJourney is the pursuit of this project. We are trying to make
it more powerful, with new functionalities.</p>
<h2>Questions, Proposals...?</h2>
<p>We are listening to anyone! Contribute on our Git, or <a href=\"mailto:<EMAIL>\">send us a mail</a>!</p>");
//===> technical.php
define("_TECHNICAL_TITLE", "Technical Informations");
define("_TECHNICAL_TEXT", "This website is still under construction, please come back later ;)");
<file_sep>/include/bas.php
<br/><br/>
</div>
<div id="pied">
<table>
<tr>
<th><?php echo _OUR_PARTNERS; ?></th>
<!--<th>Statut Légal</th>-->
</tr>
<tr>
<td><?php echo _NO_PARTNERS_LOL; ?></td>
<!--<td>Blabla</td>-->
</tr>
</table>
</div>
</body>
</html>
<file_sep>/lg/fr.php
<?php
//========================================================//
//============> <NAME> : FRANCAIS <============//
//========================================================//
//===================> Global Content <===================//
//===> General
define("_TITLE", "Wiki Journey - Revisitez le tourisme.");
define("_SRC_IMAGE_LOGO", "./images/design/logo_and_catchphrase/fr.png");
//===> Top
define("_INDEX", "Accueil");
define("_TEAM", "L'Équipe");
define("_ABOUT", "À propos");
define("_TECHNICAL", "Informations Techniques");
//===> Bottom
define("_OUR_PARTNERS", "Nos partenaires");
define("_NO_PARTNERS_LOL", "Pas de partenaires pour l'instant. Un partenariat vous intéresse ? Contactez nous !");
//========================> Pages <========================//
//===> index.php
define("_WELCOME_TITLE", "Bienvenue !");
define("_BUTTON_POI_AROUND","Trouver des points d'intérêts autour de moi !");
define("_ADRESS_LOOK_UP", "Ou à proximité d'une adresse !");
//===> team.php
define("_TEAM_TITLE", "Notre Équipe");
define("_TEAM_WHO_R_WE", "Qui sommes nous ?");
define("_TEAM_QUICKDESC", "Nous sommes une équipe de sept étudiants de l'École Centrale de Lille, école d'ingénieur généraliste située à Lille,
dans le Nord de la France. Il nous est imposé durant nos deux premières années d'études de développer un projet
multidisciplinaire, dans lequel nous mettrons nos connaissances en commun. Nous nous sommes donc retrouvés à sept
sur ce projet." );
//===> about.php
define("_ABOUT_TITLE", "Qu’est-ce que Wikijourney ?");
define("_ABOUT_TEXT","
<p>Wikijourney est un projet étudiant visant à mettre en lien un utilisateur et le contenu informatif de Wikipedia, via sa position dans une ville.
<br> Concrètement, nous souhaitons coder une application qui proposerait au touriste des points d’intérêts à visiter. Rentrez vos préférences, choisissez un itinéraire et c’est parti !
</p>
<h2>Pourquoi une application ? </h2>
<p>
Tout simplement parce qu’il s’agit du moyen technologique le plus portatif. Grâce aux forfaits 3G, il est plus simple de jeter un coup d’oeil à son portable pour obtenir des informations, un itinéraire, que de transporter avec soi son ordinateur !
<br>Nous proposerons également de préparer son parcours à l’avance, via un module web ainsi qu’un mode hors-ligne.
</p>
<h2>WanderWiki revient ! </h2>
<p>
Si vous utilisiez déjà l’application <a href=\"http://wiki-geolocalisation.wix.com/wanderwiki\">WanderWiki</a>, vous ne serez pas désorientés : WikiJourney reprend le projet. Wanderwiki revient, avec une nouvelle charte graphique et de nouvelles fonctionnalités !
</p>
<h2>Des questions, des propositions ? </h2>
<p>
Nous sommes ouverts à toute piste d’amélioration ! Contribuez au projet <a href=\"mailto:<EMAIL>\">en nous contactant par mail</a> ou en codant directement tes propositions sur notre Git !
</p>");
//===> technical.php
define("_TECHNICAL_TITLE", "Informations Techniques");
define("_TECHNICAL_TEXT", "Ce site web est encore en construction, merci de revenir plus tard ! ;)");
| d133f0739e35f86d7550871ea2cfbc458ec37e88 | [
"Markdown",
"PHP"
] | 7 | Markdown | Achway/wikijourney_website | 9fad01684bd60ed7b6107ff5ce238e1d50f806ab | 9b18ffd95629916dd0b3802add99822b5e458cf2 |
refs/heads/master | <repo_name>dwisulfahnur/devlovers<file_sep>/schema/roles.sql
INSERT INTO `roles` (`id`, `name`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'Software Engineer', NULL, NULL, NULL),
(2, 'Backend Programmer', NULL, NULL, NULL),
(3, 'Frontend Programmer', NULL, NULL, NULL),
(4, 'Web Designer', NULL, NULL, NULL);
<file_sep>/app/Http/Controllers/Auth/RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests;
use App\Http\Requests\UserRequest;
use App\Http\Requests\LoginRequest;
use App\Http\Controllers\Controller;
class RegisterController extends Controller
{
public function register()
{
$roles = DB::table('roles')->select('id', 'name')->get();
$programming_languages = DB::table('programming_languages')->select('id','name')->get();
$cities = DB::table('cities')->select('id', 'name')->get();
$data['roles'] = $roles;
$data['programming_languages'] = $programming_languages;
$data['cities'] = $cities;
return view('auth.register', $data);
}
public function postRegister(UserRequest $request)
{
//hashing password of Password field
$password = <PASSWORD>($request->input('password'));
//Set Name of Profile_piture File
$imageName = $request->input('username').time().'.'.$request->image->getClientOriginalExtension();
//Create Objects of User and User programming language
$user = [
'full_name' => $request->input('full_name'),
'email' => $request->input('email'),
'username' => $request->input('username'),
'password' => $<PASSWORD>,
'dob' => $request->input('dob'),
'gender' => $request->input('gender'),
'roles_id' => $request->input('roles'),
'city_id' => $request->input('city'),
'profile_picture' => $imageName,
"created_at" => \Carbon\Carbon::now(),
"updated_at" => \Carbon\Carbon::now()
];
$user_programming_languages = $request->input('programming_languages');
//Save User data and Profile picture to Storage if not Fail.
$image = \Input::file('image');
if ( \Image::make($image->getRealPath())->resize(250, 250)->save(storage_path('images/').$imageName) And DB::table('users')->insert([$user]) )
{
$user_self_id = DB::table('users')->where('email', $user['email'])->first()->id;
if($user_self_id){
foreach ($user_programming_languages as $language) {
DB::table('users_programming_languages')->insert(['user_id' => $user_self_id, 'programming_languages_id' => $language]);
}
return redirect()->route('login')->with('success','You has resgistered, login please!');
}
}
else{
return redirect()->back()->withErrors('Failed to save user data');
}
}
}
<file_sep>/app/Libraries/DevLovers/UserLike.php
<?php
namespace App\Libraries\DevLovers;
use Illuminate\Support\Facades\DB;
class UserLike
{
static function getUserLike($user_self_id, $target_user_id)
{
$user = DB::table('users_likes')->where('user_id', $user_self_id)
->where('target_user_id', $target_user_id)
->first();
return $user;
}
static function createUserLike($user_self_id, $target_user_id, $like)
{
$user_like = ['user_id' => $user_self_id,
'target_user_id' => $target_user_id,
'like' => $like,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
];
DB::table('users_likes')->insert($user_like);
}
static function updateUserLike($user_self_id, $target_user_id, $like)
{
DB::table('users_likes')->where('user_id', $user_self_id)
->where('target_user_id', $target_user_id)
->update(['like' => $like, 'updated_at' => \Carbon\Carbon::now()]);
}
}
<file_sep>/app/Http/Controllers/DevLovers/LikeController.php
<?php
namespace App\Http\Controllers\DevLovers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Libraries\DevLovers\UserObject;
use App\Libraries\DevLovers\UserLike;
use App\Libraries\DevLovers\UserMatch;
class LikeController extends Controller
{
public function like(Request $request)
{
//------------------------- Handle like request and user matches ---------------------------//
if($request->has('like','target')){
$user_self_id = session('id');
$target_user_id = $request->input('target');
$like = $request->input('like') ? 1 : 0;
$user_like = UserLike::getUserLike($user_self_id, $target_user_id);
if($user_like And !($user_like->like === $like)){
if($like === 1){
if(UserMatch::isMatch($user_self_id, $target_user_id)){ //check if User is Match
UserMatch::createMatch($user_self_id, $target_user_id); //Create User Match
}
if($user_like->like === 0){ //If user want to change dislike to like
UserLike::updateUserLike($user_self_id, $target_user_id, $like); //Update to Like (1)
}
}
}
if(!$user_like){
UserLike::createUserLike($user_self_id, $target_user_id, $like);
if(UserMatch::isMatch($user_self_id, $target_user_id)){ //check if User is Match
UserMatch::createMatch($user_self_id, $target_user_id); //Create User Match
}
}
}
return redirect()->back();
}
}
<file_sep>/schema/city.sql
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'ADL', 'Kabupaten Konawe Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'AFT', 'Kabupaten Maybrat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'AGM', 'Kabupaten Bengkulu Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'AGT', 'Kabupaten Asmat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'AKK', 'Kabupaten Labuhanbatu Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'AMB', 'Kota Ambon', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'AMR', 'Kabupaten Minahasa Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'AMS', 'Kabupaten Sorong', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'AMT', 'Kabupaten Hulu Sungai Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'APN', 'Kabupaten Tojo Una Una', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'ARM', 'Kabupaten Minahasa Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'ARS', 'Kabupaten Solok', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'ATB', 'Kabupaten Belu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BAA', 'Kabupaten Rote Ndao', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BAN', 'Kabupaten Bantaeng', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BAR', 'Kabupaten Barru', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BAU', 'Kota Bau Bau', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BBS', 'Kabupaten Brebes', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BBU', 'Kabupaten Way Kanan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BDG', 'Kota Bandung', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BDL', 'Kota Bandar Lampung', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BDW', 'Kabupaten Bondowoso', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BEK', 'Kabupaten Bengkayang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BEN', 'Kabupaten Kepulauan Selayar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BGK', 'Kabupaten Morowali', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BGL', 'Kota Bengkulu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BGR', 'Kota Bogor', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BHN', 'Kabupaten Kaur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BIK', 'Kabupaten Biak Numfor', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BIM', 'Kota Bima', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BIR', 'Kabupaten Bireuen', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BIT', 'Kota Bitung', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BJB', 'Kota Banjarbaru', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BJM', 'Kota Banjarmasin', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BJN', 'Kabupaten Bojonegoro', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BJR', 'Kota Banjar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BJW', 'Kabupaten Ngada', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BKJ', 'Kabupaten Gayo Lues', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BKL', 'Kabupaten Bangkalan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BKN', 'Kabupaten Kampar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BKO', 'Kabupaten Merangin', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BKS', 'Kota Bekasi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BKT', 'Kota Bukittinggi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BLA', 'Kabupaten Blora', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BLG', 'Kabupaten Toba Samosir', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BLI', 'Kabupaten Bangli', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BLK', 'Kabupaten Bulukumba', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BLN', 'Kabupaten Tanah Bumbu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BLS', 'Kabupaten Bengkalis', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BLT', 'Kota Blitar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BLU', 'Kabupaten Bolaang Mongondow Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BNA', 'Kota Banda Aceh', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BNG', 'Kabupaten Buton Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BNJ', 'Kota Binjai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BNR', 'Kabupaten Banjarnegara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BNT', 'Kabupaten Barito Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BON', 'Kota Bontang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BPD', 'Kabupaten Aceh Barat Daya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BPP', 'Kota Balikpapan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BRB', 'Kabupaten Hulu Sungai Tengah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BRG', 'Kabupaten Manggarai Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BRK', 'Kabupaten Bolaang Mongondow Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BRM', 'Kabupaten Mamberamo Raya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BSB', 'Kabupaten Bintan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BSK', 'Kabupaten Tanah Datar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BTA', 'Kabupaten Ogan Komering Ulu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BTG', 'Kabupaten Batang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BTI', 'Kabupaten Teluk Bintuni', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BTL', 'Kabupaten Bantul', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BTM', 'Kota Batam', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BTU', 'Kota Batu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BTW', 'Kabupaten Waropen', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BUL', 'Kabupaten Buol', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BYL', 'Kabupaten Boyolali', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'BYW', 'Kabupaten Banyuwangi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CAG', 'Kabupaten Aceh Jaya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CBI', 'Kabupaten Bogor', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CBN', 'Kota Cirebon', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CJR', 'Kabupaten Cianjur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CKG', 'Kota Adm. Jakarta Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CKR', 'Kabupaten Bekasi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CLG', 'Kota Cilegon', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CLP', 'Kabupaten Cilacap', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CMH', 'Kota Cimahi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CMS', 'Kabupaten Ciamis', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CPT', 'Kota Tangerang Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'CRP', 'Kabupaten Rejang Lebong', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'DGL', 'Kabupaten Donggala', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'DKL', 'Kabupaten Lingga', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'DLS', 'Kabupaten Humbang Hasundutan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'DMK', 'Kabupaten Demak', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'DOB', 'Kabupaten Kepulauan Aru', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'DPK', 'Kota Depok', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'DPR', 'Kota Denpasar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'DPU', 'Kabupaten Dompu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'DRH', 'Kabupaten Seram Bagian Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'DTH', 'Kabupaten Seram Bagian Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'DUM', 'Kota Dumai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'ELL', 'Kabupaten Yalimo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'END', 'Kabupaten Ende', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'ENR', 'Kabupaten Enrekang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'ERT', 'Kabupaten Paniai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'FEF', 'Kabupaten Tambrauw', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'FFK', 'Kabupaten Fak Fak', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'GDT', 'Kabupaten Pesawaran', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'GGP', 'Kota Adm. Jakarta Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'GIN', 'Kabupaten Gianyar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'GNS', 'Kabupaten Lampung Tengah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'GNT', 'Kabupaten Padang Lawas Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'GRG', 'Kabupaten Lombok Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'GRT', 'Kabupaten Garut', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'GSK', 'Kabupaten Gresik', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'GST', 'Kabupaten Nias', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'GTO', 'Kabupaten Gorontalo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'IDL', 'Kabupaten Ogan Ilir', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'IDM', 'Kabupaten Indramayu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'ILG', 'Kabupaten Puncak', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'JAP', 'Kabupaten Jayapura', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'JBG', 'Kabupaten Jombang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'JLL', 'Kabupaten Halmahera Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'JMB', 'Kota Jambi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'JMR', 'Kabupaten Jember', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'JNP', 'Kabupaten Jeneponto', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'JPA', 'Kabupaten Jepara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'JTH', 'Kabupaten Aceh Besar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KAG', 'Kabupaten Ogan Komering Ilir', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KBA', 'Kabupaten Bangka Tengah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KBG', 'Kabupaten Tolikara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KBJ', 'Kabupaten Karo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KBK', 'Kabupaten Mamberamo Tengah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KBM', 'Kabupaten Kebumen', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KBR', 'Kabupaten Kotabaru', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KDI', 'Kota Kendari', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KDL', 'Kabupaten Kendal', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KDR', 'Kabupaten Kediri', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KDS', 'Kabupaten Kudus', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KEP', 'Kabupaten Mappi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KFM', 'Kabupaten Timor Tengah Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KGM', 'Kabupaten Dogiyai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KGN', 'Kabupaten Hulu Sungai Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KIS', 'Kabupaten Asahan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KJN', 'Kabupaten Pekalongan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KKA', 'Kabupaten Kolaka', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KKN', 'Kabupaten Gunung Mas', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KLA', 'Kabupaten Lampung Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KLB', 'Kabupaten Alor', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KLK', 'Kabupaten Kapuas', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KLN', 'Kabupaten Klaten', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KLP', 'Kabupaten Seruyan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KLT', 'Kabupaten Tanjung Jabung Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KMN', 'Kabupaten Kaimana', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KNG', 'Kabupaten Kuningan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KNR', 'Kabupaten Blitar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KOT', 'Kabupaten Tanggamus', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KPG', 'Kabupaten Kupang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KPH', 'Kabupaten Kepahiang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KPI', 'Kabupaten Labuhanbatu Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KPN', 'Kabupaten Malang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KRA', 'Kabupaten Karangasem', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KRB', 'Kabupaten Aceh Tamiang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KRG', 'Kabupaten Karanganyar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KRS', 'Kabupaten Probolinggo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KRT', 'Kabupaten Bengkulu Tengah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KSN', 'Kabupaten Katingan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KSU', 'Kabupaten Adm. Kepulauan Seribu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KTB', 'Kabupaten Lampung Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KTG', 'Kota Kotamobagu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KTN', 'Kabupaten Aceh Tenggara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KTP', 'Kabupaten Ketapang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KWD', 'Kabupaten Gorontalo Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KWG', 'Kabupaten Karawang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KYB', 'Kota Adm. Jakarta Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'KYM', 'Kabupaten Nduga', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LBA', 'Kabupaten Halmahera Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LBB', 'Kabupaten Agam', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LBJ', 'Kabupaten Manggarai Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LBP', 'Kabupaten Deli Serdang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LBS', 'Kabupaten Pasaman', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LGS', 'Kabupaten Aceh Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LHM', 'Kabupaten Nias Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LHT', 'Kabupaten Lahat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LIW', 'Kabupaten Lampung Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LLG', 'Kota Lubuk Linggau', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LLK', 'Kabupaten Bolaang Mongondow', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LMG', 'Kabupaten Lamongan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LMJ', 'Kabupaten Lumajang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LMP', 'Kabupaten Batu Bara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LRT', 'Kabupaten Flores Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LSK', 'Kabupaten Aceh Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LSM', 'Kota Lhokseumawe', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LSS', 'Kabupaten Kolaka Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LTU', 'Kabupaten Nias Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LWK', 'Kabupaten Banggai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'LWL', 'Kabupaten Lembata', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MAB', 'Kabupaten Halmahera Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MAD', 'Kota Madiun', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MAK', 'Kabupaten Tana Toraja', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MAM', 'Kabupaten Mamuju', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MAR', 'Kabupaten Pahuwato', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MBL', 'Kabupaten Musi Rawas', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MBN', 'Kabupaten Batanghari', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MBO', 'Kabupaten Aceh Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MBY', 'Kabupaten Nagekeo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MDN', 'Kota Medan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MET', 'Kota Metro', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MGG', 'Kota Magelang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MGL', 'Kabupaten Tulang Bawang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MGN', 'Kabupaten Kepulauan Talaud', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MGR', 'Kabupaten Belitung Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MGT', 'Kabupaten Magetan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MGW', 'Kabupaten Badung', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MJK', 'Kabupaten Mojokerto', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MJL', 'Kabupaten Majalengka', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MJN', 'Kabupaten Majene', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MJY', 'Kabupaten Madiun', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MKD', 'Kabupaten Magelang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MKM', 'Kabupaten Muko Muko', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MKS', 'Kota Makassar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MLG', 'Kota Malang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MLL', 'Kabupaten Luwu Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MLN', 'Kabupaten Malinau', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MME', 'Kabupaten Sikka', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MMS', 'Kabupaten Mamasa', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MNA', 'Kabupaten Bengkulu Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MND', 'Kota Manado', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MNK', 'Kabupaten Manokwari', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MPR', 'Kabupaten Oku Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MPW', 'Kabupaten Pontianak', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MRB', 'Kabupaten Bungo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MRD', 'Kabupaten Oku Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MRE', 'Kabupaten Muara Enim', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MRH', 'Kabupaten Barito Kuala', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MRJ', 'Kabupaten Sijunjung', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MRK', 'Kabupaten Merauke', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MRN', 'Kabupaten Pidie Jaya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MRS', 'Kabupaten Maros', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MRT', 'Kabupaten Tebo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MSB', 'Kabupaten Luwu Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MSH', 'Kabupaten Maluku Tengah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MSJ', 'Kabupaten Mesuji', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MSK', 'Kabupaten Tanjung Jabung Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MTK', 'Kabupaten Bangka Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MTP', 'Kabupaten Banjar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MTR', 'Kota Mataram', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MTS', 'Kabupaten Pulau Morotai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MTW', 'Kabupaten Barito Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'MUL', 'Kabupaten Puncak Jaya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NAB', 'Kabupaten Nabire', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NBA', 'Kabupaten Landak', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NGA', 'Kabupaten Jembrana', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NGB', 'Kabupaten Lamandau', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NGP', 'Kabupaten Melawi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NGW', 'Kabupaten Ngawi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NJK', 'Kabupaten Nganjuk', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NLA', 'Kabupaten Buru', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NMR', 'Kabupaten Buru Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NNK', 'Kabupaten Nunukan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NPH', 'Kabupaten Bandung Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'NPM', 'Kabupaten Padang Pariaman', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'ODS', 'Kabupaten Kepulauan Siau Tagulandang Biaro', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'OSB', 'Kabupaten Pegunungan Bintang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PAD', 'Kota Padang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PAL', 'Kota Palu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PBG', 'Kabupaten Purbalingga', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PBL', 'Kota Probolinggo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PBM', 'Kota Prabumulih', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PBR', 'Kota Pekanbaru', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PBU', 'Kabupaten Kotawaringin Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PCT', 'Kabupaten Pacitan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PDA', 'Kabupaten Solok Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PDG', 'Kabupaten Pandeglang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PDP', 'Kota Padang Panjang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PGA', 'Kota Pagar Alam', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PGP', 'Kota Pangkal Pinang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PIN', 'Kabupaten Pinrang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PKB', 'Kabupaten Banyuasin', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PKJ', 'Kabupaten Pangkajene Kepulauan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PKK', 'Kabupaten Pelalawan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PKL', 'Kota Pekalongan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PKY', 'Kabupaten Mamuju Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PLG', 'Kota Palembang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PLI', 'Kabupaten Tanah Laut', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PLJ', 'Kabupaten Dharmasraya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PLK', 'Kota Palangkaraya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PLP', 'Kabupaten Luwu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PLW', 'Kabupaten Polewali Mandar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PMK', 'Kabupaten Pamekasan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PML', 'Kabupaten Pemalang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PMN', 'Kota Pariaman', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PMS', 'Kabupaten Simalungun', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PNG', 'Kabupaten Ponorogo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PNJ', 'Kabupaten Penajam Paser Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PNN', 'Kabupaten Pesisir Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PPS', 'Kabupaten Pulang Pisau', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PRC', 'Kabupaten Murung Raya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PRE', 'Kota Pare Pare', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PRG', 'Kabupaten Parigi Moutong', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PRN', 'Kabupaten Balangan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PRP', 'Kabupaten Rokan Hulu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PRR', 'Kabupaten Samosir', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PRW', 'Kabupaten Pringsewu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PSN', 'Kota Pasuruan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PSO', 'Kabupaten Poso', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PSP', 'Kabupaten Tapanuli Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PSR', 'Kabupaten Pasuruan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PSW', 'Kabupaten Buton', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PTI', 'Kabupaten Pati', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PTK', 'Kota Pontianak', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PTS', 'Kabupaten Kapuas Hulu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PWD', 'Kabupaten Grobogan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PWK', 'Kabupaten Purwakarta', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PWR', 'Kabupaten Purworejo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PWT', 'Kabupaten Banyumas', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PYA', 'Kabupaten Lombok Tengah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PYB', 'Kabupaten Mandailing Natal', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'PYH', 'Kota Payakumbuh', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RAH', 'Kabupaten Muna', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RAN', 'Kabupaten Natuna', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RAP', 'Kabupaten Labuhanbatu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RAS', 'Kabupaten Teluk Wondama', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RBG', 'Kabupaten Rembang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RGT', 'Kabupaten Indragiri Hulu', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RKB', 'Kabupaten Lebak', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RMB', 'Kabupaten Bombana', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RTA', 'Kabupaten Tapin', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RTG', 'Kabupaten Manggarai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RTN', 'Kabupaten Minahasa Tenggara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'RTP', 'Kabupaten Toraja Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SAB', 'Kota Sabang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SAG', 'Kabupaten Sanggau', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SAK', 'Kabupaten Siak', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SAL', 'Kabupaten Pakpak Bharat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SBB', 'Kabupaten Sabu Raijua', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SBG', 'Kabupaten Tapanuli Tengah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SBH', 'Kabupaten Padang Lawas', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SBM', 'Kabupaten Sukabumi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SBR', 'Kabupaten Cirebon', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SBS', 'Kabupaten Sambas', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SBW', 'Kabupaten Sumbawa', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SBY', 'Kota Surabaya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SDA', 'Kabupaten Sidoarjo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SDK', 'Kabupaten Dairi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SDN', 'Kabupaten Lampung Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SDR', 'Kabupaten Sidenreng Rappang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SDW', 'Kabupaten Kutai Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SED', 'Kabupaten Sekadau', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SEL', 'Kabupaten Lombok Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SGB', 'Kabupaten Sigi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SGI', 'Kabupaten Pidie', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SGL', 'Kabupaten Bangka', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SGM', 'Kabupaten Gowa', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SGN', 'Kabupaten Sragen', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SGP', 'Kabupaten Intan Jaya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SGR', 'Kabupaten Buleleng', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SGT', 'Kabupaten Kutai Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SIT', 'Kabupaten Situbondo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SKB', 'Kota Sukabumi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SKD', 'Kabupaten Kayong Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SKG', 'Kabupaten Wajo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SKH', 'Kabupaten Sukoharjo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SKL', 'Kabupaten Aceh Singkil', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SKM', 'Kabupaten Nagan Raya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SKN', 'Kabupaten Banggai Kepulauan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SKR', 'Kabupaten Sukamara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SKT', 'Kota Surakarta', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SKW', 'Kota Singkawang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SKY', 'Kabupaten Musi Banyuasin', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SLK', 'Kota Solok', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SLT', 'Kota Salatiga', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SLW', 'Kabupaten Tegal', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SMD', 'Kabupaten Sumedang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SMG', 'Kota Semarang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SMH', 'Kabupaten Yahukimo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SMI', 'Kabupaten Sarmi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SML', 'Kabupaten Maluku Tenggara Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SMN', 'Kabupaten Sleman', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SMP', 'Kabupaten Sumenep', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SMR', 'Kota Samarinda', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SNB', 'Kabupaten Simeulue', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SNG', 'Kabupaten Subang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SNJ', 'Kabupaten Sinjai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SNN', 'Kabupaten Kepulauan Sula', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SNT', 'Kabupaten Muaro Jambi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SOE', 'Kabupaten Timor Tengah Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SON', 'Kota Sorong', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SOR', 'Kabupaten Bandung', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SPA', 'Kabupaten Tasikmalaya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SPE', 'Kabupaten Pasaman Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SPG', 'Kabupaten Sampang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SPN', 'Kabupaten Kerinci', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SPT', 'Kabupaten Kotawaringin Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SRG', 'Kabupaten Serang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SRH', 'Kabupaten Serdang Bedagai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SRK', 'Kabupaten Lima Puluh Kota', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SRL', 'Kabupaten Sarolangun', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SRP', 'Kabupaten Klungkung', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SRU', 'Kabupaten Kepulauan Yapen', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SRW', 'Kabupaten Supiori', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SRY', 'Kabupaten Kubu Raya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'STB', 'Kabupaten Langkat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'STG', 'Kabupaten Sintang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'STR', 'Kabupaten Bener Meriah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SUS', 'Kota Subulussalam', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SWL', 'Kota Sawahlunto', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'SWW', 'Kabupaten Bone Bolango', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TAB', 'Kabupaten Tabanan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TAM', 'Kabupaten Sumba Barat Daya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TAR', 'Kota Tarakan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TAS', 'Kabupaten Seluma', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TBG', 'Kabupaten Empat Lawang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TBH', 'Kabupaten Indragiri Hilir', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TBK', 'Kabupaten Karimun', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TBL', 'Kabupaten Bangka Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TBN', 'Kabupaten Tuban', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TBT', 'Kota Tebing Tinggi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TDN', 'Kabupaten Belitung', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TDP', 'Kabupaten Tana Tidung', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TDR', 'Kota Tidore Kepulauan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TGL', 'Kota Tegal', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TGR', 'Kabupaten Tangerang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TGT', 'Kabupaten Paser', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'THN', 'Kabupaten Kepulauan Sangihe', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TIG', 'Kabupaten Deiyai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TIM', 'Kabupaten Mimika', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TJB', 'Kota Tanjung Balai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TJG', 'Kabupaten Tabalong', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TJN', 'Kabupaten Lombok Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TJP', 'Kota Adm. Jakarta Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TJS', 'Kabupaten Bulungan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TKA', 'Kabupaten Takalar', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TKN', 'Kabupaten Aceh Tengah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TKR', 'Kabupaten Maluku Barat Daya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TLD', 'Kabupaten Nias Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TLG', 'Kabupaten Tulungagung', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TLI', 'Kabupaten Toli Toli', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TLK', 'Kabupaten Kuantan Singingi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TLW', 'Kabupaten Sumbawa Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TMB', 'Kabupaten Sorong Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TMG', 'Kabupaten Temanggung', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TMH', 'Kota Tomohon', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TML', 'Kabupaten Barito Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TMR', 'Kabupaten Boven Digoel', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TMT', 'Kabupaten Boalemo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TNA', 'Kota Adm. Jakarta Pusat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TNG', 'Kota Tangerang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TNN', 'Kabupaten Minahasa', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TNR', 'Kabupaten Berau', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TOB', 'Kabupaten Halmahera Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TOM', 'Kabupaten Lanny Jaya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TPG', 'Kota Tanjung Pinang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TPT', 'Kabupaten Kepulauan Mentawai', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TRG', 'Kabupaten Kutai Kertanegara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TRK', 'Kabupaten Trenggalek', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TRP', 'Kabupaten Kepulauan Anambas', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TRT', 'Kabupaten Tapanuli Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TSM', 'Kota Tasikmalaya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TTE', 'Kota Ternate', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TTG', 'Kabupaten Kepulauan Meranti', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TTN', 'Kabupaten Aceh Selatan', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TTY', 'Kabupaten Bolaang Mongondow Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TUB', 'Kabupaten Lebong', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TUL', 'Kabupaten Maluku Tenggara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'TWG', 'Kabupaten Tulang Bawang Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'UJT', 'Kabupaten Rokan Hilir', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'UNH', 'Kabupaten Konawe', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'UNR', 'Kabupaten Semarang', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WAM', 'Kabupaten Jayawijaya', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WAS', 'Kabupaten Raja Ampat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WAT', 'Kabupaten Kulon Progo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WBL', 'Kabupaten Sumba Tengah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WED', 'Kabupaten Halmahera Tengah', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WGD', 'Kabupaten Konawe Utara', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WGP', 'Kabupaten Sumba Timur', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WGW', 'Kabupaten Wakatobi', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WHO', 'Kabupaten Bima', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WKB', 'Kabupaten Sumba Barat', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WNG', 'Kabupaten Wonogiri', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WNO', 'Kabupaten Gunung Kidul', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WNS', 'Kabupaten Soppeng', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WRS', 'Kabupaten Keerom', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WSB', 'Kabupaten Wonosobo', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'WTP', 'Kabupaten Bone', 1);
INSERT INTO `cities`(`code`,`name`, `country_id`) VALUES ( 'YYK', 'Kota Yogyakarta', 1);
<file_sep>/app/Libraries/DevLovers/UserMatch.php
<?php
namespace App\Libraries\DevLovers;
use Illuminate\Support\Facades\DB;
class UserMatch
{
static function isMatch($user_self_id, $target_user_id)
{
$user1 = UserLike::getUserLike($user_self_id, $target_user_id);
$user2 = UserLike::getUserLike($target_user_id, $user_self_id);
if( !$user1 and !$user2 ){
return false;
}
return true;
}
static function createMatch($user_self_id, $target_user_id)
{
$user_matches = [['user_id' => $user_self_id,
'user_match_id' => $target_user_id,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()],
['user_id' => $target_user_id,
'user_match_id' => $user_self_id,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]];
DB::table('users_matches')->insert($user_matches);
}
}
<file_sep>/README.md
# How to run DevLovers App
## Clone repository
<tt>git clone https://gitlab.com/dwisulfahnur/devlovers</tt>
## Configure App
First, Go to the directory where the project is.
copy file .env.example to .env
<tt>copy .env.example .env </tt>
Install composer package require and generate key for laravel
<tt> composer install </tt>
<tt>php artisan key:generate </tt>
## Configure Database
This app using Mysql as database.
You need a database.
To setup database to this application, setup in .env file and enter the command below
<tt>php artisan migrate</tt>
Then, you need some schema file in your database like Country, City and Roles. You will found schema directory on this repository.
Import some schema in the directory to your database
then Run the app using the command below:
<tt>php artisan serve</tt>
Happy testing :)<file_sep>/app/Http/Controllers/DevLovers/FileController.php
<?php
namespace App\Http\Controllers\DevLovers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use File;
class FileController extends Controller
{
public function getImage($profile_picture)
{
$path = storage_path() . '/images/' . $profile_picture;
if(!File::exists($path)) abort(404);
$file = File::get($path);
$type = File::mimeType($path);
$response = \Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
}
}
<file_sep>/schema/countries.sql
INSERT INTO `countries` (`id`, `name`, `code`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'INDONESIA', 'IND', NULL, NULL, NULL);
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::get('', function(){
return redirect()->route('browse_user');
})->name('home');
Route::group(['middleware' => 'auth'], function(){
//Register Controller
Route::get('register', 'Auth\RegisterController@register')->name('register');
Route::post('register', 'Auth\RegisterController@postRegister');
//Login Routes
Route::get('login', 'Auth\LoginController@login')->name('login');
Route::post('login', 'Auth\LoginController@postlogin');
});
Route::group(['middleware' => 'unauth'], function(){
//browse User
Route::get('browse_user', 'DevLovers\BrowseUserController@browse_user')->name('browse_user');
Route::get('filter_user', 'DevLovers\BrowseUserController@filter_user')->name('filter_user');
// edit_profile route
Route::get('edit_profile', 'DevLovers\UserController@edit_profile')->name('edit_profile');
Route::put('edit_profile', 'DevLovers\UserController@put_edit_profile');
// Password Change Route
Route::get('change_password', 'Auth\ChangePasswordController@change')->name('change_password');
Route::put('change_password', 'Auth\ChangePasswordController@put_change');
//Image Route
Route::get('images/{profile_picture}', 'DevLovers\FileController@getImage')->name('image');
//like route
Route::get('like', 'DevLovers\LikeController@like')->name('like');
// Logout Route
Route::get('logout', 'Auth\LoginController@logout')->name('logout');
//detail user route
Route::get('{username}', 'DevLovers\UserController@detail_user')->name('detail_user');
});
<file_sep>/app/Http/Controllers/Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Http\Requests\RegisterRequest;
use App\Http\Requests\LoginRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Libraries\DevLovers\UserObject;
class LoginController extends Controller
{
public function login()
{
return view('auth.login');
}
public function postLogin(LoginRequest $request)
{
$email = $request->email;
$password = $request->password;
$user = UserObject::getUserByEmail($email);
if($user And Hash::check($password, $user->password))
{
$request->session()->put('id', $user->id);
$request->session()->put('username', $user->username);
$request->session()->put('full_name', $user->full_name);
$request->session()->put('email', $user->email);
return redirect('/');
}
else{
return redirect('login')->withErrors('Invalid Email or Password');
}
}
public function logout(Request $request){
$request->session()->flush();
return redirect('login')->with('success', 'You has logged out!');
}
}
<file_sep>/app/Http/Controllers/DevLovers/BrowseUserController.php
<?php
namespace App\Http\Controllers\DevLovers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests;
use App;
use App\Http\Controllers\Controller;
class BrowseUserController extends Controller
{
public function browse_user(Request $request){
//----------- make an array of user id which will be hidden in view-------------//
$user_like = DB::table('users_likes')->select('target_user_id')
->where('user_id', session('id'))
->where('like', 1)
->get();
$user_hide = [];
foreach ($user_like as $user){
array_push($user_hide, $user->target_user_id);
}
array_push($user_hide, $request->session()->get('id'));
//---------------------------------###########---------------------------------//
// Handle browse user with filter or without filter
$_gender = $request->has('gender');
$_roles = $request->has('roles');
$_city = $request->has('city');
if(!$_gender and !$_roles and !$_city){
$user = DB::table('users')->select('id', 'full_name', 'profile_picture', 'gender', 'username')
->whereNotIn('id', $user_hide)
->paginate(5);
}
else{
$gender = ($request->input('gender') === '0') ? '0' : '1';
$roles = ($request->input('roles')) ? $request->input('roles') : '%';
$city = ($request->input('city')) ? $request->input('city') : '%';
$user = DB::table('users')->select('id', 'full_name', 'profile_picture', 'username')
->where('gender', 'LIKE', $gender)
->where('roles_id', 'LIKE', $roles)
->where('city_id', 'LIKE', $city)
->whereNotIn('id',$user_hide)
->paginate(5);
}
$data['users'] = $user;
return view('devlovers.browse', $data);
}
public function filter_user(Request $request){
$roles = DB::table('roles')->select('id', 'name')->get();
$cities = DB::table('cities')->select('id', 'name')->get();
$data['roles'] = $roles;
$data['cities'] = $cities;
return view('devlovers.browse_filter', $data);
}
}
<file_sep>/app/Http/Controllers/DevLovers/UserController.php
<?php
namespace App\Http\Controllers\DevLovers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserRequest;
use App\Http\Requests;
use App\Libraries\DevLovers\UserView;
use App\Libraries\DevLovers\UserObject;
class UserController extends Controller
{
public function detail_user(Request $request, $username)
{
// check user if not exist
if(UserObject::getUserByUsername($username) === null){
return abort(404);
}
#------------------------------ Get User object ---------------#
$user = DB::table('users')
->join('roles', 'users.roles_id', '=', 'roles.id') //Join table roles
->join('cities', 'users.city_id', '=', 'cities.id') //Join table city
->select('users.id as id',
'users.username as username',
'users.full_name as full_name',
//'users.dob as dob',
'users.profile_picture as profile_picture',
//'users.gender as gender',
'roles.name as role')
//'cities.name as city')
->where('users.username', $username)
->first();
// Create User programming language Object
$user->programming_languages = DB::table('users')
->join('users_programming_languages', 'users.id', '=', 'users_programming_languages.user_id')
->join('programming_languages', 'users_programming_languages.programming_languages_id', '=', 'programming_languages.id')
->select('programming_languages.name')
->where('users.id', $user->id)
->get();
// Count User Age by DOB
//$user->gender = $user->gender===0 ? "Female" : "Male";
//$user->age = date_diff(date_create($user->dob), date_create('today'))->y;
#---------------- End of Get User object ----------------------#
#------------------------ Handle of User view ---------------------#
if($username !== session('username')){
UserView::createView(session('id'), $user->id);
}
#----------------------- Handle of User view ---------------------#
$data['user'] = $user;
return view('devlovers.detail_user', $data);
}
public function edit_profile(Request $request){
$user_self = UserObject::getUserById(session('id'));
$user_self->programming_languages = [];
# Add programming_languages_id to array
foreach(UserObject::getUserProgrammingLanguage(session('id')) as $language){
array_push($user_self->programming_languages, $language->id);
}
$roles = DB::table('roles')->select('id', 'name')->get();
$programming_languages = DB::table('programming_languages')->select('id','name')->get();
$cities = DB::table('cities')->select('id', 'name')->get();
$data['user_self'] = $user_self;
$data['roles'] = $roles;
$data['programming_languages'] = $programming_languages;
$data['cities'] = $cities;
return view('devlovers.edit_profile', $data);
}
public function put_edit_profile(UserRequest $request){
$user = DB::table('users')->where('id', session('id'))->first();
//create user object
$user_object = [
'full_name' => $request->input('full_name'),
'email' => $request->input('email'),
'username' => $request->input('username'),
'dob' => $request->input('dob'),
'gender' => $request->input('gender'),
'roles_id' => $request->input('roles'),
'city_id' => $request->input('city'),
'updated_at' => \Carbon\Carbon::now()
];
if($request->hasFile('image')){
$image = \Input::file('image');
$imgName = \Input::get('username').time().'.'.$request->image->getClientOriginalExtension();
\Image::make($image->getRealPath())->resize(250, 250)->save(storage_path('images/') . $imgName);
$user_object['profile_picture'] = $imgName;
}
if(DB::table('users')->where('id', $user->id)->update($user_object)){
DB::table('users_programming_languages')->where('user_id', $user->id)->delete();
$users_programming_languages = $request->programming_languages;
foreach($users_programming_languages as $language){
DB::table('users_programming_languages')->insert(['user_id' => $user->id, 'programming_languages_id' => $language]);
}
}
return redirect()->back()->with('success', 'Profile updated!');
}
}
<file_sep>/app/Libraries/DevLovers/UserView.php
<?php
namespace App\Libraries\DevLovers;
use Illuminate\Support\Facades\DB;
class UserView
{
static function isView($user_self_id, $target_user_id)
{
$user_view = DB::table('users_views')->where('user_id', $user_self_id)
->where('target_user_id', $target_user_id)
->first();
if($user_view === null){
return false;
}
return true;
}
static function createView($user_self_id, $target_user_id)
{
$user_view_object = ['user_id' => $user_self_id,
'target_user_id' => $target_user_id,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()];
DB::table('users_views')->insert($user_view_object);
}
static function updateView($user_self_id, $target_user_id)
{
$user_view_object = ['updated_at' => \Carbon\Carbon::now()];
DB::table('users_views')->where('user_id', $user_self_id)
->where('target_user_id', $target_user_id)
->update(['updated_at'=> \Carbon\Carbon::now()]);
}
}
<file_sep>/app/Http/Requests/UserRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Http\FormRequest;
class UserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
if($this->isMethod('post')){
return [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2024',
'full_name' => 'required|min:8|max:50',
'email' => 'required|min:8|email|unique:users,email',
'username' => 'required|min:8|unique:users,username',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>',
'dob' => 'required|before:now',
'gender' => 'required|boolean',
'roles' => 'required|exists:cities,id',
'programming_languages' => 'exists:programming_languages,id',
'city' => 'required|exists:cities,id'
];
}
if($this->isMethod('put')){
return [
'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2024',
'full_name' => 'required|min:8|max:50',
'email' => 'required|min:8|email|unique:users,email,'.$this->session()->get('id'),
'username' => 'required|min:8|unique:users,username,'.$this->session()->get('id'),
'dob' => 'required|before:now',
'gender' => 'required|boolean',
'roles' => 'required|exists:roles,id',
'programming_languages' => 'exists:programming_languages,id',
'city' => 'required|exists:cities,id'
];
}
}
}
<file_sep>/app/Libraries/DevLovers/UserObject.php
<?php
namespace App\Libraries\DevLovers;
use Illuminate\Support\Facades\DB;
class UserObject
{
static function getUserById($id)
{
$user = DB::table('users')->where('id', $id)->first();
return $user;
}
static function getUserByEmail($email)
{
$user = DB::table('users')->where('email', $email)->first();
return $user;
}
static function getUserByUsername($username)
{
$user = DB::table('users')->where('username', $username)->first();
return $user;
}
static function createUser($user_object)
{
}
static function getUserProgrammingLanguage($id){
$user_self_language = DB::table('users')
->join('users_programming_languages', 'users.id', '=', 'users_programming_languages.user_id')
->join('programming_languages', 'users_programming_languages.programming_languages_id', '=', 'programming_languages.id')
->select('programming_languages.id', 'programming_languages.name')
->where('users.id', $id)
->get();
return $user_self_language;
}
}
<file_sep>/app/Http/Controllers/Auth/ChangePasswordController.php
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\ChangePasswordRequest;
use App\Http\Requests;
class ChangePasswordController extends Controller
{
public function change(){
return view('auth.change_password');
}
public function put_change(ChangePasswordRequest $request){
$user = DB::table('users')->where('id', session('id'))->first();
$old_password = $request->input('password');
$new_password = $request->input('new_password');
$hash_password = <PASSWORD>::make($new_password);
if(Hash::check($old_password, $user->password)){
if($old_password === $new_password){
$error = 'The password should not be same as the old password!';
}
else{
DB::table('users')->where('id', session('id'))->update(['password' => $hash_password]);
}
}
else{
$error = 'Your password is wrong!';
}
if(isset($error)){
return redirect()->back()->withErrors([$error]);
}
return redirect()->back()->with('status', 'Password is changed !');
}
}
| 8b39fbb4467b298a1c96fb20d4d9ad93ff06f97c | [
"Markdown",
"SQL",
"PHP"
] | 17 | SQL | dwisulfahnur/devlovers | 6a73e33d241859517e8aba2f93a08eb537284f4d | 8525d865a42cb52fc3ba9b5b944b6b06bd43037b |
refs/heads/master | <file_sep>import Navbar from './Navbar';
import Main from './Main';
import Footer from './Footer';
const App = () => {
let user = {
nombre: 'Ezequiel',
apellido: 'Caceres',
cumple: new Date(2005, 5, 17)
};
// render
return (
<>
<Navbar />
<Main title="Mi app que buena" user={user} />
<Footer />
</>
);
}
export default App;
<file_sep>import { useState } from 'react';
const Contador = () => {
// hook
const [numero, setNumero] = useState(0);
const handleClick = () => {
console.log('me clickeaste');
setNumero(numero + 1);
console.log(numero);
};
return (
<>
<h1 style={{textAlign: 'center'}}>{numero}</h1>
<button onClick={handleClick}>Clickeame</button>
</>
);
};
export default Contador;<file_sep>const Saludo = props => {
const { user } = props;
return (
<h4>Hola de nuevo, {user.nombre} {user.apellido}</h4>
);
};
export default Saludo;<file_sep>import Saludo from './Saludo';
import Contador from './Contador';
const Main = props => {
const { title, user } = props;
return (
<main>
<h1>{title}</h1>
<h2>Subtitulo</h2>
<Saludo user={user} />
<Contador />
</main>
);
};
export default Main; | 2e35d4af2d0409a49e7e684c3c200880a0ceb983 | [
"JavaScript"
] | 4 | JavaScript | santiagotrini/ejemplo-react | 0b104cb6464d0b1cd058f2f44404d6ae454ba861 | 6b5bea817ca9d560af2c602c6b65d1d0a971214e |
refs/heads/master | <file_sep>var fs = require('fs');
var path = require('path');
var express = require('express')
var app = express();
var async = require('async');
if (app.get('env') === 'production'){
var mongoServer = 'mongo';
var redisServer = 'redis';
var mysqlServer = 'mysql';
}else{
var mongoServer = 'localhost';
var redisServer = 'localhost';
var mysqlServer = 'localhost';
}
/* **********
*** Mount ***
************* */
var file = path.join(__dirname, '../uploads/myFile.txt');
var testFile = function(callback){
fs.writeFile(file, "This text is from a local file!", function(err) {
if (err) return callback("write: " + err.message, null);
fs.readFile(file, function(err, res){
if (err) return callback("read: " + err.message, null);
return callback(null, res);
});
});
};
/* ************
*** MongoDB ***
*************** */
// docker run --name mongo -p 27017:27017 -d mongo mongod --smallfiles
// persistence: -v /path/to/data:/data
var mongo = require('mongodb').MongoClient;
mongo.connect('mongodb://' + mongoServer + ':27017/test', function(err, db) {
if (err) return console.log(err);
console.log("Mongo database connected");
collection = db.collection('test');
});
var testMongo = function(callback){
collection.insert({key: "one", message: "This text is from MongoDB!"}, function(err, result) {
if (err) return callback(err, null);
collection.findAndModify({key: "one"}, [], {remove:true}, function(err, res) {
if(err) return callback(err, null);
return callback(null, res.value.message);
});
});
};
/* **********
*** MySQL ***
************* */
// docker run --name mysql -p 3306:3306 --env MYSQL_ROOT_PASSWORD=<PASSWORD> -d mysql
// persistence: -v /path/to/data:/var/lib/mysql
var mysql = require('mysql').createConnection({
host : mysqlServer,
user : 'root',
password : '<PASSWORD>'
});
mysql.connect(function(err){
if (err) return console.log(err);
var queries = [
'CREATE DATABASE IF NOT EXISTS mydb',
'USE mydb',
'CREATE TABLE IF NOT EXISTS collection (id INT(100) NOT NULL AUTO_INCREMENT, message TINYTEXT, PRIMARY KEY(id))'
];
var run = function(query, callback){
mysql.query(query, function(err, results){
if (err) return callback(err);
return callback(null);
});
};
async.mapSeries(queries, run, function(err, res){
if (err) return console.log(err);
console.log("MySQL connected");
});
});
var testMySQL = function(callback){
var post = {message: "This text is from MySQL!"};
mysql.query('INSERT INTO collection SET ?', post, function(err, res) {
if (err) return callback(err.message,null);
mysql.query("DELETE FROM collection WHERE id = ? ", [res.insertId], function(err, res) {
if (err) return callback(err.message,null);
return callback(null, post.message);
});
});
};
/* **********
*** Redis ***
************* */
// docker run --name redis -p 6379:6379 -d redis redis-server --appendonly yes
// persistence: -v /path/to/data:/data
var redis = require('redis').createClient({host: redisServer});
redis.on('ready',function() {
console.log("Redis database connected");
})
redis.on('error',function(err) {
console.log(err);
});
var testRedis = function(callback){
redis.set('test', 'This text is from Redis!', function(err, reply) {
if (err) return callback (err, null);
redis.get('test', function(err, res){
if (err) return callback (err, null);
redis.del('test');
callback(null, res);
});
});
};
/* **********
*** Route ***
************* */
app.get('/', function (req, res, next) {
var tasks = [];
tasks.push(testFile);
tasks.push(testMongo);
tasks.push(testMySQL);
tasks.push(testRedis);
async.series(tasks, function(err, results){
if (err) return res.status(500).end(err);
results.push("And it works with HTTPS!");
return res.end(results.join("\n"));
});
});
var http = require("http");
http.createServer(app).listen(3000, function(){
console.log('HTTP on port 3000');
});<file_sep>FROM node
RUN mkdir -p /home/nodejs/app
COPY ./app /home/nodejs/app
WORKDIR /home/nodejs/app
RUN npm install --production
EXPOSE 3000
CMD NODE_ENV=production node app.js
| 16657bedfe65b47f14fc318b7f5b13bfa13b65ad | [
"JavaScript",
"Dockerfile"
] | 2 | JavaScript | ThierrySans/docker-host-test | 8a7823acfdd7a1f2f83475fbd7821c624c9e6471 | 8aad64fca4f1fe3c223299bfb95a3595ba5b2f09 |
refs/heads/master | <repo_name>TanSaalik/RockPaperScissorsGame<file_sep>/app/src/main/java/com/example/tan/rpcgame/ScoreBoard.java
package com.example.tan.rpcgame;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class ScoreBoard extends AppCompatActivity {
ListView listScores;
String file = "file";
ArrayList<String> listItems = new ArrayList<>();
ArrayList<String> filepath = new ArrayList<>();
ArrayAdapter<String> listAdapter;
String line = null;
File textFile = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DCIM), file);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_board);
onShow();
}
public void playAgainFromScoreBoard(View view) {
Intent playAgainIntent = new Intent(this, MainActivity.class);
startActivity(playAgainIntent);
}
private boolean isExternalStorageReadable(){
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState())){
Log.i("State", "Readable");
return true;
}
else return false;
}
public void onShow() {
listScores = findViewById(R.id.scoreBoardList);
listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File externalDirectory = new File (String.valueOf
(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)));
ShowDirectoryFilesInList(externalDirectory);
}
if(isExternalStorageReadable()){
try{
FileInputStream fileInputStream = new FileInputStream(textFile);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
while((line = bufferedReader.readLine()) != null){
listItems.add(line + "\n");
listScores.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
bufferedReader.close();
fileInputStream.close();
} catch (IOException ex) {ex.printStackTrace();}
} else Toast.makeText(this, "Can't read from external storage",
Toast.LENGTH_SHORT).show();
}
public void ShowDirectoryFilesInList(File externalDirectory){
File listFile[] = externalDirectory.listFiles();
if(listFile != null){
for(int i = 0; i < listFile.length; i++){
if(listFile[i].isDirectory()){
ShowDirectoryFilesInList(listFile[i]);
} else filepath.add(listFile[i].getAbsolutePath());
}
}
}
}
<file_sep>/app/src/main/java/com/example/tan/rpcgame/GameOver.java
package com.example.tan.rpcgame;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class GameOver extends AppCompatActivity {
Bundle extras;
String playerScore;
String NameAndScore;
private static final int REQUEST_CODE_PERMISSION = 1;
ArrayList<String> filepath = new ArrayList<>();
String file = "file";
File textFile = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DCIM), file);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_over);
active();
Button submitNameBtn = findViewById(R.id.submitNameBtn);
submitNameBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
submitName(v);
}
});
int writeExternalStoragePermission = ContextCompat.checkSelfPermission(GameOver.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (writeExternalStoragePermission != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(GameOver.this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File externalDirectory = new File(String.valueOf
(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)));
ShowDirectoryFilesInList(externalDirectory);
}
}
public void active(){
final TextView scoreEdit = findViewById(R.id.scoreEdit1);
extras = getIntent().getExtras();
if (extras != null) {
playerScore = extras.getString("playerScore");
scoreEdit.setText(playerScore);
}
}
public void playAgain(View view) {
Intent playAgainIntent = new Intent(this, MainActivity.class);
startActivity(playAgainIntent);
}
public void submitName(View view) {
EditText submitNameField = findViewById(R.id.submitNameField);
NameAndScore = (submitNameField.getText().toString()) + " " + playerScore;
if(isExternalStorageWritable()){
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(textFile, true));
bw.write(NameAndScore);
bw.newLine();
bw.flush();
Toast.makeText(this, "Name and score saved", Toast.LENGTH_LONG).show();
} catch (IOException ex) {ex.printStackTrace();}
}
else Toast.makeText(this, "External storage isn't mounted",
Toast.LENGTH_LONG).show();
Intent scoreBoardIntent = new Intent(this, ScoreBoard.class);
startActivity(scoreBoardIntent);
}
public void ShowDirectoryFilesInList(File externalDirectory){
File listFile[] = externalDirectory.listFiles();
if(listFile != null){
for(int i = 0; i < listFile.length; i++){
if(listFile[i].isDirectory()){
ShowDirectoryFilesInList(listFile[i]);
} else filepath.add(listFile[i].getAbsolutePath());
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == REQUEST_CODE_PERMISSION){
int grantResultsLength = grantResults.length;
if(grantResultsLength > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(getApplicationContext(),
"You granted write external storage permission.",
Toast.LENGTH_LONG).show();
}
else Toast.makeText(getApplicationContext(),
"You denied write external storage permission", Toast.LENGTH_LONG).show();
}
}
private boolean isExternalStorageWritable(){
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Log.i("State", "Writable");
return true;
}
else return false;
}
}
| 6c1f0866a9ba3852c1fdbabff70276695222efee | [
"Java"
] | 2 | Java | TanSaalik/RockPaperScissorsGame | 574548ffbd2bbc3b0dce5d0b8086e8b2ab13efb8 | f750556c5288a2596362b48f9a7bb5540e5c3770 |
refs/heads/master | <repo_name>dasibre/insurance_pricing<file_sep>/lib/estimator/estimate_calculator.rb
class EstimateCalculator
class << self
def estimate(opts = {})
new(opts).calculate
end
end
attr_reader :age, :gender, :location, :conditions, :base_cost
def initialize(attrs = {})
@age = attrs.fetch(:age).to_i
@gender = attrs.fetch(:gender)
@location = attrs.fetch(:location)
@conditions = attrs.fetch(:conditions)
@base_cost = individual_base_cost
end
def calculate
return 0 if age < minimum_age_eligibility
adjusted_price = base_cost - (base_cost * location_discount).to_i
adjusted_price = adjusted_price + (adjusted_price * precond_increases)
adjusted_price - gender_discount
end
private
def individual_base_cost
age_based_price_inc * ((age - minimum_age_eligibility) / 5) + annual_base_cost
end
def annual_base_cost
100
end
def precond_increases
conditions.reduce(0.0) do |total,condition|
total += health_conditions_price_inc.fetch(condition.downcase,0)
total
end
end
def gender_discount
female? ? 12 : 0
end
def age_based_price_inc
20
end
def location_discount
east_coast? ? 0.05 : 0
end
def east_coast?
["Boston", "New York"].include?(location)
end
def female?
gender == "female"
end
def minimum_age_eligibility
18
end
def health_conditions_price_inc
{
'allergies' => 0.01,
'sleep apnea' => 0.06,
'heart disease' => 0.17,
'high cholesterol' => 0.08,
'asthma' => 0.04,
'n/a' => 0.0
}
end
end
<file_sep>/spec/run_estimates_spec.rb
require './run_estimates'
describe 'EstimateRunner' do
describe '.run' do
it 'runs insurance estimates for given data' do
data = [['first_name', 'Age', 'Gender', 'Location', 'Health Conditions'], ['Brad', '20', 'male', 'San Francisco', 'n/a'],]
estimator = double('Estimator')
allow(EstimateRunner).to receive(:estimate_calculator).and_return(estimator)
expect(estimator).to receive(:estimate).and_return('100')
expect(EstimateRunner.run(data)).to match_array(["Brad's policy is estimated at $100"])
end
end
end<file_sep>/run_estimates.rb
$LOAD_PATH.unshift File.expand_path('./lib', File.dirname(__FILE__))
require 'estimator'
module EstimateRunner
class << self
def run(data)
hash_data = table_to_hash(data)
hash_data.map do |ind|
ind['estimate'] = estimate_calculator.estimate({ age: ind['age'], gender: ind['gender'], location: ind['location'], conditions: ind['health_conditions'] })
if ind['estimate'] == 0
p "#{ind['first_name']} is not eligible for a life insurance policy"
else
p "#{ind['first_name']}'s policy is estimated at $#{ind['estimate']}"
end
end
end
private
def estimate_calculator
EstimateCalculator
end
def table_to_hash(tabular_data)
data = tabular_data.clone
headings = data.shift
data.map do |row|
row_hash = {}
row.each_with_index do |_, idx|
header = headings[idx]
if header == 'Health Conditions'
row_hash[header.downcase.tr(' ', '_')] = row[idx].split(',')
else
row_hash[header.downcase.tr(' ', '_')] = row[idx]
end
end
row_hash
end
end
end
end
data = [
['first_name', 'Age', 'Gender', 'Location', 'Health Conditions'],
['Kelly', '50', 'female', 'Boston', 'Allergies'],
['Josh', '40', 'male', 'Seattle', 'Sleep Apnea'],
['Jan', '30', 'female', 'New York', 'Heart Disease,High Cholesterol'],
['Brad', '20', 'male', 'San Francisco', 'n/a'],
['Petr', '10', 'male', 'Los Angeles', 'Asthma']
]
EstimateRunner.run(data)
<file_sep>/lib/estimator.rb
require 'estimator/estimate_calculator'
<file_sep>/spec/estimator_spec.rb
require 'spec_helper'
describe EstimateCalculator do
subject { EstimateCalculator }
describe '.estimate' do
it 'calculates price for given demographics' do
demographics = { age: '20', gender: 'male', location: 'Some Location', conditions: ['n/a']}
expect(subject.estimate(demographics)).to eq(100)
end
end
describe '#calculate' do
let(:demographics) { { age: '20', gender: 'male', location: 'Some Location', conditions: ['n/a']} }
context 'every 5 years over minimum age of 18' do
specify 'exactly 5 years over age $20 increase' do
demographics[:age] = '23'
expect(subject.new(demographics).calculate).to eq(120)
end
specify 'exactly 10 years over age $40 increase' do
demographics[:age] = '28'
expect(subject.new(demographics).calculate).to eq(140)
end
specify '11 years over age $120 increase' do
demographics[:age] = '29'
expect(subject.new(demographics).calculate).to eq(140)
end
specify '32 years over age $40 increase' do
demographics[:age] = '50'
expect(subject.new(demographics).calculate).to eq(220)
end
end
context 'when candidate under minimum age of 18' do
it 'returns 0 for ineligible candidates' do
demographics[:age] = '17'
expect(subject.new(demographics).calculate).to eq(0)
end
end
context 'when gender is female' do
it 'receives $12 discount on final price' do
demographics[:gender] = 'female'
expect(subject.new(demographics).calculate).to eq(88)
end
end
context 'location price discount' do
it 'receives 5 percent discount for east coast' do
demographics[:location] = 'New York'
expect(subject.new(demographics).calculate).to eq(95)
end
end
context 'pre-condition price adjustments' do
it 'increases by 1 percent for allergies' do
demographics[:conditions] = ['Allergies']
expect(subject.new(demographics).calculate).to eq(101)
end
context 'when candidate has more than one health condition' do
it 'makes correct price adjustments for each condition' do
demographics = { age: '30', gender: 'female', location: 'New York', conditions: ['Heart Disease', 'High Cholesterol']}
expect(subject.new(demographics).calculate).to eq(154.25)
end
end
it 'increases by 6 percent for sleep apnea' do
demographics[:conditions] = ['Sleep Apnea']
expect(subject.new(demographics).calculate).to eq(106)
end
it 'increases by 4 percent for asthma' do
demographics[:conditions] = ['Asthma']
expect(subject.new(demographics).calculate).to eq(104)
end
it 'increases by 17 percent for heart disease' do
demographics[:conditions] = ['Heart Disease']
expect(subject.new(demographics).calculate).to eq(117)
end
it 'increases by 8 percent for high cholesterol' do
demographics[:conditions] = ['High Cholesterol']
expect(subject.new(demographics).calculate).to eq(108)
end
end
end
end
<file_sep>/README.rdoc
== README
Created by <NAME>
* Ruby version
- ruby 2.2.5p319
*Dependencies
- Rspec 3
*Setup
-Run bundle install
| 8920393f97f5fa1388343c8d288bdd64e2ac9f5c | [
"RDoc",
"Ruby"
] | 6 | Ruby | dasibre/insurance_pricing | 3fb0e37c5de065aa7cb4350530192fc58c04c17b | e6b08d8dc9516bd994b24dc758818df329892e51 |
refs/heads/master | <repo_name>tippecanoe88/reena<file_sep>/first.c
#include <stdio.h>
int main() {
printf("fav human!\n");
return 0;
}
<file_sep>/README.md
# reena
Pat's Main repository
| 92f5dd48272f4e3647368272799a7183499de5ea | [
"Markdown",
"C"
] | 2 | C | tippecanoe88/reena | 254e6cd8a80d7c1130ff898d783fc90d61d6726e | 70aef2cadeac918dbb3e7b33d77aafa374443e34 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace WindowsFormsExterminator
{
public class Exterminator
{
/// <summary>
/// Левая координата отрисовки автомобиля
/// </summary>
private float _startPosX;
/// <summary>
/// Правая кооридната отрисовки автомобиля
/// </summary>
private float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private int _pictureWidth;
//Высота окна отрисовки
private int _pictureHeight;
/// <summary>
/// Ширина отрисовки автомобиля
/// </summary>
private const int extermWidth = 170;
/// <summary>
/// Ширина отрисовки автомобиля
/// </summary>
private const int extermHeight = 160;
/// <summary>
/// Максимальная скорость
/// </summary>
public int MaxSpeed { private set; get; }
/// <summary>
/// Вес автомобиля
/// </summary>
public float Weight { private set; get; }
/// <summary>
/// Основной цвет кузова
/// </summary>
public Color MainColor { private set; get; }
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color DopColor { private set; get; }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="maxSpeed">Максимальная скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="mainColor">Основной цвет кузова</param>
/// <param name="dopColor">Дополнительный цвет</param>
public Exterminator(int maxSpeed, float weight, Color mainColor, Color dopColor, bool
frontSpoiler, bool sideSpoiler, bool backSpoiler)
{
MaxSpeed = maxSpeed;
Weight = weight;
MainColor = mainColor;
DopColor = dopColor;
}
/// <summary>
/// Установка позиции автомобиля
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public void SetPosition(int x, int y, int width, int height)
{
_startPosX = x;
_startPosY = y;
_pictureWidth = width;
_pictureHeight = height;
}
/// <summary>
/// Изменение направления пермещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(Direction direction)
{
float step = MaxSpeed * 100 / Weight;
switch (direction)
{
// вправо
case Direction.Right:
if (_startPosX + step < _pictureWidth - extermWidth)
{
_startPosX += step;
}
break;
//влево
case Direction.Left:
if (_startPosX - step > 0)
{
_startPosX -= step;
}
break;
//вверх
case Direction.Up:
if (_startPosY - step > 0)
{
_startPosY -= step;
}
break;
//вниз
case Direction.Down:
if (_startPosY + step < _pictureHeight - extermHeight)
{
_startPosY += step;
}
break;
}
}
/// <param name="g"></param>
public void DrawExterminator(Graphics g)
{
Pen pen = new Pen(Color.Black, 2);
//1
g.DrawLine(pen, _startPosX + 100, _startPosY + 110, _startPosX + 170, _startPosY + 120);
//2
g.DrawLine(pen, _startPosX + 100, _startPosY + 130, _startPosX + 170, _startPosY + 120);
//3
g.DrawLine(pen, _startPosX + 100, _startPosY + 110, _startPosX + 65, _startPosY + 80);
//4
g.DrawLine(pen, _startPosX + 100, _startPosY + 130, _startPosX + 65, _startPosY + 160);
//5
g.DrawLine(pen, _startPosX + 65, _startPosY + 80, _startPosX + 50, _startPosY + 95);
//6
g.DrawLine(pen, _startPosX + 65, _startPosY + 160, _startPosX + 50, _startPosY + 145);
//7
g.DrawLine(pen, _startPosX + 50, _startPosY + 95, _startPosX + 65, _startPosY + 110);
//8
g.DrawLine(pen, _startPosX + 50, _startPosY + 145, _startPosX + 65, _startPosY + 130);
//9
SolidBrush fillRect = new SolidBrush(Color.Blue);
g.DrawRectangle(pen, _startPosX + 40, _startPosY + 110, 25, 20);
g.FillRectangle(fillRect, _startPosX + 40, _startPosY + 110, 25, 20);
//10
g.DrawLine(pen, _startPosX + 40, _startPosY + 120, _startPosX + 25, _startPosY + 110);
//11
g.DrawLine(pen, _startPosX + 40, _startPosY + 120, _startPosX + 25, _startPosY + 130);
//12
SolidBrush fillQuad = new SolidBrush(Color.Red);
g.FillRectangle(fillQuad, _startPosX + 61, _startPosY + 90, 10, 10);
//13
SolidBrush fillQuadSec = new SolidBrush(Color.Red);
g.FillRectangle(fillQuad, _startPosX + 61, _startPosY + 140, 10, 10);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//составной файл, отвечающий за форму
//хранится вся логика обработки формы
namespace WindowsFormsExterminator
{
public partial class FormExterm : Form
{
private Exterminator exterminator;
/// <summary>
/// Конструктор
/// </summary>
public FormExterm()
{
InitializeComponent();
}
/// <summary>
/// Метод отрисовки машины
/// </summary>
private void Draw()
{
Bitmap bmp = new Bitmap(pictureBoxExterminator.Width, pictureBoxExterminator.Height);
Graphics gr = Graphics.FromImage(bmp);
exterminator.DrawExterminator(gr);
pictureBoxExterminator.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
{
Random rnd = new Random();
exterminator = new Exterminator(rnd.Next(100, 300), rnd.Next(1000, 2000), Color.Blue,
Color.Yellow, true, true, true);
exterminator.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxExterminator.Width,
pictureBoxExterminator.Height);
Draw();
}
/// <summary>
/// Обработка нажатия кнопок управления
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
//получаем имя кнопки
string name = (sender as Button).Name;
switch (name)
{
case "buttonUp":
exterminator.MoveTransport(Direction.Up);
break;
case "buttonDown":
exterminator.MoveTransport(Direction.Down);
break;
case "buttonLeft":
exterminator.MoveTransport(Direction.Left);
break;
case "buttonRight":
exterminator.MoveTransport(Direction.Right);
break;
}
Draw();
}
}
} | a416e1be34faba218b948e9330b7fe82840d7d3b | [
"C#"
] | 2 | C# | ChekulaevMaksim/ISEbd-21-Chekulaev-MD | fc9c4960e14d29d20a30341e33edf2fa5a858d62 | a2970c16663d12dcf7bc0d5ae9af83e06622b3c1 |
refs/heads/master | <file_sep># CS_1_Lab
the Lab for the class of CS1
<file_sep>a = int(input())
b = int(input())
add = (a+b)
sub = (a-b)
mult = (a*b)
print(add)
print(sub)
print(mult) | 901c0cc14a8b671b8669994db5c33302414ff862 | [
"Markdown",
"Python"
] | 2 | Markdown | clokata/CS_1_Lab | 0166202e400cba7a4bf1026a12948634d084ee00 | 0a7aaf445ebc46d9d2c06582987805097e5d5848 |
refs/heads/main | <file_sep><?php
require('../model/database.php');
require('../model/assignments_db.php');
$action = filter_input(INPUT_POST, 'action');
if ($action == NULL) {
$action = filter_input(INPUT_GET, 'action');
if ($action == NULL) {
$action = 'list_employees';
}
}
if ($action == 'list_employees') {
$employees = get_employees();
include('employee_list.php');
}<file_sep><?php include '../view/header.php'; ?>
<html>
<head>
<link rel="stylesheet" href="../view/style.css">
</head>
<body>
<div id="spacer"></div>
<div id="mainPage">
<div id="pageMenu">
<p class="menuList">Menu</p>
<ul>
<li><a href="../index.php">Home</a></li>
</ul>
<p class="menuList">Assignments</p>
<ul>
<li><a href='../assignment_display'>Display All Assignments</a></li>
<li><a href='../assignment_insert/'>Insert new assignment</a></li>
</ul>
<p class="menuList">Employees</p>
<ul>
<li><a href="../employees">Display Employees</a></li>
</ul>
</div>
<?php foreach ($assignmentUpdate as $assignment) :
$dateForm = strtotime($assignment['dateAssigned']);
$releaseDateFormatted = date('m/d/Y', $dateForm);
?>
<?php endforeach; ?>
<form action='index.php' method='post'>
<input type='hidden' name='action' value='update_assignment_execute'>
<input type='hidden' name='assignment_id' value='<?php echo $assignment['assignmentID']; ?>'
<label style='font-weight: bold;'>Assignment # <?php echo $assignment['assignmentID']; ?> </label>
<br><br>
<label>Date Assigned:</label>
<input type='text' name='date_assigned' value='<?php echo $releaseDateFormatted; ?>'>
<br><br>
<label>Owner First Name:</label>
<input type='text' name='first_name' value='<?php echo $assignment['ownerFirstName']; ?>'>
<br><br>
<label>Owner Last Name:</label>
<input type='text' name='last_name' value='<?php echo $assignment['ownerLastName']; ?>'>
<br><br>
<label>Address:</label>
<input type='text' name='address' value='<?php echo $assignment['address']; ?>'>
<br><br>
<label>Phone Number:</label>
<input type='text' name='phone_number' value='<?php echo $assignment['phoneNumber']; ?>'>
<br><br>
<label style="vertical-align: top;">Problem Description:</label>
<textarea name='description' cols='50' rows='10'><?php echo $assignment['problemDescription']; ?></textarea>
<br><br>
<label>Completed:</label>
<select name='completed'>
<option value="0">0 - No</option>
<option value="1">1 - Yes</option>
</select>
<br><br>
<label>Employee ID:</label>
<select name='employee_id'>
<?php foreach ($employees as $employee) : ?>
<option value="<?php echo $employee['employeeID']; ?>"><?php echo $employee['firstName'].' '.$employee['lastName']; ?></option>
<?php endforeach; ?>
</select>
<br><br>
<input type='submit' value='Update Assignment'>
</form>
</div>
<br>
</div>
</body>
</html><file_sep><?php
function get_assignments() {
global $db;
$query = 'SELECT e.firstName, e.lastName, a.*
FROM assignments a
JOIN employees e ON e.employeeID = a.employeeID
ORDER BY assignmentID';
try {
$statement = $db->prepare($query);
$statement->execute();
return $statement;
} catch (PDOException $e) {
display_db_error($e->getMessage());
}
}
function delete_assigment($assignmentID) {
global $db;
$query = 'DELETE FROM assignments
WHERE assignmentID = :assignment_id';
try {
$statement = $db->prepare($query);
$statement->bindValue(':assignment_id', $assignmentID);
$statement->execute();
$statement->closeCursor();
} catch (PDOException $e) {
display_db_error($e->getMessage());
}
}
function update_assignment($assignmentID, $dateAssigned, $ownerFirstName, $ownerLastName,
$address, $phoneNumber, $problemDescription, $completed, $employeeID) {
global $db;
$query = 'UPDATE assignments
SET dateAssigned = :date_assigned,
ownerFirstName = :owner_first_name,
ownerLastName = :owner_last_name,
address = :address,
phoneNumber = :phone_number,
problemDescription = :description,
completed = :completed,
employeeID = :employee_id
WHERE assignmentID = :assignment_id';
$dateForm = strtotime($dateAssigned);
$releaseDateFormatted = date('Y-m-d', $dateForm);
$statement = $db->prepare($query);
$statement->bindValue(':date_assigned', $releaseDateFormatted);
$statement->bindValue(':owner_first_name', $ownerFirstName);
$statement->bindValue(':owner_last_name', $ownerLastName);
$statement->bindValue(':address', $address);
$statement->bindValue(':phone_number', $phoneNumber);
$statement->bindValue(':description', $problemDescription);
$statement->bindValue(':completed', $completed);
$statement->bindValue(':employee_id', $employeeID);
$statement->bindValue(':assignment_id', $assignmentID);
$statement->execute();
$statement->closeCursor();
}
function get_assignment_forUpdate($assignmentID) {
global $db;
$query = 'SELECT * FROM assignments WHERE assignmentID = :assignment_id';
$statement = $db->prepare($query);
$statement->bindValue(':assignment_id', $assignmentID);
$statement->execute();
return $statement;
}
function insert_new_assignment($dateAssigned, $ownerFirstName, $ownerLastName,
$address, $phoneNumber, $problemDescription, $completed, $employeeID) {
global $db;
$query = 'INSERT INTO assignments (dateAssigned, '
. 'ownerFirstName, ownerLastName, address, phoneNumber, problemDescription, completed, employeeID)'
. 'VALUES (:date_assigned, :owner_first_name, :owner_last_name, :address, :phone_number, :description, :completed, :employee_id)';
$dateForm = strtotime($dateAssigned);
$releaseDateFormatted = date('Y-m-d', $dateForm);
$statement = $db->prepare($query);
$statement->bindValue(':date_assigned', $releaseDateFormatted);
$statement->bindValue(':owner_first_name', $ownerFirstName);
$statement->bindValue(':owner_last_name', $ownerLastName);
$statement->bindValue(':address', $address);
$statement->bindValue(':phone_number', $phoneNumber);
$statement->bindValue(':description', $problemDescription);
$statement->bindValue(':completed', $completed);
$statement->bindValue(':employee_id', $employeeID);
$statement->execute();
$statement->closeCursor();
}
function get_employees() {
global $db;
$query = 'SELECT * FROM employees
WHERE employeeID > 0
ORDER BY employeeID ASC';
try {
$statement = $db->prepare($query);
$statement->execute();
return $statement;
} catch (PDOException $e) {
display_db_error($e->getMessage());
}
}
function display_by_employee($employeeID) {
global $db;
$query = 'SELECT e.firstName, e.lastName, a.*
FROM assignments a
JOIN employees e ON e.employeeID = a.employeeID
WHERE :employee_id = a.employeeID
ORDER BY assignmentID';
$statement = $db->prepare($query);
$statement->bindValue(':employee_id', $employeeID);
$statement->execute();
return $statement;
}
<file_sep><?php include 'view/header.php'; ?>
<main class="nofloat">
<p> Hope this works!</p>
<table>
<th>
Test
</th>
<th>ing</th>
<tr>1</tr>
<td>ok<td>
</main><file_sep><?php include '../view/header.php'; ?>
<html>
<head>
<link rel="stylesheet" href="../view/style.css">
</head>
<body>
<div id="spacer"></div>
<div id="mainPage">
<div id="pageMenu">
<p class="menuList">Menu</p>
<ul>
<li><a href="../index.php">Home</a></li>
</ul>
<p class="menuList">Assignments</p>
<ul>
<li><a href='../assignment_display'>Display All Assignments</a></li>
<li><a href='../assignment_insert'>Insert new assignment</a></li>
</ul>
<p class="menuList">Employees</p>
<ul>
<li><a href="../employees">Display Employees</a></li>
</ul>
</div>
<div id="tableData">
<div>
<form action="index.php" method="post">
<input type="hidden" name="action" value="select_by_employee">
<label>Select Assignments by Employee: </label>
<select name="employee_id">
<?php foreach ($employees as $employee) : ?>
<option value="<?php echo $employee['employeeID']; ?>"><?php echo $employee['firstName'].' '.$employee['lastName']; ?></option>
<?php endforeach; ?>
<input type="submit" style="margin-left: 10px;" value="Display Results">
</select>
</form>
</div>
<table>
<tr>
<th>Assignment ID</th>
<th>Date Assigned</th>
<th>Owner Name</th>
<th>Address</th>
<th>Phone Number</th>
<th>Problem Description</th>
<th>Completed<br> 0- No, 1- Yes</th>
<th>Assigned<br>Employee</th>
<th>Update</th>
<th>Delete</th>
</tr>
<?php foreach ($assignments as $assignment) :
$dateForm = strtotime($assignment['dateAssigned']);
$releaseDateFormatted = date('m/d/Y', $dateForm);
?>
<tr>
<td><?php echo $assignment['assignmentID']; ?></td>
<td><?php echo $releaseDateFormatted; ?></td>
<td class="right"><?php echo $assignment['ownerFirstName'].' '.$assignment['ownerLastName']; ?></td>
<td><?php echo $assignment['address']; ?></td>
<td><?php echo $assignment['phoneNumber']; ?></td>
<td><?php echo $assignment['problemDescription']; ?></td>
<td><?php echo $assignment['completed']; ?></td>
<td><?php echo $assignment['firstName'].' '.$assignment['lastName']; ?></td>
<td><form action="." method="post">
<input type="hidden" name="action"
value="update_assignment">
<input type="hidden" name="assignment_id"
value="<?php echo $assignment['assignmentID']; ?>">
<input type="submit" value="Update">
</form></td>
<td><form action="." method="post">
<input type="hidden" name="action"
value="delete_assignment">
<input type="hidden" name="assignment_id"
value="<?php echo $assignment['assignmentID']; ?>">
<input type="submit" value="Delete">
</form></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div>
</div
<br>
</body>
</html><file_sep><?php
require('../model/database.php');
require('../model/assignments_db.php');
$action = filter_input(INPUT_POST, 'action');
if ($action == NULL) {
$action = filter_input(INPUT_GET, 'action');
if ($action == NULL) {
$action = 'insert_assignment';
}
}
if ($action == 'insert_assignment') {
$employees = get_employees();
include('insert_assignment.php');
}
else if ($action == 'insert_new_assignment') {
$dateAssigned = filter_input(INPUT_POST, 'date_assigned');
$ownerFirstName = filter_input(INPUT_POST, 'first_name');
$ownerLastName = filter_input(INPUT_POST, 'last_name');
$address = filter_input(INPUT_POST, 'address');
$phoneNumber = filter_input(INPUT_POST, 'phone_number');
$problemDescription = filter_input(INPUT_POST, 'description');
$completed = filter_input(INPUT_POST, 'completed');
$employeeID = filter_input(INPUT_POST, 'employee_id');
insert_new_assignment($dateAssigned, $ownerFirstName, $ownerLastName,
$address, $phoneNumber, $problemDescription, $completed, $employeeID);
$assignments = get_assignments();
include('../assignment_display/display_assignments.php');
}
?><file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Feb 02, 2021 at 05:44 PM
-- Server version: 10.4.10-MariaDB
-- PHP Version: 7.3.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `advprogp1`
--
-- --------------------------------------------------------
--
-- Table structure for table `assignments`
--
DROP TABLE IF EXISTS `assignments`;
CREATE TABLE IF NOT EXISTS `assignments` (
`assignmentID` int(11) NOT NULL AUTO_INCREMENT,
`dateAssigned` date NOT NULL,
`ownerFirstName` varchar(255) NOT NULL,
`ownerLastName` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`phoneNumber` varchar(255) NOT NULL,
`problemDescription` text NOT NULL,
`completed` tinyint(1) NOT NULL,
`employeeID` int(11) NOT NULL,
PRIMARY KEY (`assignmentID`),
KEY `employeeID` (`employeeID`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `assignments`
--
INSERT INTO `assignments` (`assignmentID`, `dateAssigned`, `ownerFirstName`, `ownerLastName`, `address`, `phoneNumber`, `problemDescription`, `completed`, `employeeID`) VALUES
(6, '2019-05-12', 'Chris', 'Gilpin', '1232 Louisiana St.', '8937477473', 'Railroad broken.', 1, 5),
(7, '2019-05-10', 'John', 'Doe', '657 Anderson Rd.', '7063399922', 'Toilet leaking', 0, 0),
(8, '2018-01-04', 'Nick', 'Barker', '576 Tennessee Dr.', '8748930239', 'Oven broken.', 1, 9),
(9, '2020-04-01', 'Kevin', 'Fair', '5860 Anderson Rd.', '7063399922', 'Electricity out.', 0, 1),
(10, '2018-01-04', 'Timothy', 'Fair', '5860 Anderson Rd.', '7063399922', 'Water heater not working.', 0, 6),
(11, '2016-05-16', 'John', 'Doe', '657 Anderson Rd.', '7063399922', 'Broken window. Needs new glass.', 0, 2);
-- --------------------------------------------------------
--
-- Table structure for table `employees`
--
DROP TABLE IF EXISTS `employees`;
CREATE TABLE IF NOT EXISTS `employees` (
`employeeID` int(11) NOT NULL AUTO_INCREMENT,
`firstName` varchar(255) NOT NULL,
`lastName` varchar(255) NOT NULL,
PRIMARY KEY (`employeeID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `employees`
--
INSERT INTO `employees` (`employeeID`, `firstName`, `lastName`) VALUES
(0, 'None', 'Assigned'),
(1, 'Kevin', 'Fair'),
(2, 'Prescott', 'Lerch'),
(5, 'Harcourt', 'Bull'),
(6, 'Nick', 'Barker'),
(8, 'Jack', 'Jackson'),
(9, 'William', 'Fleming');
--
-- Constraints for dumped tables
--
--
-- Constraints for table `assignments`
--
ALTER TABLE `assignments`
ADD CONSTRAINT `assignments_ibfk_1` FOREIGN KEY (`employeeID`) REFERENCES `employees` (`employeeID`);
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('../model/database.php');
require('../model/assignments_db.php');
$action = filter_input(INPUT_POST, 'action');
if ($action == NULL) {
$action = filter_input(INPUT_GET, 'action');
if ($action == NULL) {
$action = 'list_assignments';
}
}
if ($action == 'list_assignments') {
$assignments = get_assignments();
$employees = get_employees();
include('display_assignments.php');
}
else if ($action == 'delete_assignment') {
$assignmentID = filter_input(INPUT_POST, 'assignment_id');
if ($assignmentID == NULL || $assignmentID == FALSE) {
$error = "Missing or incorrect product code.";
include('../errors/error.php');
} else {
delete_assigment($assignmentID);
}
$assignments= get_assignments();
include('display_assignments.php');
}
else if ($action == 'update_assignment') {
$assignmentID = filter_input(INPUT_POST, 'assignment_id');
$assignmentUpdate = get_assignment_forUpdate($assignmentID);
$employees = get_employees();
include('update_assignment.php');
}
else if ($action == 'update_assignment_execute') {
$assignmentID = filter_input(INPUT_POST, 'assignment_id');
$dateAssigned = filter_input(INPUT_POST, 'date_assigned');
$ownerFirstName = filter_input(INPUT_POST, 'first_name');
$ownerLastName = filter_input(INPUT_POST, 'last_name');
$address = filter_input(INPUT_POST, 'address');
$phoneNumber = filter_input(INPUT_POST, 'phone_number');
$problemDescription = filter_input(INPUT_POST, 'description');
$completed = filter_input(INPUT_POST, 'completed');
$employeeID = filter_input(INPUT_POST, 'employee_id');
update_assignment($assignmentID, $dateAssigned, $ownerFirstName, $ownerLastName,
$address, $phoneNumber, $problemDescription, $completed, $employeeID);
$employees = get_employees();
$assignments = get_assignments();
include('display_assignments.php');
}
else if ($action == 'select_by_employee') {
$employeeID = filter_input(INPUT_POST, 'employee_id');
$assignments = display_by_employee($employeeID);
$employees = get_employees();
include('display_assignments.php');
}<file_sep><?php include 'view/header.php'; ?>
<html>
<head>
<link rel="stylesheet" href="view/style.css">
</head>
<body>
<div id="spacer"></div>
<div id="mainPage">
<div id="pageMenu">
<p class="menuList">Menu</p>
<ul>
<li><a href="./index.php">Home</a></li>
</ul>
<p class="menuList">Assignments</p>
<ul>
<li><a href='assignment_display'>Display All Assignments</a></li>
<li><a href='assignment_insert'>Insert new assignment</a></li>
</ul>
<p class="menuList">Employees</p>
<ul>
<li><a href="employees">Display Employees</a></li>
</ul>
</div>
<div id="tableData">
<img src="https://www.narpm.org/wp-content/uploads/2020/09/NARPM-Convention-2020.jpg" alt="Manage your property!" width="1150" height="700">
</div>
<br>
</div>
</body>
</html><file_sep><?php include '../view/header.php'; ?>
<main>
<p> Hi! </p>
</main><file_sep><?php include '../view/header.php'; ?>
<html>
<head>
<link rel="stylesheet" href="../view/style.css">
</head>
<body>
<div id="spacer"></div>
<div id="mainPage">
<div id="pageMenu">
<p class="menuList">Menu</p>
<ul>
<li><a href="../index.php">Home</a></li>
</ul>
<p class="menuList">Assignments</p>
<ul>
<li><a href='../assignment_display'>Display All Assignments</a></li>
<li><a href='../assignment_insert'>Insert new assignment</a></li>
</ul>
<p class="menuList">Employees</p>
<ul>
<li><a href="../employees">Display Employees</a></li>
</ul>
</div>
<div id="tableData" style="width: 50%;">
<table>
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
</tr>
<?php foreach ($employees as $employee) :
?>
<tr>
<td><?php echo $employee['employeeID']; ?></td>
<td class="right"><?php echo $employee['firstName'].' '.$employee['lastName']; ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<br>
</div>
</body>
</html> | 0bbf8e0881659c302bd06c4a8442fe162ac39b2d | [
"SQL",
"PHP"
] | 11 | PHP | kevinfair1/Basic-Property-Management-App | a194c0d2566b28ca20627eba823da3168ac97603 | 3d052163ebd78d3c29e2d22adbc0f49a82eccdc3 |
refs/heads/main | <file_sep># GHFollowers
iOS Application To follow up on developers, save them on favorites, and do a search for them on Github








<file_sep>//
// DataLoadingVC.swift
// GHFollowers
//
// Created by <NAME> on 6/23/21.
//
import UIKit
class DataLoadingVC: UIViewController {
var containerView:UIView!
func showLoadingView(){
containerView = UIView(frame: view.bounds)
view.addSubview(containerView)
containerView.alpha = 0
containerView.backgroundColor = .systemBackground
UIView.animate(withDuration: 0.3) { self.containerView.alpha = 0.8 }
let activityIndicatorView = UIActivityIndicatorView(style: .large)
containerView.addSubview(activityIndicatorView)
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
activityIndicatorView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
activityIndicatorView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor)
])
activityIndicatorView.startAnimating()
}
func dismissLoadingView(){
DispatchQueue.main.async { [self] in
containerView.removeFromSuperview()
containerView = nil
}
}
func showEmptyStateView(with message:String , in view : UIView){
let emptyStateView = GFEmptyStateView(message: message)
emptyStateView.frame = view.bounds
view.addSubview(emptyStateView)
}
}
<file_sep>//
// User.swift
// GHFollowers
//
// Created by <NAME> on 6/19/21.
//
import Foundation
struct User: Codable{
let login : String
let avatarUrl : String
let htmlUrl : String
let name : String?
let location : String?
let bio : String?
let createdAt : String
let publicRepos : Int
let publicGists : Int
let followers : Int
let following : Int
}
<file_sep>//
// GFButton.swift
// GHFollowers
//
// Created by <NAME> on 6/19/21.
//
import UIKit
class GFButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(backgroundColor:UIColor , title:String) {
self.init(frame: .zero)
set(backgroundColor: backgroundColor, title: title)
}
private func configure(){
translatesAutoresizingMaskIntoConstraints = false
layer.cornerRadius = 10
titleLabel?.textColor = .white
titleLabel?.font = UIFont.preferredFont(forTextStyle: .headline)
}
func set(backgroundColor : UIColor , title: String){
self.backgroundColor = backgroundColor
setTitle(title, for: .normal)
}
}
<file_sep>//
// UIViewController+Ext.swift
// GHFollowers
//
// Created by <NAME> on 6/19/21.
//
import UIKit
import SafariServices
extension UIViewController{
func presentAlertOnMainThread(title:String , message:String , titleButton:String){
DispatchQueue.main.async {
let alertVC = GFAlertVC(alertTitle: title , message: message, titleButton: titleButton)
alertVC.modalPresentationStyle = .overFullScreen
alertVC.modalTransitionStyle = .crossDissolve
self.present(alertVC, animated: true, completion: nil)
}
}
func presentSafariVC(with url : URL) {
let safariVC = SFSafariViewController(url: url)
safariVC.preferredControlTintColor = .systemGreen
present(safariVC, animated: true)
}
}
<file_sep>//
// Follower.swift
// GHFollowers
//
// Created by <NAME> on 6/19/21.
//
import Foundation
struct Follower: Codable , Hashable {
let login : String
let avatarUrl : String
}
| 4f3ef58a07b9b9250b1742672049be44a3644dd4 | [
"Markdown",
"Swift"
] | 6 | Markdown | mahmoud10Yousef/GHFollowers | f0af6b1c22172bde7b48c6c66543b0eb57e7ef02 | df8b0199f16d5533ddee8e2460f6bdb4ab8d272f |
refs/heads/master | <file_sep>// Send joystick data wirelessly via RFM69 module
// Library by <NAME> - <EMAIL>
// Get the RFM69 library at: https://github.com/LowPowerLab/
#include <RFM69.h>
#include <SPI.h>
const int joyLR = A0; // L/R Parallax Thumbstick
const int joyUD = A3; // U/D Parallax Thumbstick
int LR_value;
int UD_value;
// RADIO DEFINES
#define NETWORKID 0 //the same on all nodes that talk to each other
#define NODEID 1 //unique for each node on same network
#define TONODEID 2 // ID of the controller node
#define FREQUENCY RF69_433MHZ
#define ENCRYPTKEY "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
#define SERIAL_BAUD 115200
RFM69 radio;
void setup() {
// Open a serial port so we can send keystrokes to the module:
Serial.begin(SERIAL_BAUD);
Serial.print("Node ");
Serial.print(NODEID,DEC);
Serial.println(" ready");
radio.initialize(FREQUENCY,NODEID,NETWORKID); // Initialize radio
radio.setHighPower(); // Always use this for RFM69HCW
radio.encrypt(ENCRYPTKEY); // Use encryption
}
void loop() {
// Set up a "buffer" for characters that we'll send:
static byte sendbuffer[2]; // We will send 2 bytes of data
static int sendlength = 2;
LR_value = map(analogRead(joyLR), 0, 1023, 0, 180); // Map each joystick reading to appropriate servo angle
UD_value = map(analogRead(joyUD), 0, 1023, 0, 180);
sendbuffer[0] = LR_value; // Store data in buffer for later transmission
sendbuffer[1] = UD_value;
Serial.print("sending to node ");
Serial.print(TONODEID, DEC);
Serial.println(":");
Serial.print("L/R:");
Serial.println(sendbuffer[0]);
Serial.print("U/D:");
Serial.println(sendbuffer[1]);
// No need to use ACK
radio.send(TONODEID, sendbuffer, sendlength); // Send buffer wirelessly to node 2 (the maze game board)
}
<file_sep>// Send joystick data wirelessly via RFM69 module
// Library for RFM69 by <NAME> - <EMAIL>
// Get the RFM69 library at: https://github.com/LowPowerLab/
#include <RFM69.h>
#include <SPI.h>
#include <Servo.h>
const int servo1 = 12; // first servo
const int servo2 = 19; // second servo
Servo UD_servo;
Servo LR_servo;
int LR_value; // LR value from joystick
int UD_value; // UD value from joystick
// RADIO DEFINES
#define NETWORKID 0 //the same on all nodes that talk to each other
#define NODEID 2 //unique for each node on same network
#define TONODEID 1 // ID of receiver node on the maze game board
#define FREQUENCY RF69_433MHZ
#define ENCRYPTKEY "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
#define SERIAL_BAUD 115200
RFM69 radio
void setup() {
// Open a serial port so we can send keystrokes to the module:
Serial.begin(SERIAL_BAUD);
Serial.print("Node ");
Serial.print(NODEID,DEC);
Serial.println(" ready");
radio.initialize(FREQUENCY,NODEID,NETWORKID); // Initialize radio
radio.setHighPower(); // Always use this for RFM69HCW
radio.encrypt(ENCRYPTKEY);
UD_servo.attach(servo1); // Initialize all servos
LR_servo.attach(servo2);
UD_servo.write(90); // Set both servos to the middle of their range
LR_servo.write(90);
}
void loop() {
//check for any received packets
if (radio.receiveDone())
{
LR_value = map(radio.DATA[0], 0, 180, 2250, 750); // Map received value to pulse width
UD_value = map(radio.DATA[1], 0, 180, 750, 2250);
LR_servo.writeMicroseconds(LR_value); // Write appropriate pulse width to each servo
UD_servo.writeMicroseconds(UD_value);
Serial.print('[');Serial.print(radio.SENDERID, DEC);Serial.println("] ");
Serial.print("L/R:");
Serial.println(radio.DATA[0]);
Serial.print("U/D:");
Serial.println(radio.DATA[1]);
Serial.print(" [RX_RSSI:");Serial.print(radio.RSSI);Serial.print("]");
Serial.println();
delay(15); // wait for servos to move to correct position
}
}
<file_sep># the-maze-runner
The Maze Runner is a project done for ELEC 327 at Rice University. The concept was to create a more interesting implementation of the game where you navigate a ball from start to finish by tilting the maze.
We did this by:
a) Adding servo motors to control the motion of the board
b) Controlling those servos using a wireless joystick controller
The design files for the PCB's and code are included in this repository.
This project was worked on by:
<NAME> (patrick-han), <NAME> (chiraagk7), <NAME> (ty19)
A detailed report for this project can be found in the Documentation folder of this repository.
Here is the associated website with videos!: https://patrick-han.github.io/ee_projects/the-maze-runner.html
| aeda43c3ca8cf017d2ffac4abadb5a415071bd5c | [
"Markdown",
"C++"
] | 3 | C++ | patrick-han/the-maze-runner | 3336cfc171852b33e40dc919d3738c11debde057 | 69ca89fa3180dcc2042c531b887f31c0d33bed9d |
refs/heads/master | <file_sep>Bare minimum Babel and Webpack example.
> This is not a boilerplate
- Babel ES6/ES2015 support
- Webpack dev server with hot module replacement
Just run `npm start` and build stuff.
<file_sep>const hello = world => {
const root = document.querySelector('.root');
root.innerHTML = `Hello ${world}!`;
};
document.addEventListener(
'DOMContentLoaded',
hello('👋')
);
| 90c595f8dd94230314c42bb60aab56a13ce09d3e | [
"Markdown",
"JavaScript"
] | 2 | Markdown | henriquea/babel-webpack-min | 0500420ad1f60f63a8121c79aa091efc897e3c12 | a294920ec62ca8e5d716b57651100c3fa745e391 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Models
{
public class DomainAttribute : ValidationAttribute, IClientValidatable
{
public DomainAttribute(int minLength, params string[] propertyNames)
{
this.PropertyNames = propertyNames;
this.MinLength = minLength;
}
public string[] PropertyNames { get; private set; }
public int MinLength { get; private set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
//var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
//var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();
//var totalLength = values.Sum(x => x.Length) + Convert.ToString(value).Length;
//if (totalLength < this.MinLength)
//{
// return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
//}
//return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var modelClientValidationRule = new ModelClientValidationRule
{
ValidationType = "requiredif",
ErrorMessage = ErrorMessage //Added
};
modelClientValidationRule.ValidationParameters.Add("param", this.PropertyNames); //Added
return new List<ModelClientValidationRule> { modelClientValidationRule };
}
// public IEnumerable<string> Values { get; private set; }
// public DomainAttribute(string value)
// {
// this.Values = new string[] { "w" };
// }
// //public DomainAttribute(prams string[] values)
// //{
// // this.Values = values;
// //}
// protected override ValidationResult IsValid(object value, ValidationContext validationContext)
// {
// return new ValidationResult("error");
// }
// public override string FormatErrorMessage(string name)
//{
// string[] values = this.Values.Select(value => string.Format("'{0}'", value)).ToArray();
// //return string.Format("{0}{1}", name, string.Join(",", values));
// return string.Format(base.ErrorMessageString, name, string.Join(",", values));
// }
}
}<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 AspNetMVC;
namespace AspNetMVC.Controllers
{
public class MVC0116Controller : Controller
{
private CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0116
public ActionResult Index()
{
return View(db.BookMasters.ToList());
}
// GET: MVC0116/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// GET: MVC0116/Create
public ActionResult Create()
{
return View();
}
// POST: MVC0116/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.BookMasters.Add(bookMaster);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
// GET: MVC0116/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: MVC0116/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.Entry(bookMaster).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
// GET: MVC0116/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: MVC0116/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
BookMaster bookMaster = db.BookMasters.Find(id);
db.BookMasters.Remove(bookMaster);
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.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System.Xml;
using System.Net;
namespace AspnetCore.Controllers
{
public class Core0321Controller : Controller
{
[Authorize]
public IActionResult Index()
{
//Startup.connectionString = "FR";
return View();
}
public IActionResult Index2()
{
string strUrl = "http://www.w3school.com.cn/example/xmle/note.xml";
XmlDocument doc = new XmlDocument();
//doc.BaseURI = strUrl;
doc.LoadXml(strUrl);
NewMethod();
//System.Net.HttpWebResponse a=new HttpWebResponse ("");
//a.ResponseUri();
//string reply = client.DownloadString(address);
return View();
}
private static void NewMethod()
{
//WebClient client = new WebClient();
}
public IActionResult Index3() {
string a = "2.8,3.3";
string a1 = "2.3";
string[] b = a.Split(',');
string[] b1 = a1.Split(',');
string d = "0";
if (b.Count() == 2) {
d = b[1];
}
Console.Write(d); //print 3.3
string d1 = "0";
if (b1.Count() == 2)
{
d1 = b1[1];
}
Console.Write(d1); ////print 0
return View();
}
public IActionResult Index4() {
//System.Data.SqlClient.SqlConnection vConn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
//vConn.Open();
//String vQuery = "Select * from Employee";
//SqlDataAdapter vAdap = new SqlDataAdapter(vQuery, vConn);
//DataSet vDs = new DataSet();
//vAdap.Fill(vDs, "Employee");
//vConn.Close();
//DataTable vDt = vDs.Tables[0];
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspnetCore.Data;
namespace AspnetCore.Models
{
public static class DataSeeder
{
// TODO: Move this code when seed data is implemented in EF 7
/// <summary>
/// This is a workaround for missing seed data functionality in EF 7.0-rc1
/// More info: https://github.com/aspnet/EntityFramework/issues/629
/// </summary>
/// <param name="app">
/// An instance that provides the mechanisms to get instance of the database context.
/// </param>
public static void SeedData(this Microsoft.AspNetCore.Builder.IApplicationBuilder app)
{
var db = app.ApplicationServices.GetService(typeof(ApplicationDbContext));
// TODO: Add seed logic here
//db.SaveChanges();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplicationForm
{
public partial class WebForm0302 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TVcolors_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
{
List<string> childitemList = new List<string>();
foreach (TreeNode tn in TVcolors.CheckedNodes)
{
//check whether it contains child node.
if (tn.ChildNodes.Count == 0)
{
childitemList.Add(tn.Value);
}
}
//based on the checked child node values to filter the database
//then populate the other threeview
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirst
{
public partial class Contact1
{
[Key]
public string Accountno { get; set; }
public string Company { get; set; }
public string Contact { get; set; }
//... other fields
public string Recid { get; set; }
public virtual Contact2 Contact2s { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace AspNetMVC.Models
{
public class Conexion
{
//public IfxConnection AbreConexion()
//{
// IfxConnection conexion = new IfxConnection(ConfigurationManager.ConnectionStrings["001"].ToString());
// try
// {
// conexion.Open();
// }
// catch (Exception)
// {
// throw;
// }
// return conexion;
//}
}
}<file_sep>using AspNetMVC.Models;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0405Controller : Controller
{
CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0405
public ActionResult Index()
{
db.Database.ExecuteSqlCommand("");
return View();
}
public class Product
{
public string ProductId { get; set; }
public string Name { get; set; }
public int CategoryID { get; set; }
//public virtual Category Categories { get; set; }
public virtual IEnumerable<ProductImageMapping> ProductImageMappings { get; set; }
}
public class ProductImageMapping
{
public int Id { get; set; }
public string ImagePath { get; set; }
//public Boolean MainImage { get; set; }
public string ProductId { get; set; }
public virtual Product Products { get; set; }
}
// GET: MVC0405/Details/5
[ChildActionOnly]
//[MultipleButton()
public ActionResult Details(int id)
{
ApplicationDbContext db = new ApplicationDbContext();
var b= db.Products.Select(t=>new { t.Name , ImagePath = t.ProductImageMappings.Where(y=>y.ProductId==t.ProductId).FirstOrDefault().ImagePath});
var a= Request.Form["a"];
return View();
}
// GET: MVC0405/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
//[MultipleButton(Name = "action", Argument = "Submit")]
public ActionResult Submit(Product d, HttpPostedFileBase upfile, IEnumerable<int> STRMSelected)
{
return Content("abc");
}
// POST: MVC0405/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: MVC0405/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: MVC0405/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: MVC0405/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: MVC0405/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleCodeFirst
{
public class Student
{
public Student() { }
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual StudentAddress Address { get; set; }
}
public class StudentAddress
{
public int StudentId { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public int Zipcode { get; set; }
public string State { get; set; }
public string Country { get; set; }
public virtual Student Student { get; set; }
}
public class MyPerson {
public MyPerson()
{
}
public int IdPart1 { get; set; }
public int IdPart2 { get; set; }
//public MyId MyIds { get; set; }
public string Name { get; set; }
}
public class MyId
{
public MyId()
{
}
public int IdPart1 { get; set; }
public int IdPart2 { get; set; }
}
public class ApplicatioDbContext : DbContext
{
public ApplicatioDbContext()
: base("name=CodeFirstDbDemo")
{
}
//public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Entity<MyPerson>().HasRequired(p => p.MyIds );
modelBuilder.Entity<MyId>().HasKey(p => new { p. IdPart1 });
// Configure StudentId as PK for StudentAddress
modelBuilder.Entity<StudentAddress>()
.HasKey(e => e.StudentId);
// Configure StudentId as FK for StudentAddress
modelBuilder.Entity<Student>()
.HasOptional(s => s.Address)
.WithRequired(ad => ad.Student);
modelBuilder.Entity<Contact1>().HasKey(e => e.Accountno);
modelBuilder.Entity<Contact4>().HasKey(e => e.Accountno);
modelBuilder.Entity<Contact1>().HasOptional(s => s.Contact4s).WithRequired(ad => ad.Contact1s);
//modelBuilder.Entity<Contact1>()
// .HasOptional(s => s.Contact2s) // Mark Address property optional in Student entity
// .WithRequired(ad => ad.Accountno1);
//
//var model = modelBuilder.Entity<Contact1>()
// .HasForeignKey(c=>c.Accountno,"e")
// .HasKey(c1 => c1.Accountno);
// //.HasOne(c2 => c2.Contact2s)
// // .WithOne(c1 => c1.Contact1)
//model.Property(e => e.Recid)
// .HasColumnName("recid")
// .HasColumnType("varchar(15)").IsRequired();
//model.Property(e => e.Accountno)
// .HasColumnName("ACCOUNTNO")
// .HasColumnType("varchar(20)");
//modelBuilder.Entity<Contact1>().ToTable("Contact1");
//modelBuilder.Entity<Contact2>(entity =>
//{
// entity.HasKey(e => e.Accountno);
// entity.HasOne(c1 => c1.Contact1)
// .WithOne(c2 => c2.Contact2);
// entity.Property(e => e.Recid)
// .HasColumnName("recid")
// .HasColumnType("varchar(15)");
// entity.Property(e => e.Accountno)
// .IsRequired()
// .HasColumnName("ACCOUNTNO")
// .HasColumnType("varchar(20)");
// entity.Property(e => e.Callbackon)
// .HasColumnName("CALLBACKON")
// .HasColumnType("datetime");
//});
//base.OnModelCreating(modelBuilder);
}
public DbSet<Student> students { get; set; }
public DbSet<StudentAddress> studentAddress { get; set; }
public DbSet<Contact1> Contact1ss { get; set; }
public DbSet<Contact4> Contact2ss { get; set; }
public DbSet<MyPerson> MyPersons { get; set; }
public DbSet<MyId> MyIds { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0213Controller : Controller
{
// GET: MVC0213
public ActionResult Index()
{
ViewBag.FormSubmit = true;
return View();
}
public async Task<ActionResult> Contact(EmailFormModel model)
{
if (true)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("<EMAIL>")); //replace with valid value
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
message.IsBodyHtml = true;
//using (var smtp = new SmtpClient())
{
await Task.Delay(1000);
//await smtp.SendMailAsync(message);
return View();
}
}
return View(model);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using AspnetCore.Data;
using AspnetCore;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace AspnetCore.Controllers
{
public class Core0309Controller : Controller
{
private readonly ApplicationDbContext _context;
public Core0309Controller(ApplicationDbContext context)
{
_context = context;
}
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
public IActionResult Create()
{
//ViewData["InspectDate"] = new DateTime();
//ViewData["ConditionID"] = new SelectList(_context.Conditions.OrderBy(e => e.EqCondition), "ConditionID", "EqCondition");
//ViewData["EqTypeID"] = new SelectList(_context.EqTypes.OrderBy(e => e.EquipmentType), "EqTypeID", "EquipmentType");
//ViewData["MakeID"] = new SelectList(_context.Makes.OrderBy(m => m.EqMake), "MakeID", "EqMake");
//ViewData["SiteID"] = new SelectList(_context.Sites.OrderBy(s => s.SiteName), "SiteID", "SiteName");
ViewData["Accountno"] = new SelectList(_context.Contact1ss , "Accountno", "Company");
ViewData["Company"] = new SelectList(_context.Contact1ss, "Company", "Accountno");
return View();
}
public IActionResult GetWaterBody(int siteID)
{
var waterBody = new List<Contact1>();
waterBody = getWaterBodyFromDataBaseBySiteID(siteID);
return Json(waterBody);
}
public List<Contact1> getWaterBodyFromDataBaseBySiteID(int siteID)
{
return _context.Contact1ss.ToList();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApplicationCodeFirst
{
public class Contact3
{
//public Contact2()
//{
// Contact1s = new Contact1();
//}
//[Key]
public string Accountno { get; set; }
public DateTime? Callbackon { get; set; }
///... other fields
public string Recid { get; set; }
public virtual Contact1 Contact1s { get; set; }
}
}
<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 identy.Models;
namespace identy.Controllers
{
public class BookMastersController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: BookMasters
public ActionResult Index()
{
return View(db.BookMasters.ToList());
}
[HttpPost]
public ActionResult Index0110(string UnAssignedGroupList)
{
if (string.IsNullOrEmpty(UnAssignedGroupList))
{
ModelState.AddModelError("error ", " At least one unassgined group is Required.");
ViewData["UnAssignedGroupList"] = GetSelectListItem();
return View();
}
return Redirect("");
}
public List<SelectListItem> GetSelectListItem()
{
return new List<SelectListItem>()
{
new SelectListItem(){Text="null",Value=""},
new SelectListItem(){Text="one",Value="001"},
new SelectListItem(){Text="two",Value="002",Selected=true}
};
}
public ActionResult Index0110()
{
ViewData["nameList"] = GetSelectListItem();
//ViewData["nameList"] = list;
//At least one unassgined group is Required.
ViewBag.Message = "Your contact page.";
//var model = db.BookMasters.Where(u => u.Id == 1).FirstOrDefault();
return View(new BookMaster());
}
// GET: BookMasters/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// GET: BookMasters/Create
public ActionResult Create()
{
ViewData["nameList"] = GetSelectListItem();
return View();
}
// POST: BookMasters/Create
// 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关
// 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,strBookTypeId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.BookMasters.Add(bookMaster);
db.SaveChanges();
return RedirectToAction("Index");
}
ModelState.AddModelError("strBookTypeIdd ", " strBookTypeIdd At least one unassgined group is Required.");
ViewData["nameList"] = GetSelectListItem();
return View(bookMaster);
}
// GET: BookMasters/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: BookMasters/Edit/5
// 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关
// 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,strBookTypeId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.Entry(bookMaster).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
// GET: BookMasters/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: BookMasters/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
BookMaster bookMaster = db.BookMasters.Find(id);
db.BookMasters.Remove(bookMaster);
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.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace AspNetMVC
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//定义名为"mycss"的捆绑,js对应为 new JsMinify()
//var b = new Bundle("~/mycss", new CssMinify());
////添加Content文件夹下的所有css文件到捆绑
////第三个参数false表示,Content文件夹下的子文件夹下不添加到捆绑
//b.AddDirectory("~/Content", "*.css", false);
////添加到BundleTable
//BundleTable.Bundles.Add(b);
}
protected void Application_BeginRequest()
{
//RegExRewriteRule rule = new RegExRewriteRule();
//rule.VirtualUrl = "~/test";
//rule.DestinationUrl = "/";
//rule.IgnoreCase = true;
//rule.Redirect = RedirectOption.Application;
//rule.RewriteUrlParameter = RewriteUrlParameterOption.ExcludeFromClientQueryString;
//UrlRewriting.AddRewriteRule("ruleTest", rule);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Speech.Synthesis;
namespace AspNetMVC.Controllers
{
public class MVC0309Controller : Controller
{
CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0309
public ActionResult Index()
{
return View();
}
public ActionResult SpeechPlay()
{
Task task = new Task(Function2);
task.Start();
return Content("ok");
}
public void Function2()
{
SpeechSynthesizer voice = new SpeechSynthesizer();
voice.Rate = -1;
voice.Volume = 100;
voice.SpeakAsync("Hello World Hello World Hello World Hello World Hello World i like speech");
}
public ActionResult Index2() {
return View();
}
//class Program
//{
// static void Main(string[] args)
// {
// SpeechSynthesizer voice = new SpeechSynthesizer(); //Create Object
// voice.Rate = -1; //set Speed [-10,10]
// voice.Volume = 100; //set volume [0,100]
// voice.SpeakAsync("Hello World"); //Play the specified string (asynchronous)
// Console.ReadKey();
// //The following code for some of the attributes of the 'SpeechSynthesizer' see actual situation whether need to use
// //voice.Dispose(); //Release all voice resources
// //voice.SpeakAsyncCancelAll(); //Cancel to read
// //voice.Speak("Hello World"); //Synchronous read
// //voice.Pause(); //Pause
// //voice.Resume(); //go on
// }
//}
//public ActionResult SpeechPlay()
//{
// Task<bool> task = new Task<bool>(() =>
// {
// bool res = Function();
// return res;
// });
// task.Start();
// task.Wait();
// if (task.Result)
// {
// return Content("ok");
// }
// return Content("no");
//}
//public bool Function()
//{
// bool isSuccess;
// try
// {
// SpeechSynthesizer voice = new SpeechSynthesizer();
// voice.Rate = -1;
// voice.Volume = 100;
// voice.SpeakAsync("Hello Wrold");
// isSuccess = true;
// }
// catch (Exception ex)
// {
// isSuccess = false;
// }
// return isSuccess;
//}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplicationForm
{
public partial class About : Page
{
private int _AccessLevel;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed1_Click(object sender, ImageClickEventArgs e)
{
try
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
//if (_AccessLevel == 1)
//{
// _Success = SQL_Functions.DeleteMeetingNotes(Convert.ToInt64(Session["_DateID"]));
// if (_Success == true)
// {
// MessageBox("Your Meeting Note Has Been Removed!");
// _LastIndex = 0;
// Build_MeetingNotes();
// }
// else
// {
// MessageBox("Failed To Delete The Meeting Note!");
// }
//}
//else
{
//MessageBox("Access Denied");
}
}
else
{
//this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
}
}
catch (Exception ex)
{
}
}
protected void GridView1_DataBinding(object sender, EventArgs e)
{
var data=new DataTable();
if (data== null)
{
GridView1.Columns[2].Visible = false;
Button1.Visible = false;
}
else
{
//data = new List<Product>();
}
GridView1.DataSource = data;
GridView1.DataBind();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication
{
class Param
{
public string callerName;
public Param(string s)
{
callerName = s;
}
}
class ThreadTester
{
string myName;
public ThreadTester(string s)
{
myName = s;
}
public static void GlobalWorker()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Global worker {0}", i);
Thread.Sleep(2000);
}
Console.WriteLine("Global worker - done");
}
public void ObjectWorker()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("I'm {0} - repeating {1}", myName, i);
Thread.Sleep(2000);
}
Console.WriteLine("I'm {0} - done", myName);
}
}
public class MainClass
{
public MainClass()
{
}
// simplest threading method
public static void Simplest()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Simplest worker {0}", i);
Thread.Sleep(1000);
}
Console.WriteLine("Simplest worker - done");
}
public static int Main(string[] args)
{
// simplest way
Console.WriteLine("Simple thread - create");
ThreadStart simplest = new ThreadStart(Simplest); //static Simplest work 1 s
Thread thread1 = new Thread(simplest);
thread1.Start();
Console.WriteLine("Simple thread - started");
// simple way with static class method
Console.WriteLine("Thread on static method - create");
ThreadStart entry2 = new ThreadStart(ThreadTester.GlobalWorker); //global 2
Thread thread2 = new Thread(entry2);
thread2.Start();
Console.WriteLine("Thread on static method - started");
// thread on object
Console.WriteLine("Thread on objects - create");
ThreadTester testObject1 = new ThreadTester("First"); //I'am repat 2
ThreadTester testObject2 = new ThreadTester("Second");
ThreadStart entry3 = new ThreadStart(testObject1.ObjectWorker);
ThreadStart entry4 = new ThreadStart(testObject2.ObjectWorker);
Thread thread3 = new Thread(entry3);
Thread thread4 = new Thread(entry4);
thread3.Start();
thread4.Start();
Console.WriteLine("Thread on objects - started");
Console.ReadLine();
return 0;
}
}
}
<file_sep>namespace AspNetMVC.Controllers
{
internal class StateEntity
{
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0210Controller : Controller
{
// GET: MVC0210
public ActionResult Index()
{
return View();
}
public async Task<bool> LaunchTasks(List<int> waitTimes)
{
bool result = false;
List<Task> tasks = new List<Task>();
try
{
foreach (int wait in waitTimes)
{
var task1 = FirstWait(wait);
tasks.Add(task1);
var task2 = SecondWait(wait);
tasks.Add(task2);
}
Debug.WriteLine("About to await on {0} Tasks", tasks.Count);
await Task.WhenAll(tasks);
Debug.WriteLine("After WhenAll");
}
catch (Exception ex)
{
}
return result;
}
private async Task<bool> FirstWait(int waitTime)
{
var task = Task.Factory.StartNew<bool>((delay) =>
{
try
{
int count = (int)delay;
for (int i = 0; i < count; i++)
{
Debug.WriteLine("FirstWait is at {0}", i);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return true;
}, waitTime);
await Task.WhenAll(task);
Debug.WriteLine("After FirstWait");
return task.Result;
}
private async Task<bool> SecondWait(int waitTime)
{
var task = Task.Factory.StartNew<bool>((delay) =>
{
try
{
int count = (int)delay;
for (int i = 0; i < count; i++)
{
Debug.WriteLine("SecondWait is at {0}", i);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return true;
}, waitTime);
await Task.WhenAll(task);
Debug.WriteLine("After SecondWait");
return task.Result;
}
[HttpPost]
public ActionResult Index(int id)
{
return View();
}
public ActionResult Index3() {
var result = LaunchTasks(new List<int>() { 5, 3 });
Debug.WriteLine("The final result is {0}", result.Result);
return View();
}
}
}<file_sep>using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplicationForm
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sFileImage = @"C:\Users\Administrator\Pictures\images\101.jpg";
String sFilePath = @"C:\Users\Administrator\Pictures\images\101"+".xls";
if (File.Exists(sFilePath)) { File.Delete(sFilePath); }
ApplicationClass objApp = new ApplicationClass();
Worksheet objSheet = new Worksheet();
Workbook objWorkBook = null;
//object missing = System.Reflection.Missing.Value;
try
{
System.Data.DataTable a= new System.Data. DataTable();
a.Columns.Add("cc");
//XLWorkbook wb = new XLWorkbook()
//objWorkBook = objApp.Workbooks.Add(a);
//objWorkBook = objApp.Workbooks.Add(a);
objWorkBook = objApp.Workbooks.Add(Type.Missing);
//objWorkBook = objApp.Workbooks.Add(Type.Missing);
objSheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkBook.ActiveSheet;
//Add picture to single sheet1
objSheet = (Worksheet)objWorkBook.Sheets[1];
objSheet.Name = "Graph with Report";
// //////////////
// //Or multiple sheets
//for (int iSheet = 0; iSheet < objWorkBook.Sheets.Count - 1; iSheet++)
//{
// objSheet = objWorkBook.Sheets[iSheet] as Worksheet;
(objSheet as _Worksheet).Activate();
//}
// /////////////////
objSheet.Shapes.AddPicture(sFileImage, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 10, 10, 700, 350);
objWorkBook.SaveAs(sFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
catch (Exception)
{
//Error Alert
}
finally
{
objApp.Quit();
objWorkBook = null;
objApp = null;
}
}
}
}<file_sep>using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace WebApplicationCodeFirst.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
//protected override void OnModelCreating(ModelBuilder modelBuilder)
//{
// modelBuilder.Entity<Contact1>(entity =>
// {
// entity.HasKey(c1 => c1.Accountno);
// entity.HasOne(c2 => c2.Contact2s)
// .WithOne(c1 => c1.Contact1)
// .HasForeignKey<Contact2>(c2 => c2.Accountno);
// entity.Property(e => e.Recid)
// .HasColumnName("recid")
// .HasColumnType("varchar(15)");
// entity.Property(e => e.Accountno)
// .IsRequired()
// .HasColumnName("ACCOUNTNO")
// .HasColumnType("varchar(20)");
// });
// //modelBuilder.Entity<Contact2>(entity =>
// //{
// // entity.HasKey(e => e.Accountno);
// // entity.HasOne(c1 => c1.Contact1)
// // .WithOne(c2 => c2.Contact2);
// // entity.Property(e => e.Recid)
// // .HasColumnName("recid")
// // .HasColumnType("varchar(15)");
// // entity.Property(e => e.Accountno)
// // .IsRequired()
// // .HasColumnName("ACCOUNTNO")
// // .HasColumnType("varchar(20)");
// // entity.Property(e => e.Callbackon)
// // .HasColumnName("CALLBACKON")
// // .HasColumnType("datetime");
// //});
// //base.OnModelCreating(modelBuilder);
//}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}<file_sep> using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleCodeFirst
{
class Program
{
static void Main(string[] args)
{
using (var db = new ApplicatioDbContext0325())
{
db.Database.CreateIfNotExists();
db.SaveChanges();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleCodeFirst
{
public class Contact1
{
public Contact1()
{
}
public string Accountno { get; set; }
public string Company { get; set; }
public string Contact { get; set; }
//... other fields
public string Recid { get; set; }
public virtual Contact4 Contact4s { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleCodeFirst
{
class Class0403
{
}
public class Town {
public Town() {
//Streets = new HashSet< Street >();
}
//[ForeignKey("Supplier")]
public int TownID { get; set; }
public string TownName { get; set; }
//public virtual Supplier Supplier { get; set; }
//public virtual ICollection< Street> Streets { get; set; }
}
//before i use //[ForeignKey("Supplier")]
// public int TownID { get; set; }
public class Street
{
public Street() {
//this.Town = new HashSet<Town>();
}
//[ForeignKey("Supplier")]
public int StreetID { get; set; }
public string StreetName { get; set; }
//public virtual Supplier Supplier { get; set; }
//public virtual ICollection<Town> Town { get; set; }
}
public class Adress
{
[Key, Column(Order = 0)]
public int TownID { get; set; }
[Key, Column(Order = 1)]
public int StreetID { get; set; }
//[Key]
////[ForeignKey("Town")]
//public int TownID { get; set; }
////[ForeignKey("Street")]
////[Key]
//public int StreetID { get; set; }
public virtual Town Town { get; set; }
public virtual Street Street { get; set; }
//public int AdressID { get; set; }
public int NumberAdress { get; set; }
//public int StreetID { get; set; }
}
public class Supplier
{
public Supplier() {
}
public int SupplierID { get; set; }
public string SupplierName { get; set; }
//public string Phone { get; set; }
//public string Email { get; set; }
public Nullable<int> TownID { get; set; }
public Nullable<int> StreetID { get; set; }
//public Nullable<int> AdressNumber { get; set; }
public virtual Town Town { get; set; }
public virtual Street Street { get; set; }
public virtual Adress Adress { get; set; }
}
//Columns of table Town: TownID(primary key), NameTown</p>
//<p>Columns of table Street: TownID,StreetID(composite primary key),NameStreet</p>
//<p>Columns of table Adress: TownID,StreetID,NumberAdress(<wbr>all of these columns are composite primary key)</p>
//<p>Columns of table Supplier: SupplierID,NameSupplier,<wbr>TownID,StreetID,NumberAdress,NumberOfPhone, Email</p>
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0306Controller : Controller
{
CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0306
public ActionResult Index()
{
var c= (from r in db.BookMasters
where r.Id==1
&& r.Id == 1
select new { r.Id }).Single();
db.BookMasters.Where(m => m.Id == 1).Single();
db.BookMasters.Find(1 );
return View();
}
}
}<file_sep>
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirst
{
public class ApplicationDbContext : DbContext
{
//public DbSet<Contact> Contacts { get; set; }
public virtual DbSet<Contact1> Contact1s { get; set; }
public virtual DbSet<Contact2> Contact2s { get; set; }
//protected override void OnModelCreating(ModelBuilder modelBuilder)
//{
// modelBuilder.Entity<Contact1>(entity =>
// {
// entity.HasKey(c1 => c1.Accountno);
// entity.HasOne(c2 => c2.Contact2s)
// .WithOne(c1 => c1.Contact1)
// .HasForeignKey<Contact2>(c2 => c2.Accountno);
// entity.Property(e => e.Recid)
// .HasColumnName("recid")
// .HasColumnType("varchar(15)");
// entity.Property(e => e.Accountno)
// .IsRequired()
// .HasColumnName("ACCOUNTNO")
// .HasColumnType("varchar(20)");
// });
// modelBuilder.Entity<Contact2>(entity =>
// {
// entity.HasKey(e => e.Accountno);
// entity.HasOne(c1 => c1.Contact1)
// .WithOne(c2 => c2.Contact2);
// entity.Property(e => e.Recid)
// .HasColumnName("recid")
// .HasColumnType("varchar(15)");
// entity.Property(e => e.Accountno)
// .IsRequired()
// .HasColumnName("ACCOUNTNO")
// .HasColumnType("varchar(20)");
// entity.Property(e => e.Callbackon)
// .HasColumnName("CALLBACKON")
// .HasColumnType("datetime");
// });
// base.OnModelCreating(modelBuilder);
//}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplicationForm
{
public partial class WebForm0222a : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// SqlConnection con = new SqlConnection("Data Source= ; initial catalog= Northwind ; User Id= ; Password= '");
// con.Open();
// SqlCommand command = new SqlCommand("RegionUpdate", con);
// command.CommandType = CommandType.StoredProcedure;
// command.Parameters.Add(new SqlParameter("@RegionID", SqlDbType.Int, 0, "RegionID"));
// command.Parameters.Add(new SqlParameter("@RegionDescription", SqlDbType.NChar, 50, "RegionDescription"));
// command.Parameters[0].Value = 4;
// command.Parameters[1].Value = "SouthEast";
// int i = command.ExecuteNonQuery();
}
SqlDataAdapter da;
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
private object userName;
public DataTable ExecuteProduce() {
con = new SqlConnection(@"Data Source=MyServer;Initial Catalog=MyDataBase;Integrated Security=True");
con.Open();
cmd= new SqlCommand("LoginUser", con);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandText = Query;
//cmd.Connection = con;
cmd.Parameters.Add("@UserName", SqlDbType.NVarChar, 20).Value= "userName";
cmd.Parameters.Add("@Password", SqlDbType.NVarChar, 20).Value= "pwd";
da = new SqlDataAdapter(cmd);
da.Fill(dt);
cmd.ExecuteNonQuery();
con.Close();
return dt;
//////////////////////
//dt = new DataTable();
//SqlConnection con = new SqlConnection(@"Data Source=MyServer;Initial Catalog=MyDataBase;Integrated Security=True");
//cmd.CommandText = spName;
//cmd.Connection = con;
//cmd.CommandType = CommandType.StoredProcedure;
//var name = cmd.Parameters.Add("@UserName", SqlDbType.NVarChar, 20);
//var pwd = cmd.Parameters.Add("@Password", SqlDbType.NVarChar, 20);
//name.Value = userName;
//pwd.Value = pwd;
//da = new SqlDataAdapter(cmd);
//da.Fill(dt);
//return dt;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0120Controller : Controller
{
private CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0120
public ActionResult Index()
{
return View();
}
// GET: MVC0117
public ActionResult Index2()
{
return View(db.BookMasters.ToList());
}
//public void ToGetCount(List<int> timelist, out int counta, out int countb, out int countc)
//{
// counta = countb = countc = 0;
// foreach (int c in timelist)
// {
// DateTime _time = System.DateTime.Now;
// int _time_num = Convert.ToInt32(_time.Hour);
// if ((_time_num >= 0 ) && (_time_num < 12))
// {
// counta++;
// //return true;
// }
// else if ((_time_num >= 12) && (_time_num < 18))
// {
// countb++;
// //return false;
// }
// else if ((_time_num >= 18) && (_time_num <=23))
// {
// countc++;
// }
// }
//}
public ActionResult Index3()
{
return View(db.BookMasters.ToList());
}
public ActionResult Index4()
{ int c = 0;
int counta, countb, countc;
/* List<int> timelist*//* =*/
counta= db.BookMasters.Where(o => o.Id > 0 && o.Id<15).Count() ;
//ToGetCount(timelist, out counta, out countb, out countc);
return View();
}
public ActionResult Index5()
{
return View();
}
[HttpPost]
public ActionResult Index5(FormCollection form)
{
return View();
}
public ActionResult Index6()
{
return View();
}
[HttpPost]
public ActionResult Index6(string param1, string param2, string param3) //4 into post page
{
if (ModelState.IsValid)
{
//perform a linq query to get report
return RedirectToAction("Index");
}
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}
//private DataClasses1DataContext context = new DataClasses1DataContext();
//private HoldingsContext db = new HoldingsContext();
public List<SelectListItem> GetSelectListItem()
{
return new List<SelectListItem>()
{
new SelectListItem(){Text="null",Value=""},
new SelectListItem(){Text="one",Value="001"},
new SelectListItem(){Text="two",Value="002",Selected=true}
};
}
// GET: Reports/ClientInvestmentsSince
public ActionResult ClientInvestmentsSince()
{
ViewData["client"] = GetSelectListItem(); ;
//ViewBag.SortedFunds = new SelectList(db.Ports.ToList().GroupBy(c => c.Fund).Select(g => g.First()), "Fund", "Fund");
return View();
}
//[HttpGet]
//public ActionResult Edit()
//{
// //Id++;
// return View();
//}
//[HttpPost]
//[ValidateAntiForgeryToken]
//public ActionResult Create([Bind(Include = "ID,LastName,Fund,PurchaseDate,Shares,PurchasePrice,PurchaseAmount")] Investments investments)
//{
// if (ModelState.IsValid)
// {
// //db.Ports.Add(movie);
// //db.SaveChanges();
// return RedirectToAction("Index");
// }
// return View(investments);
//}
//public JsonResult ClientInvestmentsSince2(int Id)
//{
//string str = @"Data Source=USER\SQLEXPRESS;Initial Catalog=HoldingsConnectionString2;Integrated Security=True";
//SqlConnection con = new SqlConnection(str);
//string query = "select ID, Fund from Investments where Client_ID = " + Id;
//SqlCommand cmd = new SqlCommand(query, con);
//con.Open();
//SqlDataReader rdr = cmd.ExecuteReader();
//List<SelectListItem> li = new List<SelectListItem>();
//while (rdr.Read())
//{
// li.Add(new SelectListItem { Text = rdr["ID"].ToString(), Value = rdr["Fund"].ToString() });
//}
//ViewData["Fund"] = li;
//// var theFunds = context.GetTable<Investment>();
//return Json(li, JsonRequestBehavior.AllowGet);
//}
}
}<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 AspNetMVC;
using System.Web.Helpers;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;
using System.IO;
using System.Collections;
//using System.Web.Helpers;
namespace AspNetMVC.Controllers
{
public class MVC0113Controller : Controller
{
private CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0113
public ActionResult Index()
{
return View(db.BookMasters.ToList());
}
//[HttpPost]
//string chartkey = "0", string chartType = "bar"
public PartialViewResult _GetChartImage(string chartkey = "0", string chartType = "bar")
{
ViewBag.chartkey = chartkey;
ViewBag.chartType = chartType;
return PartialView();
}
public class StatusNumber
{
public string Status { get; set; }
public string Number { get; set; }
}
public ActionResult CreatePieChart(string chartkey, string chartType)
{
//var chart = new Chart(width: 500, height: 200)
// .AddTitle("GDP Current Prices in Billion($)")
// .AddLegend()
// .AddSeries(
// chartType: "Pie",
// xValue: xValue,
// yValues: yValue)
// .GetBytes("png");
List<string> xValue = new List<string>();
List<string> yValue = new List<string>();
xValue.Add("17968");
xValue.Add( "11385");
yValue.Add("USA");
yValue.Add("China");
var chart = new System.Web.UI.DataVisualization.Charting.Chart();
var statusNumbers = new List<StatusNumber>
{
new StatusNumber{Number="17968", Status="USA"},
new StatusNumber{Number="11385", Status="China"},
new StatusNumber{Number="4116", Status="Japan"},
new StatusNumber{Number="3371", Status="Germany"},
new StatusNumber{Number="2865", Status="UK"},
new StatusNumber{Number="2423", Status="France"},
new StatusNumber{Number="2183", Status="India"},
};
chart.Width = 500;
chart.Height = 200;
//chart.BackColor = Color.FromArgb(211, 223, 240);
//chart.BorderlineDashStyle = ChartDashStyle.Solid;
//chart.BackSecondaryColor = Color.White;
//chart.BackGradientStyle = GradientStyle.TopBottom;
//chart.BorderlineWidth = 1;
//chart.Palette = ChartColorPalette.BrightPastel;
//chart.BorderlineColor = Color.FromArgb(26, 59, 105);
//chart.RenderType = RenderType.BinaryStreaming;
//chart.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
//chart.AntiAliasing = AntiAliasingStyles.All;
//chart.TextAntiAliasingQuality = TextAntiAliasingQuality.Normal;
chart.Titles.Add(CreateTitle());
//chart.Legends.Add(CreateLegend());
chart.Series.Add(CreateSeries(SeriesChartType.Bar, xValue, yValue ));
//chart.Series.Add(CreateSeries(SeriesChartType.Bar, statusNumbers));
chart.ChartAreas.Add(CreateChartArea());
//var chart = new System.Web.Helpers.Chart(width: 300, height: 200);
//var chart = new System.Web.Helpers.Chart(width: 300, height: 200)
// .AddTitle("Chart1")
// .AddSeries(
// //chartType: "bar",
// chartType: "bar",
// //xValue: new[] { "10 records", "20 records", "30 records", "40 records" },
// //yValues: new[] { "50", "60", "70", "80" },axisLabel: "c,c,c,c"
// yValues: new[] { "50" }, axisLabel: "500"
// )
// .GetBytes("png");
MemoryStream ms = new MemoryStream();
chart.SaveImage(ms);
// FileStream dumpFile = new FileStream(@"C:\Users\v-tiguo\Pictures\Dump.jpg", FileMode.Create, FileAccess.ReadWrite);
// ms.WriteTo(dumpFile);
// ms.Close();
// dumpFile.Seek(0, SeekOrigin.Begin);
//byte[] a= { 1,2};
//ms.Write(a, 0, 10000);
ms.Seek(0, SeekOrigin.Begin);
//return File(dumpFile, @"image/png");
return File(ms, @"image/png");
// return File(chart, "image/png");
}
public Title CreateTitle()
{
Title title = new Title
{
Text = "GDP Current Prices in Billion($)"
//,
//ShadowColor = Color.FromArgb(32, 0, 0, 0),
//Font = new Font("Trebuchet MS", 14F, FontStyle.Bold),
//ShadowOffset = 3,
//ForeColor = Color.FromArgb(26, 59, 105)
};
return title;
}
public Series CreateSeries(SeriesChartType chartType, List<string> xValue, List<string> yValue )
{
var series = new Series
{
Name = "GDP Current Prices in Billion($)",
IsValueShownAsLabel = true//display label text value
//,
//Color = Color.FromArgb(198, 99, 99),
//ChartType = chartType,
//BorderWidth = 2
};
for (int i= 0;i< yValue.Count ; i++ )
{
var point = new DataPoint
{
AxisLabel = yValue[i].ToString(),
YValues = new double[] { double.Parse(xValue[i] .ToString()) }
};
series.Points.Add(point);
}
return series;
}
//public Series CreateSeries(SeriesChartType chartType, ICollection<StatusNumber> list)
//{
// var series = new Series
// {
// Name = "GDP Current Prices in Billion($)",
// IsValueShownAsLabel = true,//display label text value
// Color = Color.FromArgb(198, 99, 99),
// ChartType = chartType,
// BorderWidth = 2
// };
// foreach (var item in list)
// {
// var point = new DataPoint
// {
// AxisLabel = item.Status,
// YValues = new double[] { double.Parse(item.Number) }
// };
// series.Points.Add(point);
// }
// return series;
//}
public ChartArea CreateChartArea()
{
var chartArea = new ChartArea();
//chartArea.Name = "GDP Current Prices in Billion($)";
//chartArea.BackColor = Color.Transparent;
//chartArea.AxisX.IsLabelAutoFit = false;
//chartArea.AxisY.IsLabelAutoFit = false;
//chartArea.AxisX.LabelStyle.Font = new Font("Verdana,Arial,Helvetica,sans-serif", 8F, FontStyle.Regular);
//chartArea.AxisY.LabelStyle.Font = new Font("Verdana,Arial,Helvetica,sans-serif", 8F, FontStyle.Regular);
//chartArea.AxisY.LineColor = Color.FromArgb(64, 64, 64, 64);
//chartArea.AxisX.LineColor = Color.FromArgb(64, 64, 64, 64);
//chartArea.AxisY.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
//chartArea.AxisX.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
//chartArea.AxisX.Interval = 1;
return chartArea;
}
//public Legend CreateLegend()
//{
// var legend = new Legend
// {
// Name = "GDP Current Prices in Billion($)",
// Docking = Docking.Bottom,
// Alignment = StringAlignment.Center,
// BackColor = Color.Transparent,
// Font = new Font(new FontFamily("Trebuchet MS"), 9),
// LegendStyle = LegendStyle.Row
// };
// return legend;
//}
#region orengin
// GET: MVC0113/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// GET: MVC0113/Create
public ActionResult Create()
{
return View();
}
// POST: MVC0113/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.BookMasters.Add(bookMaster);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
// GET: MVC0113/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: MVC0113/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
var c= db.sp_getTreeById(1).ToList();
if (ModelState.IsValid)
{
db.Entry(bookMaster).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
// GET: MVC0113/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: MVC0113/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
BookMaster bookMaster = db.BookMasters.Find(id);
db.BookMasters.Remove(bookMaster);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0313Controller : Controller
{
CodeFirstDbDemoEntities DbContext = new CodeFirstDbDemoEntities();
public class AggregateDto
{
public BookMaster Organisation { get; set; }
public List<Publisher> Meters { get; set; }
public List<C__MigrationHistory> Sites { get; set; }
public List<BookMaster> Contracts { get; set; }
}
//var query = await(from organisation in DbContext.Organisations
// where organisation.ID == request.Id
// join site in DbContext.Sites on organisation.Orgid equals site.Orgid
// into sites_joined
// from site_joined in sites_joined.DefaultIfEmpty()
// from meter in DbContext.Meters.Where(var_meter => site_joined == null ? false : var_meter.SiteLocationID == site_joined.SiteLocationID).DefaultIfEmpty()
// join contract in DbContext.Contracts on organisation.Orgid equals contract.orgid
// into contracts_joined
// from contract_joined in contracts_joined.DefaultIfEmpty()
// select new AggregateDto
// {
// Organisation = new OrganisationDto { ID = organisation.ID, OrganisationName = organisation.OrganisationName },
// Sites = --what goes here ?? ,
// Meters = --and here,
// Contracts = --and here
// }).FirstOrDefaultAsync();
// GET: MVC0313
public ActionResult Index()
{
var c = (from organisation in DbContext.BookMasters
where organisation.Id == 1
join site in DbContext.C__MigrationHistory on organisation.Id.ToString() equals site.ProductVersion
into abc select new { abc=abc }).AsEnumerable().ToList() ;
//c.FirstOrDefault().abc.
//select new AggregateDto { Organisation= new BookMaster { strAccessionId= } } ;
var query = (from organisation in DbContext.BookMasters
where organisation.Id == 1
join site in DbContext.C__MigrationHistory on organisation.Id.ToString() equals site.ProductVersion
into sites_joined
from site_joined in sites_joined.DefaultIfEmpty()
from meter in DbContext.Publishers.Where(var_meter => site_joined == null ? false : var_meter.BookMaster_Id.ToString() == site_joined.ProductVersion).DefaultIfEmpty()
//join contract in DbContext.BookMasters on organisation.Id equals contract.Id
//into contracts_joined
//from contract_joined in contracts_joined.DefaultIfEmpty()
select new AggregateDto
{
Organisation = new BookMaster
{
Id = organisation.Id,
strAccessionId = organisation.strAccessionId
},
//Sites = new List<C__MigrationHistory>() { new C__MigrationHistory() { ProductVersion= .strAccessionId } },
Meters = new List<Publisher>() { new Publisher() { PublisherId = meter.PublisherId } }
}).ToList();
return View();
}
//public Action Index2() {
// return
// Json(
// new { ok = false, msg = main.DeleteFailure, mtype = GetMessageTypeText(Constants.MessageType.error) },
// JsonRequestBehavior.AllowGet);
// return Json(new { state = true, msg = "加载成功", data = result }, JsonRequestBehavior.AllowGet);
//}
//}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace identy.Models
{
public class BookMaster
{
public int Id { get; set; }
[Required(ErrorMessage = "Required At least one unassgined group is Required.")]
public string strBookTypeId { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
public static class ForBytes
{
/// <summary>
/// Get file Bytes
/// 读取文件
/// </summary>
/// <param name="Path">file path</param>
/// <returns></returns>
public static byte[] GetByteData(string Path)
{
FileStream fs = new FileStream(Path, FileMode.Open);
byte[] byteData = new byte[fs.Length];
fs.Read(byteData, 0, byteData.Length);
fs.Close();
return byteData;
}
/// <summary>
/// byte[]转string类型
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string GetStringFromByte(byte[] bytes)
{
return System.Text.Encoding.Default.GetString(bytes);
}
/// <summary>
/// Get Bytes
/// string类型转成byte[]:
/// </summary>
/// <param name="str">strings</param>
/// <returns></returns>
public static byte[] GetByteFromString(string str)
{
return System.Text.Encoding.Default.GetBytes(str);
}
public static Stream GetStreamFromBytes(byte[] bytes)
{
return new MemoryStream(bytes);
}
/// <summary>
/// 字符串保存到文档中
/// </summary>
/// <param name="str"></param>
/// <param name="path"></param>
public static void SaveFile(string str, string path)
{
System.IO.StreamWriter _StreamWriter = new System.IO.StreamWriter(path);
_StreamWriter.Write(str);
_StreamWriter.Close();
}
//public static string GetPath(string path) {
// return Server.MapPath("~/Content/JOSN1.json");
//}
}
<file_sep>$(function(){
//页面加载完成之后执行
pageInit();
});
function pageInit(){
//创建jqGrid组件
jQuery("#list2").jqGrid(
{
url : 'data/JSONData.json',//组件创建完成之后请求数据的url
datatype : "json",//请求数据返回的类型。可选json,xml,txt
colNames : [ 'Inv No', 'Date', 'Client', 'Amount', 'Tax','Total', 'Notes' ],//jqGrid的列显示名字
colModel : [ //jqGrid每一列的配置信息。包括名字,索引,宽度,对齐方式.....
{name : 'id',index : 'id',width : 55},
{name : 'invdate',index : 'invdate',width : 90},
{name : 'name',index : 'name asc, invdate',width : 100},
{name : 'amount',index : 'amount',width : 80,align : "right"},
{name : 'tax',index : 'tax',width : 80,align : "right"},
{name : 'total',index : 'total',width : 80,align : "right"},
{name : 'note',index : 'note',width : 150,sortable : false}
],
rowNum : 10,//一页显示多少条
rowList : [ 10, 20, 30 ],//可供用户选择一页显示多少条
pager : '#pager2',//表格页脚的占位符(一般是div)的id
sortname : 'id',//初始化的时候排序的字段
sortorder : "desc",//排序方式,可选desc,asc
mtype: "get",//向后台请求数据的ajax的类型。可选post,get
viewrecords : true,
caption : "JSON Example"//表格的标题名字
});
/*创建jqGrid的操作按钮容器*/
/*可以控制界面上增删改查的按钮是否显示*/
jQuery("#list2").jqGrid('navGrid', '#pager2', { edit: false, add: false, del: false })
.navGrid('#pager2', { refresh: true } )
.jqGrid('setGroupHeaders', {
useColSpanStyle: false,
groupHeaders: [
{ startColumnName: 'amount', numberOfColumns: 2, titleText: '<em>Actions</em>' }
]
})
//.jqGrid('setGroupHeaders', {
// useColSpanStyle: false,
// groupHeaders: [
// { startColumnName: 'amount', numberOfColumns: 2, titleText: '<em>Actions</em>' }
// ]
//})
//$("#grid").jqGrid({
// defaults: {
// loadtext: "Loading Data please wait ...",
// },
// url: "/User/GetUsers",
// datatype: 'json',
// mtype: 'GET',
// colNames: ["Edit", "Delete", 'Id', 'FirstName', 'LastName'],
// colModel: [
// { name: 'Edit', search: false, width: 30, sortable: false, formatter: editLink },
// { name: 'Delete', search: false, width: 45, sortable: false, formatter: deleteLink },
// { key: false, name: 'UserId', index: 'UserId', sorttype: "int" },
// { key: false, name: 'FirstName', index: 'FirstName' },
// { key: false, name: 'LastName', index: 'LastName' }],
// pager: jQuery('#pager'),
// rowNum: 5,
// rowList: [5, 10, 15, 20, 25],
// height: '100%',
// sortname: 'UserId',
// sortorder: 'asc',
// viewrecords: true,
// jsonReader: {
// root: "rows",
// page: "page",
// total: "total",
// records: "records",
// repeatitems: false,
// Id: "0"
// },
// autowidth: true,
// multiselect: false
//}).navGrid('#pager', { refresh: true }
// .jqGrid('setGroupHeaders', {
// useColSpanStyle: false,
// groupHeaders: [
// { startColumnName: 'Edit', numberOfColumns: 2, titleText: '<em>Actions</em>' }
// ]
// })
// );
//;
//jQuery("#list2").jqGrid('setGroupHeaders', {
// useColSpanStyle: false,
// groupHeaders: [
// { startColumnName: 'amount', numberOfColumns: 3, titleText: '<em>Price</em>' },
// { startColumnName: 'closed', numberOfColumns: 2, titleText: 'Shiping' }
// ]
//});
}
<file_sep>using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace btnet
{
} // end namespace<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Net;
using System.Web.Http;
//using System.Net;
namespace AspNetMVC.Controllers
{
public class MVC0315Controller : Controller
{
CodeFirstDbDemoEntities _customerService = new CodeFirstDbDemoEntities();
// GET: MVC0315
public ActionResult Index()
{
//HttpRequestMessageExtensions.CreateResponse
//HttpContext.Request.CreateResponse("", "Customer not found");
return View();
}
// CASE #1
public BookMaster Get(string id)
{
var customer = new BookMaster();
if (customer == null)
{
var notFoundResponse = new HttpResponseMessage(HttpStatusCode.NotFound);
throw new HttpResponseException(notFoundResponse);
HttpRequestMessage request = new HttpRequestMessage();
var response = request.CreateResponse(HttpStatusCode.OK, customer);
response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
}
return customer;
}
//// CASE #2
//public HttpResponseMessage Get(string id)
//{
// var customer = _customerService.GetById(id);
// if (customer == null)
// {
// var notFoundResponse = new HttpResponseMessage(HttpStatusCode.NotFound);
// throw new HttpResponseException(notFoundResponse);
// }
// var response = Request.CreateResponse(HttpStatusCode.OK, customer);
// response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
// return response;
//}
// CASE #3
//public HttpResponseMessage Get(string id)
//{
// var customer = _customerService.GetById(id);
// if (customer == null)
// {
// var message = String.Format("customer with id: {0} was not found", id);
// var errorResponse = Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
// throw new HttpResponseException(errorResponse);
// }
// var response = Request.CreateResponse(HttpStatusCode.OK, customer);
// response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
// return response;
//}
// CASE #4
//public HttpResponseMessage Get(string id)
//{
// var customer = _customerService.GetById(id);
// if (customer == null)
// {
// var message = String.Format("customer with id: {0} was not found", id);
// var httpError = new HttpError(message);
// return Request.CreateErrorResponse(HttpStatusCode.NotFound, httpError);
// }
// var response = Request.CreateResponse(HttpStatusCode.OK, customer);
// response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
// return response;
//}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0126Controller : Controller
{
private CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0126
public class Employee
{
public int Id { get; set; }
public string EName { get; set; }
public string Address { get; set; }
public Gender Gender { get; set; }
}
public enum Gender
{
Male,
Female,
Other
}
public ActionResult Index()
{
sex field = sex.man;
ViewBag.field = field;
return View(new Employee() { Gender = Gender.Male });
}
public enum sex {
female=1,
man
}
public ActionResult Index2()
{
ViewBag.SortedClients =new SelectList( new List<SelectListItem>() { new SelectListItem() { Text = "c", Value = "1" } } ,"Value","" );
ViewBag.c = "1";
ViewBag.c= GetClientTime("+08 00");
return View();
}
public DateTime GetClientTime(string clientTimeOffset)
{
//clientTimeOffset: "+08 00"
DateTime utcTime = DateTime.UtcNow; //1 / 26 / 2017 7:33:02 AM
string[] timeOffset = clientTimeOffset.Split(' ');
int hourOffset = int.Parse(timeOffset[0]);
int minuteOffset = int.Parse(timeOffset[1]);
utcTime = utcTime.AddHours(hourOffset);
utcTime = utcTime.AddMinutes(minuteOffset);
return utcTime; // return custom time : 1 / 26 / 2017 3:33:02 PM
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AspNetMVC.Controllers
{
public class MVC0220Controller : Controller
{
CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
public byte[] FileVirtualPath { get; private set; }
// GET: MVC0220
public ActionResult Index()
{
return View();
}
public ActionResult Index2() {
return View();
}
//[HttpPost]
[Route]
public ActionResult Index3( )
{
ModelState.AddModelError("", "error");
// Response.Write("ee");
// return RedirectToAction("Index2");
return View("~/Views/MVC0220/Index2.cshtml");
}
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="obj"></param>
public void ExportData( )
{
Response.ClearContent();
//string html = "<table><tr><td>1</td><td>11</td></tr><tr><td>2</td><td>22</td></tr></table>";
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition",
"attachment; filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
Response.Write("<head>");
Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
//string fileCss = Server.MapPath("~/css/daoChuCSS.css");
//string cssText = string.Empty;
//StreamReader sr = new StreamReader(fileCss);
//var line = string.Empty;
//while ((line = sr.ReadLine()) != null)
//{
// cssText += line;
//}
//sr.Close();
//Response.Write("<style>" + cssText + "</style>");
Response.Write("<!--[if gte mso 9]><xml>");
Response.Write("<x:ExcelWorkbook>");
Response.Write("<x:ExcelWorksheets>");
Response.Write("<x:ExcelWorksheet>");
Response.Write("<x:Name>Report Data</x:Name>");
Response.Write("<x:WorksheetOptions>");
Response.Write("<x:Print>");
Response.Write("<x:ValidPrinterInfo/>");
Response.Write("</x:Print>");
Response.Write("</x:WorksheetOptions>");
Response.Write("</x:ExcelWorksheet>");
Response.Write("</x:ExcelWorksheets>");
Response.Write("</x:ExcelWorkbook>");
Response.Write("</xml>");
Response.Write("<![endif]--> ");
BookMaster bookMaster = db.BookMasters.Find(1);
View(bookMaster).ExecuteResult(this.ControllerContext);//= Response.Write(whole HTML content);
Response.Flush();
Response.End();
}
public void ExportData1( )
{
string style = "";
//if (obj.Rows.Count > 0)
//{
// style = @"<style> .text { mso-number-format:\@; } </script> ";
//}
//else
//{
// style = "no data.";
//}
Response.ClearContent();
DateTime dt = DateTime.Now;
string filename = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString();
Response.AddHeader("content-disposition", "attachment;filename=ExportData.xlsx");
//Response.ContentType = "application/ms-excel";
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
StringBuilder sb = new StringBuilder();
//GridView
View().ExecuteResult(this.ControllerContext);
sb.Append(HttpContext.Response.Output.NewLine);
StringWriter sw = new StringWriter(sb );
HtmlTextWriter htw = new HtmlTextWriter(sw);
htw.BeginRender();
//Response.TrySkipIisCustomErrors = true;
Response.Write("<!--[if gte mso 9]><xml>");
Response.Write("<x:ExcelWorkbook>");
Response.Write("<x:ExcelWorksheets>");
Response.Write("<x:ExcelWorksheet>");
Response.Write("<x:Name>Report Data</x:Name>");
Response.Write("<x:WorksheetOptions>");
Response.Write("<x:Print>");
Response.Write("<x:ValidPrinterInfo/>");
Response.Write("</x:Print>");
Response.Write("</x:WorksheetOptions>");
Response.Write("</x:ExcelWorksheet>");
Response.Write("</x:ExcelWorksheets>");
Response.Write("</x:ExcelWorkbook>");
Response.Write("</xml>");
Response.Write("<![endif]--> ");
Response.Write(sb);//这里
//Response.Write(this);
//this.ControllerContext.HttpContext.Response.End();
//obj.RenderControl(htw);
//Response.Write(style);
//Response.Write(sw.ToString());
//Response.Write(d.ToString());
Response.Flush();
Response.End();
}
//public virtual ActionResult GetFile()
// {
// return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
// }
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="obj"></param>
//public ActionResult ExportData1( )
//{
// Response.ContentType = "application/vnd.ms-excel"
// return Files();
//}
[Route("list.html")]
[Route("list_{category}.html")]
[Route("list_{category}_p{page:int}.html")]
public void ArticleList(string category, int page = 1)
{
var title = string.IsNullOrEmpty(category) ? "所有资讯" : category + "资讯";
Response.Write(string.Format("分类:{0},页码:{1}<br/>我们都是好孩子!!!", title, page));
}
public class Photo
{
public Photo (){
this.chasr = DateTime.Now;
}
[Key]
public int ID { get; set; }
public string NameofPhoto { get; set; }
[ScaffoldColumn(false)]
public string ImageName { get; set; }
[NotMapped]
public HttpPostedFileBase File { get; set; }
//[DefaultValue(TypeDescriptor DateTime.Now.ToString())]
//[DefaultValue( DateTime.Now.ToString())]
//[DefaultValue(typeof( DateTime),(new TypeConverter()).ConvertToString(DateTime.Now.Day) )]
//[DefaultValue(Guid.NewGuid())]
public DateTime chasr{ get ;set;}
private bool myVal = false;
[DefaultValue(false)]
public bool MyProperty
{
get
{
return myVal;
}
set
{
myVal = value;
}
}
}
//this is my controller for the images
public ActionResult Create()
{
return View();
}
public async Task<string> G() {
var baseAddress = new Uri("http://example.com");
using (var handler = new HttpClientHandler { UseCookies = false })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var message = new HttpRequestMessage(HttpMethod.Get, "/test");
message.Headers.Add("Cookie", "cookie1=value1; cookie2=value2");
var result = await client.SendAsync(message);
return result.EnsureSuccessStatusCode().ToString();
}
}
//[HttpPost]
//[ValidateAntiForgeryToken]
//public ActionResult Create([Bind(Include = "ID,NameofPhoto,ImageName")] Photo photo, HttpPostedFileBase file)
//{
// if (ModelState.IsValid)
// {
// try
// {
// var filename = "";
// if (file != null && file.ContentLength > 0)
// {
// Guid gid;
// gid = Guid.NewGuid();
// var extension = Path.GetExtension(file.FileName);
// filename = gid + extension;
// var path = Path.Combine(Server.MapPath("~/Content/PhotoGallery/"), filename);
// var data = new byte[file.ContentLength];
// file.InputStream.Read(data, 0, file.ContentLength);
// using (var sw = new FileStream(path, FileMode.Create))
// {
// sw.Write(data, 0, data.Length);
// }
// }
// photo.ImageName = filename;
// db.Photos.Add(photo);
// db.SaveChanges();
// }
// catch (Exception ex)
// {
// TempData["Message"] = "<div class='alert alert-danger'><a href='#' class='close' data-dismiss='alert'>× Directory</a><strong> " + ex.ToString() + "</strong> Not found.</div>";
// }
// return RedirectToAction("Index");
// }
// return View(photo);
//}
//public ActionResult Edit(int? id)
//{
// if (id == null)
// {
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);//返回状态
// }
// Photo photo = db.Photos.Find(id);
// if (photo == null)
// {
// return HttpNotFound();
// }
// return View(photo);
//}
//[HttpPost]
//[ValidateAntiForgeryToken]
//public ActionResult Edit([Bind(Include = "ID,NameofPhoto,ImageName")] Photo photo)
//{
// if (ModelState.IsValid)
// {
// try
// {
// db.Entry(photo).State = EntityState.Modified;
// db.Entry(photo).Property("ImageName").IsModified = false;
// string path = Server.MapPath("~/Content/PhotoGallery/");
// var ImageName = GetImageName(photo.ID);
// //string Fromfol = GetAlbumNameByPhotoID(photo.ID) + "/" + ImageName;
// //System.IO.File.Move(path + Fromfol);
// db.SaveChanges();
// }
// catch (IOException ex)
// {
// TempData["Message"] = "<div class='alert alert-danger'><a href='#' class='close' data-dismiss='alert'>× </a><strong> " + ex.ToString() + "</strong> </div>";
// }
// return RedirectToAction("Index");
// }
// return View(photo);
//}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using AspnetCore;
using AspnetCore.Data;
using Microsoft.AspNetCore.Http;
namespace AspnetCore.Controllers
{
public class Core02062Controller : Controller
{
private readonly ApplicationDbContext _context;
public Core02062Controller(ApplicationDbContext context)
{
_context = context;
}
// GET: Core02062
public async Task<IActionResult> Index()
{
return View(await _context.Contact1ss.ToListAsync());
}
// GET: Core02062/Details/5
//public async Task<IActionResult> Details(string? id)
//{
// if (id == null)
// {
// return NotFound();
// }
// var contact1 = await _context.Contact1ss.SingleOrDefaultAsync(m => m.Accountno == id);
// if (contact1 == null)
// {
// return NotFound();
// }
// return View(contact1);
//}
// GET: Core02062/Create
public IActionResult Create()
{
return View();
}
// POST: Core02062/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Accountno,Company,Contact,Recid")] Contact1 contact1)
{
if (ModelState.IsValid)
{
_context.Add(contact1);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(contact1);
}
// GET: Core02062/Edit/5
//public async Task<IActionResult> Edit(string? id)
//{
// if (id == null)
// {
// return NotFound();
// }
// //var contact1 = await _context.Contact1ss.SingleOrDefaultAsync(m => m.Accountno == id);
// //if (contact1 == null)
// //{
// // return NotFound();
// //}
// //return View(contact1);
// return View( );
//}
// POST: Core02062/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, [Bind("Accountno,Company,Contact,Recid")] Contact1 contact1,FormCollection form,string [] a)
{
Microsoft.Extensions.Primitives.StringValues c = new Microsoft.Extensions.Primitives.StringValues("");
List<string> b=new List<string> ();
form.TryGetValue("a", out c);
if (id != contact1.Accountno)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(contact1);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!Contact1Exists(contact1.Accountno))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(contact1);
}
// GET: Core02062/Delete/5
//public async Task<IActionResult> Delete(string? id)
//{
// if (id == null)
// {
// return NotFound();
// }
// var contact1 = await _context.Contact1ss.SingleOrDefaultAsync(m => m.Accountno == id);
// if (contact1 == null)
// {
// return NotFound();
// }
// return View(contact1);
//}
// POST: Core02062/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
var contact1 = await _context.Contact1ss.SingleOrDefaultAsync(m => m.Accountno == id);
_context.Contact1ss.Remove(contact1);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
private bool Contact1Exists(string id)
{
_context.Database.ExecuteSqlCommand("select * from Table");
_context.Database.ExecuteSqlCommandAsync("select * from Table");
return _context.Contact1ss.Any(e => e.Accountno == id);
}
}
}
<file_sep>namespace AspNetMVC.Controllers
{
internal class SSPClientMasterEntity
{
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace AspNetMVC.Models.Movies
{
public class MovieV
{
public MovieV() { }
public Movie MovieTitle { get; set; }
public Actor ActorNames { get; set; }
public Crew CrewNamesTitles { get; set; }
public Detail MovieCatDesc { get; set; }
//public Category CategoryName { get; private set; }
//public CrewTitle CrewTitleName { get; private set; }
public string strMovieTitle { get; set; }
public string strActorName { get; set; }
public string strCrewName { get; set; }
public string strCrewTitle { get; set; }
public string strCategory { get; set; }
public string strDescription { get; set; }
public IEnumerable<string> Categories { set; get; }
public int intCrewTitleID { get; set; }
public int intCategoryID { get; set; }
public MovieV(Movie Movies)
{
MovieTitle = Movies;
ActorNames = new Actor();
CrewNamesTitles = new Crew();
MovieCatDesc = new Detail();
//CategoryName = new Category();
//CrewTitleName = new CrewTitle();
strMovieTitle = "";
strActorName = "";
strCrewName = "";
strCrewTitle = "";
strDescription = "";
strCategory = "";
Categories = null;
intCrewTitleID = -1;
intCategoryID = -1;
}
}
public partial class Movie
{
/// <summary>
/// You will need to configure this module in the Web.config file of your
/// web and register it with IIS before being able to use it. For more information
/// see the following link: http://go.microsoft.com/?linkid=8101007
/// </summary>
//#region IHttpModule Members
//public void Dispose()
//{
// //clean-up code here.
//}
//public void Init(HttpApplication context)
//{
// // Below is an example of how you can handle LogRequest event and provide
// // custom logging implementation for it
// context.LogRequest += new EventHandler(OnLogRequest);
//}
//#endregion
[Key]
public int MovieID { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Name cannot be longer than 100 characters")]
[Display(Name = "Movie: ")]
public string MovieTitle { get; set; }
public virtual ICollection<Actor> Actors { get; set; }
public virtual ICollection<Crew> Crew { get; set; }
public virtual ICollection<Detail> Detail { get; set; }
//public IEnumerable<Category> Category { get; private set; }
//public IEnumerable<CrewTitle> CrewTitle { get; private set; }
public void OnLogRequest(Object source, EventArgs e)
{
//custom logging logic can go here
}
}
public class Actor
{
public int MovieId { get; set; }
public int ActorId { get; set; }
[StringLength(50, ErrorMessage = "Actor cannot be longer than 50 characters")]
[Required]
[Display(Name = "Actor: ")]
public string ActorName { get; set; }
public virtual Movie Movie { get; set; }
}
public class Crew
{
public int MovieId { get; set; }
public int CrewId { get; set; }
public Nullable<int> CrewTitleId { get; set; }
[StringLength(50, ErrorMessage = "Name cannot be longer than 50 characters")]
[Required]
[Display(Name = "Name: ")]
public string CrewName { get; set; }
public virtual Movie Movie { get; set; }
//public virtual CrewTitle CrewTitle { get; set; }
}
public class Detail
{
public int MovieId { get; set; }
public int DetailId { get; set; }
public int CategoryID { get; set; }
[Display(Name = "Description: ")]
[StringLength(255, ErrorMessage = "Description cannot be longer than 255 characters")]
public string Description { get; set; }
public virtual Movie Movie { get; set; }
//public virtual Category Category { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.Data.Linq.SqlClient;
using System.Data.SqlClient;
using System.Data;
namespace AspNetMVC.Controllers
{
public class MVC0223Controller : Controller
{
CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0223
public ActionResult Index()
{
(from c in db.BookMasters select c.Id).Union(from e in db.BookMasters where e.Id>1 select e.Id);
var str= from a in db.BookMasters
join b in db.BookMasters
on a.Id equals b.Id where b.Id>1
select new { a.Id, b.strAccessionId };
var q = from c in db.BookMasters where SqlMethods.Like(c.strAccessionId, "C%") select c ;
db.sp_getTreeById(1);
// db.Database.ExecuteSqlCommand(
//"UPDATE dbo.Posts SET Title = 'Updated Title' WHERE PostID = 99");
//SqlCommand command = new SqlCommand(commandText, connection);
//command..ExecuteNonQuery();
//command.Parameters.Add("@ID", SqlDbType.Int);
//command.Parameters["@ID"].Value = customerID;
//db.BookMasters.GroupJoin(a,m=>m.)
return View();
}
}
}<file_sep>(function ($) {
$(document).ready(function (e) {
//监听jquery中的appendTo事件而引发的自定义事件
$(".field-validation-valid").on('appendTochange', function (e) {
var errText = $(this).children().eq(0).text();
if (errText.length > 0) {
alert(errText);
//alert(this);
$(this).hide();
//$(this).parent().children
$('#strAccessionId').b.attr("data-content", errText).popover()
// alert("c")
//$(this).parent().children('.validImg').attr('title', errText).show();
//将错误提示信息span隐藏起来
}
//此时应该添加上去了一个子元素
});
//
$(".field-validation-valid").on('removeDatachange', function (e) {
alert("ca")
//此时已经验证通过了
//$(this).parent().children('.validImg').hide();
});
});
$.each(["appendTo", "removeData"], function (i, methodname) {
var oldmethod = $.fn[methodname];
$.fn[methodname] = function () {
oldmethod.apply(this, arguments);
this.trigger(methodname + "change");
return this;
}
});
})(jQuery);<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace AspnetCoreAll.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
string strUrl = "http://www.w3school.com.cn/example/xmle/note.xml";
XmlDocument doc = new XmlDocument();
doc.Load(strUrl);
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0117Controller : Controller
{
private CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0117
public ActionResult Index()
{
return View(db.BookMasters.ToList());
}
public bool Detal()
{
return true;
}
public ActionResult Index2()
{
return View();
}
[HttpPost]
public ActionResult Index2(FormCollection form)
{
foreach (var a in form.AllKeys)//form.Count=1
{
string key = a; //key=hdn_2
string value= form[a]; //value=3
}
return View();
}
public ActionResult Index3()
{
return View();
}
[HttpGet]
public IEnumerable<BookMaster> Index5()
{
return db.BookMasters.ToList();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0217Controller : Controller
{
// GET: MVC0217
public ActionResult Index()
{
return View();
}
public ActionResult Index2() {
return View();
}
[HttpPost]
public ActionResult UserRegistration( )
{
//if (ModelState.IsValid)
//{
return Json("Registration Success", JsonRequestBehavior.AllowGet);
//}
//else
//{
// return View();
//}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0307Controller : Controller
{
// GET: MVC0307
public string codedump<t>()
{
string result = string.Empty;
System.Reflection.PropertyInfo[] properties = typeof(t).GetProperties();
foreach (System.Reflection.PropertyInfo item in properties)
{
result += string.Format("{0} = record.field<{1}>(\"{0}\"),", item.Name, item.PropertyType.FullName);
}
return result;
}
public ActionResult Index()
{
//using (IDataReader dr = _db.executereader(command))
//{
// questionanswerlist = dr.getenumerator<BookMaster>(new BookMaster().createquestionanswerinfo).tolist();
//}
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleCodeFirst
{
public class Country
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int CountryId { get; set; }
[DisplayName("Country")]
public string CountryName { get; set; }
public int StateId { get; set; }
public virtual State State { get; set; }
//public virtual ICollection<State> States { get; set; }
public virtual ICollection<Customer> Customer { get; set; }
}
public class State
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int StateId { get; set; }
[DisplayName("State")]
public string StateName { get; set; }
//public int CountryId { get; set; }
public virtual ICollection< Country> Country { get; set; }
public virtual ICollection<City> Cities { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
public class City
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int CityId { get; set; }
[DisplayName("City")]
public string CityName { get; set; }
public int StateId { get; set; }
public virtual State State { get; set; }
public virtual ICollection<Customer> Customer { get; set; }
}
public class Customer
{
[Key]
public string CustomerId { get; set; }
[Required(ErrorMessage = "Please enter Customer Name")]
public string CustomerName { get; set; }
[DisplayName("Country")]
public int CountryId { get; set; }
[DisplayName("State")]
public int StateId { get; set; }
[DisplayName("City")]
public int CityId { get; set; }
public bool IsActive { get; set; }
public DateTime CreatedOnUtc { get; set; }
public virtual Country Country { get; set; }
public virtual State State { get; set; }
public virtual City City { get; set; }
}
public class ApplicatioDbContext0325 : DbContext
{
public ApplicatioDbContext0325()
: base("name=CodeFirstDbDemo0325")
{
}
public DbSet<Customer> Customer { get; set; }
public DbSet<City> City { get; set; }
public DbSet<Country> Country { get; set; }
public DbSet<State> State { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<State>().HasMany(t => t.Customers).WithRequired(a=>a.State).WillCascadeOnDelete(false);
modelBuilder.Entity<State>().HasMany(t => t.Cities).WithRequired(a => a.State).WillCascadeOnDelete(false);
modelBuilder.Entity<State>().HasMany(t => t.Country).WithRequired(a => a.State).WillCascadeOnDelete(false);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplicationForm
{
public partial class WebForm0226 : System.Web.UI.Page
{
protected void CategoriesListView_OnItemDeleting(object sender, ListViewDeleteEventArgs e)
{
//if (SubCategoriesGridView.Rows.Count > 0)
//{
// MessageLabel.Text = "You cannot delete a category that has sub-categories.";
// e.Cancel = true;
//}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
a();
}
}
public void a() {
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);
//dc = new DataColumn("col2", typeof(String));
//dt.Columns.Add(dc);
//dc = new DataColumn("col3", typeof(String));
//dt.Columns.Add(dc);
//dc = new DataColumn("col4", typeof(String));
//dt.Columns.Add(dc);
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr[0] = "coldata1" + i.ToString();
//dr[1] = "coldata2";
//dr[2] = "coldata3";
//dr[3] = "coldata4";
dt.Rows.Add(dr);
}
listviedo.DataSource = dt;
listviedo.DataBind();
}
protected void listviedo_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
this.listviedo.SelectedIndex = e.NewSelectedIndex;
////ListViewDataItem item = (ListViewDataItem)sender;
//this.listviedo.UpdateItem(e.NewSelectedIndex, false);
//this.listviedo.ItemUpdating
//ListView.UpdateItem m
//// Update the database with the changes.
//VendorsListView.UpdateItem(item.DisplayIndex, false);
a();
}
protected void listviedo_SelectedIndexChanged(object sender, EventArgs e)
{
//listviedo.UpdateItem( listviedo.SelectedIndex, false);
}
protected void listviedo_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
//listviedo.UpdateItem(listviedo.SelectedIndex, false);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AspnetCore.Models
{
public class GetStr
{
public static string getss(string a) {
Startup.connectionString = "abc";
return a;
}
}
}
<file_sep># AspNetMVC
2016/12 -Now support Asp.net
<file_sep>using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using WebApplicationCodeFirst.Models;
namespace WebApplicationCodeFirst
{
public class ApplicatioDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicatioDbContext()
: base("name=CodeFirstDbDemo3")
{
}
//public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact1>(entity =>
{
entity.HasKey(c1 => c1.Accountno);
entity.HasOne(c2 => c2.Contact2s)
.WithOne(c1 => c1.Contact1)
.HasForeignKey<Contact2>(c2 => c2.Accountno);
entity.Property(e => e.Recid)
.HasColumnName("recid")
.HasColumnType("varchar(15)");
entity.Property(e => e.Accountno)
.IsRequired()
.HasColumnName("ACCOUNTNO")
.HasColumnType("varchar(20)");
});
//modelBuilder.Entity<Contact2>(entity =>
//{
// entity.HasKey(e => e.Accountno);
// entity.HasOne(c1 => c1.Contact1)
// .WithOne(c2 => c2.Contact2);
// entity.Property(e => e.Recid)
// .HasColumnName("recid")
// .HasColumnType("varchar(15)");
// entity.Property(e => e.Accountno)
// .IsRequired()
// .HasColumnName("ACCOUNTNO")
// .HasColumnType("varchar(20)");
// entity.Property(e => e.Callbackon)
// .HasColumnName("CALLBACKON")
// .HasColumnType("datetime");
//});
//base.OnModelCreating(modelBuilder);
}
public DbSet<Contact1> Contact1s { get; set; }
public DbSet<Contact2> Contact2s { get; set; }
}
}
<file_sep>using AspNetMVC.Models;
using AspNetMVC.Models.Movies;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0201Controller : Controller
{
MovieDBContext db = new MovieDBContext();
// GET: MVC0201
public ActionResult Index()
{
return View();
}
public ActionResult Index2() {
db.Database.CreateIfNotExists();
db.MovieTitles.Add(new Movie() { MovieTitle = "e" });
db.SaveChanges();
var c = db.MovieTitles.FirstOrDefault();
var d = db.MovieTitles.ToList();
var MovieTitles = from mv in db.MovieTitles //This is where it blows up
select new { mv.MovieTitle };
//return RedirectToAction(nameof(HomeController.Index), "Home");
return View(new BookMaster() { Id=6});
}
public ActionResult Search(MovieV mvV)
{
//bookmark -- why is database context empty?
var newMovie = new Movie();
newMovie.MovieTitle = "American Pie";
using (db)
{
db.MovieTitles.Add(newMovie);
db.SaveChanges();
var MovieTitles = from mv in db.MovieTitles //This is where it blows up
select new { mv.MovieTitle };
var listmvV = MovieTitles.ToList();
}
return Content("no");
}
//public ActionResult Create()
//{
// //ViewData["client"] = "";// GetSelectListItem(); //1.Assigning value to variables ViewData["nameList"]
// ViewBag.SortedFunds = new SelectList(db.Ports.ToList().GroupBy(c => c.Fund).Select(g => g.First()), "Fund", "Fund");
// ViewBag.SortedClients = new SelectList(db.Ports.ToList().GroupBy(c => c.LastName).Select(g => g.First()), "LastName", "LastName");
// return View();
//}
//[HttpPost]
//public ActionResult Create(Investment param)
//{
// var purchaseDate = param.PurchaseDate;
// var lastName = param.LastName;
// var fund = param.Fund;
// if (!ModelState.IsValid)
// return View();
// //report query
// var result = (from res in context.Investments
// where res.LastName == lastName
// where res.Fund == fund
// where res.PurchaseDate >= purchaseDate
// select res).ToList();
// //return RedirectToAction("Index");
// return View(result);
//}
}
}<file_sep>using AspNetMVC.Models.Movies;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace AspNetMVC.Models
{
public class MovieDBContext : DbContext
{
public MovieDBContext() : base("DefaultConnection")
{
}
public DbSet<Movie> MovieTitles { get; set; }
public DbSet<Actor> ActorNames { get; set; }
public DbSet<Crew> CrewNames { get; set; }
//public DbSet<CrewTitle> CrewTitles { get; set; }
public DbSet<Detail> Details { get; set; }
//public DbSet<Category> CategoryTitles { get; set; }
}
}<file_sep>
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0301Controller : Controller
{
// GET: MVC0301
CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
public ActionResult Index()
{
SqlCommand cmd;
SqlConnection con;
//data source=VDI-V-TIGUO;initial catalog=CodeFirstDbDemo20;integrated security=True;" providerName="System.Data.SqlClient"
con = new SqlConnection(@"data source=VDI-V-TIGUO;initial catalog=CodeFirstDbDemo;integrated security=True;" );
//con = new SqlConnection(@"Data Source=MyServer;Initial Catalog=MyDataBase;Integrated Security=True");
cmd = new SqlCommand("sp_LoginUser", con);
SqlParameter RetVal = cmd.Parameters.Add
("RetVal", SqlDbType.Int);
RetVal.Direction = ParameterDirection.ReturnValue;
//cmd = new SqlCommand("sp_getTreeById", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteScalar() ;
db.Database.SqlQuery<BookMaster>
("SELECT * FROM dbo.Posts WHERE Author = @author", new SqlParameter("@author", "authornamevalue"));
//return Content(RetVal.Value.ToString() );
return View();
}
}
}<file_sep>using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AspnetCorea.ViewComponents
{
public class PriorityListViewComponent : ViewComponent
{
public IViewComponentResult Invoke(
int maxPriority, bool isDone)
{
return View( );
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleCodeFirst
{
public class MyPerson1 {
public MyPerson1()
{
MyIds = new MyId1();
}
//public int UserId { get; set; }
//public int IdPart1 { get; set; }
//public int IdPart2 { get; set; }
public MyId1 MyIds { get; set; }
public string Name { get; set; }
}
public class MyId1
{
//public MyId1()
//{
//}
public string IdPart1 { get; set; }
public string IdPart2 { get; set; }
}
public class ApplicatioDbContext0217 : DbContext
{
public ApplicatioDbContext0217()
: base("name=CodeFirstDbDemo0217")
{
}
//public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.ComplexType<MyId1>();
//modelBuilder.ComplexType<MyId1>().Property(p => p.IdPart2) ;
//modelBuilder.Entity<MyPerson1>().HasKey(p =>new string(p.MyIds.IdPart1.ToString()) );
//base.OnModelCreating(modelBuilder);
}
public DbSet<MyPerson> MyPersons { get; set; }
//public DbSet<MyId> MyIds { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0316Controller : Controller
{
// GET: MVC0316
public ActionResult Index()
{
QueryCondition queryCondition = new QueryCondition(null, "动态测试", new DateTime(2013, 1, 1), new DateTime(2013, 3, 1), null, null, 0, true);
QueryCondition queryCondition2 = new QueryCondition(null, string.Empty, null, null, null, 60, 1, false);
QueryCondition queryCondition3 = new QueryCondition(null, string.Empty, null, new DateTime(2013, 5, 1), null, 60, 5, true);
QueryCondition[] queryConditionLs = new QueryCondition[] { queryCondition, queryCondition2, queryCondition3 };
DynamicLambda dynamicLinq = new DynamicLambda();
List<TestUser> queryLs;
queryLs = dynamicLinq.GetTestData();
Console.WriteLine("原始测试数据有{0}条,如下\n", queryLs.Count);
dynamicLinq.PrintResult(queryLs);
Console.WriteLine("---------------查询分隔符------------------\n");
//queryLs = dynamicLinq.GetDataByGeneralQuery(queryConditionLs[0]);
queryLs = dynamicLinq.GetDataByDynamicQuery(queryConditionLs[0]);
Console.WriteLine("满足查询结果的数据有{0}条,如下\n", queryLs.Count);
dynamicLinq.PrintResult(queryLs);
Console.ReadKey();
return View();
}
/// <summary>
/// 动态Lambda表达式类
/// </summary>
public class DynamicLambda
{
public Dictionary<string, string> queryDict = new Dictionary<string, string>();
public OrderEntry[] orderEntries;
public DynamicLambda()
{
InitDynamicQueryMapping();
orderEntries = new OrderEntry[] {
new OrderEntry(){OrderStr="Id",OrderType=typeof(int)},
new OrderEntry(){OrderStr="Name",OrderType=typeof(string)},
new OrderEntry(){OrderStr="Birth",OrderType=typeof(string)},
new OrderEntry(){OrderStr="IsStudent",OrderType=typeof(string)},
new OrderEntry(){OrderStr="Cellphone",OrderType=typeof(string)},
new OrderEntry(){OrderStr="Email",OrderType=typeof(string)},
new OrderEntry(){OrderStr="Score",OrderType=typeof(int)}
};
}
/*在一般的业务环境中我们常常会遇到动态查询的情况,对于以前纯T-SQL情况下我们一般是采用根据相应条件动态拼接相应的where条件上去达到相应效果
如今在这个LINQ横行的年代,怎么能利用LINQ完成动态查询呢
*/
#region 一般的解决方案
//如果要根据对应的Linq的方式怎么完成
public List<TestUser> GetDataByGeneralQuery(QueryCondition queryCondition)
{
//此处一般会从数据库或者其他地方获取到业务所用到的数据源
List<TestUser> sourceLs = GetTestData();
/*根据不同情况添加不同查询条件,但是我们都摘掉平时开发中需求是不断变化的,怎么能更好的应对PM各种扭曲的要求尔不必一次一次的添加各种if条件呢
万一有一天,PM要求你将某些条件合并例如名字和ID变为OR的关系怎么办,如果需要利用LINQ进行动态的排序怎么办,或者如果过滤的名字是一个
不定的字符串数组怎么办,这些都是我们经常会遇到的,我们不能因为每次这样的改动而去修改这里的东西, 而且有的时候我们知道在Where(n=>n.?==?)
但是编译器是不知道的,这是我们就要用到动态lambda表达式(动态linq的方式)
*/
if (queryCondition.QueryId.HasValue)
sourceLs = sourceLs.Where(n => n.Id == queryCondition.QueryId).ToList<TestUser>();
if (!string.IsNullOrEmpty(queryCondition.QueryName))
sourceLs = sourceLs.Where(n => n.Name.ToLower().Contains(queryCondition.QueryName.ToLower())).ToList<TestUser>();
if (queryCondition.QueryStartTime.HasValue)
sourceLs = sourceLs.Where(n => n.Birth >= queryCondition.QueryStartTime.Value).ToList<TestUser>();
if (queryCondition.QueryEndTime.HasValue)
sourceLs = sourceLs.Where(n => n.Birth < queryCondition.QueryEndTime.Value).ToList<TestUser>();
if (queryCondition.QueryBoolean != null)
sourceLs = sourceLs.Where(n => n.IsStudent = queryCondition.QueryBoolean.Value).ToList<TestUser>();
if (queryCondition.QueryScore.HasValue)
sourceLs = sourceLs.Where(n => n.Score == queryCondition.QueryScore.Value).ToList<TestUser>();
switch (queryCondition.OrderField)
{
case 0:
{
if (queryCondition.IsDesc)
sourceLs = sourceLs.OrderByDescending(n => n.Id).ToList<TestUser>();
else
sourceLs = sourceLs.OrderBy(n => n.Id).ToList<TestUser>();
}; break;
case 1:
{
if (queryCondition.IsDesc)
sourceLs = sourceLs.OrderByDescending(n => n.Name).ToList<TestUser>();
else
sourceLs = sourceLs.OrderBy(n => n.Name).ToList<TestUser>();
}; break;
case 2:
{
if (queryCondition.IsDesc)
sourceLs = sourceLs.OrderByDescending(n => n.Birth).ToList<TestUser>();
else
sourceLs = sourceLs.OrderBy(n => n.Birth).ToList<TestUser>();
}; break;
case 3:
{
if (queryCondition.IsDesc)
sourceLs = sourceLs.OrderByDescending(n => n.IsStudent).ToList<TestUser>();
else
sourceLs = sourceLs.OrderBy(n => n.IsStudent).ToList<TestUser>();
}; break;
case 4:
{
if (queryCondition.IsDesc)
sourceLs = sourceLs.OrderByDescending(n => n.Cellphone).ToList<TestUser>();
else
sourceLs = sourceLs.OrderBy(n => n.Cellphone).ToList<TestUser>();
}; break;
case 5:
{
if (queryCondition.IsDesc)
sourceLs = sourceLs.OrderByDescending(n => n.Email).ToList<TestUser>();
else
sourceLs = sourceLs.OrderBy(n => n.Email).ToList<TestUser>();
}; break;
case 6:
{
if (queryCondition.IsDesc)
sourceLs = sourceLs.OrderByDescending(n => n.Score).ToList<TestUser>();
else
sourceLs = sourceLs.OrderBy(n => n.Score).ToList<TestUser>();
}; break;
default:
break;
}
return sourceLs;
}
#endregion
#region 动态构建Lambda表达式-动态Expression树
public List<TestUser> GetDataByDynamicQuery(QueryCondition queryCondition)
{
IQueryable<TestUser> sourceLs = GetTestData().AsQueryable<TestUser>();
string[] orderParams = new string[] { "OrderField", "IsDesc" };
Expression filter;
Expression totalExpr = Expression.Constant(true);
ParameterExpression param = Expression.Parameter(typeof(TestUser), "n");
Type queryConditionType = queryCondition.GetType();
foreach (PropertyInfo item in queryConditionType.GetProperties())
{
//反射找出所有查询条件的属性值,如果该查询条件值为空或者null不添加动态lambda表达式
string propertyName = item.Name;
var propertyVal = item.GetValue(queryCondition, null);
if (!orderParams.Contains(propertyName) && propertyVal != null && propertyVal.ToString() != string.Empty)
{
//n.property
Expression left = Expression.Property(param, typeof(TestUser).GetProperty(queryDict[propertyName]));
//等式右边的值
Expression right = Expression.Constant(propertyVal);
//此处如果有特殊的判断可以自行修改例如要是Contain的,要是时间大于小于的这种判断, 这里也可以用类似InitDynamicQueryMapping方法进行表驱动维护
if (propertyName == "QueryStartTime")
filter = Expression.GreaterThanOrEqual(left, right);
else if (propertyName == "QueryEndTime")
filter = Expression.LessThan(left, right);
else if (propertyName == "QueryName")
filter = Expression.Call(Expression.Property(param, typeof(TestUser).GetProperty(queryDict[propertyName])), typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), Expression.Constant(propertyVal));
else
filter = Expression.Equal(left, right);
totalExpr = Expression.And(filter, totalExpr);
}
}
//Where部分条件
Expression pred = Expression.Lambda(totalExpr, param);
Expression whereExpression = Expression.Call(typeof(Queryable), "Where", new Type[] { typeof(TestUser) }, Expression.Constant(sourceLs), pred);
//OrderBy部分排序
MethodCallExpression orderByCallExpression = Expression.Call(typeof(Queryable), queryCondition.IsDesc ? "OrderByDescending" : "OrderBy", new Type[] { typeof(TestUser), orderEntries[queryCondition.OrderField].OrderType }, whereExpression, Expression.Lambda(Expression.Property(param, orderEntries[queryCondition.OrderField].OrderStr), param));
//生成动态查询
sourceLs = sourceLs.Provider.CreateQuery<TestUser>(orderByCallExpression);
return sourceLs.ToList<TestUser>();
}
#endregion
/// <summary>
/// 具体查询属性和实体里面属性作Mapping,当然你可以对名字规范做一个显示那样不用做映射用反射获取到直接构建表达式也行
/// 具体这里只是假设模拟了一个这种情况,使用者可以根据自身业务情况适当修改
/// </summary>
public void InitDynamicQueryMapping()
{
//查询mapping
queryDict.Add("QueryId", "Id");
queryDict.Add("QueryName", "Name");
queryDict.Add("QueryStartTime", "Birth");
queryDict.Add("QueryEndTime", "Birth");
queryDict.Add("QueryBoolean", "IsStudent");
queryDict.Add("QueryScore", "Score");
}
/// <summary>
/// 制造测试数据
/// </summary>
/// <returns></returns>
public List<TestUser> GetTestData()
{
List<TestUser> testLs = new List<TestUser>();
testLs.AddRange(new TestUser[] {
new TestUser() { Id=1, Name="测试1", Birth=new DateTime(2013,1,1), IsStudent=true, Cellphone="123456789", Email="<EMAIL>", Score=100 },
new TestUser() { Id=2, Name="测试2", Birth=new DateTime(2013,1,2), IsStudent=false, Cellphone="23123513", Email="<EMAIL>", Score=60 },
new TestUser() { Id=3, Name="测试3", Birth=new DateTime(2013,1,3), IsStudent=true, Cellphone="36365656", Email="<EMAIL>", Score=98 },
new TestUser() { Id=4, Name="测试4", Birth=new DateTime(2013,1,4), IsStudent=false, Cellphone="23423525", Email="<EMAIL>", Score=86 },
new TestUser() { Id=5, Name="测试5", Birth=new DateTime(2013,1,5), IsStudent=true, Cellphone="9867467", Email="<EMAIL>", Score=96 },
new TestUser() { Id=6, Name="测试6", Birth=new DateTime(2013,1,6), IsStudent=false, Cellphone="536546345", Email="<EMAIL>", Score=99 },
new TestUser() { Id=7, Name="测试7", Birth=new DateTime(2013,1,7), IsStudent=true, Cellphone="45234552", Email="<EMAIL>", Score=98 },
new TestUser() { Id=8, Name="测试8", Birth=new DateTime(2013,1,8), IsStudent=false, Cellphone="536375636", Email="<EMAIL>", Score=97 },
new TestUser() { Id=9, Name="测试9", Birth=new DateTime(2013,2,1), IsStudent=true, Cellphone="123456789", Email="<EMAIL>", Score=88 },
new TestUser() { Id=10, Name="测试10", Birth=new DateTime(2013,2,2), IsStudent=false, Cellphone="4524245", Email="<EMAIL>", Score=88 },
new TestUser() { Id=11, Name="动态测试11", Birth=new DateTime(2013,2,3), IsStudent=false, Cellphone="64767484", Email="<EMAIL>", Score=87 },
new TestUser() { Id=12, Name="动态测试12", Birth=new DateTime(2013,2,4), IsStudent=true, Cellphone="78578568", Email="<EMAIL>", Score=86 },
new TestUser() { Id=13, Name="动态测试13", Birth=new DateTime(2013,2,5), IsStudent=false, Cellphone="123456789", Email="<EMAIL>", Score=60 },
new TestUser() { Id=14, Name="动态测试14", Birth=new DateTime(2013,2,6), IsStudent=true, Cellphone="123456789", Email="<EMAIL>", Score=60 },
new TestUser() { Id=15, Name="动态测试15", Birth=new DateTime(2013,2,7), IsStudent=false, Cellphone="123456789", Email="<EMAIL>", Score=59 },
new TestUser() { Id=16, Name="动态测试16", Birth=new DateTime(2013,2,8), IsStudent=true, Cellphone="34135134", Email="<EMAIL>", Score=58 },
new TestUser() { Id=17, Name="动态测试17", Birth=new DateTime(2013,3,1), IsStudent=false, Cellphone="123456789", Email="<EMAIL>", Score=100 },
new TestUser() { Id=18, Name="动态测试18", Birth=new DateTime(2013,3,2), IsStudent=true, Cellphone="34165451234", Email="<EMAIL>", Score=86 },
new TestUser() { Id=19, Name="动态测试19", Birth=new DateTime(2013,3,3), IsStudent=false, Cellphone="462645246", Email="<EMAIL>", Score=64 },
new TestUser() { Id=20, Name="动态测试20", Birth=new DateTime(2013,3,4), IsStudent=true, Cellphone="61454343", Email="<EMAIL>", Score=86 },
});
return testLs;
}
/// <summary>
/// 打印测试数据
/// </summary>
/// <param name="resultLs"></param>
public void PrintResult(List<TestUser> resultLs)
{
foreach (TestUser item in resultLs)
{
Console.WriteLine("序号:{0},姓名:{1},生日:{2},是否在读:{3},联系手机:{4},邮箱:{5},分数:{6}", item.Id, item.Name, item.Birth, item.IsStudent ? "是" : "否", item.Cellphone, item.Email, item.Score);
}
}
}
/// <summary>
/// 业务实体类-你可以想象成你业务中需要实际使用的类
/// </summary>
public class TestUser
{
public TestUser() { }
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birth { get; set; }
public bool IsStudent { get; set; }
public string Cellphone { get; set; }
public string Email { get; set; }
public int Score { get; set; }
}
/// <summary>
/// 排序帮助类
/// </summary>
public class OrderEntry
{
public string OrderStr { get; set; }
public Type OrderType { get; set; }
}
/// <summary>
/// 业务查询条件类-实际使用中你可以根据自己的需要构建你的查询条件类
/// </summary>
public class QueryCondition
{
public QueryCondition() { }
public QueryCondition(int? queryId, string queryName, DateTime? queryStart, DateTime? queryEnd, bool? queryBoolean, int? queryScore, int orderField, bool isDesc)
{
this.QueryId = queryId;
this.QueryName = queryName;
this.QueryStartTime = queryStart;
this.QueryEndTime = queryEnd;
this.QueryBoolean = queryBoolean;
this.QueryScore = queryScore;
this.OrderField = orderField;
this.IsDesc = isDesc;
}
public int? QueryId { get; set; }
public string QueryName { get; set; }
public DateTime? QueryStartTime { get; set; }
public DateTime? QueryEndTime { get; set; }
public bool? QueryBoolean { get; set; }
public int? QueryScore { get; set; }
public int OrderField { get; set; }
public bool IsDesc { get; set; }
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0227Controller : Controller
{
// GET: MVC0227
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection Collection)
{
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
namespace AspNetMVC.Models
{
public static class ClassA
{
public static t field<t>(this IDataRecord record, string fieldname)
{
t fieldvalue = default(t);
for (int i = 0; i < record.FieldCount; i++)
{
if (string.Equals(record.GetName(i), fieldname, StringComparison.OrdinalIgnoreCase))
{
if (record[i] != DBNull.Value)
{
fieldvalue = (t)record[fieldname];
}
}
}
return fieldvalue;
}
// 呵呵,这个idatarecord的扩展有点像linq to dataset中得到字段值的操作了。另外idatareader是继承了idatarecord所以这个扩展方法idatareader也可以使用。
//有个上面的两个扩展方法之后,还需要一个对idatareader的扩展,代码如下:
public static IEnumerable<t> getenumerator<t>(this IDataReader reader,
Func<IDataRecord, t> generator)
{
while (reader.Read())
yield return generator(reader);
}
// 实现都很简单,下面看看如何使
// 此文来自: 马开东博客 转载请注明出处 网址: http://www.makaidong.com
//用(代码片段):
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Windows.Forms;
namespace AspNetMVC.Controllers
{
public class MVC0214Controller : Controller
{
// GET: MVC0214
public ActionResult Index()
{
return View();
}
public ActionResult Index2()
{
return View();
}
public JsonResult IsMemberTypeExists(string MemberTypeDescription)
{
return Json(!true, JsonRequestBehavior.AllowGet);
}
public class MemberType
{
[Key]
public int MemberTypeId { get; set; }
[Remote("IsMemberTypeExists", "MVC0214", ErrorMessage = "Member Type already exists")]
public string MemberTypeDescription { get; set; }
}
public ActionResult Index3()
{
string[] a = new string[] { "000.DGDH.34H", "222.JJ8D", "333.JJ8D", "444.JJ8D", "999.YDH77", "A.383JD", "B.HDJ738", "D.J8829", "Z.78WY8" };
List<string> d=new List<string>();
string e1, e2;
e1 = "333";
e2 = "999";
foreach (string b in a)
{
string i= b.Split('.')[0];
int c = 0;
if (int.TryParse(i, out c)) {
if (int.Parse(e1)<=c && int.Parse(e2)>=c) {
d.Add(b);
}
};
}
List<string> d2 = new List<string>();
string e11, e22;
e11 = "B";
e22 = "D";
foreach (string b in a)
{
string i = b.Split('.')[0];
if (string.CompareOrdinal(e11, i)<=0 && string.CompareOrdinal(e22, i)>=0)
{
d.Add(b);
}
}
//output the result d
return View();
}
[HttpPost]
public JsonResult Create(MemberType objMemberType)
{
try
{
if (ModelState.IsValid)
{
//db.MemberTypes.Add(objMemberType);
//db.SaveChanges();
return Json(new { success = true });
}
}
catch (Exception ex)
{
throw ex;
}
return Json(objMemberType, JsonRequestBehavior.AllowGet);
}
}
// IList<SSPClientMasterEntity> clientlist = mFactory.GetPartyDetailsFromSSPClientMaster(HttpContext.User.Identity.Name);
// IList<CountryEntity> country = mdmFactory.GetCountries(string.Empty, string.Empty);
// IList<StateEntity> state = mdmFactory.GetStatesByCountry(string.Empty, string.Empty, string.Empty);
// public object DBConnectionMode { get; private set; }
// ViewBag.country = country;
//ViewBag.state = state;
//ViewBag.Shipper = clientlist;
//public List<CountryEntity> GetCountries(string Code, string Name)
// {
// List<CountryEntity> mEntity = new List<CountryEntity>();
// string Query = "select C.COUNTRYID,C.CODE,C.NAME,C.DESCRIPTION,C.BASECURRENCYID " +
// "from SMDM_COUNTRY C Inner Join DataProfileClassWFStates DP on C.STATEID=DP.STATEID Where 1=1 ";
// if (!string.IsNullOrEmpty(Code.Trim()))
// {
// Query = Query + " AND Upper(C.Code) like '%" + Code.ToUpper() + "%'";
// }
// if (!string.IsNullOrEmpty(Name.Trim()))
// {
// Query = Query + " AND Upper(C.NAME) like '%" + Name.ToUpper() + "%'";
// }
// ReadText(DBConnectionMode.FOCiS, Query,
// new OracleParameter[] { }
// , delegate (IDataReader r)
// {
// mEntity.Add(DataReaderMapToObject<CountryEntity>(r));
// });
// return mEntity;
// }
// private T DataReaderMapToObject<T>(IDataReader r)
// {
// throw new NotImplementedException();
// }
// public List<StateEntity> GetStatesByCountry(int CountryId, string Code, string Name)
// {
// List<StateEntity> mEntity = new List<StateEntity>();
// if (CountryId != 0 && CountryId != null)
// {
// string Query = "Select SUBDIVISIONID,COUNTRYID,CODE,NAME,DESCRIPTION from SMDM_SUBDIVISIONS where COUNTRYID=" + CountryId;
// if (!string.IsNullOrEmpty(Code.Trim()))
// {
// Query = Query + " AND Upper(Code) like '%" + Code.ToUpper() + "%'";
// }
// if (!string.IsNullOrEmpty(Name.Trim()))
// {
// Query = Query + " AND Upper(NAME) like '%" + Name.ToUpper() + "%'";
// }
// ReadText(DBConnectionMode.FOCiS, Query,
// new OracleParameter[] { }
// , delegate (IDataReader r)
// {
// mEntity.Add(DataReaderMapToObject<StateEntity>(r));
// });
// }
// return mEntity;
// }
// public JsonResult FillCountry()
// {
// try
// {
// MDMDataFactory mdmFactory = new MDMDataFactory();
// IList<CountryEntity> country = mdmFactory.GetCountries(string.Empty, string.Empty);
// if (country != null)
// {
// var Countrylist = (
// from items in country
// select new
// {
// Text = items.NAME,
// Value = items.COUNTRYID
// }).Distinct().ToList().OrderBy(x => x.Text);
// return Json(Countrylist, JsonRequestBehavior.AllowGet);
// //return Json(new SelectList(Countrylist, "Value", "Text"));
// }
// else
// {
// return Json(null, JsonRequestBehavior.AllowGet);
// }
// }
// catch (Exception ex)
// {
// throw ex;
// }
// }
// private void ReadText(object fOCiS, string query, OracleParameter[] oracleParameter, Func<IDataReader, object> p)
// {
// throw new NotImplementedException();
// }
// }
// internal class MDMDataFactory
// {
// }
}<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 AspNetMVC;
using AspNetMVC.Models;
namespace AspNetMVC.Controllers
{
public class PartalController : Controller
{
CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: Partal
public ActionResult Index()
{
return View(db.BookMasters.ToList());
}
public PartialViewResult _PartialView(string strBookTypeId) {
return PartialView(db.BookMasters.Where(u => u.strBookTypeId == strBookTypeId));
}
// GET: Partal/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// GET: Partal/Create
public ActionResult Create()
{
return View();
}
// POST: Partal/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.BookMasters.Add(bookMaster);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
// GET: Partal/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: Partal/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.Entry(bookMaster).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
// GET: Partal/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: Partal/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
BookMaster bookMaster = db.BookMasters.Find(id);
db.BookMasters.Remove(bookMaster);
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.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0310Controller : Controller
{
CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0310
public class TestDbSet<T> : DbSet<T>, IQueryable, IEnumerable<T>
where T : class
{
ObservableCollection<T> _data;
IQueryable _query;
public TestDbSet()
{
_data = new ObservableCollection<T>();
_query = _data.AsQueryable();
}
//public override T Add(T item)
//{
// _data.Add(item);
// return item;
//}
}
class TestProductDbSet : TestDbSet<BookMaster>
{
//public BookMaster NoFind(params object[] keyValues)
//{
// return this.SingleOrDefault(product => product.Id == (int)keyValues.Single());
//}
public override BookMaster Find(params object[] keyValues)
{
return this.SingleOrDefault(product => product.Id != (int)keyValues.Single());
}
}
public ActionResult Index()
{
DbSet<BookMaster> u = db.BookMasters;
var o = db.BookMasters.ToList();
//db.BookMasters
//new object[] = new int[] { 1, 2, 3 };
//IEnumerable<TestProductDbSet>[] g = o;
//var y=o as IEnumerable<TestProductDbSet>[] g;
//var y1= y.NoFind(1, 2, 3);
//var y2 = y.Find(2);
//var d= db.BookMasters.NoFind(1, 2, 3);
var t = db.BookMasters.SingleOrDefault(product => product.Id == (new int[]{ 1, 2, 3}).Single());
//var b = (from i in db.BookMasters where i.Id != (new int[] { 1, 2 }).Single() select i).ToList();
var c = db.BookMasters.SingleOrDefault(m => m.Id != (new int[] { 1, 2 }).Single());
//this.SingleOrDefault(product => product.Id == (int)keyValues.Single());
//var a =( from i in db.BookMasters where i.Id != (new int[] { 1, 2 }).Single() select i).ToList();
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace AspNetMVC.Controllers
{
public class Default2Controller : ApiController
{
// GET: api/Default2
int a = 1;
public IEnumerable<string> Get()
{
//TempData["sa"] = "sat";
a = 2;
return new string[] { "value1", "value2" };
}
// GET: api/Default2/5
public string Get(int id)
{
return a.ToString();
}
// POST: api/Default2
public void Post([FromBody]string value)
{
}
// PUT: api/Default2/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/Default2/5
public void Delete(int id)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class HomeController : Controller
{
CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
public static List<Publisher> GetPublishers()
{
return new List<Publisher>{
new Publisher{PublisherId="1", PublisherName="Volvo" },
new Publisher{PublisherId="2", PublisherName="Mercedes-Benz" },
new Publisher{PublisherId="3", PublisherName="Saab" },
new Publisher{PublisherId="4", PublisherName="Audi" },
new Publisher{PublisherId="5", PublisherName="Audi2" }
};
}
public ActionResult Index()
{
var ui = db.BookMasters.ToList();
//var model = db.BookMasters.Where(u => u.Id == 1).FirstOrDefault();
List<Publisher> listP = new List<Publisher>();
List<Publisher> listP2 = GetPublishers();
var model = db.BookMasters.Where(u => u.Id == 1).FirstOrDefault();
db.BookMasters.Where(u => u.Id == 1).FirstOrDefault().Publishers.ToList();
foreach (var p in model.Publishers)
{
listP.Add(new Publisher() { PublisherId = p.PublisherId, PublisherName = p.PublisherName });
}
// ..ToList().Select(i=>i.FirstOrDefault()) ;
//x.Publishers.Select(c => new Publisher() { PublisherId = c.PublisherId, PublisherName = c.PublisherName }
//var pus = (from a in model select a.Publishers).Select(r=>r);
// SelectList Publishers = new SelectList(listP as List<Publisher>, "PublisherId", "PublisherName", 2);
SelectList Publishers = new SelectList(db.BookMasters.Where(u => u.Id == 1).FirstOrDefault().Publishers, "PublisherId", "PublisherName", 2);
ViewData["list"] = Publishers;
return View(model);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
//If UnAssignedGroupList Is a property in MyViewModel class and please refer to code below:
public class MyViewModel
{
[Required(ErrorMessage = " At least one unassgined group is Required.")]
public string UnAssignedGroupList { get; set; }
}
//If not:
//In controller.cs :
[HttpPost]
public ActionResult Index0110(string UnAssignedGroupList)
{
if (string.IsNullOrEmpty(UnAssignedGroupList))
{
ModelState.AddModelError("error ", " At least one unassgined group is Required.");
ViewData["UnAssignedGroupList"] = GetSelectListItem();
return View();
}
return Redirect("");
}
public List<SelectListItem> GetSelectListItem()
{
return new List<SelectListItem>()
{
new SelectListItem(){Text="null",Value=""},
new SelectListItem(){Text="one",Value="001"},
new SelectListItem(){Text="two",Value="002",Selected=true}
};
}
public ActionResult Index0110()
{
ViewData["UnAssignedGroupList"] = GetSelectListItem();
//ViewData["nameList"] = list;
//At least one unassgined group is Required.
ViewBag.Message = "Your contact page.";
//var model = db.BookMasters.Where(u => u.Id == 1).FirstOrDefault();
return View(new BookMaster());
}
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplicationForm
{
public partial class WebForm0216 : System.Web.UI.Page
{
int flag = 1;
SqlConnection con = new SqlConnection("Data Source=INSPIRE-1;Initial Catalog=new;Integrated Security=True");
public static int parent = 0;
int[] a = new int[50];
Panel pnlDropDownList;
protected void Page_PreInit(object sender, EventArgs e)
{
//Create a Dynamic Panel
pnlDropDownList = new Panel();
pnlDropDownList.ID = "pnlDropDownList";
pnlDropDownList.BorderWidth = 1;
pnlDropDownList.Width = 300;
this.form1.Controls.Add(pnlDropDownList);
}
protected void Page_Load(object sender, EventArgs e)
{
//string[] arr1 = new string[10];
//Session["myarray"] = arr1;
// Session["ddl"]= Session["myarray"][0];
//OnSelectedIndexChanged(sender, e);
// UpdatePanel updatePanel = new UpdatePanel();
// updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
// updatePanel.ID = "UpdatePanel1";
// updatePanel.ContentTemplateContainer.Controls.Add(ddl);
// updatePanel.ContentTemplateContainer.Controls.Add(ddl);
// AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
// trigger.ControlID = ddl.ClientID;
// trigger.EventName = "OnSelectedIndexChanged";
// updatePanel.Triggers.Add(trigger);
// this.Page.Form.Controls.Add(updatePanel);
//int[,] array6 = new int[10, 10];
Hashtable asd = new Hashtable();
int cnt =FindOccurence("ddlDynamic");
if (cnt == 0)
{
//a[cnt + 1] =1; //a[1]=0;
Session["parents"] = a;
CreateDropDownList("ddlDynamic-" + Convert.ToString(cnt + 1), a[cnt + 1]);//CreateDropDownList("ddlDynamic-1",0);a[1]=0;
}
else {
RecreateControls("ddlDynamic", "DropDownList");
}
if (flag == 1)
{
flag = 0;
}
}
private int FindOccurence(string substr)
{
//return 2;
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateControls(string ctrlPrefix, string ctrlType)
{
DropDownList ddl = new DropDownList();
// ddl.ID = ID;//ID :_Page
ddl.ID = "ddlDynamic-1";
int value = 1;
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
a = (int[])Session["parents"];//a awalays 0
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
int b = Convert.ToInt32(ctrlID.Split('-')[1]);
int c = Convert.ToInt32(Session["ddl"]);
//if (b > c)
//{
// break;
//}
//else
//{
//if (ctrlType == "DropDownList")
//{
CreateDropDownList(ctrlID, a[value]);
//value++;
//}
//}
break;
}
}
}
}
}
private void CreateDropDownList(string ID, int parent)//ID:ddlDynamic-1 parent:0
{
//con.Open();
SqlDataAdapter abc;
//if (parent == 0)
//{
abc = new SqlDataAdapter("select catid,name from catgry where parent =" + parent, con);//
//}
//else
//{
// abc = new SqlDataAdapter("select catid,name from catgry where parent=" + parent, con);
//}
DropDownList ddl = new DropDownList();
ddl.ID = ID;
//DataTable b = new DataTable();
//abc.Fill(b);
//if (b.Rows.Count != 0)
//{
//ddl.DataSource = b;
//ddl.DataTextField = "name";
//ddl.DataValueField = "catid";
//ddl.DataBind();
ddl.Items.Add(new ListItem("1", "1"));
ddl.Items.Add(new ListItem("2", "2"));
ddl.Items.Add(new ListItem("3", "3"));
ddl.Items.Add(new ListItem("4", "4"));
ddl.Items.Insert(0, new ListItem("Select Category", "0"));
// con.Close();
ddl.AutoPostBack = true;
ddl.SelectedIndexChanged += new EventHandler(ddl_OnSelectedIndexChanged);
pnlDropDownList.Controls.Add(ddl);
Literal lt = new Literal();
lt.Text = "<br />abc";
pnlDropDownList.Controls.Add(lt);
//}
}
protected void ddl_OnSelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
string ID = ddl.ID;
// int[,] array6 = new int[10, 10];
// string[] arr1 = new string[10];
// Session["myarray"] = arr1;
//Session["ddl"] = ddl.ID;
Session["ddl"] = ddl.ID.Split('-')[1];
int cnt = FindOccurence("ddlDynamic");
//int[] a = (int[])Session["parents"];
a = (int[])Session["parents"];
a[cnt] = int.Parse(ddl.SelectedValue);
Session["parents"] = a;
CreateDropDownList("ddlDynamic-" + Convert.ToString(cnt), a[cnt]);
//ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "<script type = 'text/javascript'>alert('" + ID + " fired SelectedIndexChanged event');</script>");
//parent = Convert.ToInt32(ddl.SelectedValue);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0216Controller : Controller
{
// GET: MVC0216
public ActionResult Index()
{
//ViewEngines.Engines.Clear();
////Add Razor Engine
//ViewEngines.Engines.Add(new RazorViewEngine());
return View();
}
}
}<file_sep>using System.Web;
using System.Web.Optimization;
namespace AspNetMVC
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
bundles.Add(new StyleBundle("~/mycss").Include(
"~/Content",
"~/Content/site.css"));
////定义名为"mycss"的捆绑,js对应为 new JsMinify()
//var b = new Bundle("~/mycss", new CssMinify());
////添加Content文件夹下的所有css文件到捆绑
////第三个参数false表示,Content文件夹下的子文件夹下不添加到捆绑
////b.AddDirectory("~/Content", "*.css", false);
////添加到BundleTable
//BundleTable.Bundles.Add(b);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirst
{
public partial class Contact2
{
[Key]
public string Accountno { get; set; }
public DateTime? Callbackon { get; set; }
///... other fields
public string Recid { get; set; }
public virtual Contact1 Contact1 { get; set; }
}
}
<file_sep>
//using System;
//using System.Collections.Generic;
//using System.Data;
//using System.Data.SqlClient;
//using System.Linq;
//using System.Text;
//using System.Web;
//namespace AspNetMVC.Models
//{
// public class DbUtil
// {
// ///////////////////////////////////////////////////////////////////////
// public static object execute_scalar(string sql)
// {
// //if (Util.get_setting("LogSqlEnabled", "1") == "1")
// //{
// // Util.write_to_log("sql=\n" + sql);
// //}
// using (SqlConnection conn = get_sqlconnection())
// {
// object returnValue;
// SqlCommand cmd = new SqlCommand(sql, conn);
// returnValue = cmd.ExecuteScalar();
// conn.Close(); // redundant, but just to be clear
// return returnValue;
// }
// }
// ///////////////////////////////////////////////////////////////////////
// public static void execute_nonquery_without_logging(string sql)
// {
// using (SqlConnection conn = get_sqlconnection())
// {
// SqlCommand cmd = new SqlCommand(sql, conn);
// cmd.ExecuteNonQuery();
// conn.Close(); // redundant, but just to be clear
// }
// }
// ///////////////////////////////////////////////////////////////////////
// public static void execute_nonquery(string sql)
// {
// //if (Util.get_setting("LogSqlEnabled", "1") == "1")
// //{
// // Util.write_to_log("sql=\n" + sql);
// //}
// using (SqlConnection conn = get_sqlconnection())
// {
// SqlCommand cmd = new SqlCommand(sql, conn);
// cmd.ExecuteNonQuery();
// conn.Close(); // redundant, but just to be clear
// }
// }
// ///////////////////////////////////////////////////////////////////////
// public static void execute_nonquery(SqlCommand cmd)
// {
// log_command(cmd);
// using (SqlConnection conn = get_sqlconnection())
// {
// try
// {
// cmd.Connection = conn;
// cmd.ExecuteNonQuery();
// conn.Close(); // redundant, but just to be clear
// }
// finally
// {
// conn.Close(); // redundant, but just to be clear
// cmd.Connection = null;
// }
// }
// }
// ///////////////////////////////////////////////////////////////////////
// public static SqlDataReader execute_reader(string sql, CommandBehavior behavior)
// {
// //if (Util.get_setting("LogSqlEnabled", "1") == "1")
// //{
// // Util.write_to_log("sql=\n" + sql);
// //}
// SqlConnection conn = get_sqlconnection();
// try
// {
// using (SqlCommand cmd = new SqlCommand(sql, conn))
// {
// return cmd.ExecuteReader(behavior | CommandBehavior.CloseConnection);
// }
// }
// catch
// {
// conn.Close();
// throw;
// }
// }
// ///////////////////////////////////////////////////////////////////////
// public static SqlDataReader execute_reader(SqlCommand cmd, CommandBehavior behavior)
// {
// log_command(cmd);
// SqlConnection conn = get_sqlconnection();
// try
// {
// cmd.Connection = conn;
// return cmd.ExecuteReader(behavior | CommandBehavior.CloseConnection);
// }
// catch
// {
// conn.Close();
// throw;
// }
// finally
// {
// cmd.Connection = null;
// }
// }
// ///////////////////////////////////////////////////////////////////////
// public static System.Data.DataSet get_dataset(string sql)
// {
// //if (Util.get_setting("LogSqlEnabled", "1") == "1")
// //{
// // Util.write_to_log("sql=\n" + sql);
// //}
// System.Data.DataSet ds = new System.Data.DataSet();
// using (SqlConnection conn = get_sqlconnection())
// {
// {
// using (SqlDataAdapter da = new SqlDataAdapter(sql, conn))
// {
// if (sql == null)
// sql = "";
// System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
// stopwatch.Start();
// da.Fill(ds);//// here there is a problem
// stopwatch.Stop();
// log_stopwatch_time(stopwatch);
// conn.Close(); // redundant, but just to be clear
// return ds;
// }
// }
// }
// }
// ///////////////////////////////////////////////////////////////////////
// public static void log_stopwatch_time(System.Diagnostics.Stopwatch stopwatch)
// {
// //if (Util.get_setting("LogSqlEnabled", "1") == "1")
// //{
// // Util.write_to_log("elapsed milliseconds:" + stopwatch.ElapsedMilliseconds.ToString("0000"));
// //}
// }
// ///////////////////////////////////////////////////////////////////////
// public static DataView get_dataview(string sql)
// {
// DataSet ds = get_dataset(sql);
// return new DataView(ds.Tables[0]);
// }
// ///////////////////////////////////////////////////////////////////////
// public static DataRow get_datarow(string sql)
// {
// DataSet ds = get_dataset(sql);
// if (ds.Tables[0].Rows.Count != 1)
// {
// return null;
// }
// else
// {
// return ds.Tables[0].Rows[0];
// }
// }
// ///////////////////////////////////////////////////////////////////////
// public static SqlConnection get_sqlconnection()
// {
// string connection_string = Util.get_setting("bugtrackerConnectionString", "MISSING CONNECTION STRING");
// SqlConnection conn = new SqlConnection(connection_string);
// conn.Open();
// return conn;
// }
// ///////////////////////////////////////////////////////////////////////
// private static void log_command(SqlCommand cmd)
// {
// if (Util.get_setting("LogSqlEnabled", "1") == "1")
// {
// StringBuilder sb = new StringBuilder();
// sb.Append("sql=\n" + cmd.CommandText);
// foreach (SqlParameter param in cmd.Parameters)
// {
// sb.Append("\n ");
// sb.Append(param.ParameterName);
// sb.Append("=");
// if (param.Value == null || Convert.IsDBNull(param.Value))
// {
// sb.Append("null");
// }
// else if (param.SqlDbType == SqlDbType.Text || param.SqlDbType == SqlDbType.Image)
// {
// sb.Append("...");
// }
// else
// {
// sb.Append("\"");
// sb.Append(param.Value);
// sb.Append("\"");
// }
// }
// //Util.write_to_log(sb.ToString());
// }
// }
// } // end DbUtil
//}<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleCodeFirst
{
class Program
{
static void Main(string[] args)
{
using (var db = new ApplicatioDbContext0403())
{
db.Database.Delete();
db.Database.CreateIfNotExists();
Supplier su = new Supplier() { SupplierName = "person1" };
Town to = new Town() { TownName = "TownName" };
Street st = new Street() { StreetName = "StreetName" };
Supplier su2 = new Supplier() { SupplierName = "person2" };
Town to2 = new Town() { TownName = "TownName2" };
Street st2 = new Street() { StreetName = "StreetName2" };
Adress ad = new Adress() { /*Town = to, Street = st,*/ NumberAdress = 100 };
Adress ad2 = new Adress() { /*Town = to, Street = st,*/ NumberAdress = 200 };
su.Town = to;
su.Street = st;
su.Adress = ad;
su2.Town = to2;
su2.Street = st2;
su2.Adress = ad2;
db.Supplier.Add(su);
db.SaveChanges();
db.Supplier.Add(su2);
db.SaveChanges();
Supplier a1 = new Supplier() { SupplierID = 2, StreetID = 1, TownID = 1, SupplierName = "abc" };
a1= db.Supplier.Where(r => r.SupplierID == 2).FirstOrDefault();
a1.SupplierName = "12e34";
a1.StreetID = 1;
IEnumerable< Supplier> a = db.Supplier.ToList();
IEnumerable< Adress > c = db.Adress.ToList();
Adress add = db.Supplier.Where(r => r.SupplierID == 2).FirstOrDefault().Adress;
db.Adress.Remove(add);
//add.StreetID = 1;
Adress add2 = add;
//db.Adress.Add();
a1.Adress = new Adress() { StreetID = 1, TownID = 2, NumberAdress = add.NumberAdress };
//Town to2= new Town() { TownName = "TownName2" , Streets=new List<Street>()};
//Town to3 = new Town() { TownName = "TownName3" };
// Street st2 = new Street() { StreetName = "StreetName2" };
// Street st3 = new Street() { StreetName = "StreetName3" };
//to2.Streets =new System.Collections.Generic.List<Street>() { st2 ,st3};
//to3.Streets = new System.Collections.Generic.List<Street>() { st };
//st3.Town = new System.Collections.Generic.List<Town>() { to2 };
//db.Town.Add(to2);
////db.Street.Add(st3);
//db.SaveChanges();
//a1.Adress= db.Supplier.Find(2).Adress;
//db.Street.Add(new Street() { })
//db.Supplier.Add(new Supplier() { Name = "person2" });
//a1.Town = db.Town.Find(1);
//a1.Street = db.Street.Find(1);
//a1.Adress = db.Adress.Where(v => v.StreetID == 1 && v.TownID == 1).FirstOrDefault();
db.Entry(a1).State = EntityState.Modified;
//db.Supplier.Add(a1);
db.SaveChanges();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
using (var db = new ApplicatioDbContext())
{
// Create and save a new Blog
//Console.Write("Enter a name for a new Blog: ");
//var name = Console.ReadLine();
//db.Database.CreateIfNotExists();
//db.Contact1s.Add(new Contact1() { Accountno="v", Recid = "1" });
////var blog = new Blog { Name = name };
////db.Blogs.Add(blog);
db.Database.CreateIfNotExists();
db.SaveChanges();
// Display all Blogs from the database
//var query = from b in db.Blogs
// orderby b.Name
// select b;
//Console.WriteLine("All blogs in the database:");
//foreach (var item in query)
//{
// Console.WriteLine(item.Name);
//}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0203Controller : Controller
{
// GET: MVC0203
public ActionResult Index()
{
//ViewData.Model = data;
//return View(data);
return View( );
}
public ActionResult Index2() {
return View();
}
}
}<file_sep>using Microsoft.ReportingServices.ReportProcessing.ReportObjectModel;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0215Controller : Controller
{
//[AlwaysFails(ErrorMessage = "Contact")]
private CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
public class Contact
{
[Required]
public string Name { get; set; }
[Required]
public string PhoneNo { get; set; }
[Required]
public string EmailAddress { get; set; }
[Required]
public Address Address { get; set; }
}
public class Address
{
[Required]
public string Province { get; set; }
[Required]
public string City { get; set; }
[Required]
public string District { get; set; }
[Required]
public string Street { get; set; }
}
//public ActionResult Index1()
//{
// Address address = new Address
// {
// Province = "江苏",
// City = "苏州",
// District = "工业园区",
// Street = "星湖街328号"
// };
// Contact contact = new Contact
// {
// Name = "张三",
// PhoneNo = "123456789",
// EmailAddress = "<EMAIL>",
// Address = address
// };
// return View(contact);
//}
public ActionResult Index1()
{
//DataTable a = db.Database..SqlQuery("").AsQueryable() ;
return View( );
}
[HttpPost]
public void Index1(Contact contact)
{
foreach (string key in ViewData.ModelState.Keys)
{
Response.Write(key + "<br/>");
ModelState modelState = ViewData.ModelState[key];
Response.Write(string.Format(" Value: {0}<br/>", modelState.Value.ConvertTo(typeof(string))));
foreach (ModelError error in modelState.Errors)
{
Response.Write(string.Format(" Error: {0}<br/>", error.ErrorMessage));
}
}
}
public bool ToGet(string str) {
return true;
}
public void index3() {
//db.BookMasters.Where(m => m.Id >= 1).Where(u => u.);
db.BookMasters.Where(m=>ToGet(m.strAccessionId)).ToList();
db.BookMasters.Where(m => true);
//db.BookMasters.Select(u => { new List<string>() {
// int c=0;
// if (int.TryParse(u., out c))
// { //if it can covert to int type successfully
// if (int.Parse(e1) <= c && int.Parse(e2) >= c)
// {
// d.Add(b);
// }
// };
//} });
var c= db.Database.SqlQuery<BookMaster>("select * from BookMaster where column like '%u%'");
// return Find(m => m.CreatedDate >= startDate && m.CreatedDate <= endDate
//&& m.Marc21Id == 15
//&& m.Name != null
//&& m.Name.StartsWith(startValue)
//&& m.Name.EndsWith(endValue);
}
// GET: MVC0215
public ActionResult Index()
{
string path= Server.MapPath("~/Content/JOSN1.json");
string str= ForBytes.GetStringFromByte( ForBytes.GetByteData(path));
string whichProperty = "CountryCode";
string whichasValue = "IN";
int i=0;
for ( ; str.IndexOf(whichProperty, i) > 0 ;)
{
i = str.IndexOf(whichProperty,i);
i += whichProperty.Length + 1;
int i1 = str.IndexOf("\"", i)+1; //find the first " index which need to be replace
int i2 = str.IndexOf("\"", i1);//find the second " index which need to be replace
string test1 = str.Substring(i1);
//The first time ,the test1 value:
// US","TimeZoneName":"Central Standard Time","TimeZoneLocation":"America / Indiana / Petersburg","TimeZoneDisplayName":"US / Central Standard Time (UTC - 06:00)","TimeZoneAbbreviation":"CST","UTCOffset":"UTC - 06:00"},"BeginningDayOfWeek":"Tue","PreferredDateDisplayFormat":"yyyy / mm / dd","PreferredLanguageCode":"hi - IN","DefaultLandingPage":"MerchantPortal.Dashboard.GlobalDashboard","EnableNotification":"true","PreferredRegionInfo":{
// "AssociatedBusinessPartyID":100488,"CurrencyCode":"SEK","CountryName":"Switzerland",
//"CountryCode":"CH"}
string test2 = str.Substring(i2);
//The first time,the test2 value:
// ","TimeZoneName":"Central Standard Time","TimeZoneLocation":"America / Indiana / Petersburg","TimeZoneDisplayName":"US / Central Standard Time (UTC - 06:00)","TimeZoneAbbreviation":"CST","UTCOffset":"UTC - 06:00"},"BeginningDayOfWeek":"Tue","PreferredDateDisplayFormat":"yyyy / mm / dd","PreferredLanguageCode":"hi - IN","DefaultLandingPage":"MerchantPortal.Dashboard.GlobalDashboard","EnableNotification":"true","PreferredRegionInfo":{
// "AssociatedBusinessPartyID":100488,"CurrencyCode":"SEK","CountryName":"Switzerland",
//"CountryCode":"CH"}
str = str.Remove(i1, i2-i1);
str = str.Insert(i1, whichasValue);
}
string a = "vbljadsflvnbaijdlfj654613213";
int b = a.IndexOf('v');
a = a.Remove(b, 1);
string content = "这是中国一个中国二个中国";
int aa= content.IndexOf("中国");
content.IndexOf("中国",aa);
//con
Regex r1 = new Regex(@"中国");
MatchCollection matchCollection = r1.Matches(content);
foreach (Match m in matchCollection)
{
//m.Index
content.Substring(m.Index, 5);
//content.Replace();
Debug.WriteLine("m");
// 将匹配出来的中国随机替换为世界,地球,宇宙,或不替换(根据随机数判断) , 不能将全部中国替换为一个词.
}
Debug.WriteLine("m");
//string c = "abcdefghi";
//c.IndexOfAny("county");
//c.Substring("");
return View();
}
}
}<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 AspNetMVC;
namespace AspNetMVC.Controllers
{
public class MVC0124Controller : Controller
{
private CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0124
public ActionResult Index()
{
return View(db.BookMasters.ToList());
}
// GET: MVC0124/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// GET: MVC0124/Create
public ActionResult Create()
{
//var categories = db.BookMasters.Select(c => new List< SelectListItem>()
//{new SelectListItem() {
// Text = c.strBookTypeId,
// Value = c.Id.ToString()
//}}) ;
//http://www.mikesdotnetting.com/article/265/asp-net-mvc-dropdownlists-multiple-selection-and-enum-support
ViewBag.list = new MultiSelectList(db.BookMasters, "Id", "strBookTypeId", new[] { 1, 2 });
return View();
}
// POST: MVC0124/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.BookMasters.Add(bookMaster);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
public class BookMasterModel
{
public int Id { get; set; }
}
// GET: MVC0124/Edit/5
public ActionResult Edit()
{
BookMaster b= new BookMaster();
//IEnumerable< List<BookMaster>> c = from a in db.BookMasters select new List<BookMaster>() { new BookMaster() { Id = a.Id } }.ToList();
var c = from a in db.BookMasters select new List< BookMasterModel>() { new BookMasterModel() { Id = a.Id } } ;
IEnumerable< List<BookMaster>> d = db.BookMasters.Where(m => m.Id == 1).Select(a =>
new List<BookMaster>() {
new BookMaster() { Id = a.Id }
}
);
List<BookMaster> d1 = db.BookMasters.Where(m => m.Id == 1).ToList();
var d2= d1.Select(a =>
new List<BookMaster>() {
new BookMaster() { Id = a.Id }
});
//db.BookMasters.ToList();
//var categories = db.BookMasters.Select(f => new List<BookMaster>()
//{new BookMaster() {
// strBookTypeId = f.strBookTypeId,
// Id = f.Id
//}});
var t = (from a in db.BookMasters where a.Id==1
select a).ToList();
var t3 = (from a in db.BookMasters
where a.Id == 1
select a).FirstOrDefault();
var t1 = db.BookMasters.Where(a=> a.Id == 1).ToList();
return View(t3);
}
// POST: MVC0124/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.Entry(bookMaster).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
// GET: MVC0124/Delete/5
public ActionResult Delete( )
{
bool v= ModelState.IsValid;
return View( );
}
//// POST: MVC0124/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(BookMaster bm)
{
bool v = ModelState.IsValid;
//BookMaster bookMaster = db.BookMasters.Find(id);
//db.BookMasters.Remove(bookMaster);
//db.SaveChanges();
return View();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleCodeFirst
{
public class ApplicatioDbContext0403 : DbContext
{
public ApplicatioDbContext0403()
: base("name=CodeFirstDbDemo0403")
{
}
//public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Entity<Street>()
// .HasMany<Town>(s => s.Town)
// .WithMany(c => c.Streets)
// .Map(cs =>
// {
// cs.MapLeftKey("StreetID");
// cs.MapRightKey("TownID");
// cs.ToTable("Adress");
// });
}
public DbSet<Town> Town { get; set; }
public DbSet<Street> Street { get; set; }
public DbSet<Adress> Adress { get; set; }
public DbSet<Supplier> Supplier { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Xml;
namespace AspNetMVC.Controllers
{
public class MVC0321Controller : Controller
{
private CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0321
public ActionResult Index()
{
string strUrl = "http://www.w3school.com.cn/example/xmle/note.xml";
XmlDocument doc = new XmlDocument();
doc.Load(strUrl);
return View();
}
public ActionResult Index2(string flag = "PHM") {
ViewBag.flag = flag;
return View(db.BookMasters.ToList());
}
public ActionResult Details(int? id,string flag= "PHM")
{
ViewBag.flag = flag;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
[HttpPost]
public HttpStatusCode Index3(FormCollection form) {
string FilePath = Server.MapPath("~/Content/") + "Pictures";
HttpFileCollectionBase HFC =Request.Files; //Request.Form["file1"]
for (int i = 0; i < HFC.Count; i++)
{
HttpPostedFileBase UserHPF = HFC[i];
if (UserHPF.ContentLength > 0)
{
string fileName = UserHPF.FileName.Substring(UserHPF.FileName.LastIndexOf("\\"));
string pathes = FilePath + "\\" + System.IO.Path.GetFileName(UserHPF.FileName);
if (!Directory.Exists(FilePath))
Directory.CreateDirectory(FilePath);
UserHPF.SaveAs(pathes);
Bitmap image = new Bitmap(UserHPF.InputStream);
Bitmap target = new Bitmap(50, 50);
string pathesSmall = FilePath + "\\smail\\" + System.IO.Path.GetFileName(UserHPF.FileName);
Graphics graphic = Graphics.FromImage(target);
graphic.DrawImage(image, 0, 0, 50, 50);
if (!Directory.Exists(FilePath + "\\smail"))
Directory.CreateDirectory(FilePath + "\\smail");
target.Save(pathesSmall);
}
}
return HttpStatusCode.OK;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AspnetCore.Data;
using AspnetCore;
using Microsoft.Extensions.Configuration;
namespace AspnetCore.Controllers
{
public class HomeController : Controller
{
ApplicationDbContext db ;
public HomeController(ApplicationDbContext _db)
{
db = _db;
}
public IActionResult Index()
{
var a = Startup.Configuration["DefaultConnection"];
//if (true)
//{
Startup.Configuration["DefaultConnection"] = "123";
var b = Startup.Configuration["DefaultConnection"];
//}
// Create and save a new Blog
//Console.Write("Enter a name for a new Blog: ");
//var name = Console.ReadLine();
//db.Database.CreateIfNotExists();
//db.Contact1s.Add(new Contact1() { Accountno="v", Recid = "1" });
////var blog = new Blog { Name = name };
////db.Blogs.Add(blog);
//db.Database.EnsureCreated();
for (int i = 2; i < 6; i++) {
db.Contact1ss.Add(new Contact1() { Accountno = i.ToString() ,Recid="Recid"+i, Company= "Company"+i });
}
//db.SaveChanges();
return View();
}
public IActionResult About()
{
//db.Contact1ss.FirstOrDefault();
ViewData["Message"] = "Your application description page.";
return View(new Contact1() { Birth_Date = DateTime.Now });
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0308Controller : Controller
{
CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0308
public ActionResult Index()
{
return View();
}
public ActionResult Index2() {
return View();
}
public ActionResult Index3() {
return View(db.BookMasters.ToList());
}
public ActionResult Index4()
{
return View( );
}
[HttpPost]
public PartialViewResult _PartialStepOne(BookMaster one)
{
//...
//db.BookMasters.Add(one);
//db.SaveChanges();
return PartialView("~/Views/MVC0308/_PartialStepTwo.cshtml");
}
[HttpPost]
public PartialViewResult _PartialStepTwo(Publisher two)
{
//...
//db.Publisher.Add(two);
//db.SaveChanges();
return PartialView("~/Views/MVC0308/_PartialStepThree.cshtml");
}
[HttpPost]
public ActionResult _PartialStepThree(BookMaster Three)
{
//...
//db.BookMasters.Add(Three);
//db.SaveChanges();
return Redirect("...");//done
}
}
}<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 AspNetMVC;
using System.Runtime.Serialization;
using System.IO;
using static AspNetMVC.Controllers.MVC0112Controller.Customers;
using System.Runtime.Serialization.Json;
using System.Net.Http;
using System.Net.Mail;
using System.Web.Mail;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.Office.Interop.Excel;
namespace AspNetMVC.Controllers
{
public class MVC0112Controller : Controller
{
private CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
private System.Net.Mail.MailMessage objMailMessage;
public class Customers
{
[DataContract]
public class ExtData
{
[DataMember]
public List<object> videos { get; set; }
}
[DataContract]
//[KnownType(typeof( Customers))]
public class RootParent
{
[DataMember]
public string name { get; set; }
[DataMember]
public Sites site { get; set; }
}
public class Sites
{
public int SitesID { get; set; }
}
}
// GET: MVC0112
public ActionResult Index()
{
Customers customers = new Customers() { };
RootParent rootParent = new RootParent() { name = "name", site = new Sites() { SitesID = 1 } };
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer dcs = new DataContractJsonSerializer(typeof(RootParent));
dcs.WriteObject(ms, rootParent); // Note: rootParent is an instance, which i'm using to assign data to. Its this line the program crashes on
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string json = sr.ReadToEnd();
//stream1.Position = 0;
return View(db.BookMasters.ToList());
}
public class NewsModels
{
public List<ArticleDetails> entryList = new List<ArticleDetails>();
}
public class ArticleDetails
{
public string id { get; set; }
public string updated { get; set; }
public string published { get; set; }
public string title { get; set; }
public string summary { get; set; }
}
public async Task<ActionResult> Index3()
{
//LoadImage.GetByteData()
NewsModels objNews = new NewsModels() { entryList=new List<ArticleDetails>() { new ArticleDetails() { id="2" } } };
using (var client = new HttpClient())
{
string url = string.Format("http://export.arxiv.org/api/query?search_query=ti:{0}&sortBy=lastUpdatedDate&sortOrder=descending", Server.UrlEncode("\"quantum simulator\""));
var uri = new Uri(url);
//string getxml = await client.GetStringAsync(uri);
//var deserializer = new System.Xml.Serialization.XmlSerializer(typeof(ArticleDetails));
//var xmlReader = System.Xml.XmlReader.Create(uri.ToString());
//var xmlReader = System.Xml.XmlReader.Create(getxml);
XmlDocument xmlDoc = new XmlDocument();
//ForBytes.GetStreamFromBytes(ForBytes.GetByteFromString(getxml));
//xmlDoc.LoadXml(getxml);
//doc.Load(@"C:\Users\Administrator\Source\Repos\AspNetMVC\AspNetMVC\HtmlPage1.xml");
////string str = doc.ChildNodes.Item(1).OuterXml;
//XmlDocument xmlDoc = new XmlDocument();
// XmlReaderSettings settings = new XmlReaderSettings();
// settings.IgnoreComments = true;//忽略文档里面的注释
//XmlReader reader = XmlReader.Create(@"C:\Users\Administrator\Source\Repos\AspNetMVC\AspNetMVC\HtmlPage1.xml", settings);
XmlReader reader = XmlReader.Create(uri.ToString());
xmlDoc.Load(reader);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("bk", "http://www.w3.org/2005/Atom");
// Select the first book written by an author whose last name is Atwood.
XmlNodeList book;
XmlElement root = xmlDoc.DocumentElement;
book = root.SelectNodes("descendant::bk:entry", nsmgr);
//XmlElement xefeed = (XmlElement)xmlDoc.ChildNodes.Item(1);
foreach (XmlNode node in book) {
XmlElement xe = (XmlElement)node;
XmlNodeList xn10 = xe.ChildNodes;
string id = xn10.Item(0).InnerText;// <id>http://arxiv.org/abs/1701.02683v1</id>
}
//string str = XDocument.Load(getxml)
//.XPathSelectElements("/feed/entry").ToList().ToString();
//doc.LoadXml(str);
//.ToList();
//XmlNode root = .SelectSingleNode("feed/link") ;
//var obj2 = (ArticleDetails)deserializer.Deserialize(ForBytes.GetStreamFromBytes(ForBytes.GetByteFromString(str)));
//var obj = (ArticleDetails)deserializer.Deserialize(ForBytes.GetStreamFromBytes(ForBytes.GetByteFromString(str)));
Conexion conexion = new Conexion();
//conexion conexion.AbreConexion();
bool bo=true;
//if( conn.State == ConnectionState.Closed)
// {
// Console.Write("close");
// // or bo = false;
// }
return View("Index" );
}
}
public class Conexion
{
public void AbreConexion()
{
}
}
// GET: MVC0112/Details/5
public ActionResult Details(int? id)
{
//IfxConnection
// IfxConnection(myConnectionString)
//Dim myInsertQuery As String = "INSERT INTO STAFF (ID, NAME) Values(...)"
//Dim myIfxCommand As New IfxCommand(myInsertQuery)
//myIfxCommand.Connection = myConn
//myConn.Open()
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// GET: MVC0112/Create
public ActionResult Create()
{
return View();
}
// POST: MVC0112/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster, FormCollection collection)
{
var c= Request["userId"] ;
string[] userIds = collection.GetValues("userId");
if (userIds != null)// collection.GetValues("userId") value is string array ,such as { "1", "2" };
{
foreach(string userid in userIds)
{
BookMaster bookmaster = db.BookMasters.Find(userIds);
System.Web.Mail.MailMessage objMailMessage = new System.Web.Mail.MailMessage();
objMailMessage.From = "<EMAIL>";
objMailMessage.To = "<EMAIL>";
objMailMessage.Subject = "my subject:hello";
objMailMessage.Body = "test data";
objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
//username
objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "username");//bookmaster.username
//password
objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "<PASSWORD>");//bookmaster.password
//SMTPaddress
SmtpMail.SmtpServer = "smtp.sina.com.cn";
//开始发送邮件
SmtpMail.Send(objMailMessage);
}
}
return View(bookMaster);
}
// GET: MVC0112/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: MVC0112/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.Entry(bookMaster).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
// GET: MVC0112/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: MVC0112/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
BookMaster bookMaster = db.BookMasters.Find(id);
db.BookMasters.Remove(bookMaster);
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.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0208Controller : Controller
{
// GET: MVC0208
//public ActionResult Edit(Furniture furniture, HttpPostedFileBase fileTwo, HttpPostedFileBase file)
//{
// if (ModelState.IsValid)
// {
// //New Files
// for (int i = 0; i < Request.Files.Count; i++)
// {
// fileTwo = Request.Files[i];
// if (fileTwo != null && fileTwo.ContentLength > 0)
// {
// var fileNameTwo = Path.GetFileName(fileTwo.FileName);
// MainFileDetails mainFileDetail = new MainFileDetails()
// {
// FileName = fileNameTwo,
// Extension = Path.GetExtension(fileNameTwo),
// Id = Guid.NewGuid(),
// FurnitureId = furniture.FurnitureId
// };
// var pathMain = Path.Combine(Server.MapPath("~/Upload/MainPage/"), mainFileDetail.Id + mainFileDetail.Extension);
// fileTwo.SaveAs(pathMain);
// db.Entry(mainFileDetail).State = EntityState.Modified;
// FileDetail fileDetail = new FileDetail()
// {
// NameFile = fileNameTwo, //or mainFileDetail.FileName
// Extension = Path.GetExtension(fileNameTwo),//or mainFileDetail.Extension
// Id = Guid.NewGuid(),
// FurnitureId = furniture.FurnitureId //or mainFileDetail. FurnitureId
// };
// var path = Path.Combine(Server.MapPath("~/Upload/"), fileDetail.Id + fileDetail.Extension);
// fileTwo.SaveAs(path);
// db.Entry(fileDetail).State = EntityState.Added;
// }
// }
// db.Entry(furniture).State = EntityState.Modified;
// db.SaveChanges();
// TempData["message"] = string.Format("Changes in \"{0}\" has been saved", furniture.Name);
// return RedirectToAction("Index");
// }
// ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", furniture.CategoryId);
// return View(furniture);
//}
public ActionResult Index()
{
return View();
}
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace WebApplicationForm
{
public partial class WebForm0316 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) {
string FilePath = Server.MapPath("./") + "Pictures";
//获取上传图片的集合
HttpFileCollection HFC = Request.Files;
for (int i = 0; i < HFC.Count; i++)
{
HttpPostedFile UserHPF = HFC[i];
if (UserHPF.ContentLength > 0)
{
// 获取上传图片的文件名
string fileName = UserHPF.FileName.Substring(UserHPF.FileName.LastIndexOf("\\"));
string pathes = FilePath + "\\" + System.IO.Path.GetFileName(UserHPF.FileName);
if (!Directory.Exists(FilePath))
Directory.CreateDirectory(FilePath);
//保存图片到指定的位置
UserHPF.SaveAs(pathes);
Bitmap image = new Bitmap(UserHPF.InputStream);
Bitmap target = new Bitmap(50, 50);
string pathesSmall = FilePath + "\\smail\\" + System.IO.Path.GetFileName(UserHPF.FileName);
Graphics graphic = Graphics.FromImage(target);
graphic.DrawImage(image, 0, 0, 50, 50);
if (!Directory.Exists(FilePath + "\\smail"))
Directory.CreateDirectory(FilePath + "\\smail");
target.Save(pathesSmall);
}
}
}
}
//private void AddFileUpload()
//{
// //定义数组
// ArrayList arrayList = new ArrayList();
// //清除Table中的行
// tab_FileUpload_Area.Rows.Clear();
// //调用自定义方法,获取上传文件控件集
// GetFileUpload();
// HtmlTableRow tabRow = new HtmlTableRow();
// HtmlTableCell tabCell = new HtmlTableCell();
// //添加上传控件
// tabCell.Controls.Add(new FileUpload());
// tabRow.Controls.Add(tabCell);
// tab_FileUpload_Area.Rows.Add(tabRow);
// //调用自定义方法,保存控件集信息到缓存中
// SetFileUpload();
//}
//// 获取缓存中上传文件控件集
//private void GetFileUpload()
//{
// //声明数组对象
// ArrayList arrayList = new ArrayList();
// if (Session["FilesControls"] != null)
// {
// //将生成的上传控件,显示在Table表格中
// arrayList = (System.Collections.ArrayList)Session["FilesControls"];
// for (int i = 0; i < arrayList.Count; i++)
// {
// HtmlTableRow tabRow = new HtmlTableRow();
// HtmlTableCell tabCell = new HtmlTableCell();
// tabCell.Controls.Add((System.Web.UI.WebControls.FileUpload)arrayList[i]);
// tabRow.Controls.Add(tabCell);
// tab_FileUpload_Area.Rows.Add(tabRow);
// }
// }
//}
//// 保存当前页面上传文件控件集到缓存中
//private void SetFileUpload()
//{
// //创建动态数组
// ArrayList arrayList = new ArrayList();
// foreach (Control C in tab_FileUpload_Area.Controls)
// {
// //判断控件类型
// if (C.GetType().ToString() == "System.Web.UI.HtmlControls.HtmlTableRow")
// {
// HtmlTableCell tabCell = (HtmlTableCell)C.Controls[0];
// //在Table单元格中检索FileUpload控件
// foreach (Control control in tabCell.Controls)
// {
// //判断控件类型
// if (control.GetType().ToString() == "System.Web.UI.WebControls.FileUpload")
// {
// //将FileUpload控件信息保存到ArrayList控件中
// FileUpload f = (FileUpload)control;
// arrayList.Add(f);
// }//CodeGo.net/
// }
// }
// }
// Session.Add("FilesControls", arrayList);
//}
////添加上传图片按钮
//protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
//{
// this.AddFileUpload();
//}
////多图片上传
//protected void imgBtnUploadPic_Click(object sender, ImageClickEventArgs e)
//{
// //设置上传图片保存的路径
// string FilePath = Server.MapPath("./") + "Pictures";
// //获取上传图片的集合
// HttpFileCollection HFC = Request.Files;
// for (int i = 0; i < HFC.Count; i++)
// {
// HttpPostedFile UserHPF = HFC[i];
// if (UserHPF.ContentLength > 0)
// {
// // 获取上传图片的文件名
// String fileName = UserHPF.FileName.Substring(UserHPF.FileName.LastIndexOf("\\"));
// //保存图片到指定的位置
// UserHPF.SaveAs(FilePath + "\\" + System.IO.Path.GetFileName(UserHPF.FileName));
// //如果上传图片为1张,则不按编号进行命名,如果为多张图片上传,则进行按编号命名。
// if (UserHPF.ContentLength == 1)
// imgData.AddNode(txtPicName.Text.Trim(), "Pictures" + fileName, "0", ViewState["ImgID"].ToString());
// else
// imgData.AddNode(txtPicName.Text.Trim() + i.ToString(), "Pictures" + fileName, "0", ViewState["ImgID"].ToString());
// }
// }
// //删除所有的FileUpload控件
// if (Session["FilesControls"] != null)
// {
// Session.Remove("FilesControls");
// }
//}
}
}<file_sep>//using AspNetMVC;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplicationForm
{
public partial class WebForm0224 : System.Web.UI.Page
{
//CodeFirstDbDemoEntities DB = new CodeFirstDbDemoEntities();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);
//dc = new DataColumn("col2", typeof(String));
//dt.Columns.Add(dc);
//dc = new DataColumn("col3", typeof(String));
//dt.Columns.Add(dc);
//dc = new DataColumn("col4", typeof(String));
//dt.Columns.Add(dc);
for (int i = 0; i < 5; i++) {
DataRow dr = dt.NewRow();
dr[0] = "coldata1"+i.ToString();
//dr[1] = "coldata2";
//dr[2] = "coldata3";
//dr[3] = "coldata4";
dt.Rows.Add(dr);
}
listviedo.DataSource = dt;
listviedo.DataBind(); }
}
protected void listviedo_ItemCommand(object sender, ListViewCommandEventArgs e)
{
//Literal lblvedio = (Literal)e.Item.FindControl("lblvedio");
//Label lblname = (Label)e.Item.FindControl("lblname");
//if (e.CommandName == "Select")
//{
// int ID = Convert.ToInt32(e.CommandArgument);
// //Database.Tbl obj = DB.BookMasters.Single(p => p.Id == ID);
// //if (obj.IsUrl == false)
// //{
// // string Link = "<iframe></iframe>";
// //}
// //else
// //{
// string Link = "<iframe></iframe>";
// //}
//}
//if (e.CommandName == "Resume")
//{
// int ID = Convert.ToInt32(e.CommandArgument);
// //Database.Tbl objcar = DB.Tbl.Single(p => p.VID == ID);
//}
}
protected void listviedo_ItemDataBound(object sender, ListViewItemEventArgs e)
{
//Label lblid = (Label)e.Item.FindControl("lblid");
//LinkButton linkresuume = (LinkButton)e.Item.FindControl("linkresuume");
//int ID = Convert.ToInt32(lblid.Text);
//Database.Tbl objcar = DB.Tbl.Single(p => p.VID == ID);
}
protected void listviedo_SelectedIndexChanged(object sender, EventArgs e)
{
// //if (Session["USER"] == null)
// //{
// // Response.Redirect("Login");
// //}
// //else
// //{
// if (listviedo.SelectedIndex >= 0)
// {
// int id1 = Convert.ToInt32(listviedo.SelectedValue.ToString());
// lblvedio.Text = getvalue(id1);
// //VDOName.Text = getName(id1);
// //VDODesc.Text = getDesc(id1);
// //lblView.Text = getView(id1).ToString();
// //lblLike.Text = getLike(id1).ToString();
// }
// //}
}
//private string getvalue(int id1)
//{
// return id1.ToString();
//}
protected void listviedo_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
CheckBox chkBox = (CheckBox)sender;
// Gets the item that contains the CheckBox object.
ListViewDataItem item = (ListViewDataItem)chkBox.Parent.Parent;
// Update the database with the changes.
//VendorsListView.UpdateItem(item.DisplayIndex, false);
this.listviedo.SelectedIndex = e.NewSelectedIndex;
//this.listviedo.. = e.NewSelectedIndex;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0209Controller : Controller
{
// GET: MVC0209
public ActionResult Index()
{
return View();
}
public ActionResult Index2()
{
return View();
}
public class yy {
public string txt1 { get; set; }
public string txt2 { get; set; }
}
[HttpPost]
public ActionResult Index2(yy yys)
{
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace AspnetCore.Controllers
{
public class MVC0322Controller : Controller
{
Data.ApplicationDbContext db;
public MVC0322Controller(Data.ApplicationDbContext _db) {
db = _db;
}
// GET: MVC0308
public ActionResult Index()
{
ViewBag.Title = "Index";
return View(); //Start
}
[HttpPost]
public PartialViewResult _PartialStepOne(Contact1 one)
{
//...
//db.BookMasters.Add(one);
//db.SaveChanges();
return PartialView("~/Views/MVC0308/_PartialStepTwo.cshtml");
}
[HttpPost]
public PartialViewResult _PartialStepTwo(Contact4 two)
{
//...
//db.Publisher.Add(two);
//db.SaveChanges();
return PartialView("~/Views/MVC0308/_PartialStepThree.cshtml");
}
//[HttpPost]
//public ActionResult _PartialStepThree(Students Three)
//{
// //...
// //db.Students.Add(Three);
// //db.SaveChanges();
// return Redirect("...");//done
//}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using AspnetCorea.ViewComponents;
using System.Xml;
namespace AspnetCorea.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
//string strUrl = "http://www.w3school.com.cn/example/xmle/note.xml";
//XmlDocument doc = new XmlDocument();
//doc.Load(strUrl);
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
//new UserRole();
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public class Class4
{
private int add(int num2, int num3)
{
int res = num2 + num3;
return res;
}
private int obj1;
public int myprop
{
get { return obj1; }
set { obj1 = add(value, value); }
}
}
public IActionResult Error()
{
return View();
}
public IActionResult Core0206a()
{
ViewData["Message"] = "Your application description page.";
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Core0206a(FormCollection form, string[] a, string[] b,string c)
{
var t = Request.Form["a"];
var h = Request.Form["b"];
var y = Request.Form["c"];
Microsoft.Extensions.Primitives.StringValues d = new Microsoft.Extensions.Primitives.StringValues("");
List<string> g = new List<string>();
form.TryGetValue("a", out d);
return NotFound();
}
// public bool ValiCheckForDuplicate(string str, string name)
// {
// if (!CheckForDuplicate(str))
// {
// ModelState.AddModelError("", name + " already exist");
// return true;
// }
// return false;
// }
// public IActionResult VersionOne(TestModel model)
// {
// if (!ModelState.IsValid || ValiCheckForDuplicate(model.Title, " name ") || ValiCheckForDuplicate(model.Title, " url "))
// {
// model.SelectList1 = GetSelectList1();
// model.SelectList2 = GetSelectList2();
// model.SelectList3 = GetSelectList3();
// return View(model);
// }
// if (string.IsNullOrEmpty(model.UrlFriendlyTitle))
// model.UrlFriendlyTitle = GenerateUrlFriendlyTitle(model.Title);
// // do something else
// // mapping and saving to database
// return RedirectToAction("Index");
// }
public IActionResult Core0207a() {
Class4 a = new Class4();
a.myprop = 5;
string b = a.myprop.ToString();
return ViewComponent("PriorityList", new { maxPriority = 3, isDone = false });
}
[HttpPost]
public ActionResult Method1()
{
return ViewComponent("PriorityList" );
}
public IActionResult Core0222() {
return View();
}
}
}
<file_sep>using Microsoft.ReportingServices.DataProcessing;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0222Controller : Controller
{
// GET: MVC0222
public ActionResult Index()
{
return View();
}
public JsonResult YourMethodName()
{
// Your data connection and query stuff here
List<string> result = new List<string>();
result.Add("1");
result.Add("2");
result.Add("3");
// Return your JSON here
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult Index2() {
return View();
}
public ActionResult Index3() {
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplicationForm
{
public partial class WebForm0221 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
//DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
//DataRow drCurrentRow = dtCurrentTable.NewRow(); ;
// drCurrentRow["Column1"] = "";
// drCurrentRow["Column2"] = "";
// drCurrentRow["Column3"] = "";
//dtCurrentTable.Rows.InsertAt(drCurrentRow,0);
//Gridview1.DataSource = dtCurrentTable;
//Gridview1.DataBind();
// DataTable a=new DataTable();
//a.NewRow().;
//a.ImportRow(new DataRow() );
//GridView1.
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0221Controller : Controller
{
CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0221
public ActionResult Index()
{
var a= new Guid();
//var showbind = (from t1 in db.tbl_RegistrationPartners
// join t2 in db.aspnet_Memberships
// on t1.UserId equals t2.UserId
// join t3 in db.aspnet_UsersInRoles
// on t1.UserId equals t3.UserId
// where t1.ApplicationId == applicationid() && t2.IsApproved == true && t3.RoleId == new Guid("F03F89DB-6CBA-4B81-B75B-89BB08B0BD96") &&
// (t1.FirstName.Contains(txtSearch.Text.Trim()) ||
// t1.LastName.Contains(txtSearch.Text.Trim()) ||
// t1.CompanyName.Contains(txtSearch.Text.Trim()) ||
// t1.ContactPhone.Contains(txtSearch.Text.Trim()) ||
// t1.CellPhone.Contains(txtSearch.Text.Trim()) ||
// t1.SkypeName.Contains(txtSearch.Text.Trim()) ||
// t1.Address1.Contains(txtSearch.Text.Trim()) ||
// t1.Address2.Contains(txtSearch.Text.Trim()) ||
// t1.State.Contains(txtSearch.Text.Trim()) ||
// t1.Zip.Contains(txtSearch.Text.Trim()) ||
// t1.Country.Contains(txtSearch.Text.Trim()) ||
// t1.Currency.Contains(txtSearch.Text.Trim()) ||
// t1.WebsiteUrl.Contains(txtSearch.Text.Trim()) ||
// t1.Question.Contains(txtSearch.Text.Trim()) ||
// t1.Answer.Contains(txtSearch.Text.Trim()) ||
// t1.AffiliateCode.Contains(txtSearch.Text.Trim()))
// select new
// {
// t1.UserId,
// t1.FirstName,
// t1.LastName,
// t1.CompanyName,
// t1.ContactPhone,
// t1.CellPhone,
// t1.SkypeName,
// t1.Address1,
// t1.Address2,
// t1.State,
// t1.Zip,
// t1.Country,
// t1.Currency,
// t1.WebsiteUrl,
// t1.Question,
// t1.Answer,
// t1.AffiliateCode,
// t2.CreateDate,
// GetAmountAff = GetAmountAff(new Guid(t1.UserId.Value.ToString())),
// AmountPartnerCommission = t1.CommissionPartner,
// }).OrderByDescending(ui => ui.GetAmountAff).ToList();
return View();
Guid g;
}
public void Yes() {
// db.BookMasters.Select(u =>new BookMaster() { strBookTypeId= new Guid(u.strBookTypeId).ToString() });
var d = from c in db.BookMasters select new { c.strBookTypeId};
var e = from c in db.BookMasters select new { strBookTypeId = "" };
var r = from c in db.BookMasters select new { strBookTypeId = new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709").ToString() };
RedirectToAction("GG");
//var d= from c in db.BookMasters select new { strBookTypeId = new Guid(c.strBookTypeId).ToString() };
}
[HttpPost]
public void GG() {
Content("success");
}
private object GetAmountAff(Guid guid)
{
throw new NotImplementedException();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Windows.Forms;
using System.Web.Mvc;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
namespace AspNetMVC.Controllers
{
public class MVC0119Controller : Controller
{
// GET: MVC0119
public ActionResult Index()
{
string[] strs= "a,b,c".Split(',');
string firstname = strs[1];
return View();
}
// GET: MVC0119/Details/5
public ActionResult Details()
{
return View();
}
// GET: MVC0119/Create
public ActionResult Create()
{
return View();
}
// POST: MVC0119/Create
[HttpPost]
public ActionResult Create(System.Web.Mvc.FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: MVC0119/Edit/5
public ActionResult Edit( )
{
//Microsoft.Office.Interop.Excel.Application xlApp;
//Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
//Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
//object misValue = System.Reflection.Missing.Value;
//xlApp = new Microsoft.Office.Interop.Excel.Application();
//xlWorkBook = xlApp.Workbooks.Add(misValue);
//xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// Screenshot().Save(@"C:\Users\v-tiguo\Downloads\jakeydocs\cc.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
//Create a bitmap with the same dimensions like the screen
Bitmap b = new Bitmap(@"C:\Users\v-tiguo\Downloads\jakeydocs\cc.jpg", true);
//Clipboard.SetDataObject(b);
////Microsoft.Office.Interop.Excel.Application thisApp ;
//Microsoft.Office.Interop.Excel.Application thisApp = new Microsoft.Office.Interop.Excel.Application();
////Excel.Application thisApp =
//Microsoft.Office.Interop.Excel.Worksheet sheet1 = thisApp.Workbooks.get_Item(1).Worksheets.get_Item(1) as Microsoft.Office.Interop.Excel.Worksheet;
//Microsoft.Office.Interop.Excel.Range rng = sheet1.get_Range("A1:F40");
//sheet1.Paste(rng, false);
//thisApp.GetSaveAsFilename("csharp.net-informations.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
//thisApp.Close(true, misValue, misValue);
//thisApp.Quit();
//string sFileImage = @"C:\Users\Administrator\Pictures\images\101.jpg";
//String sFilePath = @"C:\Users\Administrator\Pictures\images\101" + ".xls";
//if (File.Exists(sFilePath)) { File.Delete(sFilePath); }
ApplicationClass objApp = new ApplicationClass();
Worksheet objSheet = new Worksheet();
Workbook objWorkBook = null;
//object missing = System.Reflection.Missing.Value;
//using (XLWorkbook wb = new XLWorkbook())
//{ //here
// wb.Worksheets.Add(dt, "Error Measurements");
// wb.Worksheets.Add(dt2, "Regression Forecast");
// wb.Worksheets.Add(dt3, "Regression Equation");
// wb.Worksheets.Add(headerTable, "Regression Graph");
//}
//try
//{
//objWorkBook = objApp.Workbooks.Add(Type.Missing);
//objSheet = (Worksheet)objWorkBook.ActiveSheet;
////Add picture to single sheet1
//objSheet = (Worksheet)objWorkBook.Sheets[2];
//objSheet.Name = "Graph with Report";
//objSheet.Shapes.AddPicture(@"C:\Users\v-tiguo\Downloads\jakeydocs\cc.jpg", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 10, 10, 700, 350);
//objWorkBook.SaveAs(@"C:\Users\v-tiguo\Downloads\jakeydocs\cc.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
//Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//}
//catch (Exception)
//{
// //Error Alert
//}
//finally
//{
// objApp.Quit();
// objWorkBook = null;
// objApp = null;
//}
return View();
}
private Bitmap Screenshot()
{
//Create a bitmap with the same dimensions like the screen
Bitmap screen = new Bitmap(SystemInformation.VirtualScreen.Width,
SystemInformation.VirtualScreen.Height);
//Create graphics object from bitmap
Graphics g = Graphics.FromImage(screen);
//Paint the screen on the bitmap
g.CopyFromScreen(SystemInformation.VirtualScreen.X,
SystemInformation.VirtualScreen.Y,
0, 0, screen.Size);
g.Dispose();
//return bitmap object / screenshot
return screen;
}
// POST: MVC0119/Edit/5
[HttpPost]
public ActionResult Edit(int id, System.Web.Mvc.FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: MVC0119/Delete/5
public ActionResult Delete()
{
return View();
}
// POST: MVC0119/Delete/5
[HttpPost]
public ActionResult Delete(int id, System.Web.Mvc.FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
<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 AspNetMVC;
namespace AspNetMVC.Controllers
{
public class BookMasters1Controller : Controller
{
private CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: BookMasters1
public ActionResult Index()
{
var IssuesList = new List<System.Collections.IList>();
IssuesList.Add(new List<string>() { "a" ,"b"} );
ViewBag.IssuesList = IssuesList;
var IssuesList2 = new List<System.Collections.IList>();
IssuesList2.Add(new List<BookMaster>() { new BookMaster() { strAccessionId="1"} });
ViewBag.IssuesList2 = IssuesList2;
return View(db.BookMasters.ToList());
}
// GET: BookMasters1/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
[HttpGet]
public JsonResult GetItem()
{
//var Issued = db.Clearances.Select(a => a.AssignId).ToList();
//var NotIssued = db.Assigns.Where(Clearance => !Issued.Contains(Clearance.AssignId))
// .Select(x => new { AssignId = x.AssignId, Item = x.IatpRequest.Item.ItemName }).ToList();
List<ass> c = new List<ass>() { new ass() { AssignId=1, Item= "Apple" }, new ass() { AssignId = 3, Item = "Mango" } };
return Json(c, JsonRequestBehavior.AllowGet);
}
public class ass {
public int AssignId { get; set; }
public string Item { get; set; }
}
// GET: BookMasters1/Create
public ActionResult Create()
{
return View();
}
// POST: BookMasters1/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.BookMasters.Add(bookMaster);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
// GET: BookMasters1/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: BookMasters1/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
//db.BookMasters.OrderBy(a=>a.Id).ThenBy(a=>a.strAccessionId)
if (ModelState.IsValid)
{
db.Entry(bookMaster).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
// GET: BookMasters1/Delete/5
public ActionResult Delete( )
{
return View( );
}
// POST: BookMasters1/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
BookMaster bookMaster = db.BookMasters.Find(id);
db.BookMasters.Remove(bookMaster);
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.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using AspnetCore.Models;
namespace AspnetCore.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//{
// //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
// //optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
// optionsBuilder.UseSqlServer(@"data source = VDI-V-TIGUO; initial catalog = CodeFirstDbDemo8; integrated security = True;");
//}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Contact1>(entity =>
{
entity.HasKey(e => e.Accountno);
entity.Property(e => e.Recid).IsRequired();
});
builder.Entity<Contact4>(entity =>
{
entity.HasKey(e => e.Accountno);
entity.HasOne(d => d.Contact1s)
.WithOne(p => p.Contact4s);
//.HasForeignKey(d => d.);
});
//builder.Entity<Contact1>().HasKey(e => e.Accountno);
//builder.Entity<Contact4>().HasKey(e => e.Accountno);
//builder.Entity<Contact1>().HasOptional(s => s.Contact4s).WithRequired(ad => ad.Contact1s);
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
public DbSet<Contact1> Contact1ss { get; set; }
public DbSet<Contact4> Contact2ss { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplicationForm
{
public partial class WebForm0228 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Butremove.Visible = false;
}
protected void ButAdd_Click(object sender, EventArgs e)
{
Button tb = (Button)sender;
tb.Visible = false;
//ButAdd.Visible = false;
Butremove.Visible = true;
}
}
}<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 AspNetMVC;
using System.Data.Entity.Validation;
using System.Diagnostics;
namespace AspNetMVC.Controllers
{
public class MVC0118Controller : Controller
{
private CodeFirstDbDemoEntities db = new CodeFirstDbDemoEntities();
// GET: MVC0118
// POST: MVC0118/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
//[HttpPost]
//[ValidateAntiForgeryToken]
//[HttpPost]
public JsonResult Create2( BookMaster bookMaster)
{
if (ModelState.IsValid)
{
//db.BookMasters.Add(bookMaster);
//db.SaveChanges();
return Json(new { Success = true });
//return RedirectToAction("Index");
}
return Json(bookMaster, JsonRequestBehavior.AllowGet);
}
// GET: MVC0118/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: MVC0118/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,strBookTypeId,strAccessionId")] BookMaster bookMaster)
{
if (ModelState.IsValid)
{
db.Entry(bookMaster).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bookMaster);
}
public ActionResult EditUserExpDetails(tblOpsUserEmpDetail exp)
{
var DbEntity = db;
return Json(new { name=1});
//try
//{
// if (Session["LoginDetails"] != null)
// {
// int userID = Convert.ToInt16(Session["LoginDetails"].ToString());
// tblOpsUserEmpDetail tblObj = DbEntity.tblOpsUserEmpDetails.Find(userID);
// //ModelState.Remove("Password");
// tblObj.userID = userID;
// tblObj.modifiedDate = DateTime.Today;
// tblObj.empName =
// exp.empName ?? tblObj.empName;
// tblObj.empAddress = exp.empAddress ?? tblObj.empAddress;
// tblObj.annualSalary = exp.annualSalary ?? tblObj.annualSalary;
// tblObj.currentDesignation = exp.currentDesignation ?? tblObj.currentDesignation;
// tblObj.lastDesignation = exp.lastDesignation ?? tblObj.lastDesignation;
// tblObj.joininSalary = exp.joininSalary ?? tblObj.joininSalary;
// tblObj.lastSalary = exp.lastSalary ?? tblObj.lastSalary;
// tblObj.joiningDate = exp.joiningDate;
// tblObj.lastDate = exp.lastDate;
// tblObj.createdDate = exp.createdDate;
// try
// {
// DbEntity.Entry(tblObj).State = EntityState.Modified;
// DbEntity.SaveChanges();
// TempData["Msg"] = "Profile has been updated succeessfully";
// }
// catch (DbEntityValidationException ex)
// {
// var error = ex.EntityValidationErrors.First().ValidationErrors.First();
// this.ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
// return View();
// }
// return RedirectToAction("ViewUserProfile");
// }
//}
//catch (DbEntityValidationException dbEx)
//{
// foreach (var validationErrors in dbEx.EntityValidationErrors)
// {
// foreach (var validationError in validationErrors.ValidationErrors)
// {
// Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
// }
// }
//}
//return View(exp);
}
// GET: MVC0118/Delete/5
public class tblOpsUserEmpDetail
{
public int userempID { get; set; }
public int userID { get; set; }
public string empName { get; set; }
public string empAddress { get; set; }
public string currentDesignation { get; set; }
public string lastDesignation { get; set; }
public string annualSalary { get; set; }
public System.DateTime joiningDate { get; set; }
public System.DateTime lastDate { get; set; }
public string joininSalary { get; set; }
public string lastSalary { get; set; }
public Nullable<System.DateTime> modifiedDate { get; set; }
public System.DateTime createdDate { get; set; }
}
#region orgain
public ActionResult Index()
{
return View(db.BookMasters.ToList());
}
// GET: MVC0118/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// GET: MVC0118/Create
public ActionResult Create()
{
return View();
}
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BookMaster bookMaster = db.BookMasters.Find(id);
if (bookMaster == null)
{
return HttpNotFound();
}
return View(bookMaster);
}
// POST: MVC0118/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
BookMaster bookMaster = db.BookMasters.Find(id);
db.BookMasters.Remove(bookMaster);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Controllers
{
public class MVC0202Controller : Controller
{
// GET: MVC0202
public ActionResult Index()
{
return View();
}
public ActionResult GetImage() {
// http://www.cnblogs.com/CareySon/archive/2012/03/07/2383690.html
byte[] data = Convert.FromBase64String("GQ8XQAYFAiEMfN0qD0COTgMX");
return File(data, "image/gif");
// return File("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", "data: image / gif; base64");
// return File("data: image / gif; base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AspNetMVC.Models
{
public class DateInValidationAttribute : ValidationAttribute
{
}
} | 27aa9f93ac918252811a6313b82d3dc21b94fa2f | [
"JavaScript",
"C#",
"Markdown"
] | 95 | C# | TinaGitGuo/AspNetMVC | 4400711959bd66aede599a466c5af67cdc1abde2 | 36f817ec4e9d40edac197fa69b5b0bd227c6028c |
refs/heads/master | <file_sep>module Swat
module UI
module RspecSetup
def init_ui(options = {})
before(:each) do |example|
end
after(:each) do |example|
end
end
end
end
end
<file_sep>module Swat
module UI
require 'swat/ui/config'
def self.setup(rspec_config, opts)
@config = Config.new(rspec_config, opts)
end
def self.config
@config
end
end
end
<file_sep>module Swat
module UI
require 'swat/ui/rspec_setup'
class Config
def initialize(rspec_config, opts = {})
@options = DEFAULT_OPTIONS.merge opts
rspec_config.extend RspecSetup
end
def options
@options
end
end
end
end
<file_sep>module Swat
module TestWorld
class Base
BASE_OPTIONS = {}
DEFAULT_OPTIONS = {}
SITUATIONS = {}
attr_reader :options
def initialize(opts = {})
@options = init_options(opts)
init_situation
end
def self.moment
m = TestWorld.config.options[:moment]
return unless m
m.is_a?(Time) ? m : Time.parse(m.to_s)
end
def moment
self.class.moment
end
alias_method :now, :moment
protected
def base_options
self.class::BASE_OPTIONS
end
def default_options
self.class::DEFAULT_OPTIONS
end
def situations
self.class::SITUATIONS
end
def init_situation
raise 'method "init_situation" should be implemented in subclass'
end
def before_each(example, context)
#can be implemented in subclass
end
def after_each(example, context)
#can be implemented in subclass
end
private
def init_options(opts)
res = if opts.is_a?(Hash)
default_options.merge(opts)
elsif opts.is_a?(Symbol)
default_options.merge(situations[opts])
else
raise 'Invalid TW options passed! should be Hash or Symbol(situation identifier)'
end
base_options.merge res
end
end
end
end
<file_sep>Gem::Specification.new do |s|
s.name = 'swat-ui'
s.version = '0.0.0'
s.date = '2014-11-20'
s.summary = 'Swat UI'
s.description = 'Tool for end-to-end tests'
s.authors = ['<NAME>']
s.email = '<EMAIL>'
s.files = ['lib/swat_ui.rb']
s.add_dependency('swat-capybara', '~> 0.0.0')
s.add_dependency('firebase-ruby', '~> 0.2.2')
s.homepage = 'http://tw.coming.soon'
s.license = 'MIT'
end | 0991f009ca078dc496b58e3fa7001fbae09077e9 | [
"Ruby"
] | 5 | Ruby | sashasashas11/sw2at-ui | b58056b2e78800c0a64603048576dc418c50d8e1 | fbfa80dc6135c59230e451b96c434a3b886c8860 |
refs/heads/master | <file_sep>feature "Signing in:" do
let!(:user) do
User.create(email: '<EMAIL>',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>')
end
scenario "user can sign in" do
sign_in(email: user.email, password: <PASSWORD>)
expect(page).to have_content "Welcome, #{user.email}"
end
end
<file_sep>feature "Users sign-up:" do
scenario "user can sign up" do
expect { sign_up }.to change(User, :count).by(1)
expect(page).to have_content('Welcome, <EMAIL>')
expect(User.first.email).to eq('<EMAIL>')
end
end
| d178e40847ccaa482d374049e119d59ff8857010 | [
"Ruby"
] | 2 | Ruby | cyberplanner/chitter-challenge | 2a65f9058c93d28be4cb25e39309f6a81acc450e | 83d612c462d4a224424bf87ea02ad1b13b8c884a |
refs/heads/master | <repo_name>vsanna/ml_training<file_sep>/negaposi/readme.md
02/04 negaposi判定の勉強会に出た際の勉強メモとデータセット。
自然言語から二値分類を行なう分類器を実装した。
- 素性選択としてはbag of wordsを頻度ベクトルで利用した。
- 分類方法はSVM、カーネルはrbfを利用した
<file_sep>/negaposi/0204_seminar/lesson.py
#coding: UTF-8
#============
def td(f_name):
return np.genfromtxt("%s" % f_name,
delimiter="\t",
comments=None,
dtype=[('DATA1', 'S25'), ('DATA2','S200')])
# comments=#などと設定しておくと、#以降を無視する
# dtype=[('DATA1', 'S25')] ... DATA1列は文字列で25byteという意味. 列に名前を付与してもる。
# 指定より長いデータは途中で切られて読み込まれる
#===========
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import svm
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
print('Train Start')
# 1. データの読込
f_name = 'data_3000.tsv'
twi_data = td(f_name)
# 2. データをbowに素性選択(特徴抽出)
# bowを記憶するし、ベクトル化する関数
# min_df: 1回しか出ていない単語を足切りしている(max_dfもある)
# token_pattern: ...でも読み込める?
# CountVectorizer#fit(strのarr) ... スペース区切りで覚えてくれる
word_vectorizer = CountVectorizer(min_df=1, token_pattern=u'(?u)\\b\\w+\\b')
word_vectorizer.fit(twi_data['DATA2']) # BoWの生成
# BoWの表示
# print(len(word_vectorizer.get_feature_names())) #=> 279
# for word in word_vectorizer.get_feature_names():
# print(word)
# 今word_vectorizerはbowを保有している
# それを元に、各twitter textデータをベクトルに変換している
X_train = word_vectorizer.transform(twi_data['DATA2'])
Y_train = twi_data['DATA1']
# print(X_train[1]) #=> (0, 2) 1 ... タプルの頭の0はよくわからないが、X_train[0]はBoWの2番目のデータを1つもつと解釈する
# 3. 学習
# support vector classifier
# - 分類する直線を引いているところ
# - ref: support vector regression: 回帰問題
# C: cost ... あとで解説
classifier = svm.SVC(C=1.0, kernel='rbf')
classifier.fit(X_train, Y_train)
print('Train Finished')
# 4. 予測してみる
print('Test Start')
f_name2 = 'data_20.tsv' # 未知データ
twi_data2 = td(f_name2)
X_test = word_vectorizer.transform(twi_data2['DATA2'])
Y_test = twi_data2['DATA1']
Y_pred = classifier.predict(X_test)
cm = confusion_matrix(Y_test, Y_pred)
print(cm)
# [[5 5]
# [1 9]]
# この読み方はノートにメモした
out_fname = 'out_twi.txt'
f = open(out_fname, 'w')
z = zip(Y_test, Y_pred, twi_data2['DATA2'])
for t_tag, p_tag, twi in z:
f.write(("%s\t%s\t%s\n") % (t_tag, p_tag, twi))
f.close()
# 5. confusion_matrixの読み方がわかりにくいので、レポートの形にする
target_names = ['negative', 'positive']
print(classification_report(Y_test, Y_pred, target_names=target_names))
# precision recall f1-score support
#
# negative 0.83 0.50 0.62 10
# positive 0.64 0.90 0.75 10
#
# avg / total 0.74 0.70 0.69 20
# recall: 当たった数 / 予測した数 ... negativeだと5 / 6 = 0.83
# precision: あった数 / データの個数 ... negativeだと5 / 10 = 0.5
# f1-score: 1 / (1/P + 1/R): recallとprecisionの調和平均. ... negativeだと 1 /(0.83 + 0.5) = 0.75
# 6. 精度向上
<file_sep>/deep-learning-from-scratch-notes/README.md
# about this
ゼロから作るDeep Learningの学習メモをまとめ、また各章のサマリーをまとめる(予定)
## 二章 パーセプトロン
- パーセプトロンとは
- 複数の信号を受取り、一つの信号を出力するもの
- y = 1 if wx + b > 0 else 0
- パラメーターである、wとb(θ)をコンピューターが適切に設定する作業を学習という
- w: 重みは入力信号の重要度を示し、b: バイアスは発火しやすさを示す
- 人間の仕事は、
1. パーセプトロンの構造 = モデルを考え、
2. 学習データをコンピューターに与えること
- パーセプトロンでは層を重ねることで、表現が柔軟になる
## 三章 ニューラルネットワーク
- 適切な重みパラメータをデータから自動で学習できるというのがニューラルネットワークの特徴
- 活性化関数の導入: x -> a -> yの2段階に今までの一層での処理を分離
- パーセプトロン: ステップ関数(階段関数)
- NN: 様々な非線形の関数
- sigmoid, ReLU: 2クラス分類
- y = 1/(1 + np.exp(-a))
- y = np.maxmim(0, a)
- 恒等関数: 回帰問題
- y = a
- softmax: 多クラス分類 ... ex: MNIST
- yk = exp(ak) / ∑(exp(ai))
- y = np.exp(a) / np.sum(np.exp(a))
- pythonへの習熟と、今後を見据えバッチ処理の工夫の仕方を学ぶ
## 四章 NNの学習
- ここまでの推測の種類の生理
1. 入力 -> 人間の考えたアルゴリズム -> 出力
2. 入力 -> 人間の考えた特徴量 -> 機械学習 -> 出力
3. 入力 -> NN(deep learning) -> 出力
- 特徴量とは、入力データから、本質的なデータを的確に抽出できるように設計された「変換器」を指す
- 画像の特徴量は一般的にベクトルで記述される
- コンピュータビジョンで有名な特徴量としては、SIFT, SURF, HOGなどがある
- 画像データを変換器 = 特徴量によってベクトルに変換し、そのベクトルに対して「識別器」で学習させる
- SVN, KNN等があるらしい
- この「特徴量」については人間が設計する必要がある
- 問題に応じて特徴量 = 変換器を使い分ける必要がある
- ココには人の手が介在する
- 過学習とは
- one-hot表現
- 損失関数
- 二乗和誤差
- 交差エントロピー誤差
<file_sep>/nl_math/example_codes/2_6.py
import numpy as np
def sen2vec(sen):
sen = sen.split(" ")
result = {}
for word in sen:
result[word] = 0 if not(word in result) else result[word]
result[word] += 1
return result
def pretty_sen2vec(vec):
for key, count in vec.items():
print(key, count)
# v = sen2vec("hoge geho geho gahgah")
# pretty_sen2vec(v)
v1 = sen2vec("A cat sat on the mat")
pretty_sen2vec(v1)
v2 = sen2vec("Cats are sitting on the mat")
pretty_sen2vec(v2)
v1_vec = np.array(list(v1.values()))
v2_vec = np.array(list(v2.values()))
print( np.dot(v1_vec, v2_vec) / (np.linalg.norm(v1_vec) * np.linalg.norm(v2_vec)) )
<file_sep>/README.md
# 機械学習を学ぶ
- deep learning ... NN含む
- NN以外の機械学習
- クラスタリング
- ナイーブベイズ, etx
- データ種別毎のベクトル化 = 素性選択 手法のまとめ
- 画像 / 自然言語 etc
主にdlでは画像を、NN以外の機械学習では自然言語を扱っている
| 60f409950ccb1a3b6b1476c03ee4ea936a524332 | [
"Markdown",
"Python"
] | 5 | Markdown | vsanna/ml_training | 7b6dfbed408faecda5bdbfa1d53bb324abaf32e5 | 9eac09023177154e66549cdf08bc6fb74d6a3733 |
refs/heads/master | <file_sep>from flask import Blueprint
from flask_restx import Api
from .routes import ctftime_namespace
def load(app):
api = Blueprint("ctftime_api", __name__, url_prefix="/api/v1")
CTFTime_API_v1 = Api(api, version="v1", doc=app.config.get("SWAGGER_UI"))
CTFTime_API_v1.add_namespace(ctftime_namespace, "/ctftime")
app.register_blueprint(api)
<file_sep>from flask_restx import Namespace, Resource
from flask import session, jsonify
from CTFd.models import Solves, Challenges
from CTFd.cache import cache, make_cache_key
from CTFd.utils.scores import get_standings
from CTFd.utils import get_config
from CTFd.utils.modes import get_model, TEAMS_MODE
from CTFd.utils.dates import unix_time
from CTFd.utils.decorators import (
during_ctf_time_only
)
from CTFd.utils.decorators.visibility import (
check_challenge_visibility,
check_score_visibility,
check_account_visibility
)
from CTFd.utils.config.visibility import (
scores_visible,
accounts_visible,
challenges_visible,
)
from sqlalchemy.sql import or_, and_, any_
ctftime_namespace = Namespace('ctftime', description="Endpoint to retrieve scores for ctftime")
def unicode_safe(string):
return string.encode('unicode_escape').decode()
@ctftime_namespace.route('')
class ScoreboardList(Resource):
@check_challenge_visibility
@check_score_visibility
@cache.cached(timeout=60, key_prefix=make_cache_key)
def get(self):
response = {
'tasks': [],
'standings': []
}
mode = get_config("user_mode")
freeze = get_config("freeze")
# Get Challenges
challenges = Challenges.query.filter(
and_(Challenges.state != 'hidden', Challenges.state != 'locked')
).order_by(Challenges.value).all()
challenges_ids = {}
for i, x in enumerate(challenges):
response['tasks'].append(unicode_safe(x.name) + " " + str(x.value))
challenges_ids[x.id] = unicode_safe(x.name) + " " + str(x.value)
# Get Standings
if mode == TEAMS_MODE:
standings = get_standings()
team_ids = [team.account_id for team in standings]
else:
abort(501, "CTFTime only accepts team scores.")
solves = Solves.query.filter(Solves.account_id.in_(team_ids))
if freeze:
solves = solves.filter(Solves.date < unix_time_to_utc(freeze))
for i, team in enumerate(team_ids):
team_standing = {
'pos': i+1,
'team': unicode_safe(standings[i].name),
'score': float(standings[i].score),
'taskStats': {}
}
team_solves = solves.filter(Solves.account_id == standings[i].account_id)
for solve in team_solves:
chall_name = challenges_ids[solve.challenge_id]
team_standing["taskStats"][chall_name] = {
"points": solve.challenge.value,
"time": unix_time(solve.date),
}
response['standings'].append(team_standing)
return response
<file_sep># CTFTime Api Endpoint
Adds an endpoint to the CTFd api to allow for uploading the scores to [CTFtime.org](https://ctftime.org/)
This endpoint is designed to match CTFtime's [scoreboard feed specifications](https://ctftime.org/json-scoreboard-feed)
The endpoint can be reached at `/api/v1/ctftime`
## Beware of challenge dependencies
This plugin shows the challenge name and value for all challenges that are visible. This includes challenges that should be hidden until their dependencies are solved.
| 0558d1208403fb4572dd2c8849f6dc39372d5a51 | [
"Markdown",
"Python"
] | 3 | Python | durkinza/CTFd_CTFTime_endpoint | 4500a3561ede546946d36fd8b5bda828a178b4cc | 2f408ca348b882cb71297943674e132175c87fdc |
refs/heads/master | <file_sep>/* 基本类型拓展,别冲突了哦 */
Date.prototype.taDateFormat = function(format) {
// --格式化时间
// 抽离时间的各个单位
var obj = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
};
// --替换表达式
if(/(y+)/.test(format)) { // 由于年份是四位,所以单独抽离
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for(var key in obj) { // 提取时间的其他单位,并组装
if(new RegExp("(" + key + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? obj[key] : ("00" + obj[key]).substr(("" + obj[key]).length));
}
}
return format;
}
/* 寻城项目工具js */
$.xuncheng = {
load: function(msg) { // 页面加载开始
var msgTxt = msg || '数据加载中...';
var $load = $('#xc-modal-loading');
if(!$load.length) {
var html = [];
html.push('<div class="am-modal am-modal-loading am-modal-no-btn" tabindex="-1" id="xc-modal-loading">');
html.push('<div class="am-modal-dialog">')
html.push('<div class="am-modal-hd">' + msgTxt + '</div>')
html.push('<div class="am-modal-bd">')
html.push('<span class="am-icon-spinner am-icon-spin"></span>')
html.push('</div>')
html.push('</div>')
html.push('</div>')
$load = $(html.join('')).appendTo('body');
}
$load.modal();
},
loadEnd: function() { // 页面加载完毕
$('#xc-modal-loading').modal('close')
},
back: function() { // 返回上一页
window.history.go(-1)
setTimeout(function() {
window.location.href = window.location.origin;
}, 300)
},
backTop: function(scroll) { // 返回顶部
var $backTop = $('#xc-back-top');
if(scroll > 500) {
if(!$backTop.length) {
$backTop = $('<a href="javascript: $.xuncheng.scrollTop();" title="回到顶部" class="animated fadeInUp xc-back-top xc-b" id="xc-back-top"><i class="iconfont icon-fanhuidingbu "></i></a>').appendTo('body');
}
$backTop.show();
} else {
$backTop.hide();
}
},
scrollTop: function() {
$('html, body').scrollTop(0)
},
share: function() {
$.DialogFx.alert('点击微信右上角菜单功能进行分享')
},
toDecimal2: function(x) { // 始终保存2位小数
var f = parseFloat(x);
if(isNaN(f)) {
return false;
}
var f = Math.round(x * 100) / 100;
var s = f.toString();
var rs = s.indexOf('.');
if(rs < 0) {
rs = s.length;
s += '.';
}
while(s.length <= rs + 2) {
s += '0';
}
return s;
},
outLogin: function() { // 退出登录
$.AMUI.store.remove('uid');
window.location.href = '../user/index.html'
},
reLogin: function(statusCode) { // 判断账户是否过期
if(statusCode == 10002) {
$.DialogFx.alert({
content: '账户已过期或未登录,请重新登录',
end: function() {
window.location.href = '../component/login.html'
}
})
setTimeout(function() {
window.location.href = '../component/login.html'
}, 2000)
return false;
}else {
return true;
}
},
setUid: function(uid) { // 记录账户ID
$.AMUI.store.set('uid', uid);
return uid;
},
getUid: function() { // 获取账户ID
return $.AMUI.store.get('uid') || false
}
}
// 获取系统信息
$.xuncheng.getSystem = function() {
var agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod']
var system = 'PC';
agents.forEach(function(value) {
if(navigator.userAgent.indexOf(value) > 0) {
system = value;
}
})
return system.trim();
}
// 获取随机数
$.xuncheng.getRandom = function(min, max) {
/*
* 不传参返回随机数
* 传递一个数字返回当前位数的随机数
* $.getRandom(3) = nnn
* 传递二个数字返回范围内的随机数
* */
if(min && !max) {
var str = '9';
var str1 = '1'
$.each(new Array(min), function(i) {
str += '9';
str1 += '0';
});
str = parseInt(str) / 10;
str1 = parseInt(str1) / 10;
return parseInt(Math.random() * (str - str1 + 1) + str1)
} else if(min || min == 0 && max) {
return parseInt(Math.random() * (max - min + 1) + min)
} else {
return parseInt(Math.ceil(Math.random() * (new Date).getTime()))
}
}
// 时间格式
$.xuncheng.getTime = function(options) {
/* option ==
* option type value
* timestamp Boolean 时间戳参数
* timeFormat String 时间格式
*
* 传入type 后则是获取时间间隔值
* type after 后 (默认)
* before 前
*
* value number 时间间隔
*
* select minute 分钟
* day 天
* */
var option = options || false;
var time = false;
if(typeof option == 'object') {
if(option.hasOwnProperty("type")) {
// 如果具备 type 参数则是获取时间间隔值
var newOption = $.extend(true, {
value: 5,
select: 'minute',
type: 'after'
}, option);
var interTimes = parseInt(newOption.value) * 60 * 1000;
var newDate;
// TODO 暂未处理获取传参后的时间间隔
if(newOption.type == 'after') {
newDate = new Date(Date.parse(new Date()) + interTimes);
} else {
newDate = new Date(Date.parse(new Date()) - interTimes);
}
time = newDate.taDateFormat(option.timeFormat || "yyyy-MM-dd hh:mm:ss");
} else if(option.hasOwnProperty("timestamp")) {
// 参数包含时间戳参数时
time = new Date(parseInt(option.timestamp)).taDateFormat(option.timeFormat || "yyyy-MM-dd hh:mm:ss");
} else if(option.hasOwnProperty("timeFormat")) {
// 参数只具备时间格式参数时
time = new Date().taDateFormat(option.timeFormat);
}
} else if(typeof option == 'boolean') {
//传入 option 为 true 时返回 object ,否则返回 String
if(option) {
var _date = new Date();
time = {
"y": _date.getFullYear(),
"M": _date.getMonth() + 1,
"d": _date.getDate(),
"h": _date.getHours(),
"m": _date.getMinutes(),
"s": _date.getSeconds(),
"ms": _date.getMilliseconds()
};
} else {
time = new Date().taDateFormat("yyyy-MM-dd hh:mm:ss");
}
}
return time
}
// 获取路径参数
$.xuncheng.getUrlParam = function(key, url) {
/**
* 获取url参数值
* @param key 需要获取的参数
* @param url 传递域名
* @return string
* @demo gs.getUrlParam(null,"key")
* @demo gs.getUrlParam(xx.com?id=1&name=22,"id")
*/
var newUrl = url || window.location;
newUrl = decodeURI(newUrl);
var params = {};
var arr = newUrl.split("?");
if(arr.length <= 1) {
return false;
}
arr = arr[1].split("&");
for(var i = 0, l = arr.length; i < l; i++) {
var a = arr[i].split("=");
params[a[0]] = a[1];
}
if($.isEmptyObject(params)) {
return false;
}
return key ? params[key] : params;
}
// 公用 js 初始化
$(function() {
// 去除点击 300ms延时
FastClick.attach(document.body);
$.fn.ripple = function(event) {
var $elm = this;
var elmLeft = $elm.offset().left;
var elmTop = $elm.offset().top;
var elmWidth = $elm.width();
var elmHeight = $elm.height();
if(elmWidth >= elmHeight) {
elmHeight = elmWidth;
} else {
elmWidth = elmHeight;
}
var x = event.pageX - elmLeft - elmWidth / 2;
var y = event.pageY - elmTop - elmHeight / 2;
var _style = 'width:' + elmWidth + 'px;height:' + elmHeight + 'px;top:' + y + 'px;left:' + x + 'px;';
var $rippleSpan = $('<span class="ta-ripple-span" style="' + _style + '"></span>').appendTo($elm)
.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oAnimationEnd animationend', function() {
$rippleSpan.remove();
});
return $elm;
}
var $body = $('body');
$body.on('click', '.ta-ripple', function(event) {
$(this).ripple(event);
}).on('focus', 'input', function() {
mobileInputCover(this)
}).on('click', 'textarea', function() {
mobileInputCover(this)
})
// 解决移动端遮盖输入框
function mobileInputCover(elm) {
if($.xuncheng.getSystem() != 'PC') { // 解决移动端遮盖输入框事件
if($(elm).hasClass('no-cover')) {
return false;
}
$(window).one('resize', function() {
elm.scrollIntoView()
})
}
}
$(window).on('scroll', function() {
$.xuncheng.backTop($(this).scrollTop())
});
// 滚动加载
var $footerLazy = $('#xc-footer-lazy');
if($footerLazy.length) {
// 监听滚动数据加载完毕事件
$footerLazy.on('lazy.end', function() {
$footerLazy.data('xcLazy', true)
}).trigger('lazy.end');
$(window).on('scroll', function() {
if($footerLazy.data('xcLazy')) {
var $this = $(this);
var winStop = $this.scrollTop() + $this.height();
if(winStop > $footerLazy.offset().top) {
// 触发事件并设置滚动监听事件失效
$footerLazy.data('xcLazy', false).trigger('lazy.open');
}
}
});
}
});
/* 弹窗组件 */
$(function() {
function DialogFx($el, options) {
this.$el = $el;
this.options = options;
this.$overlay = this.$el.find('.xc-dialog-overlay')
this.$confirmBtn = this.$el.find('[data-dialog-confirm]');
this.$cancelBtn = this.$el.find('[data-dialog-cancel]');
this._initEvents();
this.open()
}
// 绑定事件
DialogFx.prototype._initEvents = function() {
var self = this;
self.$confirmBtn.on('click', function(e) {
self.options.confirm(self)
self.close()
})
self.$cancelBtn.on('click', function(e) {
self.options.cancel(self)
self.close()
})
self.$overlay.on('touchstart', function(e) {
self.close()
})
}
// 打开
DialogFx.prototype.open = function() {
this.$el.addClass('xc-dialog-open')
this.options.open(this)
}
// 关闭
DialogFx.prototype.close = function() {
var self = this;
var xdContent = self.$el.find('.xc-dialog-content')
if($.isArray(self.options.anim)) {
xdContent.removeClass(self.options.anim[0]).addClass(self.options.anim[1])
.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
self.$el.remove()
})
} else {
self.$el.removeClass('xc-dialog-open').addClass('xc-dialog-close')
xdContent.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
self.$el.remove()
})
}
self.options.end(self)
}
/*
* options
* title 标题
* content 内容
* time 持续时间
* anim 动画效果 0-5 或者 使用animated ['in','out']
* open 打开回调
* end 关闭回调
* confirm 确定回调
* cancel 取消回调
* */
$.DialogFx = {
anim: ['susan', 'sandra', 'don', 'ken', 'alex'],
init: function(options) {
var animArr = $.DialogFx.anim;
if(typeof options == 'string') {
options = {
content: options
}
}
var opt = $.extend(true, {
title: '提示',
time: 1500,
content: '提示内容',
anim: 2,
open: function() {
return false;
},
end: function() {
return false;
},
confirm: function() {
return false;
},
cancel: function() {
return false;
}
}, options);
var xdialogAnim = '';
var xdContetAnim = '';
if($.isArray(opt.anim)) {
xdContetAnim = 'animated ' + opt.anim[0]
} else {
if(opt.anim >= animArr.length) {
console.error('DialogFx:没有找到的动画效果')
return false;
} else {
xdialogAnim = 'xc-dialog-' + animArr[opt.anim]
}
}
return {
opt: opt,
xdialogAnim: xdialogAnim,
xdContetAnim: xdContetAnim
}
}
};
$.DialogFx.msg = function(options) {
var newOpt = $.DialogFx.init(options);
var html = [];
html.push('<div class="xc-dialog ' + newOpt.xdialogAnim + ' ">')
html.push('<div class="xc-dialog-overlay"></div>')
html.push('<div class="xc-dialog-content ' + newOpt.xdContetAnim + ' ">')
html.push('<div class="am-modal-dialog">');
html.push('<div class="am-modal-bd">' + newOpt.opt.content + '</div>');
html.push('</div>');
html.push('</div>')
html.push('</div>')
var dialog = new DialogFx($(html.join('')).appendTo('body'), newOpt.opt);
setTimeout(function(){
dialog.close()
}, newOpt.opt.time)
return dialog;
}
$.DialogFx.alert = function(options) {
var newOpt = $.DialogFx.init(options);
var html = [];
html.push('<div class="xc-dialog ' + newOpt.xdialogAnim + ' ">')
html.push('<div class="xc-dialog-overlay"></div>')
html.push('<div class="xc-dialog-content ' + newOpt.xdContetAnim + ' ">')
html.push('<div class="am-modal-dialog">');
// html.push('<div class="am-modal-hd">' + newOpt.opt.title + '</div>');
html.push('<div class="am-modal-bd">' + newOpt.opt.content + '</div>');
html.push('<div class="am-modal-footer"><span class="am-modal-btn" data-dialog-confirm>确定</span></div>');
html.push('</div>');
html.push('</div>')
html.push('</div>')
return new DialogFx($(html.join('')).appendTo('body'), newOpt.opt)
}
$.DialogFx.confirm = function(options) {
var newOpt = $.DialogFx.init(options);
var html = [];
html.push('<div class="xc-dialog ' + newOpt.xdialogAnim + ' ">')
html.push('<div class="xc-dialog-overlay"></div>')
html.push('<div class="xc-dialog-content ' + newOpt.xdContetAnim + ' ">')
html.push('<div class="am-modal-dialog">');
// html.push('<div class="am-modal-hd">' + newOpt.opt.title + '</div>');
html.push('<div class="am-modal-bd">' + newOpt.opt.content + '</div>');
html.push('<div class="am-modal-footer">');
html.push('<span class="am-modal-btn" data-dialog-cancel>取消</span>');
html.push('<span class="am-modal-btn" data-dialog-confirm>确定</span>');
html.push('</div>');
html.push('</div>')
html.push('</div>')
return new DialogFx($(html.join('')).appendTo('body'), newOpt.opt)
};
$.DialogFx.alertError = function(txt, url) {
$.DialogFx.alert({content: txt || '服务器内部错误', end:function(){
if(url == 'login'){
window.location.href = '../component/login.html';
}else{
$.xuncheng.back()
}
}})
}
});
$(function() {
var $videoBox = $('#xc-video-box');
var $videoPlay = $videoBox.children('.xc-video-play');
var $video = $videoBox.children('.xc-video');
var _video = $video[0];
$videoBox.on('click', function() {
_video.play()
});
$video.on('playing', function() {
$videoBox.addClass('play')
})
})<file_sep># 小鹿寻城
## 访问
># 复制连接,使用移动设备打开
http://m.xunchengweidao.com/xuncheng/
| 26175d4eddb17e1de66f7df9204737514ee074f7 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | topoadmin/xuncheng | 7404d2ddfdf12e000651a10679f8153b981e7a3b | 62736d59aa1c9d0b8163e29c21b307b10a421e3a |
refs/heads/master | <file_sep>---
prev: ch11-项目风险管理.md
next: ch13-项目相关方管理.md
---
# 12.项目采购管理
<a data-fancybox title="12.项目采购管理" href="img/12.png"></a>
## 概述
### 核心概念
#### 项目采购管理包括从项目外部采购或获取所需产品、服务或成果的各个过程
#### 项目采购管理过程涉及到用协议来描述买卖双方之间的关系
#### 协议可以是合同、服务水平协议(SLA)、谅解备忘录、协议备忘录(MOA)或订购单
#### 合同应明确说明预期的可交付成果和结果,包括从卖方到买方的任何知识转移
#### 本节假设项目所需物品或服务的买方是项目团队,卖方是项目提供物品或服务的一方,通常来自执行组织外部
### 趋势和新兴实践
#### 工具的改进
#### 更先进的风险管理
#### 变化中的合同简述实践
#### 物流和供应链管理
#### 技术和相关方关系
#### 试用采购
### 裁剪
#### 采购的复杂性
#### 物理地点
#### 治理和法规环境
#### 承包商的可用性
## 12.1规划采购管理
### 定义
#### 是记录项目采购决策、明确采购方法,以及识别潜在卖方的过程
### 作用
#### 确定是否从项目外部获取货物和服务,如果是,则还要确定将在什么时间、以什么方式获取什么货物和服务
### 仅开展一次或仅在项目的预定义点开展
### 输入
#### 项目章程
#### 商业文件
##### 商业论证
##### 效益管理计划
#### 项目管理计划
##### 范围管理计划
##### 质量管理计划
##### 资源管理计划
##### 范围基准
#### 项目文件
##### 里程碑清单
##### 项目团队派工单
##### 需求文件
##### 需求跟踪矩阵
##### 资源需求
##### 风险登记册
##### 相关方登记册
#### 事业环境因素
#### 组织过程资产
##### 预先批准的卖方清单
##### 正式的采购政策、程序和指南
##### 合同类型
###### 总价合同
####### 明确定义需求,且不会出现重大范围变更的情况下使用
####### 类型
######## 固定总价(FFP)
######## 总价加激励费用(FPIF)
######## 总价加经济价格调整(FPEPA)
###### 成本补偿合同
####### 工作范围预计会在合同执行期间发生重大变更
####### 类型
######## 成本加固定费用(CPFF)
######## 成本加激励费用(CPIF)
######### 成本低于或高于原始估算成本,分享节约或超值的部分
######### 2/8原则
######## 成本加奖励费用(CPAF)
###### 工料合同
####### 无法快速编制出准确的工作说明书的情况下扩充人员、聘用专家或寻求外部支持
### 工具与技术
#### 专家判断
#### 数据收集
##### 市场调研
#### 数据分析
##### 自制或外购分析
#### 供方选择分析
##### 最低成本
##### 仅凭资质
##### 基于质量或技术方案得分
##### 基于质量和成本
##### 独有来源
##### 固定预算
#### 会议
### 输出
#### 采购管理计划
#### 采购策略
##### 交付方法
##### 合同支付类型
##### 采购阶段
#### 招标文件
##### 信息邀请书(RFI)
##### 报价邀请书(RFQ)
##### 建议邀请书(RFP)
#### 采购工作说明书
#### 供方选择标准
#### 自制或外购决策
#### 独立成本估算
#### 变更请求
#### 项目文件更新
##### 经验教训登记册
##### 里程碑清单
##### 需求文件
##### 需求跟踪矩阵
##### 风险登记册
##### 相关方登记册
#### 组织过程资产更新
## 12.2实施采购
### 定义
#### 是获取卖方应答、选择卖方并授予合同的过程
### 作用
#### 选定合格卖方并签署关于货物或服务交付的法律协议
### 整个项目定期开展
### 输入
#### 项目管理计划
##### 范围管理计划
##### 需求管理计划
##### 沟通管理计划
##### 风险管理计划
##### 采购管理计划
##### 配置管理计划
##### 成本基准
#### 项目文件
##### 经验教训登记册
##### 项目进度计划
##### 需求文件
##### 风险登记册
##### 相关方登记册
#### 采购文档
#### 卖方建议书
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 广告
#### 招标人会议
#### 数据分析
##### 建议书评价
#### 人际关系与团队技能
##### 谈判
###### 应由采购团队中拥有合同签署职权的成员主导
###### 项目经理和项目管理团队的其他成员可以参加谈判并提供必要的协助
### 输出
#### 投标人会议
#### 协议
#### 变更请求
#### 项目管理计划更新
##### 需求管理计划
##### 质量管理计划
##### 沟通管理计划
##### 风险管理计划
##### 采购管理计划
##### 范围基准
##### 进度基准
##### 成本基准
#### 项目文件更新
##### 经验教训登记册
##### 需求文件
##### 需求跟踪矩阵
##### 资源日历
##### 风险登记册
##### 相关方登记册
#### 组织过程资产更新
## 12.3控制采购
### 定义
#### 是管理采购关系,监督合同绩效,实施必要的变更和纠偏
### 作用
#### 确保买卖双方旅行法律协议,满足项目需求
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 需求管理计划
##### 风险管理计划
##### 采购管理计划
##### 变更管理计划
##### 进度基准
#### 项目文件
##### 假设日志
##### 经验教训登记册
##### 里程碑清单
##### 质量报告
##### 需求文件
##### 需求跟踪矩阵
##### 风险登记册
##### 相关方登记册
#### 协议
#### 采购文档
#### 批准的变更请求
#### 工作绩效数据
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 索赔管理
##### 谈判是解决所有索赔和争议的首选方法
#### 数据分析
##### 绩效审查
##### 挣值分析
##### 趋势分析
#### 检查
#### 审计
### 输出
#### 采购关闭
##### 正式书面通知
#### 工作绩效信息
#### 采购文档更新
#### 变更请求
#### 项目管理计划更新
##### 风险管理计划
##### 采购管理计划
##### 进度基准
##### 成本基准
#### 项目文件更新
##### 经验教训登记册
##### 资源需求
##### 需求跟踪矩阵
##### 风险登记册
##### 相关方登记册
#### 组织过程资产更新
<file_sep>---
prev: false
next: /ch2-项目运行环境
---
# 1. 引论
## 1.1 指南概述和目的
* 本《PMBOK》指收录项目管理知识体系中被**普遍认可**为“良好实践”的那一部分。
* 本《PMBOK指南》与方法论有所不同。
* 方法论是由专门的从业人员所采用的实践、技术、程序和规则所组成的体系。
### 1.1.1 项目管理标准
* 标准是基于权威、惯例或共识而建立并用作模式或范例的文件。
* 《项目管理标准》是PMI项目管理专业发展计划和项目管理实践的基本参考资料。
* 项目管理标准是《项目管理知识体系指南》(PMBOK指南)的第二部分。
### 1.1.2 通用词汇
* 《PMI项目管理术语词典》[4]收录了基本的专业词汇,供组织、项目组合、项目集和项目经理及其他项目相关方统一使用。
### 1.1.3 道德与专业行为规范
* 全球项目管理业界定义的最重要的价值观是责任、尊重、公正和诚实。《道德与专业行为规范》确立了这四个价值观的基础地位。
* 《道德与专业行为规范》包括期望标准和强制标准。
* 身为**PMI会员、证书持有者或志愿者的从业者**,如果不依照这些标准行事,将受到**PMI道德审查委员会**的纪律处罚。
## 1.2 基本要素
### 1.2.1 项目
* 项目是为创造独特的产品、服务或成果而进行的临时性工作。
* 独特的产品、服务或成果。 可交付成果指的是在某一过程、阶段或项目完成时,必须产出的任何独特并可核实的产品、成果或服务能力。可交付成果可能是有形的,也可能是无形的。
* 临时性工作。
* 项目的“临时性”是指项目有明确的起点和终点。“临时性”并不一定意味着项目的持续时间短。
* 虽然项目是临时性的工作,但其可交付成果可能会在项目的终止后依然存在。
* 项目驱动变革。
* 从商业角度来看,项目旨在推动组织从一个状态转到另一个状态,从而达成特定目标。
* 项目创造商业价值。
* 商业价值被视为回报。
* 项目带来的效益可以是有形的、无形的或两者兼有之。
* 项目启动背景。
* 符合法规、法律或社会要求。
* 满足相关方的要求或需求。
* 执行、变更业务或技术战略。
* 创造、改进或修复产品、过程或服务。
### 1.2.2 项目管理的重要性
* 项目管理就是将知识、技能、工具与技术应用于项目活动,以满足项目的要求。
### 1.2.3 项目、项目集、项目组合以及运营管理之间的关系
#### 1.2.3.1 概述
* 项目集是一组相互关联且被协调管理的项目、子项目集和项目集活动,以便获得分别管理所无法获得的利益。
* 项目组合是指为实现战略目标而组合在一起管理的项目、项目集、子项目组合和运营工作。
#### 1.2.3.2 项目集管理
* 项目集管理注重项目与项目以及项目项目与项目集之间的依赖关系,以确定管理这些项目的最佳时间。
#### 1.2.3.3 项目组合管理
* 项目组合是指为实现战略目标而组合在一起管理的项目、项目集、子项目组合和运营工作。
* 项目组合管理是指为了实现战略目标而对一个或多个项目组合进行的集中管理。项目组合中的项目集或项目不一定彼此依赖或直接相关。
#### 1.2.3.4 运营管理
#### 1.2.3.5 运营与项目管理
* 项目与运营会在产品生命周期的不同时点交叉。
#### 1.2.3.6 组织级项目管理(OPM)和战略
### 1.2.4 指南的组成部分
#### 1.2.4.1 项目和开发生命周期
* 项目生命周期指项目从启动到完成开始到结束所经历的一系列阶段。
#### 1.2.4.2 项目阶段
* 项目阶段是一组具有逻辑关系的项目活动的集合,通常以一个或多个可交付成果的完成为结束。
* 项目可以分解为不同的阶段或子组件。
#### 1.2.4.3 阶段关口
* 阶段关口可能被称为阶段审查、阶段门、关键决策点和阶段入口或阶段出口。
#### 1.2.4.4 项目管理过程
* 每个项目管理过程通过合适的项目管理工具和技术将一个或多个输入转化成一个或多个输出。
#### 1.2.4.5 项目管理过程组
* 过程组不同于项目阶段。
* 项目管理过程组划分
* 启动过程组
* 规划过程组
* 执行过程组
* 监控过程组
* 收尾过程组
#### 1.2.4.6 项目管理知识领域
* 知识领域指按所需知识内容来定义的项目管理领域,并用其所含过程、实践、输入、输出、工具和技术进行描述。
* 十大知识领域
* 项目整合管理
* 项目范围管理
* 项目进度管理
* 项目成本管理
* 项目质量管理
* 项目资源管理
* 项目沟通管理
* 项目风险管理
* 项目采购管理
* 项目相关方管理
#### 1.2.4.7 项目管理数据和信息
* 工作绩效数据。
在执行项目工作的过程中,从每个正在执行的活动中收集到的**原始观察结果和测量值**。
* 工作绩效信息。
从各控制过程收集,并结合相关背景和跨领域关系**进行整合分析而得到的**绩效数据。
* 工作绩效报告。
为制定决策、提出问题、采取行动或引起关注,而**汇编工作绩效信息所形成的实物或电子项目文件**。
### 1.2.5 剪裁
* 项目经理与项目团队、发起人或组织管理层合作进行剪裁。
### 1.2.6 项目管理商业文件
* 项目发起人通常负责项目商业论证文件的制定和维护。
* 项目经理负责提供建议和见解,使项目商业论证、项目管理计划、项目章程和项目效益管理计划中的成功标准相一致,并与组织的目的和目标保持一致。
#### 1.2.6.1 项目商业论证
* 项目商业论证指文档化的经济可行性研究报告。
* 商业论证列出了项目启动的目标和理由。
* 有助于在项目结束时根据项目目标衡量项目是否成功。
#### 1.2.6.2 项目效益管理计划
* 项目效益管理计划描述了项目实现效益的方式和时间,以及制定的效益衡量机制。
#### 1.2.6.3 项目章程和项目管理计划
#### 1.2.6.4 项目成功标准
<file_sep>---
prev: ch4-项目整合管理.md
next: ch6-项目进度管理.md
---
# 5.项目范围管理
<a data-fancybox title="5.项目范围管理" href="img/5.png"></a>
## 概述
### 定义和控制哪儿些工作应该包含在项目内,哪儿些不应该包括再项目内
### 范围
#### 产品范围
##### 某项产品、服务或成果具有的特征和功能
#### 项目范围
##### 为交付具有规定特性与功能的产品、服务或成果而必须完成的工作。项目范围有时也包括产品范围
#### 项目范围的完成情况是根据项目管理计划来衡量的,而产品范围完成情况是根据产品需求来衡量的。
#### 确认范围是正式验收已完成的项目可交付成果的过程。
### 发展趋势和新兴实践
#### 需求管理过程结束于需求关闭
### 剪裁
#### 知识和需求管理
#### 确认和控制
#### 开发方法
#### 需求的稳定性
#### 治理
## 5.1规划范围管理
### 定义
#### 为记录如何定义、确认和控制项目范围及产品范围,而创建范围管理计划的过程。
### 作用
#### 在整个项目期间对如何管理范围提供指南和方向
### 仅开展一次或仅在项目的预定义点开展
### 输入
#### 项目章程
#### 项目管理计划
##### 质量管理计划
##### 项目生命周期描述
##### 开发方法
#### 事业环境因素
#### 组织过程资产
### 工具和技术
#### 专家判断
#### 数据分析
#### 会议
### 输出
#### 范围管理计划
##### 制定项目范围说明书
##### 根据详细项目范围说明书创建WBS
##### 确定如何审批和维护范围基准
##### 正式验收已完成的项目可交付成果
#### 需求管理计划
##### 如何规划、跟踪和报告各种需求活动
##### 配置管理活动
##### 需求优先级排序
##### 测量指标
##### 跟踪结构
## 5.2收集需求
### 定义
#### 为实现目标而确定、记录并管理相关方的需要和需求的过程
### 作用
#### 为定义产品范围和项目范围奠定基础
### 仅开展一次或仅在项目预定义点开展
### 输入
#### 项目章程
#### 项目管理计划
##### 范围管理计划
##### 需求管理计划
##### 相关方参与计划
#### 项目文件
##### 假设日志
##### 经验教训登记册
##### 相关方登记册
#### 商业文件
#### 协议
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据收集
##### 头脑风暴
##### 访谈
##### 焦点小组
##### 问卷调查
##### 标杆对照
#### 数据分析
##### 文件分析
#### 决策
##### 投票
##### 独裁型决策制定
##### 多标准决策分析
#### 数据表现
##### 亲和图
##### 思维导图
#### 人际关系与团队技能
##### 名义小组技术
##### 观察和交谈
##### 引导
#### 系统交互图
#### 原型法
### 输出
#### 需求文件
##### 业务需求
##### 相关方需求
##### 解决方案需求
###### 功能需求
###### 非功能需求
##### 过渡和就绪需求
##### 项目需求
##### 质量需求
#### 需求跟踪矩阵
##### 业务需要、机会、目的和目标
##### 项目目标
##### 项目范围和WBS可交付成果
##### 产品设计
##### 产品开发
##### 测试策略和测试场景
##### 高层级需求到详细需求
## 5.3定义范围
### 定义
#### 制定项目和产品详细描述的过程
### 作用
#### 描述产品、服务或成果的边界和验收标准
### 输入
#### 项目章程
#### 项目管理计划
#### 项目文件
##### 假设日志
##### 需求文件
##### 风险登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据分析
##### 备选方案分析
#### 决策
##### 多标准决策分析
#### 人际关系与团队技能
#### 产品分析
### 输出
#### 项目范围说明书
##### 产品范围描述
##### 可交付成果
##### 验收标准
##### 项目的除外责任
#### 项目文件更新
##### 假设日志
##### 需求文件
##### 需求跟踪矩阵
##### 相关方登记册
## 5.4创建WBS
### 定义
#### 把项目可交付成果和项目工作分解成较小、更容易管理的组件的过程
### 作用
#### 为所要交付的内容提供架构
### 开展一次或仅在项目预定义点开展
### 输入
#### 项目管理计划
#### 项目文件
##### 项目范围说明书
##### 需求文件
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 分解
### 输出
#### 范围基准
##### 项目范围说明书
##### WBS
##### 工作包
##### 规划包
##### WBS词典
#### 项目文件更新
##### 假设日志
##### 需求文件
## 5.5确认范围
### 定义
#### 正式验收已完成的项目可交付成果的过程
### 作用
#### 验收过程客观性、提高获得验收的可能性
### 整个项目期间定期开展
### 输入
#### 项目管理计划
##### 范围管理计划
##### 需求管理计划
##### 范围基准
#### 项目文件
##### 经验教训登记册
##### 质量报告
##### 需求文件
##### 需求跟踪矩阵
#### 核实的可交付成果
#### 工作绩效数据
### 工具与技术
#### 检查
#### 决策
### 输出
#### 验收的可交付成果
#### 工作绩效信息
#### 变更请求
#### 项目文件更新
##### 经验教训登记册
##### 需求跟踪矩阵
##### 需求文件
## 5.6 控制范围
### 定义
#### 监督项目和产品的范围状态、管理范围基准变更的过程
### 作用
#### 对范围基准的维护
### 在整个项目期间展开
### 输入
#### 项目管理计划
##### 范围管理计划
##### 变更管理计划
##### 需求管理计划
##### 配置管理计划
##### 范围基准
##### 绩效测量基准
#### 项目文件
##### 经验教训登记册
##### 需求文件
##### 需求跟踪矩阵
#### 工作绩效数据
#### 组织过程资产
### 工具与技术
#### 数据分析
##### 偏差分析
##### 趋势分析
### 输出
#### 工作绩效数据
#### 变更请求
#### 项目管理计划更新
##### 范围管理计划
##### 范围基准
##### 进度基准
##### 成本基准
##### 绩效测量基准
#### 项目文件更新
##### 经验教训登记册
##### 需求文件
##### 需求跟踪矩阵
<file_sep>---
prev: ch5-项目范围管理.md
next: ch7-项目成本管理.md
---
# 6.项目进度管理
<a data-fancybox title="6.项目进度管理" href="img/6.png"></a>
## 概述
### 核心概念
#### 项目管理团队选择进度计划方法,例如关键路径法或敏捷方法
### 趋势和新兴实践
#### 具有未完项的迭代型进度计划
#### 按需进行计划
### 裁剪
#### 生命周期方法
#### 资源可用性
#### 项目维度
#### 技术支持
## 6.1规划进度管理
### 定义
#### 为规划、编制、管理、执行和控制项目进度而制定政策、程序和文档的过程
### 作用
#### 提供指南和方向
### 仅开展一次或仅在项目预定义节点开展
### 输入
#### 项目章程
#### 项目管理计划
##### 范围管理计划
##### 开发方法
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据分析
##### 备选方案分析
#### 会议
### 输出
#### 进度管理计划
##### 项目进度模型制定
##### 进度计划的发布和迭代长度
##### 准确度
##### 计量单位
##### 组织程序链接
##### 项目君度模型维护
##### 控制临界值
##### 绩效测量规则
##### 报告格式
## 6.2定义活动
### 定义
#### 识别和记录为完成项目可交付成果而采取的具体行动的过程
### 作用
#### 将工作包分解为进度活动,作为对项目工作进行君度估算、规划、执行、监督和控制的基础
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 进度管理计划
##### 范围基准
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 分解
##### 把项目范围和项目可交付成果逐步划分为更小、更便于管理的组成部分的技术
#### 滚动式规划
##### 是一种迭代式的规划技术,即详细规划近期要完成的工作,同时在较高层级上粗略规划远期工作。它是一种渐进明细的规划方式。
#### 会议
### 输出
#### 活动清单
#### 活动属性
#### 里程碑清单
#### 变更请求
#### 项目管理计划更新
##### 进度基准
##### 成本基准
## 6.3排列活动顺序
### 定义
#### 识别和记录项目活动之间的关系的过程
### 作用
#### 定义工作之间的逻辑顺序,提高效率
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 进度管理计划
##### 范围基准
#### 项目文件
##### 活动属性
##### 活动清单
##### 假设日志
##### 里程碑清单
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 紧前关系绘图法(PDM)
#### 确定和整合依赖关系
##### 强制性依赖关系
###### 法律或合同要求的或工作的内在性质决定的依赖关系,往往与客观限制有关
##### 选择性依赖关系
###### 首先逻辑关系、优先逻辑关系或软逻辑关系
##### 外部依赖关系
###### 项目活动与非项目活动之间的依赖关系
##### 内部依赖关系
###### 项目活动之间的紧前关系
#### 提前量与滞后量
#### 项目管理信息系统(PMIS)
### 输出
#### 项目进度网络图
##### 表示项目进度活动之间的逻辑关系(也叫依赖关系)的图形
#### 项目文件更新
##### 活动属性
##### 活动清单
##### 假设日志
##### 里程碑清单
## 6.4估算活动持续时间
### 定义
#### 是根据资源估算的结果,估算完成单项活动所需工作时段数的过程
### 作用
#### 确定完成每个活动所需花费的时间量
### 在整个项目期间开展
### 输入
#### 项目管理计划
##### 进度管理计划
##### 范围基准
#### 项目文件
##### 活动属性
##### 活动清单
##### 假设日志
##### 经验教训登记册
##### 里程碑清单
##### 项目团队派工单
##### 资源分解结构
##### 资源日历
##### 资源需求
##### 风险登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 类比估算
#### 参数估算
#### 三点估算
#### 自下而上估算
#### 数据分析
##### 备选方案分析
##### 储备分析
#### 决策
#### 会议
### 输出
#### 持续时间估算
#### 估算依据
#### 项目文件更新
##### 活动属性
##### 假设日志
##### 经验教训登记册
## 6.5 制定进度计划
### 定义
#### 分析活动顺序、持续时间、资源需求和进度制约因素,创建进度模型,从而落实项目执行和监控的过程
### 作用
#### 为完成项目活动而制定具有计划日期的进度模型
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 进度管理计划
##### 范围基准
#### 项目文件
##### 活动属性
##### 活动清单
##### 假设日志
##### 估算依据
##### 持续时间估算
##### 经验教训登记册
##### 里程碑清单
##### 项目进度网络图
##### 项目团队派工单
##### 资源日历
##### 资源需求
##### 风险登记册
#### 协议
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 进度网络分析
#### 关键路径法
#### 资源优化
##### 资源平衡
###### 导致关键路径改变
##### 资源平滑
###### 不会改变项目关键路径
#### 数据分析
##### 假设情景分析
##### 模拟
###### 蒙特卡罗分析
#### 提前量和滞后量
#### 进度压缩
##### 赶工
###### 增加资源,以最小的成本代价来压缩进度工期
##### 快速跟进
###### 将正常情况下按顺序进行的活动或阶段改为至少是部分并行开展
#### 项目管理信息系统
#### 敏捷发布规划
### 输出
#### 进度基准
#### 项目进度计划
##### 横道图(甘特图)
##### 里程碑图
##### 项目进度网络图(纯逻辑图)
#### 进度数据
#### 项目日历
##### 规定可以开展进度活动的可用工作日和工作班次
#### 变更请求
#### 项目管理计划更新
##### 进度管理计划
##### 成本基准
#### 项目文件更新
##### 活动属性
##### 假设日志
##### 持续时间估算
##### 经验教训登记册
##### 资源需求
##### 风险登记册
## 6.6 控制进度
### 定义
#### 控制进度是监督项目状态,以更新项目进度和管理进度基准变更的过程
### 作用
#### 在整个项目期间保持对进度基准的维护
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 进度管理计划
##### 进度基准
##### 范围基准
##### 绩效测量基准
#### 项目文件
##### 经验教训登记册
##### 项目日历
##### 项目进度计划
##### 资源日历
##### 进度数据
#### 工作绩效数据
#### 组织过程资产
### 工具与技术
#### 数据分析
##### 挣值分析
##### 迭代燃尽图
##### 绩效审查
##### 趋势分析
##### 偏差分析
##### 假设情景分析
#### 关键路径法
#### 项目管理信息系统
#### 资源优化
#### 提前量和滞后量
#### 进度压缩
### 输出
#### 工作绩效信息
#### 进度预测
#### 变更请求
#### 项目管理计划更新
##### 进度管理计划
##### 进度基准
##### 成本基准
##### 绩效测量基准
#### 项目文件更新
##### 假设日志
##### 估算依据
##### 经验教训登记册
##### 项目进度计划
##### 资源日历
##### 风险登记册
##### 进度数据
<file_sep>---
prev: ch12-项目采购管理.md
---
# 13.项目相关方管理
<a data-fancybox title="13.项目相关方管理" href="img/13.png"></a>
## 概述
### 核心概念
#### 每个项目都有相关方,他们会受项目的积极或消极影响,或者能对项目施加积极或消极的影响
#### 重视与所有相关方保持持续沟通(包括团队成员),以理解他们的需求和期望、处理所发生的问题、管理利益冲突,并促进相关方参与项目决策和活动
### 趋势和新兴实践
### 裁剪
#### 相关方多样性
#### 相关方关系的复杂性
#### 沟通技术
## 13.1识别相关方
### 定义
#### 是定期识别项目相关方,分析和记录他们的利益、参与度、相互依赖性、影响力和对项目成功的潜在影响的过程
### 作用
#### 使项目团队能够建立对每个相关方或相关群体的适度关注
### 整个项目期间定期开展
### 输入
#### 项目章程
#### 商业文件
##### 商业论证
##### 效益管理计划
#### 项目管理计划
##### 沟通管理计划
##### 相关方参与计划
#### 项目文件
##### 变更日志
##### 问题日志
##### 需求文件
#### 协议
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据收集
##### 问卷调查
##### 头脑风暴
#### 数据分析
##### 相关方分析
##### 文件分析
#### 数据表现
##### 权力利益方格、权力影响方格或作用影响方格
##### 相关方立方体
##### 凸显模型
##### 影响方向
###### 向上
###### 向下
###### 向外
###### 横向
##### 优先级排序
#### 会议
### 输出
#### 相关方登记册
##### 身份信息
##### 评估信息
##### 相关方分类
#### 变更请求
#### 项目管理计划更新
##### 需求管理计划
##### 沟通管理计划
##### 风险管理计划
##### 相关方管理计划
#### 项目文件更新
##### 假设日志
##### 问题日志
##### 风险登记册
## 13.2规划相关方参与
### 定义
#### 是根据相关方的需求、期望、利益和对项目的潜在影响,制定项目相关方参与项目的方法的过程
### 作用
#### 提供与相关方进行有效互动的可行计划
### 整个项目期间定期开展
### 输入
#### 项目章程
#### 项目管理计划
##### 资源管理计划
##### 沟通管理计划
##### 风险管理计划
#### 项目文件
##### 假设日志
##### 变更日志
##### 问题日志
##### 项目进度计划
##### 风险登记册
##### 相关方登记册
#### 协议
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据收集
##### 标杆对照
#### 数据分析
##### 假设条件和制约因素分析
##### 根本原因分析
#### 决策
##### 优先级排序/分级
#### 数据表现
##### 思维导图
##### 相关方参与度评估矩阵
###### 不了解型
###### 抵制型
###### 中立型
###### 支持型
###### 领导型
#### 会议
### 输出
#### 相关方参与计划
## 13.3管理相关方参与
### 定义
#### 是与相关方进行沟通和协作以满足其需求预期望、处理问题,并促进相关方合理参与的过程
### 作用
#### 让项目经理能够提高相关方的支持,并尽可能降低相关方的抵制
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 沟通管理计划
##### 风险管理计划
##### 相关方管理计划
##### 变更管理计划
#### 项目文件
##### 变更日志
##### 问题日志
##### 经验教训登记册
##### 相关方登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 沟通技能
##### 反馈
#### 人际关系与团队技能
##### 冲突管理
##### 文化意识
##### 谈判
##### 观察/交谈
##### 政治意识
#### 基本原则
#### 会议
### 输出
#### 变更请求
#### 项目管理计划更新
##### 沟通管理计划
##### 相关方参与计划
#### 项目文件更新
##### 变更日志
##### 问题日志
##### 经验教训登记册
##### 相关方登记册
## 13.4监督相关方参与
### 定义
#### 是监督项目相关方关系,并通过修订参与策略和计划来引导相关方合理参与项目的过程
### 作用
#### 随着项目进展和环境变化,维持或提升相关方参与活动的效率和效果
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 资源管理计划
##### 沟通管理计划
##### 相关方管理计划
#### 项目文件
##### 问题日志
##### 经验教训登记册
##### 项目沟通记录
##### 风险登记册
##### 相关方登记册
#### 工作绩效数据
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 数据分析
##### 备选方案分析
##### 根本原因分析
##### 相关方分析
#### 决策
##### 多标准决策分析
##### 投票
#### 数据表现
##### 相关方参与度评估矩阵
#### 沟通技能
##### 反馈
##### 演示
#### 人际关系与团队技能
##### 积极倾听
##### 文化意识
##### 领导力
##### 人际交往
##### 政治意识
#### 会议
### 输出
#### 工作绩效信息
#### 变更请求
#### 项目管理计划更新
##### 资源管理计划
##### 沟通管理计划
##### 相关方参与计划
#### 项目文件更新
##### 问题日志
##### 经验教训登记册
##### 风险登记册
##### 相关方登记册
<file_sep>---
prev: 'ch2-项目运行环境'
next: 'ch3-项目经理的角色'
---
# 3 项目经理的角色
[[toc]]
## 3.1 概述
* 成员与角色
* 在团队中的职责
**项目经理和指挥都需要为团队的成果负责**
* 知识和技能
项目经理无需承担项目中每个角色,但应具备项目管理知识、技术知识、理解和经验。项目经理通过沟通领导项目团队进行规划和协调。
## 3.2 项目经理的定义
职能经理专注于对某个职能领域或业务部门的管理监督。
运营经理负责保证业务运行的高效性。
项目经理是由执行组织委派,领导团队实现项目目标的个人。
## 3.3 项目经理的影响力范围
### 3.3.1 概述
### 3.3.2 项目
项目经理使用软技能(例如人际关系技能和人员管理技能)来平衡项目相关方之间相互冲突和竞争的目标,以达成共识。
沟通的能力,包括(但不限于)以下各个方面:
* 通过多种方法(例如口头、书面和非口头)培养完善的技能;
* 创建、维护和遵循沟通计划和进度计划;
* 以可遇见且一致的方式进行沟通;
* 寻求了解项目相关方的沟通需求;
* 以简练、清晰、完整、简单、相关和经过裁剪的方式进行沟通;
* 包含重要的正面和负面消息;
* 合并反馈渠道;
* 人际关系技能。即通过项目经理的影响力范围拓展广泛的人际网络。
### 3.3.3 组织
项目经理需要积极地与其他项目经理互动。
其他独立项目或同一项目集的其他项目可能会对项目造成影响,原因包括:
* 对相同资源的需求
* 资金分配的优先顺序
* 可交付陈国的接受或发布;
* 项目与组织的目的和目标一致性;
### 3.3.4 行业
* 产品和技术开发
* 新兴且正在变化的市场空间;
* 标准
* 技术支持工具
* 影响当前项目的经济力量
* 影响项目管理学科的各种力量
* 过程改进和可持续发展战略
### 3.3.5 专业学科
知识传递和整合包括(但不限于):
* 在当地、全国和全球层面(例如实践社区、国际组织)向其他专业人员分享知识和专业技能。
* 参与培训、继续教育和发展:
- 项目管理管理专业
- 相关专业
- 其他专业
### 3.3.6 跨学科领域
## 3.4 项目经理的胜任力
### 3.4.1 概述
PMI人才三角重点关注三个关键技能组合:
* 技术项目管理
* 领导力
* 战略和商务管理
项目经理需要平衡这三种技能。
### 3.4.2 技术项目管理技能
关键项目管理技能,包括(但不限于):
* 重点关注所管理的各个项目的关键技术项目管理要素。简单来说,就是随时准备好合适的资料,最主要的是:
- 项目成功的关键因素。
- 进度计划;
- 指定的财务报告;
- 问题日志。
* 针对每个项目剪裁传统和敏捷工具、技术和方法。
* 花时间制定完整的计划并谨慎排定优先顺序。
* 管理项目要素,包括(但不限于)进度、成本、资源和风险。
### 3.4.3 战略和商务管理技能
战略和商务管理技能包括总览组织概况并有效协商和执行有利于战略调整和创新的决策和行动的能力。战略和商务管理技能可能还包括发展和运用相关的产品和行业专业知识。这种业务知识也被称为领域知识。
### 3.4.4 领导力技能
领导力技能包括指导、激励和带领团队的能力。人是所有项目中的共同点。
#### 3.4.4.1 人际交往
#### 3.4.4.2 领导者的品质和技能
#### 3.4.4.3 政治、权力和办好事情
领导和管理的最终目的是办好事情。
政治涉及影响、谈判、自主和权力。
### 3.4.5 领导力和管理之比较
“管理”更接近于指挥一个人采取已知的预期行动从一个位置到另一个位置。相反,“领导力”指通过讨论或辩论与他人合作,带领他们从一个位置到另一个位置。
#### 3.4.5.1 领导力风格
#### 3.4.5.2 个性
个性指人与人之间在思维、情感和行为的特征模式方面的差异。
## 3.5 执行整合
执行整合时,项目经理承担双重角色:
* 项目经理扮演重要角色,与项目发起人携手合作,来理解战略目标。
* 在项目层面上,项目经理负责指导团队关注真正重要的事务并协同工作。为此,项目经理需要整合过程、知识和人员。
### 3.5.1 在过程层面执行整合
项目管理可被看作为实现项目目标而采取的一系列过程和活动。
### 3.5.2 认知层面的整合
项目经理需要整合这些知识领域所涵盖的过程才有可能实现预期的项目结果。
### 3.5.3 背景层面的整合
### 3.5.4 整合与复杂性
复杂性的三个维度定义为:
* 系统行为。组成部分与系统之间的依赖关系。
* 人类行为。不同个体和群体之间的相互作用。
* 模糊性。出现问题、缺乏理解或困惑引发的不确定性。
<file_sep>---
prev: ch9-项目资源管理.md
next: ch11-项目风险管理.md
---
# 10.项目沟通管理
<a data-fancybox title="10.项目沟通管理" href="img/10.png"></a>
## 概述
### 组成部分
#### 制定策略,确保沟通对相关方行之有效
#### 执行必要活动,以落实沟通策略
### 核心概念
#### 沟通指有意或无意的信息交换。
#### 信息交换可以是想法、指示或情绪
#### 信息交换方式
##### 书面形式
##### 口头形式
##### 正式或非正式
##### 手势动作
##### 媒体形式
##### 遣词造句
#### 沟通活动多维度分类
##### 内部
##### 外部
##### 正式
##### 非正式
##### 层级沟通
###### 向上沟通
###### 向下沟通
###### 横向沟通
##### 官方沟通
##### 非官方沟通
##### 书面与口头沟通
### 趋势和新兴实践
#### 将相关方纳入项目评审范围
#### 让相关方参加项目会议
#### 社交工具的使用日益增多
#### 多面性沟通方法
### 裁剪
#### 相关方
#### 物理地点
#### 沟通技术
#### 语音
#### 知识管理
## 10.1 规划沟通管理
### 定义
#### 时基于每个相关方或相关方群体的信息需求、可用的组织资产,以及具体项目的需求,为项目沟通活动制定恰当的方法和计划的过程
### 作用
#### 为及时向相关方提供相关信息,引导相关方有效参与项目,编制书面沟通计划
### 整个项目期间定期开展
### 输入
#### 项目章程
#### 项目管理计划
##### 资源管理计划
##### 相关方参与计划
#### 项目文件
##### 需求文件
##### 相关方登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 沟通需求分析
#### 沟通技术
#### 沟通模型
#### 沟通方法
##### 互动沟通
##### 推式沟通
##### 拉式沟通
#### 人际关系与团队技能
##### 沟通风格评估
###### 政治意识
###### 文化意识
##### 政治意识
##### 文化意识
#### 数据表现
##### 相关方参与度评估矩阵
#### 会议
### 输出
#### 沟通管理计划
#### 项目管理计划更新
##### 相关方参与计划
#### 项目文件更新
##### 相关方登记册
##### 项目进度计划
## 10.2 管理沟通
### 定义
#### 是确保项目信息及时且恰当地收集、生成、发布、存储、检索、管理、监督和最终处置的过程
### 作用
#### 促成项目团队与相关方之间的有效信息流动
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 资源管理计划
##### 沟通管理计划
##### 相关方参与计划
#### 项目文件
##### 变更日志
##### 问题日志
##### 经验教训登记册
##### 质量报告
##### 风险报告
##### 相关方登记册
#### 工作绩效报告
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 沟通技术
#### 沟通方法
#### 沟通技能
##### 沟通胜任力
##### 反馈
##### 非言语
##### 演示
#### 项目管理信息系统
#### 项目报告
#### 人际关系与团队技能
##### 积极倾听
##### 冲突管理
##### 文化意识
##### 会议管理
##### 人际交往
##### 政治意识
#### 会议
### 输出
#### 项目沟通记录
#### 项目管理计划更新
##### 沟通管理计划
##### 相关方参与计划
#### 项目文件更新
##### 问题日志
##### 经验教训登记册
##### 项目进度计划
##### 风险登记册
##### 相关方登记册
#### 组织过程资产更新
## 10.3监督沟通
### 定义
#### 是确保满足项目机器相关方的信息需求的过程
### 作用
#### 按沟通管理计划和相关方参与计划的要求优化信息传递过程
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 沟通管理计划
##### 资源管理计划
##### 相关方参与计划
#### 项目文件
##### 问题日志
##### 经验教训登记册
##### 项目沟通记录
#### 工作绩效数据
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 项目管理信息系统
#### 数据分析
##### 相关方参与度评估矩阵
#### 人际关系与团队技能
##### 观察/交谈
#### 会议
### 输出
#### 工作绩效信息
#### 变更请求
#### 项目管理计划更新
##### 沟通管理计划
##### 相关方参与计划
#### 项目文件更新
##### 问题日志
##### 经验教训登记册
##### 相关方登记册
<file_sep>---
prev: ch10-项目沟通管理.md
next: ch12-项目采购管理.md
---
# 11.项目风险管理
<a data-fancybox title="11.项目风险管理" href="img/11.png"></a>
## 概述
### 核心概念
#### 旨在识别和管理未被其他项目管理过程所管理的风险
#### 单个风险
##### 是一旦发生,会对一个或多个项目目标产生正面或负面影响的不确定事件或条件
#### 整体项目风险
##### 是不确定性对项目整体的影响,是相关方面临的项目结果正面和负面变异区间
### 趋势和新兴实践
#### 非事件类风险
##### 变异性风险
##### 模糊性风险
#### 项目韧性
#### 整合式风险管理
### 裁剪
#### 项目规模
#### 项目复杂性
#### 项目重要性
#### 开发方法
## 11.1规划风险管理
### 定义
#### 是定义如何实施项目风险管理活动的过程
### 作用
#### 确保风险管理的水平、方法和可见度与项目风险程度
### 仅开展一次或仅在项目的预定义点开展
### 输入
#### 项目章程
#### 项目管理计划
##### 所有组件
#### 项目文件
##### 相关方登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据分析
##### 相关方分析
#### 会议
### 输出
#### 风险管理计划
##### 风险管理战略
##### 方法论
##### 角色与职责
##### 资金
##### 时间安排
##### 风险类别
###### 风险分解结构(RBS)来构建风险类别
##### 相关方风险偏好
##### 风险概率和影响定义
##### 概率和影响矩阵
##### 报告格式
##### 跟踪
## 11.2识别风险
### 定义
#### 是识别单个项目风险以及整体项目风险的来源,并记录风险特征的过程
### 作用
#### 记录现有的单个项目风险,以及整体项目风险的来源
#### 汇集相关信息,以便项目团队能够恰当应对已识别的风险
### 在整个项目期间开展
### 鼓励所有项目相关方参与单个项目风险的识别工作
### 输入
#### 项目管理计划
##### 需求管理计划
##### 进度管理计划
##### 成本管理计划
##### 质量管理计划
##### 资源管理计划
##### 风险管理计划
##### 范围基准
##### 进度基准
##### 成本基准
#### 项目文件
##### 假设日志
##### 成本估算
##### 持续时间估算
##### 问题日志
##### 经验教训登记册
##### 需求文件
##### 资源需求
##### 相关方登记册
#### 协议
#### 采购文档
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据收集
##### 头脑风暴
##### 核对单
##### 访谈
#### 数据分析
##### 根本原因分析
##### 假设条件和制约因素分析
##### SWOT分析
##### 文件分析
#### 人际关系与团队技能
##### 引导
#### 提示清单
#### 会议
### 输出
#### 风险登记册
##### 已识别风险的清单
##### 潜在风险责任人
##### 潜在风险应对措施清单
#### 风险报告
#### 项目文件更新
##### 假设日志
##### 问题日志
##### 经验教训登记册
## 11.3实施定性风险分析
### 定义
#### 是通过评估单个项目风险发生的概率和影响以及其他特征,对风险进行优先级排序,从而为后续分析或行动提供基础的过程
### 作用
#### 重点关注高优先级的风险
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 风险管理计划
#### 项目文件
##### 假设日志
##### 风险登记册
##### 相关方登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据收集
##### 访谈
#### 数据分析
##### 风险数据质量评估
##### 风险概率和影响评估
##### 其他风险参数评估
#### 人际关系与团队技能
##### 引导
#### 风险分类
#### 数据表现
##### 概率和影响矩阵
##### 层级图
###### 气泡图
####### 两个以上参数对风险进行分类
####### 三维数据
#### 会议
### 输出
#### 项目文件更新
##### 假设日志
##### 问题日志
##### 风险登记册
##### 风险报告
## 11.4实施定量风险分析
### 定义
#### 是就已识别的单个项目风险和不确定性的其他来源对整体项目目标的影响进行定量分析的过程
### 作用
#### 量化整体项目风险敞口,并提供额外的定量风险信息,以支持风险应对规划
### 整个项目期间开展
### 并非所有项目都需要实施定量风险分析
### 定量风险分析也可以在规划风险应对过程之后开展,以分析已规划的应对措施对降低整体项目风险敞口的有效性
### 输入
#### 项目管理计划
##### 风险管理计划
##### 范围基准
##### 进度基准
##### 成本基准
#### 项目文件
##### 假设日志
##### 估算依据
##### 成本估算
##### 成本预测
##### 持续时间估算
##### 里程碑清单
##### 资源需求
##### 风险登记册
##### 风险报告
##### 进度预测
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据收集
##### 访谈
#### 人际关系与团队技能
##### 引导
#### 不确定性表现方式
#### 数据分析
##### 模拟
###### 蒙特卡洛分析
##### 敏感性分析
###### 龙卷风图
##### 决策树分析
###### 用不同的分支代表不同的决策或事件,即项目的备选路径
##### 影响图
### 输出
#### 项目文件更新
##### 风险报告
## 11.5规划风险应对
### 定义
#### 是为处理整体项目风险敞口,以及应对单个项目风险,而制定可选方案、选择应对策略并商定应对行动的过程
### 作用
#### 制定应对整体项目风险和单个项目风险的适当方法
#### 本过程还将分配资源,并根据需要将相关活动添加进项目文件和项目管理计划
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 资源管理计划
##### 风险管理计划
##### 成本基准
#### 项目文件
##### 经验教训登记册
##### 项目进度计划
##### 项目团队派工单
##### 资源日历
##### 风险登记册
##### 风险报告
##### 相关方登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据收集
##### 访谈
#### 人际关系与团队技能
##### 引导
#### 威胁应对策略
##### 上报
##### 规避
##### 转移
##### 减轻
##### 接受
#### 机会应对策略
##### 上报
##### 开拓
##### 分享
##### 提高
##### 接受
#### 应急应对策略
#### 整体项目风险应对策略
##### 规避
###### 整体项目风险有严重的负面影响
##### 开拓
###### 整体项目风险有显著的正面影响
##### 转移或分享
###### 整体项目风险的级别很高,组织无法有效加以硬度,就可能需要让第三方代表组织对风险进行管理
##### 减轻或提高
###### 涉及变更整体项目风险的级别,以优化实现项目目标的可能性
##### 接受
###### 整体项目风险已超出商定的临界值,如果无法针对整体项目风险采取主动的应对策略,组织可能选择继续按当前的定义推动项目进展
#### 数据分析
##### 备选方案分析
##### 成本效益分析
#### 决策
##### 多标准决策分析
### 输出
#### 变更请求
#### 项目管理计划更新
##### 进度管理计划
##### 成本管理计划
##### 质量管理计划
##### 资源管理计划
##### 采购管理计划
##### 范围基准
##### 进度基准
##### 成本基准
#### 项目文件更新
##### 假设日志
##### 成本预测
##### 经验教训登记册
##### 项目进度计划
##### 项目团队派工单
##### 风险登记册
##### 风险报告
## 11.6实施风险应对
### 定义
#### 是执行商定的风险应对计划的过程
### 作用
#### 确保按计划执行商定的风险应对措施,来管理整体项目风险敞口、最小化单个项目威胁,以及最大化单个项目机会
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 风险管理计划
#### 项目文件
##### 经验教训登记册
##### 风险登记册
##### 风险报告
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 人际关系与团队技能
##### 影响力
#### 项目管理信息系统
### 输出
#### 变更请求
#### 项目文件更新
##### 问题日志
##### 经验教训登记册
##### 项目团队派工单
##### 风险登记册
##### 风险报告
## 11.7监督风险
### 定义
#### 监督商定的风险应对计划的实施、跟踪已识别风险、识别和分析新风险,以及评估风险管理有效性的过程
### 作用
#### 使项目决策都基于关于整体项目风险敞口和单个项目风险的当前信息
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 风险管理计划
#### 项目文件
##### 问题日志
##### 经验教训登记册
##### 风险登记册
##### 风险报告
#### 工作绩效数据
#### 工作绩效报告
### 工具与技术
#### 数据分析
##### 技术绩效分析
##### 储备分析
#### 审计
#### 会议
### 输出
#### 工作绩效信息
#### 变更请求
#### 项目管理计划更新
##### 任何组件
#### 项目文件更新
##### 假设日志
##### 问题日志
##### 经验教训登记册
##### 风险登记册
##### 风险报告
#### 组织过程资产更新
<file_sep>module.exports = {
base:'/PMPGuide/',
//站点基本信息
title: 'Pmp basic knowledge.',
description: '<PMPBOK> 6.0 basic knowledge.',
head: [
['link',{rel:'icon',href: '/img/icon.png'}],
//引入fancybox
+ ['script', { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js' }],
+ ['script', { src: 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.2/jquery.fancybox.min.js' }],
+ ['link', { rel: 'stylesheet', type: 'text/css', href: 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.2/jquery.fancybox.min.css' }]
],
host: '0.0.0.0',
port: '8888',
ga: undefined,
locales:undefined,
//默认主题配置
themeConfig:{
//导航栏
navbar:true,//禁用导航栏
nav: [
{ text:'主页',link:'/'},
{ text:'目录',
items:[
{ text:'引论' , link:'/ch1-引论.md'},
{ text:'项目运行环境' , link:'/ch2-项目运行环境.md'},
{ text:'项目经理的角色' , link:'/ch3-项目经理的角色.md'},
{ text:'项目整合管理' , link:'/ch4-项目整合管理.md'},
{ text:'项目范围管理' , link:'/ch5-项目范围管理.md'},
{ text:'项目进度管理' , link:'/ch6-项目进度管理.md'},
{ text:'项目成本管理' , link:'/ch7-项目成本管理.md'},
{ text:'项目质量管理' , link:'/ch8-项目质量管理.md'},
{ text:'项目资源管理' , link:'/ch9-项目资源管理.md'},
{ text:'项目沟通管理' , link:'/ch10-项目沟通管理.md'},
{ text:'项目风险管理' , link:'/ch11-项目风险管理.md'},
{ text:'项目采购管理' , link:'/ch12-项目采购管理.md'},
{ text:'项目相关方管理' , link:'/ch13-项目相关方管理.md'},
]
}
],
//侧边栏
sidebar:'auto',
//搜索框
search:true,
searchMaxSuggestions: 10,
//最后更新时间
lastUpdated:'Last Updated',
serviceWorker: {
updatePopup: true // Boolean | Object, 默认值是 undefined.
// 如果设置为 true, 默认的文本配置将是:
// updatePopup: {
// message: "New content is available.",
// buttonText: "Refresh"
// }
},
// 假定是 GitHub. 同时也可以是一个完整的 GitLab URL
repo: 'YXGuang/PMPGuide',
// 自定义仓库链接文字。默认从 `themeConfig.repo` 中自动推断为
// "GitHub"/"GitLab"/"Bitbucket" 其中之一,或是 "Source"。
repoLabel: '查看源码',
// 假如文档不是放在仓库的根目录下:
docsDir: 'docs',
},
//markdown 配置
markdown:{
lineNumbers: true
}
}
<file_sep>---
prev: 'ch3-项目经理的角色'
next: 'ch5-项目范围管理'
---
# 4.项目整合管理
[[toc]]
<a data-fancybox title="4.项目整合管理" href="img/4.png"></a>
## 总体概述
### 定义:对隶属于项目管理过程组的各个过程和项目管理活动进行识别、定义、组合、统一和协调的各个过程。
#### 资源分配
#### 平衡竞争性需求
#### 研究各种备选方法
#### 为实现项目目标而剪裁过程
#### 管理各项目管理知识领域之间的依赖关系
### 由项目经理负责
### 趋势和新兴实践
#### 使用自动化工具
#### 使用可视化管理工具
#### 项目知识管理
#### 增加项目经理的职责
#### 混合型方法
### 剪裁
#### 项目生命周期
#### 开发生命周期
#### 管理方法
#### 知识管理
#### 变更
#### 治理
#### 经验教训
#### 效益
## 4.1制定项目章程
### 定义:编写一份正式批准项目并授权项目经理在项目活动中使用组织资源的文件的过程
### 作用:明确项目与组织战略目标之间的直接联系,确立项目的正式地位,并展示组织对项目的承诺
### 仅开展一次或在项目的预定义点开展
### 输入
#### 商业文件
##### 商业论证
##### 效益管理计划
#### 协议
##### 合同
##### 谅解备忘录(MOUs)
##### 服务水平协议(SLA)
##### 协议书
##### 意向书
##### 口头协议
##### 电子邮件
##### 书面协议
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据收集
##### 头脑风暴
##### 焦点小组
##### 访谈
#### 人际关系与团队技能
##### 冲突管理
##### 引导
##### 会议管理
#### 会议
### 输出
#### 项目章程
##### 项目启动者或发起人发布,正式批准项目成立,授权项目经理使用组织资源开展项目活动的文件
##### 项目目的
##### 可测量的项目目标和相关成功标准
##### 高层级需求
##### 高层级项目描述、边界定义以及主要可交付成果
##### 整体项目风险
##### 总体里程碑进度计划
##### 预先批准的财务资源
##### 关键相关方名单
##### 项目审批要求
##### 项目退出标准
##### 委派的项目经理及其职责和职权
##### 发起人或其他批准项目章程的人员的姓名和权职
#### 假设日志
##### 记录整个项目周期中的所有假设条件和制约因素
## 4.2制定项目管理计划
### 定义:指定义、准备和协调项目计划的所有组成部分,并把它们整合为一份综合项目管理计划的过程。
### 作用:生成一份综合文件、用于确定所有项目工作的基础及其执行方式
### 仅开展一次或仅在项目的预定义点开展
### 输入
#### 项目章程
#### 其他过程的输出
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据收集
##### 头脑风暴
##### 核对单
##### 焦点小组
##### 访谈
#### 人际关系与团队技能
##### 冲突管理
##### 引导
##### 会议管理
#### 会议
##### 项目开工会议
###### 规划阶段结束和执行阶段开始
###### 对于多阶段项目,通常每个阶段开始时都要举行一次开工会议
### 输出
#### 项目管理计划
##### 子管理计划
###### 范围管理计划
###### 需求管理计划
###### 进度管理计划
###### 成本管理计划
###### 质量管理计划
###### 资源管理计划
###### 沟通管理计划
###### 风险管理计划
###### 采购管理计划
###### 相关方参与计划
##### 基准
###### 范围基准
###### 进度基准
###### 成本基准
##### 其他组件
###### 变更管理计划
###### 配置管理计划
###### 绩效测量基准
###### 项目生命周期
###### 开发方法
####### 预测
####### 迭代
####### 敏捷
####### 混合
###### 管理审查
## 4.3指导与管理项目工作
### 定义:为实现项目目标而领导和执行项目管理计划中所确定的工作,并实施已批准变更的过程。
### 作用:对项目工作和可交付成果开展综合管理,以提高项目成功的可能性
### 在整个项目期间开展
### 输入
#### 项目管理计划
#### 项目文件
##### 变更日志
##### 经验教训登记册
##### 里程碑清单
##### 项目沟通记录
##### 项目进度计划
##### 需求跟踪矩阵
##### 风险登记册
##### 风险报告
#### 批准的变更请求
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 项目管理信息系统(PMIS)
#### 会议
### 输出
#### 可交付成果
##### 用配置管理工具和程序来支持可交付成果的多个版本控制
#### 工作绩效数据
##### 原始观察结果和测量值
#### 问题日志
##### 问题日志是一种记录和跟进所有问题的项目文件
#### 变更请求
##### 是关于修改任何文件、可交付成果或基准的正式提议
##### 纠正措施
##### 预防措施
##### 缺陷补救
##### 更新
#### 项目管理计划更新
#### 项目文件更新
##### 活动清单
##### 假设日志
##### 经验教训登记册
##### 需求文件
##### 风险登记册
##### 相关方登记册
#### 组织过程资产更新
## 4.4 管理项目知识
### 定义:使用现有知识并生成新知识,以实现项目目标,并帮助组织学习的过程
### 作用:利用已有的组织知识来创造或改进项目成果
### 整个项目生命周期开展
### 显性知识
### 隐性知识
### 输入
#### 项目管理计划
#### 项目文件
##### 经验教训登记册
##### 项目团队派工单
##### 资源分解结构
##### 相关方登记册
#### 可交付成果
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 知识管理
#### 信息管理
#### 人际关系与团队技能
##### 积极倾听
##### 引导
##### 领导力
##### 人际交往
##### 政治意识
### 输出
#### 经验教训登记册
#### 项目管理计划更新
#### 组织过程资产更新
## 4.5监控项目工作
### 定义:跟踪、审查和报告整体项目进展,以实施项目管理计划中确定的绩效目标的过程
### 作用:让相关方了项目当前状态并认可为处理绩效问题而采取的行动,以通过成本和进度预测,让相关方了解未来项目状态
### 整个项目期间开展
### 输入
#### 项目管理计划
#### 项目文件
##### 假设日志
##### 估算依据
##### 成本预测
##### 问题日志
##### 经验教训登记册
##### 里程碑清单
##### 质量报告
##### 风险登记册
##### 进度预测
#### 工作绩效信息
#### 协议
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据分析
##### 备选方案分析
##### 成本效益分析
##### 挣值分析
##### 根本原因分析
##### 趋势分析
##### 偏差分析
#### 决策
##### 投票
###### 一致同意
###### 大多数同意
###### 相对多数原则
#### 会议
### 输出
#### 工作绩效报告
#### 变更请求
##### 纠正措施
##### 预防措施
##### 缺陷补救
#### 项目管理计划更新
#### 项目文件更新
##### 成本预测
##### 问题日志
##### 经验教训登记册
##### 风险登记册
##### 进度预测
## 4.6实施整体变更控制
### 定义:审查所有变更求、批准变更,管理对可交付成果、项目文件和项目管理计划的变更,并对变更处理结果进行沟通的过程
### 作用:确保对项目中已记录在案的变更做综合评审
### 整个项目期间开展,项目经理对此承担最终责任
### 所有变更请求都必须以书面形式记录
### 由责任人(项目发起人或项目经理)批准、推迟或否决
### 必要时由变更控制委员会(CCB)实施整体变更控制过程。
### 输入
#### 项目管理计划
##### 变更管理计划
##### 配置管理计划
##### 范围基准
##### 进度基准
##### 成本基准
#### 项目文件
##### 估算依据
##### 需求跟踪矩阵
##### 风险报告
#### 工作绩效报告
#### 变更请求
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 变更控制工具
##### 识别配置项
##### 记录并报告配置项状态
##### 进行配置项合适与审计
##### 识别变更
##### 记录变更
##### 做出变更决定
##### 跟踪变更
#### 数据分析
##### 备选方案分析
##### 成本效益分析
#### 决策
##### 投票
##### 独裁型决策制定
##### 多标准决策分析
#### 会议
### 输出
#### 批准的变更请求
#### 项目管理计划更新
#### 项目文件更新
## 4.7 结束项目或阶段
### 定义:终结项目、阶段或合同的所有活动的过程
### 作用:存档项目或阶段信息,完成计划的工作,释放组织团队资源以展开新工作。
### 仅开展一次或仅在项目的预定义点开展
### 如果项目在完工前就提前终止,结束项目或阶段过程还需要制定程序,来调查和记录提前终止的原因
### 输入
#### 项目章程
#### 项目管理计划
#### 项目文件
##### 假设日志
##### 估算依据
##### 变更日志
##### 问题日志
##### 经验教训登记册
##### 里程碑清单
##### 项目沟通记录
##### 质量控制测量结果
##### 质量报告
##### 需求文件
##### 风险登记册
##### 风险报告
#### 验收的可交付成果
#### 商业文件
##### 商业论证
##### 效益管理计划
#### 协议
#### 采购文档
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据分析
##### 文件分析
##### 回归分析
##### 趋势分析
##### 偏差分析
#### 会议
### 输出
#### 项目文件更新
#### 最终产品、服务或成果移交
#### 最总报告
#### 组织过程资产更新
##### 项目文件
##### 运营和支持文件
##### 项目或阶段收尾文件
##### 经验教训知识库<file_sep>---
home: true
heroImage: /img/icon.png
actionText: PMPBOK 6.0 →
actionLink: /zh/guide/
features:
- title: '核心'
details: '各章节核心知识点'
- title: '习题'
details: '错题分析'
- title: '备考'
details:
footer: MIT Licensed | Copyright © 2018-present yxguang
---
# PMBok 学习笔记
----------------------
项目地址[yxguang.github.io/PMPGuide](https://yxguang.github.io/PMPGuide/)
## [引论](/ch1-引论.md)
## [项目运行环境](/ch2-项目运行环境.md)
## [项目经理的角色](/ch3-项目经理的角色.md)
## [项目整合管理](/ch4-项目整合管理.md)
## [项目范围管理](/ch5-项目范围管理.md)
## [项目进度管理](/ch6-项目进度管理.md)
## [项目成本管理](/ch7-项目成本管理.md)
## [项目质量管理](/ch8-项目质量管理.md)
## [项目资源管理](/ch9-项目资源管理.md)
## [项目沟通管理](/ch10-项目沟通管理.md)
## [项目风险管理](/ch11-项目风险管理.md)
## [项目采购管理](/ch12-项目采购管理.md)
## [项目相关方管理](/ch13-项目相关方管理.md)<file_sep>---
prev: ch6-项目进度管理.md
next: ch8-项目质量管理.md
---
# 7.项目成本管理
<a data-fancybox title="7.项目成本管理" href="img/7.png"></a>
## 概述
### 核心概念
#### 重点关注完成项目活动所需的资源的成本
#### 项目决策对项目产品、服务或成果的使用成本、维护成本和支持成本的影响
### 趋势和新兴实践
#### 挣得进度(ES)
### 剪裁
#### 知识管理
#### 估算和预算
#### 挣值管理
#### 敏捷方法的使用
#### 治理
## 7.1规划成本管理
### 定义
#### 是确定如何估算、预算、管理、监督和控制项目成本的过程
### 作用
#### 在整个项目期间为如何管理项目成本提供指南和方向
### 仅开展一次或仅在项目的预定义点开展
### 输入
#### 项目章程
#### 项目管理计划
##### 进度管理计划
##### 风险管理计划
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据分析
##### 备选方案分析
#### 会议
### 输出
#### 成本管理计划
##### 计量单位
##### 精确度
##### 准确度
##### 组织程序链接
##### 控制临界值
##### 绩效测量规则
##### 报告格式
##### 其他细节
## 7.2估算成本
### 定义
#### 对完成项目工作所需资产成本进行近似估算的过程
### 作用
#### 确定项目所需的资金
### 整个项目期间定期开展
### 启动阶段粗略估算
#### 区间为-25%到+75%
### 信息详细
#### 确定性估算区间-5%到+10%
### 输入
#### 项目管理计划
##### 成本管理计划
##### 质量管理计划
##### 范围基准
#### 项目文件
##### 经验教训登记册
##### 项目进度计划
##### 资源需求
##### 风险登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 类比估算
#### 参数估算
#### 自下而上估算
#### 三点估算
##### 最可能成本(cM)
##### 最乐观成本(cO)
##### 最悲观成本(cP)
##### 计算预期成本(cE)
###### 三角分布
####### cE=(cO+cM+cP)/3
###### 贝塔分布
####### cE=(cO+4cM+cP)/6
##### 基于三点的假定分布计算出期望成本
#### 数据分析
##### 备选方案分析
##### 储备分析
###### 应急储备“应急费用”
####### 包含在成本基准内的一部分预算,用来应对已识别的风险
####### 应急储备往往被看作预算中用来应对会影响项目的“已知—未知”风险的那一部分
##### 成本分析
#### 项目管理信息系统
#### 决策
##### 投票
### 输出
#### 成本估算
##### 对完成项目可能需要的成本、应对已识别风险的应急储备,以及应对计划外工作的管理储备的量化估算
#### 估算依据
#### 项目文件更新
##### 假设日志
##### 经验教训登记册
##### 风险登记册
## 7.3制定预算
### 定义
#### 是汇总所有单个活动或工作包的估算成本,建立一个经批准的成本基准的过程
### 作用
#### 确定可据以监督和控制项目绩效的成本基准
### 仅开展一次或仅在项目的预定义点开展
### 项目预算包括经批准用于执行项目的全部资金,而成本基准是经过批准且按时间段分配的项目预算,包括应急储备,但不包括管理储备
### 输入
#### 项目管理计划
##### 成本管理计划
##### 资源管理计划
##### 范围基准
#### 项目文件
##### 估算依据
##### 成本估算
##### 项目进度计划
##### 风险登记册
#### 商业文件
##### 商业论证
##### 效益管理计划
#### 协议
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 成本汇总
#### 数据分析
##### 储备分析
###### 管理储备
####### 管理控制的目的而特别留出的项目预算,用来应对项目范围中不可预见的工作
####### 目的是用来应对会影响项目的“未知——未知”风险
####### 不包括在成本基准中,但属于项目总预算和资金需求的一部分
####### 动用管理储备增加到成本基准中,导致成本基准的变更
#### 历史信息审核
#### 资金限制平衡
##### 应该根据对项目资金的任何限制,来平衡资金支出
#### 融资
##### 为项目获取资金
### 输出
#### 成本基准
##### 经过批准的、按时间段分配的项目预算、不包括任何管理储备
#### 项目资金需求
#### 项目文件更新
##### 成本估算
##### 项目进度计划
##### 风险登记册
## 7.4控制成本
### 定义
#### 监督项目状态,以更新项目成本和管理成本基准变更的过程
### 作用
#### 在整个项目期间保持对成本基准的维护
### 在整个项目期间开展
### 输入
#### 项目管理计划
##### 成本管理计划
##### 成本基准
##### 绩效测量基准
#### 项目文件
##### 经验教训登记册
#### 项目资金需求
#### 工作绩效数据
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据分析
##### 挣值分析(EVA)
###### 计划价值(PV)
####### 为计划工作分配的经批准的预算
###### 绩效测量基准(PMB)
####### PV的总和
###### 完工预算(BAC)
####### 项目的总计划价值
###### 挣值(EV)
####### 对已完成工作的测量值
###### 实际成本(AC)
####### 是在给定时段内,执行某活动而实际发生的成本
##### 偏差分析
###### 进度偏差(SV)
####### SV=EV-PV
###### 成本偏差(CV)
####### CV=EV-AC
###### 进度绩效指数(SPI)
####### SPI=EV/PV
####### SPI 小于1.0 进度落后
####### SPI大于1.0进度超前
###### 成本绩效指数(CPI)
####### CPI=EV/AC
####### CPI小于1.0成本超支
####### CPI大于1.0成本节约
###### 完工偏差(VAC)
####### VAC=BAC-EAC
##### 趋势分析
###### 图标
###### 预测
####### 完工尚需估算(ETC)
####### 完工估算(EAC)
######## 原假设估算有重大缺陷或原估算不再适用,需重新估算
######### EAC=AC+自下而上的ETC
######## 非典型:当前的偏差被视为一种特例,将来不会发生类似偏差
######### EAC=AC+(BAC-EV)
######## 典型:当前出现的偏差被视为具有典型性,可以代表未来的偏差
######### EAC=AC+(BAC-EV)/CPI 或 EAC=BAC/CPI
######## SPI与CPI同时影响ETC工作
######### EAC=AC+(BAC-EV)/CPI 或 EAC=BAC/(CPI*SPI)
##### 储备分析
#### 完工尚需绩效指数(TCPI)
##### 为实现特定的管理目标,剩余资源的使用必须达到的成本绩效指标,是完成剩余所需的成本与剩余预算之比
##### 基于BAC计算
###### TCPI=(BAC-EV)/(BAC-AC)
##### 基于EAC计算
###### TCPI=(BAC-EV)/(EAC-AC)
#### 项目管理信息系统
### 输出
#### 工作绩效信息
#### 成本预算
#### 变更请求
#### 项目管理计划更行
##### 成本管理计划
##### 成本基准
##### 绩效测量基准
#### 项目文件更新
##### 假设日志
##### 估算依据
##### 成本估算
##### 经验教训登记册
##### 风险登记册
<file_sep>---
prev: ch8-项目质量管理.md
next: ch10-项目沟通管理.md
---
# 9.项目资源管理
<a data-fancybox title="9.项目资源管理" href="img/9.png"></a>
## 概述
### 核心概念
#### 实物资源
##### 设备、材料、设施和基础设施
#### 人力资源
##### 团队资源或人员
#### 项目经理还负责建设高校的团队
### 趋势和新兴实践
#### 资源管理方法
#### 情商(EI)
#### 自组织团队
#### 虚拟团队/分布式团队
### 裁剪
#### 多元化
#### 物理位置
#### 行业特定资源
#### 团队成员的获得
#### 团队管理
#### 生命周期方法
## 9.1 规划资源管理
### 定义
#### 是定义如何估算、获取、管理和利用团队以及实物资源的过程
### 作用
#### 根据项目类型和复杂程度确定适用于项目资源的管理方法和管理程度
### 仅开展一次或仅在项目的定义点开展
### 输入
#### 项目章程
#### 项目管理计划
##### 质量管理计划
##### 范围基准
#### 项目文件
##### 项目进度计划
##### 需求文件
##### 风险登记册
##### 相关方登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据表现
##### 层级型
###### 工作分解结构(WBS)
###### 组织分解结构(OBS)
###### 资源分解结构
##### 责任分配矩阵
##### 文本型
#### 组织理论
#### 会议
### 输出
#### 资源管理计划
##### 识别资源
##### 获取资源
##### 角色与职责
###### 角色
###### 职权
###### 职责
###### 能力
##### 项目组织图
##### 项目团队资源管理
##### 培训
##### 团队建设
##### 资源控制
##### 认可计划
#### 团队章程
##### 团队价值观
##### 沟通指南
##### 决策标准和过程
##### 冲突处理过程
##### 会议指南
##### 团队共识
#### 项目文件更新
##### 假设日志
##### 风险登记册
## 9.2估算活动资源
### 定义
#### 估算执行项目所需的团队资源,以及材料、设备和用品的类型和数量的过程
### 作用
#### 明确完成项目所需的资源种类、数量和特性
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 资源管理计划
##### 范围基准
#### 项目文件
##### 活动属性
##### 活动清单
##### 假设日志
##### 成本估算
##### 资源日历
##### 风险登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 自下而上估算
#### 类别估算
#### 参数估算
##### 准确性取决于参数模型的成熟度和基础数据的可靠性
#### 数据分析
##### 备选方案分析
#### 项目管理信息系统
#### 会议
### 输出
#### 资源需求
#### 估算依据
#### 资源分解结构
#### 项目文件更新
##### 活动属性
##### 假设日志
##### 经验教训登记册
## 9.3获取资源
### 定义
#### 获取项目所需的团队成员、设施、设备、材料、用品和其他资源的过程
### 作用
#### 概述和指导资源的选择,并将其分配给相应的活动
### 整个项目期间定期开展
### 内部资源由职能经理或资源经理负责获取(分配),外部资源则是通过采购过程获取
### 输入
#### 项目管理计划
##### 资源管理计划
##### 采购管理计划
##### 成本基准
#### 项目文件
##### 项目进度计划
##### 资源日历
##### 资源需求
##### 相关方登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 决策
##### 多标准决策分析
###### 对潜在资源进行评级或打分
#### 人际关系与团队技能
##### 谈判
#### 预分派
##### 在竞标过程中承诺分派特定人员进行项目工作
##### 项目取决于特定人员的专有技能
##### 制定项目章程过程或其他过程已经指定了某些团队成员的工作分派
#### 虚拟团队
### 输出
#### 物质资源分配单
#### 项目团队派工单
#### 资源日历
#### 变更请求
#### 项目管理计划更新
##### 资产管理计划
##### 成本基准
#### 项目文件更新
##### 经验教训登记册
##### 项目进度计划
##### 资源分解结构
##### 资源需求
##### 风险登记册
##### 相关方登记册
#### 事业环境因素更新
#### 组织过程资产更新
## 9.4建设团队
### 定义
#### 是提高工作能力,促进团队成员互动,改善团队整体气氛,以提高项目绩效的过程
### 作用
#### 改进团队协作,增强人际关系技能和胜任力、激励员工、减少摩擦以及提升整体项目绩效
### 整个项目期间开展
### 团队协作是项目成功的关键因素,而建设高效的项目团队是项目经理的主要职责之一
### 塔克曼阶梯理论
#### 形成阶段
##### 了解项目情况及正式角色与职责
#### 震荡阶段
##### 开始从事项目工作、制定技术决策和讨论项目管理方法
#### 规范阶段
##### 开始协同工作,相互信任
#### 成熟阶段
##### 相互依靠,平稳高效解决问题
#### 解散阶段
##### 完成所有工作,离开项目
### 输入
#### 项目管理计划
##### 资源管理计划
#### 项目文件
##### 经验教训登记册
##### 项目进度计划
##### 项目团队派工单
##### 资源日历
##### 团队章程
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 集中办公
#### 虚拟团队
#### 沟通技术
##### 共享门户
##### 视频会议
##### 音频会议
##### 电子邮件/聊天软件
#### 人际关系与团队技能
##### 冲突管理
##### 影响力
##### 激励
##### 谈判
##### 团队建设
#### 认可与奖励
#### 培训
#### 个人和团队评估
#### 会议
### 输出
#### 团队绩效评价
#### 变更请求
#### 项目管理计划更新
#### 项目文件更新
##### 经验教训登记册
##### 项目进度计划
##### 项目团队派工单
##### 资源日历
##### 团队章程
#### 事业环境因素更新
#### 组织过程资产更新
## 9.5管理团队
### 定义
#### 是跟踪团队成员工作表现,提供反馈,解决问题并管理团队变更,以优化项目绩效的过程
### 作用
#### 影响团队行为、管理冲突以及解决问题
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 资源管理计划
#### 项目文件
##### 问题日志
##### 经验教训登记册
##### 项目团队派工单
##### 团队章程
#### 工作绩效报告
#### 团队绩效评价
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 人际关系与团队技能
##### 冲突管理
###### 直接合作、尽早、私下处理冲突
###### 撤退/回避
###### 缓和/包容
###### 妥协/调节
###### 强迫/命令
###### 合作/解决问题
##### 制定决策
##### 情商
##### 影响力
##### 领导力
#### 项目管理信息系统
### 输出
#### 变更请求
#### 项目管理计划更新
##### 资源管理计划
##### 进度基准
##### 成本基准
#### 项目文件更新
##### 问题日志
##### 经验教训登记册
##### 项目团队派工单
#### 事业环境因素更新
## 9.6控制资源
### 定义
#### 是确保按计划为项目分配实物资源,以及根据资源使用计划监督资源实际使用情况,并采取必要纠正措施的过程
### 作用
#### 确保所分配的资源适时适地可用于项目,且在不再需要时被释放
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 资源管理计划
#### 项目文件
##### 问题日志
##### 经验教训登记册
##### 物质资源分配单
##### 项目进度计划
##### 资源分解结构
##### 资源需求
##### 风险登记册
#### 工作绩效数据
#### 协议
#### 组织过程资产
### 工具与技术
#### 数据分析
##### 备选方案分析
##### 成本效益分析
##### 绩效审查
##### 趋势分析
#### 问题解决
#### 人际关系与团队技能
##### 谈判
##### 影响力
#### 项目管理信息系统
### 输出
#### 工作绩效信息
#### 变更请求
#### 项目管理计划更新
##### 资源管理计划更新
##### 进度基准
##### 成本基准
#### 项目文件更新
##### 假设日志
##### 问题日志
##### 经验教训登记册
##### 物质资源分配单
##### 资源分解结构
##### 风险登记册
<file_sep>---
prev: ch7-项目成本管理.md
next: ch9-项目资源管理.md
---
# 8.项目质量管理
<a data-fancybox title="8.项目质量管理" href="img/8.png"></a>
## 概述
### 核心概念
#### 质量作为实现的性能或是成果,是“一系列内在特性满足要求的程度”。
#### 等级作为设计意图,是对用途相同但技术特性不同的可交付成果的级别分类
#### 项目经理及项目管理团队负责权衡,以便同时达到所要求的质量与等级水平
#### 质量水平未达到质量要求肯定是个问题,而低等级产品不一定是个问题
#### 预防胜于检查
#### 质量成本
##### 在产品生命周期中为预防不符合要求、为评价产品或服务是否符合要求,以及因未达到要求(返工)而发生的所有成本。
##### 失败成本
###### 内部(团队发现)
###### 外部(客户发现)
### 趋势和新兴实践
#### 客户满意
#### 持续改进
#### 管理层的责任
#### 与供应商互利合作
### 裁剪
#### 政策合规与审计
#### 标准与法规合规性
#### 持续改进
#### 相关方参与
## 8.1规划质量管理
### 定义
#### 是识别项目及其可交付成果的质量要求和标准,并书面描述项目将如何证明符合质量要求和标准的过程
### 作用
#### 如何管理和核实质量提供指南和方向
### 开展一次或仅在项目预定义点开展
### 输入
#### 项目章程
#### 项目管理计划
##### 需求管理计划
##### 风险管理计划
##### 相关方参与计划
##### 范围基准
#### 项目文件
##### 假设日志
##### 需求文件
##### 需求跟踪矩阵
##### 风险登记册
##### 相关方登记册
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 专家判断
#### 数据收集
##### 标杆对照
##### 头脑风暴
##### 访谈
#### 数据分析
##### 成本效益分析
##### 质量成本
###### 预防成本
###### 评估成本
###### 失败成本(内部/外部)
#### 决策
##### 多标准决策分析
#### 数据表现
##### 流程图
##### 逻辑数据模型
##### 矩阵图
##### 思维导图
#### 测试与检查规划
#### 会议
### 输出
#### 质量管理计划
#### 质量测量指标
#### 项目管理计划更新
##### 风险管理计划
##### 范围基准
#### 项目文件更新
##### 经验教训登记册
##### 需求跟踪矩阵
##### 风险登记册
##### 相关方登记册
## 8.2管理质量
### 定义
#### 把组织的质量政策用于项目,并将质量管理计划转化为可执行的质量活动的过程
### 作用
#### 提高实现质量目标的可能性,识别无效过程和导致质量低劣的原因
### 整整个项目期间开展
### 管理质量被认为是所有人的共同职责,包括项目经理、项目团队、项目发起人、执行组织的管理层、甚至是客户
### 输入
#### 项目管理计划
##### 质量管理计划
#### 项目文件
##### 经验教训登记册
##### 质量控制测量结果
##### 质量测量指标
##### 风险报告
#### 组织过程资产
### 工具与技术
#### 数据收集
##### 核对单
#### 数据分析
##### 备选方案分析
##### 文件分析
##### 过程分析
##### 根本原因分析(RCA)
#### 决策
##### 多标准决策
#### 数据表现
##### 亲和图
##### 因果图
###### 鱼骨图
###### why-why分析图
###### 石川图
##### 流程图
##### 直方图
##### 矩阵图
##### 散点图
#### 审计
##### 用于确定项目活动是否遵循了组织和项目的政策、过程与程序的一种结构化且独立的过程
##### 审计还可以确认已批准的变更请求(包括更新、纠正措施、缺陷补救和预防措施)的实施情况
#### 面向X的设计
##### (DFX)是产品设计期间可采用的一系列技术指南
#### 问题解决
#### 质量改进方法
##### 计划——实施——检查——行动和六西格玛
### 输出
#### 质量报告
#### 测试与评估文件
#### 变更请求
#### 项目管理计划更新
##### 质量管理计划
##### 范围基准
##### 进度基准
##### 成本基准
#### 项目文件更新
##### 问题日志
##### 经验教训登记册
##### 风险登记册
## 8.3控制质量
### 定义
#### 为了评估绩效、确保项目输出完整、正确且满足客户期望,而监督和记录质量管理活动执行结果的过程
### 作用
#### 核实项目可交付成果和工作已经达到主要相关方的质量要求,可供最终验收
### 整个项目期间开展
### 输入
#### 项目管理计划
##### 质量管理计划
#### 项目文件
##### 经验教训登记册
##### 质量测量指标
##### 测试与评估文件
#### 批准的变更请求
#### 可交付成果
#### 工作绩效数据
#### 事业环境因素
#### 组织过程资产
### 工具与技术
#### 工具与技术
##### 核对单
##### 核查表(计数表)
##### 统计抽样
##### 问卷调查
#### 数据分析
##### 绩效审查
##### 根本原因分析
#### 检查
#### 测试/产品评估
#### 数据表现
##### 因果图
##### 控制图
##### 直方图
##### 散点图
#### 会议
##### 审查已批准的变更请求
##### 回顾/经验教训
### 输出
#### 质量控制测量结果
#### 核实的可交付成果
#### 工作绩效信息
#### 变更请求
#### 项目管理计划更新
##### 质量管理计划
#### 项目文件更新
##### 问题日志
##### 经验教训登记册
##### 风险登记册
##### 测试与评估文件
<file_sep>---
prev: '/ch1-引论'
next: '/ch3-项目经理的角色'
---
# 2 项目运行环境
## 2.1 概述
* 事业环境因素(EEF)
* 组织过程资产(OPA)
## 2.2 事业环境因素
* 事业环境因素(EEFs)是指项目团队不能控制的,将对项目产生影响、限制或指令作用的各种条件。
### 2.2.1 组织内部的事业环境因素
* 组织文化、结构和治理。
* 设施和资源的地理分布。
* 基础设施。
* 信息技术软件。
* 资源可用性。
* 员工能力。
### 2.2.2 组织外部的事业环境因素
* 市场条件。
* 社会和文化影响与问题。
* 法律限制。
* 商业数据库。
* 学术研究。
* 政府或行业标准。
* 财务考虑因素。
* 物理环境因素。
## 2.3 组织过程资产
* 由于组织过程资产存在于组织内部,在整个项目期间,项目团队成员可对组织过程资产进行必要的更新和增补。
* 组织过程资产可分为两大类:
* 过程、政策和程序。
* 组织知识库。
### 2.3.1 过程、政策和程序
* 启动和规划
* 指南和标准
* 特定的组织标准
* 产品和项目生命周期
* 模板
* 预先批准的供应商清单和各种合同协议类型
* 执行和监控
* 变更控制程序
* 跟踪矩阵
* 财务控制程序
* 问题与缺陷管理程序
* 资源的可用性控制和分配
* 组织对沟通的要求
* 确定工作有限顺序、批准工作与签发工作授权的程序
* 模板
* 标准化的指南、工作指示、建议书评价准则和绩效测量准则
* 产品、服务或成果的核实和确认程序
* 收尾
* 项目收尾指南或要求
### 2.3.2 组织知识库
* 配置管理知识库
* 财务数据库
* 历史信息与经验教训知识库
* 问题与缺陷管理数据库
* 测量指标数据库
* 以往项目的项目档案
## 2.4 组织系统
### 2.4.1 概述
* 系统因素包括:
* 管理要素
* 治理框架
* 组织结构类型
* 系统是各种组件的集合,可以实现单个组件无法实现的成果。组件是项目或组织内的可识别要素,提供了某种特定功能或一组相关的功能。
* 系统是动态的
* 系统是能优化的
* 系统组件是能优化的
* 系统及其组件不能同时优化
* 系统呈现非线性响应(输入的变更并不会产生可预测的输出)
* 系统通常由组织的管理层负责
### 2.4.2 组织治理框架
* 治理是在组织各个层级上的组织性或结构性安排,旨在决定和影响组织成员的行为。
#### 2.4.2.1 治理框架
* 治理是在组织内形式职权的框加,其内容包括(但不限于):
* 规则
* 政策
* 程序
* 规范
* 关系
* 系统
* 过程
* 这个框加会影响:
* 组织目标的设定和实现方式
* 风险监控和评估方式
* 绩效优化方式
#### 2.4.2.2 项目组合、项目集和项目治理
* 组织级项目管理(OPM)与项目组合、项目集和项目管理的常见治理框架
* 项目治理是指用于指导项目管理活动的框架、功能和过程,从而创造独特的产品、服务或结果以满足组织、战略和运营目标。
### 2.4.3 管理要素
* 管理要素是组织中的关键职能或一般管理原则。
### 2.4.4 组织结构类型
* 不存在一种结构类型适用于任何特定组织。因要考虑各种可变因素,特定组织的最终结构是独特的。
#### 2.4.4.1 组织结构类型
#### 2.4.4.2 组织结构选择的考虑因素
#### 2.4.4.3 项目管理办公室
* 项目管理办公室(PMO)是对与项目相关的治理过程进行标准化,并促进资源、方法论、工具和技术共享的一种组织结构。
* PMO有几种不同的类型:
* 支持型。 项目资源库,对项目的控制程度很低。
* 控制型。 对项目的控制程度属于中等。
* 指令型。 对项目的控制程度很高。
* PMO在组织的项目组合、项目集、项目与组织考评体系(如平衡积分卡)之间建立联系。
* PMO所支持或管理的项目不一定彼此联系。
* PMO 的一个主要职能是通过各种方式向项目经理提供支持:
* 共享资源管理
* 识别和制定项目管理方法、最佳实践和标准
* 指导、辅导、培训和监督
* 通过项目审计、监督对项目管理标准、政策、程序和模板的遵守程度
* 制定和管理项目政策、程序、模板和其他共享的文件(组织过程资产)
* 对跨项目的沟通进行协调
| c1ff07e1fc0c57a5d767a9374d9b447748e74b8a | [
"Markdown",
"JavaScript"
] | 15 | Markdown | yangmingdizi/PMPGuide | e78c1c9da8acb702030bf2a2bc91dba66d36836e | a80fe3dd8c4cd99e3e3bfddd9fef2f67a80a35e9 |
refs/heads/master | <file_sep>// NOTE: run `make tooling` if getting CCLS warnings
#include <stdio.h>
#include <ctype.h>
#include <http.h>
#include <stdlib.h>
#include <scan.h>
#include <string.h>
void print_help() {
printf("Available commands: scan, http\n");
}
int main(int argc, char** argv) {
if (argc == 1) {
printf("No argument passed to command.\n");
print_help();
exit(0);
}
if (strcmp(argv[1], "scan") == 0) {
scan_devices();
}
else if (strcmp(argv[1], "http") == 0) {
HTTPResponse res = http_client(argv);
printf("Response Code: %d\n", res.response_code);
}
else {
printf("ERROR: <%s> is not a valid argument\n", argv[1]);
print_help();
}
return(0);
}
<file_sep># toy-car
The chip used is the ATmega328P, the microcontroller used on the Arduino Uno and Arduino Nano.
## Software Dependencies
### Installing on ArchLinux
Libraries required to cross compile:
sudo pacman -S avr-gcc avrdude
Optional, an Arduino UNO was used as the hardware programmer.
sudo pacman -S arduino
## Notes
The Makefile assumes that the first USB device you plug in is the programmer. For a quick hack, unplug everything, unplug everything, plug in the programmer first and then plug everything else back in.
<file_sep>/** @file */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "util.h"
int gives_5() {
return 5;
}
/// Print each element of int array
void printa(int size, int* arr) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("]\n");
}
/// Compare two int arrays, returning 1 if all indexes up to `s`
/// are equal between `arr1` and `arr2`
int arrcmp(int s, int* arr1, int* arr2) {
int is_equal = 1;
for (int i = 0; i < s; i++) {
is_equal = is_equal && arr1[i] == arr2[i];
}
return is_equal;
}
/// Persistent insertion sort. Sorted array is in `new_arr`
void insertion_sort(int s, int* arr, int* new_arr) {
int j;
new_arr[0] = arr[0];
for (int i=1; i < s; i++) {
j = i - 1;
while ((j > -1) && (arr[i] < new_arr[j])) {
new_arr[j+1] = new_arr[j];
j--;
}
new_arr[j+1] = arr[i];
printa(s, new_arr);
}
return;
}
/// Insertion sort. Mutates input
void insertion_sort_mut(int s, int* arr) {
int j;
int val;
for (int i=1; i < s; i++) {
val = arr[i];
j = i - 1;
while ((j > -1) && (val < arr[j])) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = val;
}
return;
}
<file_sep>export PATH=$HOME/bin:$PATH
export EDITOR="vim"
alias ta="tmux attach"
neofetch
<file_sep>HEADERS = scan.h http.h
OBJECTS = main.o scan.o http.o
INCLUDE_DIR =../include
CC=gcc
CFLAGS=-g -I$(INCLUDE_DIR)
TARGET_DIR=../target
LIBS=-lm -lpcap -lcurl
_HEADERS = $(patsubst %,$(INCLUDE_DIR)/%,$(HEADERS))
_OBJECTS = $(patsubst %,$(TARGET_DIR)/%,$(OBJECTS))
$(TARGET_DIR)/%.o: %.c $(_HEADERS)
$(CC) -c -o $@ $< $(CFLAGS)
build: $(_OBJECTS)
mkdir -p $(TARGET_DIR)
$(CC) -o ../$(BINARY_NAME) $^ $(CFLAGS) $(LIBS)
.PHONY: clean
clean:
rm -f $(TARGET_DIR)/*.o *~ ../$(BINARY_NAME)
<file_sep>.PHONY: scan android
SUBDIRS := scan android
all: $(SUBDIRS)
$(SUBDIRS):
echo $@
cd $@ && $(MAKE) build && $(MAKE) install
android: scan
<file_sep>int gives_5(void);
int arrcmp(int, int*, int*);
void printa(int, int*);
void insertion_sort(int, int*, int*);
void insertion_sort_mut(int, int*);
<file_sep>BINARY_NAME = qq
BINARY_PATH = $$HOME/bin
build:
cd src && $(MAKE) $@ BINARY_NAME=$(BINARY_NAME) BINARY_PATH=$(BINARY_PATH)
# yay -S bear
# Tool to generate a compile_commands.json for ccls
tooling:
bear make
.PHONY: clean
clean:
cd src && $(MAKE) $@ BINARY_NAME=$(BINARY_NAME) BINARY_PATH=$(BINARY_PATH)
install: local-bin-dir
cp ./$(BINARY_NAME) $(BINARY_PATH)/$(BINARY_NAME)
@echo "If first time install, make sure to source ~/.bashrc"
local-bin-dir:
mkdir -p $(BINARY_PATH)
chown -R $(shell whoami) $(BINARY_PATH)
echo 'export PATH=$(BINARY_PATH):$$PATH' >> ~/.bashrc
<file_sep>.PHONY: all build flash programmer
TARGET = main
INCLUDE_DIR=include/
SOURCES=$(wildcard *.c $(LIBDIR)/*.c)
HEADERS=$(wildcard $(INCLUDE_DIR)/*.h $(LIBDIR)/*.h)
CFLAGS = -g -Os -std=gnu99 -Wall -mcall-prologues -I$(INCLUDE_DIR)
OBJECTS=$(SOURCES:.c=.o)
## MCU specific
PART_NO = m328p
MMCU = atmega328
F_CPU = 8000000UL
BAUD =
PORT = /dev/ttyACM0
## Toolchain
CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
AVRSIZE = avr-size
AVRDUDE = avrdude
## Flash
PROGRAMMER_ID = avrispv2
######## --------------- compile --------------- ########
build: $(TARGET).hex
%.o: %.c $(HEADERS)
$(CC) -mmcu=$(MMCU) -c -o $@ $< $(CFLAGS)
%.obj: $(OBJECTS)
$(CC) $(CFLAGS) -mmcu=$(MMCU) $^ -o $@
%.hex: %.obj
$(OBJCOPY) -R .eeprom -O ihex $< $@
######## --------------- flash --------------- ########
## Check connection to programmer okay
progconn:
$(AVRDUDE)-vvv -p $(PART_NO) -P $(PORT) -c $(PROGRAMMER_ID)
flash: build
$(AVRDUDE) -c $(PROGRAMMER_ID) -p $(PART_NO) -P $(PORT) -e -v -U flash:w:$(TARGET).hex
######## --------------- dev tooling --------------- ########
ccls:
bear make
env:
@echo "SOURCES:" $(SOURCES)
@echo "OBJECTS:" $(OBJECTS)
@echo "HEADERS:" $(HEADERS)
clean:
rm -f *.elf *.obj *.hex *.o *.s
<file_sep># home
Some scripts for the cube
- [ ] Central log server with ESP-8266
- [ ] Octoprint physical killswitch
- [ ] Train model on camera images/video to detect for anomalies; overextrusion, elephants foot, skips, stringing, fire
- [ ] Ender 3 Screen Cover
- [ ] Webcam mount
- [X] Network address and mask of nearby network devices
- [ ] Raspberry Pi time, voltage, temperature and octoprint status logging
## android
$ git clone <EMAIL>:eltonlaw/home.git
$ cd home
$ sh android/setup.sh
## cli
Miscellaneous shared scripts:
- Get IP address of current device
## cv
Some OpenCV code
## rc-car
Small autonomous toy car that changes direction when it detects an impact.
<file_sep>cp cfg/vimrc $HOME/.vimrc
cp cfg/bashrc $HOME/.bashrc
cp cfg/tmux.conf $HOME/.tmux.conf
pkg install -y make vim tmux python neofetch nmap
python -m pip install requests
<file_sep>INCLUDE_DIR =../include
HEADERS=$(wildcard $(INCLUDE_DIR)/*.h)
SOURCES=$(wildcard *.c)
OBJECTS=$(SOURCES:.c=.o)
CC=gcc
CFLAGS=-g -Wall -I$(INCLUDE_DIR)
LIBS=-lm
TARGET_DIR=../target
%.o: %.c $(HEADERS)
$(CC) -c -o $@ $< $(CFLAGS)
build: $(OBJECTS)
cp *.o $(TARGET_DIR)/
.PHONY: clean
clean:
rm -f *.o
<file_sep>/* Timer code */
#define BAUD 9600
#define F_CPU 1000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <usart.h>
void flash(uint8_t b) {
PORTB |= b;
_delay_ms(100);
PORTB &= ~b;
_delay_ms(100);
}
int main(void) {
uint8_t buffer;
DDRB |= (1 << DDB0) | (1 << DDB1) | (1 << DDB2) | (1 << DDB7);
usart_init();
print_string("Hello World!\r\n");
PORTB = 0xff;
flash_twice(0b10000111);
while (1) {
_delay_ms(100000);
buffer = receive_byte();
transmit_byte(buffer);
PORTB = buffer;
}
return (0);
}
<file_sep>#include "util.h"
#include "unity.h"
void setUp(void) {
// set stuff up here
}
void tearDown(void) {
// clean stuff up here
}
void test_gives_5(void)
{
TEST_ASSERT_EQUAL_INT(5, gives_5());
}
void test_arrcmp(void) {
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5] = {2, 1, 3, 4, 5};
int arr3[5] = {1, 2, 3, 4, 6};
TEST_ASSERT_TRUE(arrcmp(5, arr1, arr1));
TEST_ASSERT_FALSE(arrcmp(5, arr1, arr2));
TEST_ASSERT_FALSE(arrcmp(5, arr1, arr3));
}
void test_insertion_sort(void) {
int unsorted[7] = {5, 4, 6, 2, 3, 9, 8};
int actual[7];
insertion_sort(7, unsorted, actual);
int expected[7] = {2, 3, 4, 5, 6, 8, 9};
TEST_ASSERT_TRUE(arrcmp(7, expected, actual));
}
void test_insertion_sort_mut(void) {
int actual[7] = {5, 4, 6, 2, 3, 9, 8};
insertion_sort_mut(7, actual);
int expected[7] = {2, 3, 4, 5, 6, 8, 9};
TEST_ASSERT_TRUE(arrcmp(7, expected, actual));
}
int main(void) {
UNITY_BEGIN();
RUN_TEST(test_gives_5);
RUN_TEST(test_arrcmp);
RUN_TEST(test_insertion_sort);
RUN_TEST(test_insertion_sort_mut);
return UNITY_END();
}
<file_sep>#ifndef BAUD
#define BAUD 9600
#endif
#ifndef F_CPU
#define F_CPU 1000000UL
#endif
#include <avr/io.h>
#include <util/delay.h>
#include <util/setbaud.h>
#include "usart.h"
void usart_init(void) {
UBRR0H = (UBRRH_VALUE >> 8);
UBRR0L = UBRRL_VALUE;
// Disable double speed operation (synchronous comms)
UCSR0A &= ~(1 << U2X0);
/* Enable USART transmitter and receiver */
UCSR0B = (1 << TXEN0) | (1 << RXEN0);
UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);
}
void transmit_byte(uint8_t data) {
loop_until_bit_is_set(UCSR0A, UDRE0);
UDR0 = data;
}
uint8_t receive_byte(void) {
loop_until_bit_is_set(UCSR0A, RXC0);
return UDR0;
}
void print_str(const char s[]) {
int i = 0;
while (s[i]) {
transmit_byte(s[i]);
i++;
}
}
<file_sep>void scan_devices(void);
<file_sep>#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#define __AVR_ATmega328P__ 1
#define FORWARD 1
#define BACKWARD 2
static inline void init_l289n(void) {
/* ------ Set output pins ------- */
// PD0 connected to IN1 (pin 8)
// PD1 connected to IN2 (pin 9)
DDRD = (1 << PIND0) | (1 << PIND1);
// PB1 connected to ENA (pin 7)
DDRB = (1 << PINB1);
// Output Compare 16-bit, this is done in two clock cycles (compiler magic)
OCR1A = 0x01FF;
// Protect 16-bit access
unsigned char sreg;
sreg = SREG; // save global interrupt flag
cli(); // disable interupts
/* -------- Timer Counter 1 Control Register A ------------ */
// OC1A output overrides the normal port functionality of I/O pin it is
// connected to
TCCR1A |= (1 << COM1A1);
// set non-inverting mode
// PWM phase correct 10 bit
TCCR1A |= (1 << WGM11) | (1 << WGM10);
// set 10bit phase corrected PWM Mode
/* -------- Timer Counter 1 Control Register B ------------ */
TCCR1B |= (1 << CS11);
// Restore global interrupt flag
SREG = sreg;
}
static inline void init_adc0(void) {
ADMUX |= (1 << REFS0); // Reference voltage on AVCC (disables AREF usage)
// ADC Control and Status Register A
ADCSRA |= (1 << ADPS1) | (1 << ADPS0); // ADC clock prescaler /8
ADCSRA |= (1 << ADEN); // Enable ADC
// Use ADC[7:0] pins to replace negative input of the analog comparator
// ADCSRA ^= ~(1 << ADEN); // Disable ADC
// ADCSRB |= (1 << ACME); // Set Analog Comparator Multiplexer Enable to 1
// ADMUX |= (1 << MUX1) | (1 << MUX2); // Use ADC6 as AC Negative Input
// ADCSRA |= (1 << ADATE); // Enable ADC Auto Trigger Enable Bit
// ADCSRA |= (1 << ADTS2); // Select trigger source for Auto Trigger Enable
// You can use the ADC Interrupt Flag as a trigger source to make the ADC
// start a new conversion as soon as the ongoing conversion has finished
// ADCSRA |= (1 << ADIF);
}
int main() {
/* If the piezo sensor senses a vibration, light up the LED */
// uint8_t led_value;
// uint8_t i;
volatile uint16_t adc_value; // ADC value is a 10 bit value
init_adc0();
init_l289n();
// Initialize indicator LED
DDRB |= (1 << PINB0);
PORTB = (1 << PINB0);
// Initialize Direction of Wheels
PORTD |= (1 << PIND0);
// Initialize input variable from piezo sensor
int vibration_sensed = 0;
while (1) {
// Datasheet specification for a single conversion
PRR &= ~(1 << PRADC); // Write 0 to Power Reduction ADC bit
ADCSRA |= (1 << ADSC); // Write 1 to ADC Start Conversion bit
// ADCS will stay high while conversion is in progress, low when done
adc_value = ADC;
if (adc_value < 512) {
if (!vibration_sensed) {
PORTD ^= ((1 << PIND0) | (1 << PIND1)); // Toggle only
PORTB ^= (1 << PINB0); // Toggle only PB0
vibration_sensed = 1;
}
} else {
vibration_sensed = 0;
}
}
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pcap.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
char* address_text(in_addr_t p) {
struct in_addr addr;
addr.s_addr = p;
char* a = inet_ntoa(addr);
if(a == NULL) {
perror("inet_ntoa");
exit(1);
}
return a;
}
/* Prints network address and mask of all capture devices */
void scan_devices(void) {
int ret;
char errbuf[PCAP_ERRBUF_SIZE];
/* Get all valid devices */
pcap_if_t* alldevs;
ret = pcap_findalldevs(&alldevs, errbuf); if(ret == -1) {
printf("Error encountered looking up device.\n%s\n",errbuf);
exit(1);
}
if(alldevs == NULL) {
printf("No devices found");
exit(0);
}
bpf_u_int32 netp; // ip
bpf_u_int32 maskp; // subnet mask
char net[20];
char mask[20];
char* dev_name;
pcap_if_t *dev;
dev = alldevs;
while (1) {
dev_name = dev->name;
/* network address and mask of the device */
ret = pcap_lookupnet(dev_name, &netp, &maskp, errbuf);
if(ret == -1) {
printf("%s\n", errbuf);
exit(1);
}
strcpy(net, address_text(netp));
strcpy(mask, address_text(maskp));
dev = dev->next;
if (dev == NULL)
break;
if (0 != strcmp(net, "0.0.0.0"))
break;
}
printf("DEVICE: %s\n", dev_name);
printf("DESCRIPTION: %s\n", dev->description);
printf("FLAGS: %d\n", dev->flags);
printf("NET: %s\n", net);
printf("MASK: %s\n", mask);
pcap_freealldevs(alldevs);
}
<file_sep># utils
## Setup
Intall Unity (testing framework)
git clone <EMAIL>:ThrowTheSwitch/Unity.git
cd Unity
mkdir build/
cd build
cmake ..
make
sudo cp libunity.a /usr/local/lib
sudo cp ../src/unity.h /usr/local/include
sudo cp ../src/unity_internals.h /usr/local/include
<file_sep>.PHONY: clean
build clean:
cd src && $(MAKE) $@
test: build
cd test && $(MAKE) $@
docs:
doxygen Doxyfile
<file_sep>.PHONY: all build flash
MCU =
F_CPU =
# Might be able to increase from default to program it a bit faster, look at datasheet
BAUD =
PORT = /dev/ttyACM0
all: build flash
build:
# Generates assembly code
avr-gcc -g -Os -Wall -mcall-prologues -mmcu=atmega328 -S -o main.s main.c
# Generate object code
avr-gcc -g -Os -Wall -mcall-prologues -mmcu=atmega328 -c -o main.o main.c
avr-gcc -g -Os -Wall -mcall-prologues -mmcu=atmega328 main.o -o main.obj
# Remove eeprom section and translate to intel hex
avr-objcopy -R .eeprom -O ihex main.obj main.hex
flash:
# avrdude -c programmer_id -p microcontroller -P port --erasable --verbose --upload memtype:op:filename
avrdude -c avrispv2 -p m328p -P $(PORT) -e -v -U flash:w:main.hex
clean:
rm *.elf *.obj *.hex *.o
<file_sep>struct HTTPResponse {
int response_code;
};
typedef struct HTTPResponse HTTPResponse;
HTTPResponse http_client(char**);
<file_sep>void usart_init(void);
void transmit_byte(uint8_t);
uint8_t receive_byte(void);
void print_str(const char []);
<file_sep>#include <http.h>
#include <curl/curl.h>
HTTPResponse http_client(char** argv) {
long flags = CURL_GLOBAL_ALL;
curl_global_init(flags);
HTTPResponse res;
res.response_code = 200;
curl_global_cleanup();
return res;
}
<file_sep>INCLUDE_DIR =../include
HEADERS=$(wildcard $(INCLUDE_DIR)/*.h)
SOURCES=$(wildcard *.c)
OBJECTS=$(SOURCES:.c=.o)
CC=gcc
CFLAGS=-g -Wall -I$(INCLUDE_DIR)
LIBS = -l unity
TARGET_DIR=../target
test:
$(CC) -o test_util.out test_util.c $(TARGET_DIR)/util.o $(LIBS) $(CFLAGS) && ./test_util.out
build: $(OBJECTS)
%.o: %.c $(HEADERS)
$(CC) -c $@ $< $(CFLAGS)
.PHONY: clean
clean:
rm -f *.o
<file_sep>#include "ESP8266WiFi.h"
int PIN_OUT = 3;
void setup() {
pinMode(PIN_OUT, OUTPUT); // Initialize the PIN_OUT pin as an output
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(PIN_OUT, LOW);
delay(500);
digitalWrite(PIN_OUT, HIGH);
delay(500);
digitalWrite(PIN_OUT, LOW);
delay(500); // Wait for a second
digitalWrite(PIN_OUT, HIGH); // Turn the LED off by making the voltage HIGH
delay(2500); // Wait for two seconds (to demonstrate the active low LED)
}
<file_sep>#include "ESP8266WiFi.h"
int PIN_OUT = 2;
void setup() {
pinMode(PIN_OUT, OUTPUT); // Initialize the PIN_OUT pin as an output
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(PIN_OUT, LOW);
delay(500);
digitalWrite(PIN_OUT, HIGH);
delay(500);
digitalWrite(PIN_OUT, LOW);
delay(500); // Wait for a second
digitalWrite(PIN_OUT, HIGH); // Turn the LED off by making the voltage HIGH
delay(2500); // Wait for two seconds (to demonstrate the active low LED)
}
| 63a8625c59f53729367b40613a615cb9834d46b2 | [
"Markdown",
"Makefile",
"C",
"C++",
"Shell"
] | 27 | C | eltonlaw/home | da72904f15f0de0cbebb49f7d1a20f776faa38f0 | b3afd7fe8fe50be325bcbd1a4dbe1ced9ce0b01d |
refs/heads/master | <repo_name>kaunge-fork/hyperf.io<file_sep>/src/Home/data.source.js
import React from 'react';
export const Nav00DataSource = {
wrapper: { className: 'header0 home-page-wrapper jwbweljfrfi-editor_css' },
page: { className: 'home-page jwbwg2b25dc-editor_css' },
logo: {
className: 'header0-logo jwbwdwdhgqr-editor_css',
children: 'https://hyperf.oss-cn-hangzhou.aliyuncs.com/hyperf.png',
},
Menu: {
className: 'header0-menu',
children: [
{
name: 'item0',
a: {
children: '开发文档',
href: 'https://doc.hyperf.io',
className: 'jwbwev2ey7-editor_css',
},
className: 'jwbwfgejg3-editor_css',
},
{
name: 'item1',
a: {
children: 'Github',
href: 'https://github.com/hyperf/hyperf',
className: 'jwbwf54e8hn-editor_css',
},
},
],
},
mobileMenu: { className: 'header0-mobile-menu' },
};
export const Banner30DataSource = {
wrapper: { className: 'banner3 jwbvg9mw5gi-editor_css' },
textWrapper: {
className: 'banner3-text-wrapper',
children: [
{
name: 'nameEn',
className: 'banner3-name-en',
children: (
<>
<p>
<br />
</p>
</>
),
},
{
name: 'slogan',
className: 'banner3-slogan jwbvhicx5l-editor_css',
children: 'The Way to PHP Microservice',
texty: true,
},
{
name: 'name',
className: 'banner3-name jwbvj2078d8-editor_css',
children: (
<>
<p>Hyperf = Hyperspeed + Flexibility</p>
</>
),
},
{
name: 'button',
className: 'banner3-button jwbvker8eo-editor_css',
children: (
<>
<p>快速开始</p>
</>
),
href: "https://doc.hyperf.io"
},
{
name: 'time',
className: 'banner3-time',
children: (
<>
<p>
<br />
</p>
</>
),
},
],
},
};
export const Content00DataSource = {
wrapper: {
className: 'home-page-wrapper content0-wrapper jwq3fv7xmf-editor_css',
},
page: { className: 'home-page content0' },
OverPack: { playScale: 0.3, className: '' },
titleWrapper: {
className: 'title-wrapper',
children: [
{
name: 'title',
children: (
<>
<p>简单化 协程化 组件化</p>
</>
),
},
],
},
block: {
className: 'block-wrapper',
children: [
{
name: 'block0',
className: 'block',
md: 8,
xs: 24,
children: {
icon: {
className: 'icon',
children:
'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/PjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+PHN2ZyB0PSIxNTYwMTUzNzI0NTcwIiBjbGFzcz0iaWNvbiIgc3R5bGU9IiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHAtaWQ9Ij<KEY>
},
title: {
className: 'content0-title',
children: (
<>
<p>开箱即用,快人一步</p>
</>
),
},
content: {
children: (
<>
<p>官方提供超多常用组件,随用随取</p>
</>
),
},
},
},
{
name: 'block1',
className: 'block',
md: 8,
xs: 24,
children: {
icon: {
className: 'icon',
children:
'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJuby<KEY>Jn<KEY>ZCI+<KEY>IHAtaWQ9Ijk2NyIgeG1sbnM6eGxpbms9Imh0dHA<KEY>
},
title: {
className: 'content0-title',
children: (
<>
<p>原生协程,超高性能</p>
</>
),
},
content: {
children: (
<>
<p>基于Swoole原生协程,性能强悍</p>
</>
),
},
},
},
{
name: 'block2',
className: 'block',
md: 8,
xs: 24,
children: {
icon: {
className: 'icon',
children:
'<KEY>
},
title: {
className: 'content0-title',
children: (
<>
<p>丰富组件,任意组合</p>
</>
),
},
content: {
children: (
<>
<p>全组件化设计,可复用于其它框架</p>
</>
),
},
},
},
],
},
};
export const Content30DataSource = {
wrapper: {
className: 'home-page-wrapper content3-wrapper jwq3fnvddaf-editor_css',
},
page: { className: 'home-page content3 jwq3bo8n6w-editor_css' },
OverPack: { playScale: 0.3 },
titleWrapper: {
className: 'title-wrapper',
children: [
{
name: 'title',
children: (
<>
<p>生产级别的协程框架</p>
</>
),
className: 'title-h1',
},
{
name: 'content',
className: 'title-content',
children: (
<>
<p>由 Swoole 4 原生协程强力驱动</p>
</>
),
},
],
},
block: {
className: 'content3-block-wrapper',
children: [
{
name: 'block0',
className: 'content3-block',
md: 8,
xs: 24,
children: {
icon: {
className: 'content3-icon',
children:
'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZ<KEY>',
},
textWrapper: { className: 'content3-text' },
title: {
className: 'content3-title',
children: (
<>
<p>高性能</p>
</>
),
},
content: {
className: 'content3-content',
children: (
<>
<p>全协程异步实现,性能远超所有传统 PHP-FPM 框架</p>
</>
),
},
},
},
{
name: 'block1',
className: 'content3-block',
md: 8,
xs: 24,
children: {
icon: {
className: 'content3-icon',
children:
'<KEY>
},
textWrapper: { className: 'content3-text' },
title: {
className: 'content3-title',
children: (
<>
<p>生产可用</p>
</>
),
},
content: {
className: 'content3-content',
children: (
<>
<p>经历过长时间生产环境考验的企业级框架设计,稳定可靠</p>
</>
),
},
},
},
{
name: 'block2',
className: 'content3-block',
md: 8,
xs: 24,
children: {
icon: {
className: 'content3-icon',
children:
'data:image/svg+xml;base64,<KEY>0IDE2MGgtMTY0LjUxMkExMjcuNzEyIDEyNy43MTIgMCAwIDAgNTc2<KEY>
},
textWrapper: { className: 'content3-text' },
title: {
className: 'content3-title',
children: (
<>
<p>微服务</p>
</>
),
},
content: {
className: 'content3-content',
children: (
<>
<p>健全的微服务体系,gRPC、JsonRPC、服务发现、熔断,灵活完善</p>
</>
),
},
},
},
{
name: 'block3',
className: 'content3-block',
md: 8,
xs: 24,
children: {
icon: {
className: 'content3-icon',
children:
'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/PjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+PHN2ZyB0PSIxNTYwMTU2MTkyNTkwIiBjbGFzcz0iaWNvbiIgc3R5bGU9IiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0c<KEY>
},
textWrapper: { className: 'content3-text' },
title: {
className: 'content3-title',
children: (
<>
<p>组件丰富</p>
</>
),
},
content: {
className: 'content3-content',
children: (
<>
<p>
全组件化设计,超多常用组件,绝大部分组件均可复用于其它框架
</p>
</>
),
},
},
},
{
name: 'block4',
className: 'content3-block',
md: 8,
xs: 24,
children: {
icon: {
className: 'content3-icon',
children:
'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/PjwhRE9DVFlQRSBzd<KEY>DICItLy<KEY>Ly<KEY>Jn<KEY>ZCI+<KEY>9IjQ1MjIiIHhtbG5zOnhsaW5rPSJodHRwOi8vd3<KEY>
},
textWrapper: { className: 'content3-text' },
title: {
className: 'content3-title',
children: (
<>
<p>分布式</p>
</>
),
},
content: {
className: 'content3-content',
children: (
<>
<p>基于相关组件可快速搭建出企业级的分布式系统,极速扩容</p>
</>
),
},
},
},
{
name: 'block5',
className: 'content3-block',
md: 8,
xs: 24,
children: {
icon: {
className: 'content3-icon',
children:
'data:image/svg+xml;base64,<KEY>
},
textWrapper: { className: 'content3-text' },
title: {
className: 'content3-title',
children: (
<>
<p>自动化测试</p>
</>
),
},
content: {
className: 'content3-content',
children: (
<>
<p>完备的自动化测试,从开发到生产交付全流程保障</p>
</>
),
},
},
},
],
},
};
export const Footer00DataSource = {
wrapper: {
className: 'home-page-wrapper footer0-wrapper jwq3bq34q9r-editor_css',
},
OverPack: { className: 'home-page footer0', playScale: 0.05 },
copyright: {
className: 'copyright',
children: (
<>
<span>©2019 Hyperf All Rights Reserved</span>
</>
),
},
};
| 487b37c2d9a6751650f8640b9fed8315b3fd42a7 | [
"JavaScript"
] | 1 | JavaScript | kaunge-fork/hyperf.io | 1dfddddc8eae6493023df2c6cedc46d3552c0ccf | 3757f9f84ee4e9cea5752c7a7a41da6ca19c0bb4 |
refs/heads/master | <repo_name>annuDollop-12/UtilsToolAndroid<file_sep>/settings.gradle
include ':UtilsAndroid'
include ':app'
rootProject.name = "UtilsSampleProject"<file_sep>/UtilsAndroid/src/main/java/com/dollop/utilsandroid/Utils.java
package com.dollop.utilsandroid;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import java.util.Calendar;
/**
* Created by Anil on 5/1/2020.
*/
public class Utils {
public static void I(Context cx, Class<?> startActivity, Bundle data) {
Intent i = new Intent(cx, startActivity);
if (data != null)
i.putExtras(data);
cx.startActivity(i);
}
public static String showTimeInAM_PM(int hour, int min) {
String format;
if (hour == 0) {
hour += 12;
format = "AM";
} else if (hour == 12) {
format = "PM";
} else if (hour > 12) {
hour -= 12;
format = "PM";
} else {
format = "AM";
}
// return String.valueOf(new StringBuilder().append(hour).append(":").append(min).append(" ").append(format));
return String.valueOf(new StringBuilder().append(hour).append(":").append(min));
}
/*
public static void Focuslistener(EditText Edittext, LinearLayout linearlayout) {
Edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
linearlayout.setBackgroundResource(R.drawable.edittextbackyellowstroke);
} else {
linearlayout.setBackgroundResource(R.drawable.selecttypeunselectedback);
}
}
});
}
*/
/*
public static void Focuslistener(EditText Edittext, RelativeLayout linearlayout) {
Edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
linearlayout.setBackgroundResource(R.drawable.edittextbackyellowstroke);
} else {
linearlayout.setBackgroundResource(R.drawable.selecttypeunselectedback);
}
}
});
}
*/
public static String showAM_PM(int hour, int min) {
String format;
if (hour == 0) {
hour += 12;
format = "AM";
} else if (hour == 12) {
format = "PM";
} else if (hour > 12) {
hour -= 12;
format = "PM";
} else {
format = "AM";
}
// return String.valueOf(new StringBuilder().append(hour).append(":").append(min).append(" ").append(format));
return format;
}
public static void EnableRuntimePermission(Activity activity) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA}, 1);
}
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_COARSE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
public static void I_finish(Context cx, Class<?> startActivity, Bundle data) {
Intent i = new Intent(cx, startActivity);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (data != null)
i.putExtras(data);
cx.startActivity(i);
}
public static void I_clear(Context cx, Class<?> startActivity, Bundle data) {
Intent i = new Intent(cx, startActivity);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (data != null)
i.putExtras(data);
cx.startActivity(i);
}
public static void E(String msg) {
String Msg = ":::" + msg + ":::";
if (true)
Log.e("Log.E By Anil", Msg);
}
/*
public static String getFormattedDate(long smsTimeInMilis, Context context) {
Calendar smsTime = Calendar.getInstance();
smsTime.setTimeInMillis(smsTimeInMilis);
Calendar now = Calendar.getInstance();
final String timeFormatString = "h:mm aa";
final String dateTimeFormatString = "EEE, MMM d, h:mm aa";
final long HOURS = 60 * 60 * 60;
if (now.get(Calendar.DATE) == smsTime.get(Calendar.DATE)) {
return context.getString(R.string.today) + DateFormat.format(timeFormatString, smsTime);
} else if (now.get(Calendar.DATE) - smsTime.get(Calendar.DATE) == 1) {
return context.getString(R.string.yesterday) + DateFormat.format(timeFormatString, smsTime);
} else if (now.get(Calendar.YEAR) == smsTime.get(Calendar.YEAR)) {
return DateFormat.format(dateTimeFormatString, smsTime).toString();
} else {
return DateFormat.format("MMM dd yyyy, h:mm aa", smsTime).toString();
}
}
*/
/* public static Dialog initProgressDialog(Context c) {
Dialog dialog = new Dialog(c);
dialog.setCanceledOnTouchOutside(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progress_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setCanceledOnTouchOutside(false);
dialog.show();
return dialog;
}*/
public static void T(Context c, String msg) {
Toast.makeText(c, msg, Toast.LENGTH_SHORT).show();
}
public static void share(Context c, String subject, String shareBody) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
c.startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
public static void T_Long(Context c, String msg) {
Toast.makeText(c, msg, Toast.LENGTH_LONG).show();
}
} | 7bb917094f2fe8a6ea608e0da5925fcbd47c6492 | [
"Java",
"Gradle"
] | 2 | Gradle | annuDollop-12/UtilsToolAndroid | 7bf0d2b0178eb8e0fa1d2dbecca6c98fa3983c43 | 15521f9d7f8e163cdbe3ffa993ec07ad27e814e1 |
refs/heads/main | <repo_name>NsiLycee/orientation<file_sep>/ressources/script/listesIdeesGrandoral.js
/***************************************************************************
** **
** listes des thématiques et idées de questions associées **
** pour le grand oral du bac **
** **
****************************************************************************/
const themes = [
"L’histoire de l’informatique",
"Langages et programmation",
"Données structurées et structures de données",
"Algorithmique",
"Bases de données",
"Architectures matérielles, systèmes d’exploitation et réseaux",
"Interfaces Hommes-Machines (IHM)",
"Impact sociétal et éthique de l'informatique"];
const questions = [
[
"Femmes et numérique : quelle histoire ? quel avenir ?",
"<NAME>, pionnière du langage informatique",
"Les calculatrices de la NASA (étaient des femmes !)",
"<NAME>, et l’informatique fut",
"Quelle est la différence entre le web 1.0 et le web 2.0 ?",
"La numérisation des prévisions météo"
],[
"P = NP, un problème à un million de dollars ?",
"Tours de Hanoï : plus qu’un jeu d’enfants ?",
"Les fractales : informatique et mathématiques imitent-elles la nature ?",
"De la récurrence à la récursivité","Les bugs : bête noire des développeurs ?",
"Comment rendre l’informatique plus sûre ?"
],[
"L’informatisation des métros : progrès ou outil de surveillance ?",
"Musique et informatique : une alliance possible de l’art et de la science ?"
],[
"Comment créer une machine intelligente ?",
"Comment lutter contre les biais algorithmiques ?",
"Quels sont les enjeux de la reconnaissance faciale (notamment éthiques) ? ",
"Quels sont les enjeux de l’intelligence artificielle ?",
"Transformation d’images : Deep Fakes, une arme de désinformation massive ? La fin de la preuve par l’image ?",
"Qu’apporte la récursivité dans un algorithme ?",
"Quel est l’impact de la complexité d’un algorithme sur son efficacité ?"
],[
"Données personnelles : la vie privée en voie d’extinction ?",
"Comment optimiser les données ?"
],[
"L’ordinateur quantique : nouvelle révolution informatique ?",
"La course à l’infiniment petit : jusqu’où ?",
"Peut-on vraiment sécuriser les communications ?",
"Quelle est l’utilité des protocoles pour l’internet ?",
"Cyberguerre : la 3ème guerre mondiale ?"
],[
"Smart cities, smart control ?",
"La réalité virtuelle : un nouveau monde ?",
"La voiture autonome, quels enjeux ?"
],[
"Comment protéger les données numériques sur les réseaux sociaux ?",
"Quelle est l'empreinte carbone du numérique en terme de consommation ?",
"Pourquoi chiffrer ses communications ?",
"Les réseaux sociaux sont-ils compatibles avec la politique ?",
"Les réseaux sociaux sont-ils compatibles avec le journalisme ?",
"Les réseaux sociaux permettent-ils de lutter contre les infox ?",
"L'informatique-t-elle révolutionner le dessin animé ?",
"L'informatique-t-elle révolutionner la composition musicale ?",
"L'informatique-t-elle révolutionner l'art ?",
"L'informatique-t-elle révolutionner le cinéma ?",
"L'informatique-t-elle révolutionner la médecine ?",
"L'informatique-t-elle révolutionner la physique ?",
"L'informatique-t-elle révolutionner l'entreprise",
"Le numérique : facteur de démocratisation ou de fractures sociales ?",
"Informatique : quel impact sur le climat ?"]];
<file_sep>/ressources/script/tmp.js
/*
Test javascript
*/
var globale, rebour = 5;
// fonction qui s'appelle elle-même au chargement de la page
(function() {
let parag1 = document.createElement("p");
let parag2 = document.createElement("p");
parag1.innerHTML = "Ce paragraphe va s'autodétruire dans "+ rebour +" secondes !";
parag1.style.background = "rgb(200,255,200)";
parag1.style.color = "rgb(55,0,55)";
document.body.appendChild(parag1);
parag2.innerHTML = "Compte = " + rebour + " secondes";
parag2.style.background = "rgb(200,255,200)";
parag2.style.color = "rgb(55,0,55)";
document.body.appendChild(parag2);
globale = setInterval(compte,1000);
setTimeout(bang, rebour*1000);
})();
function bang () {
clearInterval(globale);
let N = document.getElementsByTagName("p").length;
document.body.removeChild(document.getElementsByTagName("p")[N-1]); //ou bien plus simplement
// dernier paragraphe
//document.body.removeChild(document.body.lastChild);
document.body.removeChild(document.getElementsByTagName("p")[N-2])
}
function compte () {
let N = document.getElementsByTagName("p").length;
// dernier paragraphe
document.getElementsByTagName("p")[N-1].innerHTML = "Compte = " + rebour + " secondes";
rebour -= 1;
}
<file_sep>/ressources/script/sommaire.js
/*
Auteur : <NAME>
Contenu : construction de la liste des items du sommaire
Date de création : 23 / 09 /2019
*/
// ressources typographique à copier /coller : À Á Â Ä Æ Ç É È Ê Ë Î Ï Ô Ö Ø OE Ú Ù Û Ü
// déclarations des variables globales (var vs let) et initialisation
var tabItems = new Array() ;
var baseURL = "http://jodenda.free.fr/programmeNSI/" ;
var URLs = ["../niveau_0.html","programmeNSIpremier_0.html","programmeNSITerm_0.html"] ;
// liste des contenus (innerTHML) des items
tabItems = [ "enseignement de SNT en seconde" ,
"enseignement de NSI en première" ,
"enseignement de NSI en terminale" ] ;
// Constantes
const nItems = tabItems.length ; // ne change pas
// fonction appelée par onload dans la balise body ou par init ()
function construireListeSommaire () {
var listeSommaire = document.getElementById("listeSommaire") ;
listeSommaire.innerHTML = "<h2>Sommaire :</h2><ul> <li>"+
"<a href='index.html' >Accueil du site</a></li>" ;
for (var i=0; i < nItems; i++) {
listeSommaire.innerHTML += "<li><a href='" + baseURL + URLs[i] +
"' target='_blank' >" + tabItems[i] +
"</a></li>" ;
}
listeSommaire.innerHTML += "<li><a href='https://www.iut-rodez.fr/fr/"+
"les-formations/but-informatique/but-informatique-programme'" +
" target='_blank' >" +"programme du BUT d'informatique</a></li>" ;
listeSommaire.innerHTML += "</ul>";
}
construireListeSommaire2 ();
/* autre méthode de constuction utilisant les propriétés du DOM : document object model | // commentaires
_____________________________________________________________________________________| // ______________________________________*/
function construireListeSommaire2 () {
// déclaration des variables locales (let vs. var) et initialisation
let nItemms = tabItems.length ,
item , // un des items du menu : <li>
lien , // lien vers href
listeSommaire = document.getElementById("listeSommaire") ,
i , // index de boucle for
menu = document.createElement("ul") ; // objet menu : balise <ul> = liste à puces
for (i=0; i < nItems; i++) {
item = document.createElement("li") ;
lien = document.createElement("a") ;
lien.href = baseURL + URLs[i] ;
lien.innerHTML = tabItems[i] ;
lien.alt = "lien vers " + tabItems[i] ;
lien.title = "lien vers " + tabItems[i] ;
item.appendChild(lien) ;
menu.appendChild(item) ;
}
// items supplémentaires
item = document.createElement("li") ;
lien = document.createElement("a") ;
lien.href = "https://www.iut-rodez.fr/fr/les-formations/but-informatique"+
"/but-informatique-programme" ;
lien.innerHTML = "programme du BUT d'informatique" ;
lien.alt = "lien vers programme du BUT d'informatique" ;
lien.title = "lien vers programme du BUT d'informatique" ;
item.appendChild(lien) ;
menu.appendChild(item) ;
listeSommaire.appendChild(menu) ;
}
<file_sep>/README.md
# orientation
Que faire après le bac avec la spécialité NSI ?
| e4112feafdf6e5ab14a52adb26143d795484de1f | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | NsiLycee/orientation | ac992856e90a3b6b894aea6667559dbbe5c62403 | 22ad0767040569dd5019b945e15382c17f1e6ff6 |
refs/heads/master | <repo_name>rekpero/timesheet-server-spring<file_sep>/my-dream-timesheet-microservice/src/main/resources/application.properties
spring.jackson.deserialization.fail-on-unknown-properties = false
<file_sep>/my-dream-project-microservice/src/main/java/com/myapp/spring/model/Member.java
package com.myapp.spring.model;
import java.io.Serializable;
import lombok.Data;
@Data
public class Member implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String hourlyrate;
}
<file_sep>/my-dream-timesheet-microservice/src/main/java/com/myapp/spring/service/TimesheetModelListener.java
package com.myapp.spring.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.stereotype.Component;
import com.myapp.spring.model.Project;
import com.myapp.spring.model.Timesheet;
@Component
public class TimesheetModelListener extends AbstractMongoEventListener<Timesheet> {
private CounterService counterService;
@Autowired
public TimesheetModelListener(CounterService counterService) {
this.counterService =counterService;
}
@Override
public void onBeforeConvert(BeforeConvertEvent<Timesheet> event) {
if (event.getSource().getId() < 1) {
event.getSource().setId(counterService.generateSequence(Timesheet.SEQUENCE_NAME));
}
}
}
<file_sep>/my-dream-project-microservice/src/main/java/com/myapp/spring/repository/ProjectRepository.java
package com.myapp.spring.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.myapp.spring.model.Project;
@Repository
public interface ProjectRepository extends MongoRepository<Project, Integer> {
}
<file_sep>/my-spring-phases-service/src/main/java/com/myapp/spring/repository/PhasesRepository.java
package com.myapp.spring.repository;
import org.springframework.data.mongodb.repository.DeleteQuery;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.myapp.spring.model.Phases;
@Repository
public interface PhasesRepository extends MongoRepository<Phases, Integer> {
@DeleteQuery
void deleteByName(String name);
}
<file_sep>/my-dream-project-microservice/src/main/java/com/myapp/spring/api/ProjectAPI.java
package com.myapp.spring.api;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.myapp.spring.model.Project;
import com.myapp.spring.repository.ProjectRepository;
import com.myapp.spring.service.CounterService;
@RestController
@CrossOrigin("http://localhost:3000")
public class ProjectAPI {
@Autowired
private ProjectRepository repository;
@Autowired
private CounterService counterService;
@GetMapping("/projects")
public ResponseEntity<List<Project>> findAll(){
List<Project> sheets=repository.findAll();
return new ResponseEntity<List<Project>>(sheets, HttpStatus.OK);
}
@GetMapping("/projects/{id}")
public ResponseEntity<Project> findById(@PathVariable("id") int id)
{
return new ResponseEntity<Project>(repository.findById(id).get(), HttpStatus.GONE);
}
@PostMapping("/projects")
public ResponseEntity<Project> addProject(@RequestBody Project project)
{
project.setId(counterService.generateSequence(Project.SEQUENCE_NAME));
project=repository.save(project);
return new ResponseEntity<Project>(project, HttpStatus.CREATED);
}
@PutMapping("/projects/{id}")
public ResponseEntity<Project> updateExistingProject(
@PathVariable("id")Integer id,@RequestBody Project project)
{
Project existingTimesheet = repository.findById(id).get();
BeanUtils.copyProperties(project, existingTimesheet);
existingTimesheet = repository.save(existingTimesheet);
return new ResponseEntity<Project>(existingTimesheet, HttpStatus.ACCEPTED);
}
@DeleteMapping("/projects/{id}")
public ResponseEntity<Project> delete(@PathVariable("id") int id)
{
repository.deleteById(id);
Project phases = new Project();
phases.setId(id);
return new ResponseEntity<Project>(phases, HttpStatus.GONE);
}
}
<file_sep>/my-dream-project-microservice/src/main/java/com/myapp/spring/model/Phases.java
package com.myapp.spring.model;
import lombok.Data;
@Data
public class Phases {
private String name;
private int id;
private Color color;
}
<file_sep>/my-spring-phases-service/src/main/java/com/myapp/spring/api/PhasesAPI.java
package com.myapp.spring.api;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.myapp.spring.model.Phases;
import com.myapp.spring.repository.PhasesRepository;
@RestController
@CrossOrigin("http://localhost:3000")
public class PhasesAPI {
@Autowired
private PhasesRepository phasesRepository;
@GetMapping("/phases")
public ResponseEntity<List<Phases>> findAll(){
return new ResponseEntity<List<Phases>>(phasesRepository.findAll(), HttpStatus.OK);
}
@GetMapping("/phases/{id}")
public Phases getById(@PathVariable("id") int id)
{
return phasesRepository.findById(id).get();
}
@PostMapping("/phases")
public ResponseEntity<Phases> addNewPhases(@RequestBody Phases phases)
{
phases = phasesRepository.save(phases);
return new ResponseEntity<Phases>(phases, HttpStatus.CREATED);
}
@PutMapping("/phases/{id}")
public ResponseEntity<Phases> updateExistingPhases(
@PathVariable("id")Integer id,@RequestBody Phases phases)
{
Phases existingPhases=phasesRepository.findById(id).get();
BeanUtils.copyProperties(phases, existingPhases);
existingPhases = phasesRepository.save(existingPhases);
return new ResponseEntity<Phases>(existingPhases, HttpStatus.ACCEPTED);
}
@DeleteMapping("/phases/{name}")
public ResponseEntity<Phases> delete(@PathVariable("name") String name)
{
phasesRepository.deleteByName(name);
Phases phases = new Phases();
phases.setName(name);
return new ResponseEntity<Phases>(phases, HttpStatus.GONE);
}
}
| 8e7a0b9b743c3cc3650373687ae57cacf83f69ef | [
"Java",
"INI"
] | 8 | INI | rekpero/timesheet-server-spring | cf9ab53f3549954b93d4bf1d0c43ef26df89c284 | 1b9c29124c484e11a5d3f6b0ca7ea5385f0d5bbd |
refs/heads/master | <repo_name>tiger7456/NutzCodeInsight<file_sep>/README.md
# NutzCodeInsight
- 1、支持NutzBoot项目快速搭建
- 2、在 Nutz Action 中点击 @Ok 前面的模版图标即可快速打开或切换至已经打开的模版文件
- 3、支持以HTML、JSP等格式文件作为模版的框架资源文件的快速定位(支持动态配置)
- 4、Navigate菜单中增加查找@At映射地址快捷方式
- 5、Nutz web环境中支持折叠显示国际化配置文件变量值(快捷键:Alt++或Alt+-)
- 6、Beetl模版中也支持国际化配置文件折叠(${i18n("login.sucess")}或者${i18n("login.sucess","参数1","参数N")} )(快捷键:Alt++或Alt+-)
- 7、Nutz 支持折叠显示java类中注入配置文件变量值 @Inject("java:$conf.get('attach.savePath')")(快捷键:Alt++或Alt+-)
- 8、支持实体类中快速创建接口与实现类(快捷键:Alt+insert)
>idea插件仓库[https://plugins.jetbrains.com/plugin/10311-nutzcodeinsight](https://plugins.jetbrains.com/plugin/10311-nutzcodeinsight "真实项目")
#### 具体功能滑动至底看GIF图
- 1 在 Nutz Action 中点击 @Ok 前面的模版图标即可快速打开或切换至已经打开的模版文件
```java
//模式1 jsp模版(默认支持)
@Ok("jsp:btl.demo.manager")
//模式2 beetl模版 (默认支持)
@Ok("btl:btl.demo.manager")
@Ok("beetl:btl.demo.manager")
//模式3 (适用于改造后得视图返回器,我自己使用的)
@Ok("btl:WEB-INF/btl/demo/manager.html")
```
- 2 支持以HTML、JSP等格式文件作为模版的框架资源文件的快速定位(支持动态配置)
```jsp
<link rel="stylesheet" href="${base}/static/plugins/bootstrap/css/bootstrap.min.css?_=${productVersion}">
<script src="${base}/static/plugins/jquery/jQuery-2.1.4.min.js"></script>
```
#### 4 持以HTML、JSP等格式文件作为页面模版得资源文件的快速定位(将光标移至 "login.sucess" 中任意位置 使用快捷键(展开:ctrl+ 收起:ctrl-))
```java
MvcI18n.message("login.sucess");
MvcI18n.messageOrDefault("login.sucess","登录成功");
MvcI18n.messageOrDefaultFormat("login.sucess","{0}帐号登录{1}","test","失败");//test帐号登录失败
Mvcs.getMessage(Mvcs.getReq(),"login.sucess");
```
### 添加自定义配置
- File >> Settings >> NutzCodeInsight
- File >> Settings >> Other Settings >> NutzCodeInsight
# 安装后效果


<file_sep>/src/com/sgaop/idea/codeinsight/FunctionTooltip.java
package com.sgaop.idea.codeinsight;
import com.intellij.util.Function;
/**
* Created by IntelliJ IDEA.
*
* @author 黄川 <EMAIL>
* @date 2018/1/3 0003 22:43
*/
public class FunctionTooltip implements Function {
@Override
public Object fun(Object o) {
return "点我快速切换至对应文件";
}
}
<file_sep>/src/com/sgaop/idea/codeinsight/navigation/AbstractNavigationHandler.java
package com.sgaop.idea.codeinsight.navigation;
import com.intellij.codeInsight.daemon.GutterIconNavigationHandler;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBList;
import com.intellij.util.ui.JBUI;
import com.sgaop.idea.codeinsight.util.NutzLineUtil;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
/**
* @author 黄川 <EMAIL>
* @date: 2018/9/3
*/
public abstract class AbstractNavigationHandler implements GutterIconNavigationHandler {
/**
* 是否匹配跳转条件
*
* @param psiElement
* @return
*/
public abstract boolean canNavigate(PsiElement psiElement);
/**
* 检索符合的资源文件
*
* @param psiElement
* @return
*/
public abstract List<VirtualFile> findTemplteFileList(PsiElement psiElement);
@Override
public final void navigate(MouseEvent mouseEvent, PsiElement psiElement) {
if (canNavigate(psiElement)) {
final Project project = psiElement.getProject();
final List<VirtualFile> fileList = findTemplteFileList(psiElement);
if (fileList.size() == 1) {
FileEditorManager.getInstance(project).openFile(fileList.get(0), true);
} else if (fileList.size() > 1) {
final List<VirtualFile> infos = new ArrayList<>(fileList);
final JBList list = new JBList(infos);
list.setFixedCellHeight(25);
PopupChooserBuilder builder = new PopupChooserBuilder(list);
builder.setTitle(" 请选择要打开的模版文件 ");
builder.setCancelOnClickOutside(true);
builder.setCancelOnWindowDeactivation(true);
list.installCellRenderer(vfile -> {
VirtualFile tempVfile = (VirtualFile) vfile;
Icon icon = NutzLineUtil.getTemplateIcon(tempVfile.getExtension());
final String path = tempVfile.getCanonicalPath()
.replace(project.getBasePath(), "")
.replace("/src/main/webapp/", " ")
.replace("/src/main/resources/", " ")
.replace("WEB-INF/", " ") + " ";
final JBLabel nameLable = new JBLabel(path, icon, SwingConstants.LEFT);
nameLable.setBorder(JBUI.Borders.empty(2));
return nameLable;
});
builder.setItemChoosenCallback(() -> {
final VirtualFile value = (VirtualFile) list.getSelectedValue();
FileEditorManager.getInstance(project).openFile(value, true);
}).createPopup().show(new RelativePoint(mouseEvent));
} else {
if (fileList == null || fileList.size() <= 0) {
JOptionPane.showMessageDialog(null, "没有找到这个资源文件,请检查!", "错误提示", JOptionPane.ERROR_MESSAGE, null);
}
}
}
}
}
| 77369cf7dc52baf588f59154ae8f68a4ab15cdf4 | [
"Markdown",
"Java"
] | 3 | Markdown | tiger7456/NutzCodeInsight | e18c715c16cb3332360ba6a9a18d2c5c31f57d5e | a6c50fa3d6c75fde9b3896414816575fb66a23e0 |
refs/heads/main | <file_sep>lista = [[],[[],[]],[]]
print('='*30)
while True:
nome = input('Nome: ')
lista[0].append(nome)
nota1 = float(input('Nota 1: '))
lista[1][0].append(nota1)
nota2 = float(input('Nota 2: '))
lista[1][1].append(nota2)
media = (nota1 + nota2) / 2
lista[2].append(media)
print('='*30)
resp = input('Quer continuar? [S/N]: ')
print('='*30)
if resp in 'Nn':
break
while True:
print('='*30)
print('No. NOME MÉDIA')
print('-'*30)
for c in range(0, len(lista[0])):
print(f'{c} {lista[0][c]} {lista[2][c]}')
res = int(input('Mostrar notas de qual aluno? (999 interrompe): '))
if res < len(lista[0]):
for c in range(0, len(lista[0])):
if res == c:
print('='*30)
print(f'Notas de {lista[0][c]} são {lista[1][0][c]} e {lista[1][1][c]}')
elif res == 999:
break
else:
print('='*30)
print('Aluno inválido! Tente novamente.')
print('='*30)
print('Volte sempre!')
print('='*30)<file_sep>lista = {
'nome': '',
'media': '',
'situacao': ''
}
lista['nome'] = input('Nome: ')
lista['media'] = float(input(f'Média de {lista["nome"]}: '))
print(f'Nome é igual a {lista["nome"]}')
print(f'Média é igual a {lista["media"]}')
if lista['media'] < 6:
lista['situacao'] = 'Reprovado!'
else:
lista['situacao'] = 'Aprovado!'
print(f'Situação é igual a {lista["situacao"]}')<file_sep>lista = []
par = []
impar = []
lista.append(par)
lista.append(impar)
for c in range(1, 8):
valor = int(input(f'Digite o {c}o. valor: '))
if valor%2 == 0:
par.append(valor)
else:
impar.append(valor)
par.sort()
impar.sort()
print(f'pares: {par}\nímpares: {impar}')<file_sep>import random
print('Sorteador')
#Pede a quantidade de participantes
#Adicionei essa opção hehe, achei interessante
n = int(input('Quantos participantes existem no sorteio? '))
#Pede o nome de todos os participantes e armazena todos eles
participantes = []
for x in range(1, n + 1):
participante = input('{}° participante:'.format(x))
participantes.append(str(participante))
random.shuffle(participantes)
print('A ordem de apresentação será ')
print(participantes)<file_sep># Desafios Resolvidos de Python 3 do <a href='https://www.cursoemvideo.com/'>Curso em Video<a>
### <a href='https://github.com/vertocode/Python3-106Desafios-Resolvidos/tree/main/Mundo%201'>Mundo 1 | Desafio 1 - 35<a>
### <a href='https://github.com/vertocode/Python3-106Desafios-Resolvidos/tree/main/Mundo%202'>Mundo 2 | Desafio 36 - 71<a>
### <a href='https://github.com/vertocode/Python3-106Desafios-Resolvidos/tree/main/Mundo%203'>Mundo 3 | Desafio 72 - 106<a>
<file_sep>lista = {}
lista['nome'] = input('Nome do jogador: ')
n = int(input(f'Quantas partidas {lista["nome"]} jogou? '))
gols = []
lista['gols'] = gols
for c in range(0, n):
gols.append(int(input(f'Quantos gols na partida {c}: ')))
total = len(gols)
lista['total'] = total
print('-='*30)
print(f'O jogador {lista["nome"]} jogou {len(gols)} partidas.')
for c in range(0, len(gols)):
print(f' => Na partida {c}, fez {gols[c]} gols.')<file_sep>print('Aumento de salário')
salario = float(input('Salário: '))
aumento = float(15)
print('Salario de R${} teve um aumento de {}%\nNovo salário é igual a R${}'.format(float(salario), float(aumento), float(salario + (salario*aumento)/100)))<file_sep>print('Conversor de Real para Dolar')
n = float(input('Digite um valor em R$: '))
#Para atualizar o programa, basta apenas digitar o valor do dolar atual abaixo
valordolar = 3.27
print('{:.3}R$ é igual a {:.3}$'.format(float(n), float(n) * float(valordolar)))<file_sep>from random import randint
print('Sorteador')
#Pede a quantidade de participantes
#Adicionei essa opção hehe, achei interessante
n = int(input('Quantos participantes existem no sorteio? '))
#Pede o nome de todos os participantes e armazena todos eles
participantes = []
for x in range(1, n + 1):
participante = input('{}° participante:'.format(x))
participantes.append(str(participante))
#Faz o sorteio no randint() e informa o resultado do sorteio
print('Vencedor do sorteio: {}'.format(participantes[randint(0, n)]))
<file_sep>def ficha(nome='desconhecido',gols='0'):
print('=-='*20)
print(f'O jogador {nome} fez {gols} gol(s) no campeonato. ')
print('=-='*20)
name = input('Nome: ')
goals = input('Números de gols: ')
if len(name) > 0:
if len(goals) > 0:
ficha(name, goals)
else:
ficha(name)
elif len(goals) > 0:
ficha(gols=goals)
else:
ficha()<file_sep>print('Calculador de dobro, triplo e raiz quadrada')
n = int(input('Número: '))
print('O dobro de {} é {}\nO triplo de {} é {}\nA raiz quadrada de {} é {}'.format(n, n*2, n, n*3, n, n**0.5))<file_sep>length = 0;
maior = 0;
menor = 999999;
media = 0;
soma = 0;
nextt = 'S';
while nextt == 'S':
nd = int(input('Digite um número: '))
soma += nd;
if nd > maior:
maior = nd
elif nd < menor:
menor = nd
nextt = input('Quer continuar?[ S / N ]').upper()
length += 1;
media = soma / length
print('Analisando os {} números digitados, percebemos que o maior é o {}, o menor é o {}, a soma entre eles é igual a {}, e a média é {:.2}'.format(length, maior, menor, soma, media))<file_sep>num = ('um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte')
res = int(input('Digite um número entre 0 e 20:\n'))
while res > 20 or res < 0:
res = int(input('Tente novamente. Digite um número entre 0 e 20:\n'))
print(f'Você digitou o número {num[res-1]}')<file_sep>print('<NAME>')
d = int(input('Quantos dias alugados? '))
km = int(input('Quantos Km rodados? '))
print('Valor a pagar: R${:.2f}'.format((d*60)+(km*0.15)))<file_sep>n1 = int(input('Digite o 1° número: '))
n2 = int(input('Digite o 2° número: '))
function = int(input('[1] somar\n[2] multiplicar\n[3] maior\n[4] novos números\n[5] sair do programa\n'))
while function == 4:
n1 = int(input('Digite o 1° número: '))
n2 = int(input('Digite o 2° número: '))
function = int(input('[1] somar\n[2] multiplicar\n[3] maior\n[4] novos números\n[5] sair do programa\n'))
if function == 1:
somar = n1 + n2
print('='*11,somar,'='*11)
elif function == 2:
multiplicar = n1 * n2
print('='*11,multiplicar,'='*11)
elif function == 3:
if n1 > n2:
maior = n1
else:
maior = n2
print('='*11,maior,'='*11)<file_sep>n = int(input('Quantos termos: '))
ultimo = 1;
penultimo = 1;
if(n==1):
print('1 -> ', end='')
elif(n==2):
print('1 -> ', end='')
print('1 -> ', end='')
else:
count = 3
print('1 -> ', end='')
print('1 -> ', end='')
while count < n:
termo = ultimo + penultimo
penultimo = ultimo
ultimo = termo
count += 1
print(termo, '-> ', end='')
print('FIM!')<file_sep>import datetime
ano = int(input('Ano de nascimento: '))
dataatual = datetime.date.today()
year = int(dataatual.strftime('%Y'))
idade = year - ano
if idade > 18:
print('Ja passou o tempo de você se alistar faz {}anos'.format(idade - 18))
elif idade >= 17:
print('Você já está no tempo do seu alistamento!')
else:
print('Ainda falta {}anos para o seu alistamento!'.format(18 - idade))<file_sep>import random
from time import sleep
#variables
player = input('PEDRA, PAPEL OU TESOURA:\n').upper()
pc = random.randint(1,3)
#transform result pc
if pc == 1:
pc = 'PEDRA'
elif pc == 2:
pc = 'PAPEL'
else:
pc = 'TESOURA'
#animation
print('JO')
sleep(1)
print('KEN')
sleep(1)
print('PO!!!')
print('-=' * 20)
#see who win and tell the player
if (player == 'PEDRA') and (pc == 'TESOURA') or (player == 'PAPEL') and (pc == 'PEDRA') or (player == 'TESOURA') and (pc == 'PAPEL'):
print('Você mostrou {} e o pc {}, Você ganhou, Parabéns!'.format(player,pc))
elif player == pc:
print('Você mostrou {} e o pc {}, Empatou!'.format(player, pc))
else:
print('Você mostrou {} e o pc {}, Você perdeu, Tente novamente!'.format(player, pc))
print('-=' * 20)<file_sep>from random import randint
num = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10),)
print(f'Os números sorteados foram {num}')
maior = num[0]
menor = num[0]
for c in num:
if c > maior:
maior = c
if c < menor:
menor = c
print(f'O maior valor sorteado foi {maior}')
print(f'O menor valor sorteado foi {menor}')<file_sep>from time import sleep
print('-~'*30)
print(' == Cadastro de jogadores == ')
print('-~'*30)
lista = {
'nome' : [],
'gols' : [],
'total' : []
}
while True:
#Pegando informações do cliente
nome = input('Nome: ')
partidas = int(input(f'Quantas partidas {nome} jogou? '))
listagol = []
total = 0;
for c in range(0, partidas):
golst = int(input(f'Quantos gols na partida {c}'))
listagol.append(golst)
total += golst
#Colocando em listas
lista['nome'].append(nome)
lista['gols'].append(listagol)
lista['total'].append(total)
res = input('Quer continuar? [S/N]: ').upper()[0]
if res == 'N':
break
#Dando opções para o cliente
while True:
print('=-'*30)
print('cod nome gols total')
print('-~'*30)
for c in range(0, len(lista['nome'])):
print(f'{c} {lista["nome"][c]} {lista["gols"][c]} {lista["total"][c]}')
opcao = int(input('Mostras dados de qual jogador?[999 para sair] '))
print('=-'*30)
if opcao == 999:
break
elif opcao > len(lista['nome'])-1:
print('Opção invalida. Tente novamente!')
else:
print(f' -- LEVANTAMENTO DO JOGADOR {lista["nome"][opcao]}')
for c in range(0, len(lista['gols'])):
sleep(1)
print(f'No jogo {c} fez {lista["total"][c]} gols.')<file_sep>import math
print('Calculador de número inteiro mais proximo')
n = float(input('Digite um número real: '))
res = math.floor(n)
print('Porção inteira do número digitado é {}'.format(res))<file_sep>print('-'*20)
print('LOJA SUPER BARATÃO')
print('-'*20)
maisdemil = 0;
menor = 99999999999999;
soma = 0;
while True:
nome = input('Nome do Produto: ')
preco = int(input('Preço: R$'))
nextt = input('Quer continuar? [ S/N ]: ').upper()
soma += preco
if preco > 1000:
maisdemil += 1;
if preco < menor:
menor = preco;
menorn = nome;
if nextt == 'N':
break
print('-'*10,'FIM DO PROGRAMA','-'*10)
print(f'O total da compra foi R${soma}\nTemos {maisdemil} custando mais de R$1000.00\nO produto mais barato foi {menorn} que custa R${menor}')<file_sep>ntermo = int(input('Qual é o primeiro termo da PA?'))
razao = int(input('Qual é a razão da PA? '))
print(ntermo, end=' => ')
c = 0;
print('\n','==' * 11)
while razao * 9 + ntermo > c:
c += razao;
print(c, end=' => ')
print('\n','==' * 11)
mais = 'a'
while mais != 0:
mais = int(input('\nQuer mais termos? quantos?(Digite 0 se não querer)'))
c1 = c;
print('==' * 11)
while razao * mais + c1 > c:
c += razao;
print(c, end=' => ')
print('\n','==' * 11)
<file_sep>nome = input('Digite seu nome completo: ').split()
print('Seu primeiro nome é {} \nSeu ultimo nome é {}'.format(nome[0],nome[len(nome)-1]))<file_sep>def maior(* n):
count = 0;
m = 0;
for c in n:
count += 1;
if count == 0:
m = c
elif c > m:
m = c;
print(f'Entre os {count} números, o maior foi o número {m}')
maior(2,7,8,6,110,4,5,10,15,25)<file_sep>from random import randint
numeros = []
def sorteio(lista):
for c in range(0, 5):
n = randint(0, 100)
lista.append(n)
print(f'Foram sorteados {lista}.')
def somaPar(lista):
sorteio(lista)
par = 0;
for c in lista:
if c%2 == 0:
par += c;
print(f'Somando os valores pares temos o número {par}')
somaPar(numeros)<file_sep>soma = 0;
cont = 0;
for c in range(1, 500, 2):
if c%3 == 0:
cont = cont + 1
soma = soma + c
print('A soma de todos os {} valores solicitados é {}'.format(cont, soma))<file_sep>price = float(input('Digite o valor normal do produto: '))
type = int(input('Qual a forma de pagamento?\n[1]À vista no dinheiro/cheque:10% de desconto\n[2]À vista no cartão:5% de desconto\n[3]em até 2x no cartão: preço normal\n[4]3x ou mais no cartão: 20% de juros\nDigite um número de acordo com a opção desejada!'))
if type == 1:
print('Valor a pagar: R${:.2f}'.format(price - (price * 0.10)))
elif type == 2:
print('Valor a pagar: R${:.2f}'.format(price - (price * 0.05)))
elif type == 3:
print('Valor a pagar: R${:.2f}'.format(price))
elif type == 4:
print('Valor a pagar: R${:.2f}'.format(price + (price * 0.20)))<file_sep>peso = float(input('Qual o seu peso? '))
altura = float(input('Qual a sua altura? '))
imc = peso / (altura ** 2)
print('Seu IMC é {:.2f}'.format(imc))
if imc < 18.5:
print('Você está abaixo do peso!')
print('Se cuide!')
elif imc >= 18.5 and imc < 25:
print('Você está com o peso ideal!')
elif imc >= 25 and imc > 30:
print('Você está em sobrepeso!')
print('Se cuide!')
elif imc >= 30 and imc > 40:
print('Voce está com obesidade!')
print('Se cuide!')
else:
print('Você está com Obesidade mórbida!')
print('Se cuide!')<file_sep>r = 0
for c in range(1, 7):
n = int(input('{}° Número: '.format(c)))
if n%2 == 0:
r += n
print(r)<file_sep>print('Desconto aplicado')
produto = float(input('Preço do produto em R$:'))
print('Produto de valor R${}\nFoi aplicado um desconto de 5%\nProduto tem um novo valor de R${} após ter sido aplicado o desconto.'.format(produto, produto * 0.05))<file_sep>print('Conversor de medidas')
valor = int(input('Valor em metros: '))
print('{} metros em centímetros é igual a {} centímetros\n{} metros em milímetros é igual a {} milímetros'.format(valor, valor * 100, valor, valor * 1000))<file_sep>km = int(input('Distancia da viagem em KM: '))
if km <= 200:
print('Valor: R${:.2f}'.format(km * 0.5))
else:
print('Valor: R${:.2f'.format(km * 0.45))<file_sep>n = int(input('Digite um número: '))
type = int(input('Digite:\n1 para binário\n2 para octal\n3 para hexadecimal\n:'))
if type == 1:
print(bin(n)[2:])
elif type == 2:
print(oct(n)[2:])
elif type == 3:
print(hex(n)[2:])
else:
print('Tipo de número invalido!')<file_sep>l1 = int(input('Primeira medida: '))
l2 = int(input('Segunda medida: '))
l3 = int(input('Terceira medida: '))
if (l1 < (l2 + l3)) or (l2 < (l1 + l3)) or (l3 < (l1 + l2)):
if (l1 == l2) and (l1 == l3):
print('É um triângulo Equilátero!')
elif ((l1 == l2) and (l1 != l3)) or ((l1 == l3) and (l1 != l2)) or ((l3 == l2) and (l3 != l1)):
print('É um triângulo Isósceles!')
else:
print('É um triângulo Escaleno')
else:
print('As medidas não formam um triângulo')<file_sep>maioridade = 0;
homens = 0;
mulhermenor = 0;
while True:
print('-'*20)
print('CADASTRE UMA PESSOA')
print('-'*20)
idade = int(input('Idade: '))
sexo = 's'
while sexo not in 'MF':
sexo = input('Sexo: [ M/F ]: ').upper()[0]
print('-'*20)
if idade > 18:
maioridade += 1;
if sexo == 'M':
homens += 1;
if sexo == 'F':
if idade < 20:
mulhermenor += 1;
nextt = input('Quer continuar? [S/N]: ').upper()
if nextt == 'N':
break;
print('=-'*20)
print(f'Total de pessoas com mais de 18 anos é igual a {maioridade}\nAo todo temos {homens} homens cadastrados\nE temos {mulhermenor} mulheres com menos de 20 anos')
print('=-'*20)<file_sep>from random import randint
print('=-' * 15)
print('VAMOS JOGAR PAR OU ÍMPAR')
print('=-' * 15)
win = 0;
while True:
value = int(input('Diga um valor: '))
pc = randint(1, 15)
if (value+pc)%2 == 0:
print('-' * 20)
print(f'Você jogou {value} e o computador {pc}. Total de {value+pc}, [DEU PAR]')
print('-' * 20)
print('Você VENCEU!')
print('Vamos jogar novamente...')
win += 1
else:
print('-' * 20)
print(f'Você jogou {value} e o computador {pc}. Total de {value+pc}, [DEU ÍMPAR]')
print('-' * 20)
print('Você PERDEU!')
print('-' * 20)
break
print(f'GAME OVER! Você venceu {win} vezes.')
print('-' * 20)<file_sep>def header_pyhelp():
print('\33[30;42m-' * 35 + f'\n{"SISTEMA DE AJUDA PyHelp":^35}\n' + '-' * 35)
def header_search_pyhelp(search):
header = f'Acessando o manual do comando "{search}"'
print('\33[30;44m~' * (len(header) + 4))
print(f' {header} ')
print('~' * (len(header) + 4))
def pyhelp(search):
header_search_pyhelp(search)
print('\33[37;40m', end='')
return help(search)
while True:
header_pyhelp()
pesquisa = input('\33[mFunção ou Biblioteca >>> ').strip().lower()
if pesquisa.upper() == 'FIM':
print('\33[30;41m=' * 20 + f'\n{"FINALIZADO":^20}\n' + '=' * 20)
break
pyhelp(pesquisa)<file_sep>from datetime import date
year = date.today().strftime('%Y')
print('=~='*30)
dic = {}
dic['nome'] = input('Nome: ')
nascimento = int(input('Ano de Nascimento: '))
idade = int(year) - nascimento
dic['idade'] = idade
dic['cttps'] = int(input('Carteira de Trabalho (0 não tem): '))
if dic['cttps'] != 0:
dic['ano de contratação'] = int(input('Ano de Contratação: '))
dic['salario'] = int(input('Salário: R$ '))
aposentadoria = ((dic['ano de contratação'] - int(year)) + 35) + idade
print('-=~'*30)
print(dic)
print(f'nome tem o valor {dic["nome"]}')
print(f'idade tem o valor {dic["idade"]}')
if dic['cttps'] != 0:
print(f'contratação tem o valor {dic["ano de contratação"]}')
print(f'salário tem o valor {dic["salario"]}')
print(f'aposentadoria tem o valor {aposentadoria}')
print('-=~'*30)<file_sep>lista = []
res = 'S'
count = 0;
while res == 'S':
lista.append(int(input('Digite um valor: ')))
res = input('Quer continuar?[S/N]').upper()[0]
count += 1;
lista.sort(reverse=True)
print(f'Tem {count} elementos')
print(f'Os valores em ordem decrescente são {lista}')
if 5 in lista:
print('Tem 5!')<file_sep>n = int(input('Digite um número: '))
v = 0;
for c in range(1, n+1):
r = n % c
if r == 0:
v += 1
if v == 2:
print('É um número primo!')
else:
print('Não é um número primo!')
print(v)<file_sep>def leiaint(m):
s = False
v = 0
while True:
n = input('\033[0;34m'+m+'\033[m')
if n.isnumeric():
v = int(n)
s = True;
else:
print('\033[0;31m[ERRO]! Digite um número inteiro válido.\033[m')
if s:
break
return v
num = leiaint('Digite um número: ')
print(f'Você digitou o número {num}')<file_sep>lista = []
for c in range(0, 5):
lista.append(int(input('Digite um valor para a Posição {}: ')))
lista2 = lista[:]
lista2.sort()
pmaior = 0;
while lista2[-1] != lista[pmaior]:
pmaior += 1;
pmenor = 0;
while lista2[0] != lista[pmenor]:
pmenor += 1;
print('=='*20)
print(f'Você digitou os valores {lista}')
print(f'O maior valor digitado foi {lista2[-1]} na posição {pmaior+1}' )
print(f'O menor valor digitado foi {lista2[0]} na posição {pmenor+1}' )<file_sep>lista = {}
nome = []
sexo = []
idade = []
while True:
nome.append(input('Nome: '))
lista['nome'] = nome
sexo.append(input('Sexo: [M/F] ').upper()[0])
lista['sexo'] = sexo
idade.append(int(input('Idade: ')))
lista['idade'] = idade
res = input('Quer continuar? [ S / N ]: ').upper()[0]
if res == 'N':
break
somaidade = 0;
for c in idade:
somaidade += c;
lista['somaidade'] = somaidade
mulheres = []
for n,c in enumerate(sexo):
if c == 'F':
mulheres.append(nome[n])
lista['mulheres'] = mulheres
media = somaidade / len(lista['nome'])
print(f' - O grupo tem {len(lista["nome"])}')
print(f' - A média de idade é de {media}')
print(f' - As mulheres cadastradas foram: {mulheres}')
print(f'Lista de pessoas que estão acima da média: ')
for c in range(0, len(nome)):
if media < idade[c]:
print(f' -Nome = {nome[c]}; sexo = {sexo[c]}; idade = {idade[c]}')<file_sep>print('Calculador de média de aluno de 2 notas')
nota1 = float(input('Primeira nota: '))
nota2 = float(input('Segunda nota: '))
print('A média entre a nota {} e a nota {} é igual a {:.3}'.format(nota1, nota2, (nota1 + nota2)/2))<file_sep>col = ('Atlético-MG', 'Palmeiras', 'Fortaleza', 'Bragantino', 'Flamengo', 'Corinthians', 'Atlético-GO', 'Ceará', 'Athletico-PR', 'Internacional', 'Fluminense', 'Santos', 'Juventude', 'São Paulo', 'Cuiabá', 'Bahia', 'América-MG', 'Grêmio', 'Sport', 'Chapecoense')
sea = col.index('Chapecoense') + 1
print(f'Os 5° primeiros colocados são {col[:5]}')
print(f'Os ultimos 4 colocados são {col[-4:]}')
print(f'Os colocados em ordem alfabética: {sorted(col)}')
print(f'O Chapecoense se encontra na {sea}° posição')<file_sep>from random import randint
from operator import itemgetter
from time import sleep
lista = {'jogador1': randint(1,6),
'jogador2': randint(1,6),
'jogador3':randint(1,6),
'jogador4':randint(1,6)}
print('=-~'*20)
print('== Sorteio dos Dados ==')
for n, v in lista.items():
sleep(0.7)
print(f'O {n} tirou {v}.')
ranking = [];
ranking = sorted(lista.items(), key=itemgetter(1), reverse=True)
print('=-~'*20)
print('== Ranking dos Jogadores ==')
for n,v in enumerate(ranking):
sleep(0.7)
print(f'{n+1}° lugar: {v[0]} com {v[1]}')
print('=-~'*20)
print('Volte Sempre!')<file_sep>from playsound import playsound
import os
song = input('Qual o nome da musica a ser tocada? ')
if os.path.exists(song):
playsound(song)
else:
print('O arquivo {} não está no diretório do script Python'.format(song))<file_sep>n = 0;
c = 0;
while True:
c += 1;
nd = int(input('Digite um valor (999 para parar): '))
n += nd;
if nd == 999:
n -= 999;
c -= 1;
break
print(f'A soma dos {c} valores foi {n}!')<file_sep>import math
print('Calculador de triangulo retângulo')
n1 = float(input('Qual o valor do cateto oposto? '))
n2 = float(input('Qual o valor do cateto adjacente? '))
res = math.hypot(n1, n2)
print('A hipotenusa é {:.1f}'.format(res))
<file_sep>sexo = input('sexo[ M / F ]:').strip().upper()[0]
while sexo not in 'MF':
sexo = input('sexo[ M / F ]:').strip().upper()[0]
print('Fim!')<file_sep>ntermo = int(input('Qual é o primeiro termo da PA?'))
razao = int(input('Qual é a razão da PA? '))
c = ntermo;
while razao * 9 + ntermo > c:
c += razao;
print(c, end=' => ')<file_sep>from random import randint
player = int(input('Tente adivinhar qual número o pc pensou de 0-10: '))
pc = randint(0, 10)
count = 1;
while player != pc:
player = int(input('Você errou, tente até acertar(0-10): '))
count += 1
print('Você acertou! foi necessário {} vezes para acertar'.format(count))<file_sep>for c in range(1, 51):
if c%2 == 0:
print(c, '... ', end='')
print('FIM!')<file_sep>from datetime import date
datetoday = int(date.today().strftime('%Y'))
def voto(age):
if age > 15 and age < 18:
return 'VOTO OPCIONAL'
elif age > 17:
return 'VOTO OBRIGATÓRIO!'
else:
return 'N<NAME>'
age = int(date.today().strftime('%Y')) - int(input('Ano de nascimento: '))
state = voto(age)
print(f'Com {age} anos: {state}')<file_sep>lista = []
res = 'S'
while res == 'S':
lista.append(int(input('Digite um número: ')))
res = input('Quer continuar?[S/N]').upper()[0]
par = []
impar = []
for c in lista:
if c%2 == 0:
par.append(c)
else:
impar.append(c)
print('-='*30)
print(f'lista:{lista}\npares:{par}\nímpares:{impar}')<file_sep>valorcasa = int(input('Qual o valor da casa? R$'))
salario = int(input('Qual o seu salário? R$'))
anos = int(input('Quantos anos você vai pagar? '))
mensal = valorcasa/(anos*12)
if mensal > (salario * 0.30):
print('Infelizmente você não pode realizar essa compra!')
else:
print('Você pode realizar essa compra!\nvalor da parcela:R${:.2f}'.format(mensal))<file_sep>a = float(input('1° Medida: '))
b = float(input('2° Medida: '))
c = float(input('3° Medida: '))
if a+b < c or a+c < b or c+b < a:
print('Não é um triangulo')
else:
print('É um triangulo')
<file_sep>peso = []
maior = 0;
menor = 999999;
for c in range(1, 6):
peso.append(float(input('{} peso:'.format(c))))
if peso[len(peso)-1] > maior:
maior = peso[len(peso)-1]
if peso[len(peso)-1] < menor:
menor = peso[len(peso)-1]
print('Dos 5 pesos pedidos,\n{}\nO maior foi {}kg\n{}\nO menor foi {}kg\n{}'.format('-=' * 11, maior, '-=' * 11, menor, '-=' * 11))<file_sep>def notas(*n, sit=False):
print('=='*30)
dic = {}
dic['Quantidade de notas'] = len(n)
count = 0
soma = 0
for c in n:
count+=1
soma+=c
if count == 1:
dic['maior nota'] = c
dic['menor nota'] = c
elif c > dic['maior nota']:
dic['maior nota'] = c
elif c < dic['menor nota']:
dic['menor nota'] = c
dic['media da turma'] = soma / len(n)
if sit == True:
if dic['media da turma'] < 6:
dic['situacao'] = 'RUIM'
elif dic['media da turma'] > 6 and dic['media da turma'] < 7:
dic['situacao'] = 'RAZOAVEL'
else:
dic['situacao'] = 'BOA'
print(dic)
print('=='*30)
notas(2,3,5,10,15, sit=True)
notas(6,7,2,4.16,15)<file_sep>import math
print('Conversor de radianos para Seno, Cosseno e Tangente')
x = float(input('Digite um valor em radianos: '))
seno = math.sin(math.radians(x))
cosseno = math.cos(math.radians(x))
tangente = math.tan(math.radians(x))
print('Seno de {}° é igual a {:.2f}\nCosseno de {}° é igual a {:.2f}\nTangente de {}° é igual a {:.2f}'.format(x, seno, x,cosseno, x, tangente))<file_sep>lista = []
res = 'S'
while res == 'S':
valor = int(input('Digite um valor: '))
if valor in lista:
print('Valor duplicado! Não vou adicionar...')
else:
lista.append(valor)
print('Valor adicionado com sucesso...')
res = input('Que continuar?[S/N]').upper()[0]
lista.sort()
print(f'Você digitou os valores {lista}')<file_sep>nums = (int(input('1° valor: ')), int(input('2° valor: ')), int(input('3° valor: ')), int(input('4° valor: ')))
print(f'Você digitou os valores: {nums}\nO valor 9 apareceu {nums.count(9)} vezes\nO valor 3 apareceu na posição {nums.index(3)+1}°\nOs números pares foram ', end='')
for c in nums:
if c % 2 == 0:
print(c, end=', ')
print('\n')<file_sep>lista = []
for c in range(0, 3):
for n in range(0, 3):
lista.append(int(input(f'Digite um valor para [{c}, {n}]: ')))
print('-='*30)
count = 0;
for c in range(0, 9):
print(f'[ {lista[c]} ]', end='')
count += 1
if count%3 == 0:
print('')
print('-='*30)
soma = 0;
terc = 0;
seg = 0;
count = 0;
for c in lista:
count += 1;
if c%2 == 0:
soma += c
if count == 3 or count == 6 or count == 9:
terc += c
if count > 3 and count < 7:
if count == 4:
seg = c
else:
if c > seg:
seg = c;
else:
break
print(f'A soma dos valores pares é {soma}')
print(f'A soma dos valores da terceira coluna é {terc}')
print(f'O maior valor da segunda linha é {seg}')<file_sep>nd = 0;
n = 0;
while nd != 999:
nd = int(input('[DIGITE 999 PARA PARAR O PROGRAMA]\nDigite um número para acumular uma soma:'))
n = n + nd
print('A soma de todos os números digitados é igual a {}'.format(n - 999))<file_sep>print('Calculador de soma')
primeironumero = int(input('Primeiro número: '))
segundonumero = int(input('Segundo número: '))
resultado = int(primeironumero + segundonumero)
print('A soma é ', resultado)
<file_sep>nome = []
idade = []
sexo = []
for c in range(1, 5):
print('========= {}° PESSOA ========='.format(c))
nome.append(input('{}° Nome: '.format(c)))
idade.append(int(input('{}° idade: '.format(c))))
sexo.append(input('{}° sexo[F] ou [M]: '.format(c)))
def CalcularMedia(idade):
valor = 0;
for m in range(0, 4):
valor += idade[m]
valor = valor / len(idade)
return valor;
def HomemMaisVelho(idade, sexo):
valor = 0
for m in range(0, 4):
if sexo[m] == 'M' or sexo[m] == 'm':
if idade[m] > idade[m - 1]:
valor = m
return valor;
def MulheresMenosDe20Anos(idade, sexo):
n = 0;
for m in range(0, 4):
if sexo[m] == 'F' or sexo[m] == 'f':
if idade[m] < 20:
n = n + 1
return n;
MediaIdade = CalcularMedia(idade)
MMaisVelho = nome[HomemMaisVelho(idade, sexo)]
FMenosDe20anos = MulheresMenosDe20Anos(idade, sexo)
print('{}\nDesafio 56\n{}\nA média de idade do grupo é {}\n{}\nO nome do homem mais velho do grupo é o {}\n{}\nO grupo possui {} mulheres com menos de 20 anos!\n{}\nOBRIGADO POR PARTICIPAR!'.format('-=' * 11, '-=' * 11, MediaIdade, '-=' * 11, MMaisVelho, '-=' * 11, FMenosDe20anos, '-=' * 11))<file_sep>def fatorial(n, show=False):
print('-=' *30)
print(f'{n}! = ', end='')
for c in range(n, 1, -1):
c -= 1
n *= c
if show==True:
if c == 1:
print(f'{c} = ', end='')
break
print(f'{c} x ', end='')
print(n)
print('-=' *30)
fatorial(5)
fatorial(5, show=True)<file_sep>print('Calculador de Área')
largura = float(input('Largura da parede em metros: '))
altura = float(input('Altura da parede em metros: '))
tintapinta = 2
print('Sendo a largura igual a {}m e a altura igual a {}m, então a área é igual a {}m², sendo que cada litro de tinta pinta {}m², serão gastos {} litros de tinta para pintar a parede toda.'.format(largura, altura, altura * largura, tintapinta, (altura * largura) / tintapinta))<file_sep>nome = input('Qual o seu nome? ').upper()
print(nome.find('SILVA') > -1)<file_sep>print('='*20)
print('<NAME>')
print('='*20)
value = int(input('Que valor você quer sacar? R$'))
m50 = 0;
m20 = 0;
m10 = 0;
m1 = 0;
while True:
if value > 0:
if value >= 50:
value -= 50;
m50 +=1
elif value >= 20:
value -= 20;
m20 +=1
elif value >= 10:
value -= 10;
m10 +=1
else:
value -= 1;
m1 += 1
else:
break
print(f'Total de {m50} cédulas de R$50\nTotal de {m20} cédulas de R$20\nTotal de {m10} cédulas de R$10\nTotal de {m1} cédulas de R$1\n', '='*20)<file_sep>from time import sleep
def contador(i, f, p):
if p < 0:
while i > f-1:
print(i, end=' ==> ')
i += p
print('FIM!')
elif i < f:
while i < f+1:
print(i, end=' ==> ')
i += p
print('FIM!')
else:
while i > f-1:
print(i, end=' ==> ')
i -= p
print('FIM!')
contador(1, 10, 1)
contador(10, 0, 2)
i = int(input('Inicio: '))
f = int(input('Fim: '))
p = int(input('Passo: '))
contador(i, f, p)<file_sep>import random
n = random.randint(0, 5)
r = int(input("Tente adivinhar o número que o computador pensou de 0 - 5, qual é: "))
print("Você acertou!" if n == r else "Você errou!")<file_sep>nota1 = float(input('Primeira nota: '))
nota2 = float(input('Segunda nota: '))
media = (nota1 + nota2) / 2
if media < 5:
print('REPROVADO!')
elif media >= 5 and media <= 6.9:
print('RECUPERAÇÃO')
elif media > 6.9:
print('APROVADO')
else:
print('Nota inválida!')<file_sep>def escreva(str):
print('=' * len(str))
print(str)
print('=' * len(str))
while True:
t = input('Digite um texto: ')
escreva(t)
r = input('Quer continuar? [S/N]: ').upper()[0]
if r == 'N':
break
escreva('VOLTE SEMPRE!')<file_sep>s = int(input('Salário em R$'))
if s > 1250:
print('Salário novo: R${}'.format(s + (s * 0.10)))
else:
print('Salário novo: R${}'.format(s + (s * 0.15)))<file_sep>n1 = int(input('1° Número: '))
n2 = int(input('2° Número: '))
n3 = int(input('3° Número: '))
if n1 > n2 and n1 > n3:
print(n1, ' é o maior número!')
elif n2 > n1 and n2 > n3:
print(n2, ' é o maior número!')
else:
print(n3, ' é o maior número!')
if n1 < n2 and n1 < n3:
print(n1, ' é o maior número!')
elif n2 < n1 and n2 < n3:
print(n2, ' é o maior número!')
else:
print(n3, ' é o maior número!')<file_sep>ntermo = int(input('Qual é o primeiro termo da PA?'))
razao = int(input('Qual é a razão da PA? '))
for c in range(ntermo, razao * 10 + ntermo, razao):
print(c, end=' => ')
print('Acabou')<file_sep>print('Calculador de antecessor e sucessor')
n = int(input('Número: '))
print('O antecessor de {} é {} \nO sucessor de {} é {}'.format(n,n-1,n,n+1))<file_sep>import datetime
date = datetime.date.today()
datenow = int(date.strftime('%Y'))
ano = int(input('Ano de nascimento: '))
idade = datenow - ano
if idade <= 9:
print('MIRIM')
elif idade <= 14:
print('INFANTIL')
elif idade <= 19:
print('JUNIOR')
elif idade <= 20:
print('SÊNIOR')
else:
print('MASTER')<file_sep>lista = []
for c in range(0, 3):
for n in range(0, 3):
lista.append(int(input(f'Digite um valor para [{c}, {n}]: ')))
print('-='*30)
count = 0;
for c in range(0, 9):
print(f'[ {lista[c]} ]', end='')
count += 1
if count%3 == 0:
print('')<file_sep>import datetime
year = datetime.datetime.now().date().strftime('%Y')
print(year)
maior = 0;
menor = 0;
for c in range(1, 8):
ano = int(input('{}° Ano de nascimento: '.format(c)))
if (int(year) - ano) >= 21:
maior += 1;
else:
menor += 1;
print('Das 7 datas de nascimento informadas, {} atingiram a maioridade e {} ainda não atingiram!'.format(maior, menor))<file_sep>print('Conversor de Temperaturas')
temp = float(input('Informa a temperatura em °C:' ))
print('A temperatura de {}°C corresponde a {}°F!'.format(temp, 9 * temp / 5 + 32))<file_sep>c = input('Cidade: ').upper()
c = c.split()
print(c[0] == 'SANTO')<file_sep>f = input('Digite uma frase: ')
f1 = f.replace(' ','')
if f1 == f1[::-1]:
print('{} é um palíndromo'.format(f))
else:
print('{} não é um palíndromo'.format(f))
<file_sep>n = input('Digite um número: ')
n = list(n)
unidade = n[len(n) - 1]
dezena = n[len(n) - 2]
centena = n[len(n) - 3]
milhar = n[len(n) - 4]
if (len(n) == 1):
print('Unidade:{}'.format(unidade))
elif (len(n) == 2):
print('Unidade:{}\nDezena:{}'.format(unidade, dezena))
elif (len(n) == 3):
unidade = n[len(n) - 1]
dezena = n[len(n) - 2]
print('Unidade:{}\nDezena:{}\nCentena:{}'.format(unidade, dezena, centena))
else:
print('unidade:{}\ndezena:{}\ncentena:{}\nmilhar:{}'.format(unidade, dezena, centena, milhar))<file_sep>nome = input('Qual é o seu nome completo? ')
print('Seu nome em maiúsculas é {}'.format(nome.upper()))
print('Seu nome em minúsculas é {}'.format(nome.lower()))
print('Seu nome tem {} letras'.format(len(nome) - nome.count(' ')))
nomedividido = nome.split()
print('Seu primeiro nome tem {} letras'.format(len(nomedividido[0])))<file_sep>n = int(input('Digite um número: '));
nf = n
c=n;
while c != 1:
c -= 1
n = n * c
print('{}!'.format(nf),'=',n)<file_sep>km = int(input("Km/h? "))
print("Multado! valor = R${:.2f}".format(km * 7) if km > 80 else '')<file_sep>print('Calculador de tipos')
algo = input('Digite qualquer coisa: ')
print('O tipo primitivo do que você escreveu é {}'.format(type(algo)))
print('é alfanumérico? ' , algo.isalnum())
print('é alpha? ' , algo.isalpha())
print('é ASCII? ' , algo.isascii())
print('é Decimal? ' , algo.isdecimal())
print('é Digito? ' , algo.isdigit())
print('é apenas letras minúsculas? ' , algo.islower())
print('é apenas letras maiúsculas? ' , algo.isupper())
print('é espaço? ' , algo.isspace()) | 62052e345bbd2ea8f6b57556c30aee9d3944c010 | [
"Markdown",
"Python"
] | 90 | Python | vertocode/python-course-challenges | 7a18bd0d8c817e968b721732ae3bd68019fa4085 | f8dbdef6215d27ebc7c8dedb2f4cdb43dd8c6f29 |
refs/heads/master | <file_sep>import * as Scrivito from "scrivito";
const FancyHeaderWidget = Scrivito.provideWidgetClass("FancyHeaderWidget", {
attributes: {
firstImage: ["reference", { only: ["Image"] }],
firstTitle: "link",
midImage: ["reference", { only: ["Image"] }],
midTitle: "link",
lastImage: ["reference", { only: ["Image"] }],
lastTitle: "link",
text: "html",
backgroundColor: [
"enum",
{
values: [
"aqua",
"brown",
"beige",
"crimson",
"deeppink",
"deepskyblue",
"darkviolet",
"green",
"ghostwhite",
"hotpink",
"indigo",
"khaki",
"lawngreen",
"magenta",
"maroon",
"navy",
"olive",
"purple",
"red",
"royalblue",
"saddlebrown",
"slateblue",
"violet",
"yellow"
]
}
]
},
});
export default FancyHeaderWidget;
<file_sep>import * as Scrivito from "scrivito";
import * as ScrivitoPicks from 'scrivito-picks';
Scrivito.provideEditingConfig("FancyHeaderWidget", {
title: "Fancy Header",
propertiesGroups: [
{
title: 'Background Color',
component: ScrivitoPicks.createComponent([
{
attribute: 'backgroundColor',
values: [
{ value: "aqua", title: "Aqua", previewStyle: {width:'100%', height:'70px', background: 'aqua' } },
{ value: "brown", title: "Brown", previewStyle: {width:'100%', height:'70px', background: 'brown' }},
{ value: "beige", title: "Beige", previewStyle: {width:'100%', height:'70px', background: 'beige' }},
{ value: "crimson", title: "Crimson", previewStyle: {width:'100%', height:'70px', background: 'crimson' }},
{ value: "deeppink", title: "Deeppink", previewStyle: {width:'100%', height:'70px', background: 'deeppink' }},
{ value: "deepskyblue", title: "Deepskyblue", previewStyle: {width:'100%', height:'70px', background: 'deepskyblue' }},
{ value: "darkviolet", title: "Darkviolet", previewStyle: {width:'100%', height:'70px', background: 'darkviolet' }},
{ value: "green", title: "Green", previewStyle: {width:'100%', height:'70px', background: 'green' }},
{ value: "ghostwhite", title: "Ghostwhite", previewStyle: {width:'100%', height:'70px', background: 'ghostwhite' }},
{ value: "hotpink", title: "Hotpink", previewStyle: {width:'100%', height:'70px', background: 'hotpink' }},
{ value: "indigo", title: "Indigo", previewStyle: {width:'100%', height:'70px', background: 'indigo' }},
{ value: "khaki", title: "Khaki", previewStyle: {width:'100%', height:'70px', background: 'khaki' }},
{ value: "lawngreen", title: "Lawngreen", previewStyle: {width:'100%', height:'70px', background: 'lawngreen' }},
{ value: "magenta", title: "Magenta", previewStyle: {width:'100%', height:'70px', background: 'magenta' }},
{ value: "maroon", title: "Maroon", previewStyle: {width:'100%', height:'70px', background: 'maroon' }},
{ value: "navy", title: "Navy", previewStyle: {width:'100%', height:'70px', background: 'navy' }},
{ value: "olive", title: "Olive", previewStyle: {width:'100%', height:'70px', background: 'olive' }},
{ value: "orangered", title: "Orangered", previewStyle: {width:'100%', height:'70px', background: 'orangered' }},
{ value: "purple", title: "Purple", previewStyle: {width:'100%', height:'70px', background: 'purple' }},
{ value: "red", title: "Red", previewStyle: {width:'100%', height:'70px', background: 'red' }},
{ value: "royalblue", title: "Royalblue", previewStyle: {width:'100%', height:'70px', background: 'royalblue' }},
{ value: "saddlebrown", title: "Saddlebrown", previewStyle: {width:'100%', height:'70px', background: 'saddlebrown' }},
{ value: "slateblue", title: "Slateblue", previewStyle: {width:'100%', height:'70px', background: 'slateblue' }},
{ value: "violet", title: "Violet", previewStyle: {width:'100%', height:'70px', background: 'violet' }},
{ value: "yellow", title: "Yellow", previewStyle: {width:'100%', height:'70px', background: 'yellow' }},
],
}
]),
},
],
attributes: {
firstImage: {
title: "First image",
},
firstTitle: {
title: "Title",
},
midImage: {
title: "Middle image",
},
midTitle: {
title: "Title",
},
lastImage: {
title: "Last image",
},
lastTitle: {
title: "Title",
},
text: {
title: "Infotext"
}
},
properties: [
"firstImage",
"firstTitle",
"midImage",
"midTitle",
"lastImage",
"lastTitle",
"text"
],
});
<file_sep># Scrivito Fancy Header
[](https://scrivito.com) [](https://opensource.org/licenses/MIT)
A fancy header React component/Scrivito widget for the Scrivito CMS.
## Screenshot

## Installation
Open your terminal.
`$ cd` to your Scrivito project
```shell
$ npm install scrivito-fancy-header
```
Import the widget in your javascript (e.g. in `index.js` or `Widgets/index.js`).
Add this line to your index.js:
```js
import "scrivito-fancy-header";
```
Also add the styling of the widget to your app. This can be done by either loading it via `css-loader` (e.g. in `index.js` or `Widgets/index.js`):
```js
import "scrivito-fancy-header/index.css";
```
Or by including the styling to your style sheets (e.g. in `index.scss`):
```scss
@import "~scrivito-fancy-header/index.css";
```
## Features
This widget renders a header with 3 sections, side by side. On mouse over the target section growth to 2/3 of the header width. Works best with full width.
## Widget properties
In the widget properties you can set:
- 3 section with a title link and an image
The link should point to an element of the same page with an id. For this you can use the widget 'Headline with an anchor id'<file_sep>import "./FancyHeaderWidgetClass";
import "./FancyHeaderWidgetComponent";
import "./FancyHeaderWidgetEditingConfig";
| 6fce578ce4a23ee62629e02db8303d2b78937ec0 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | mdwp/scrivito-fancy-header | 7d2f1225601138ef05de6c8053326013575b9aee | a5c684509973fe22aeacf2a059b1bf5bcb520ab0 |
refs/heads/master | <file_sep>1gwords-python
==============
1-gram post words collector, just want to know what word will be after number characters.
<file_sep># encoding=utf-8
import jieba
import jieba.posseg as pseg
import MySQLdb
import codecs
## 执行sql
def exec_sql(sql_str,is_select = True):
# connect to db
db = MySQLdb.connect("localhost","root","","userview_test")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute(sql_str)
if is_select:
results = cursor.fetchall()
# 关闭数据库连接
db.close()
return results
else:
db.commit()
# 关闭数据库连接
db.close()
def tokenize(raw_text):
result = []
seg_list = jieba.cut(raw_text)
for w in seg_list:
w = w.strip()
if w!="":
print w,
result.append(w)
return result
def isNumber(char):
# numbers = ["1","2","3","4","5","6","7","8","9","0",u"一",u"二",u"三",u"四",u"五",u"六",u"七",u"八",u"九",u"零",u"十",u"百",u"千",u"万",u"亿"]
numbers = ["1","2","3","4","5","6","7","8","9","0"]
if char in numbers:
return True
else:
return False
def addToHash(word,all_hash):
print "\n*"+word,"Added*"
if all_hash.has_key(word):
all_hash[word] += 1
else:
all_hash[word] = 1
return all_hash
def analyzeText(raw_text,all_hash):
print raw_text
tokens = tokenize(raw_text)
print ""
for index,token in enumerate(tokens):
if len(token) == 1:
print token
if isNumber(token) and index!=len(tokens)-1:
addToHash(tokens[index+1],all_hash)
else:
for index2,char in enumerate(token):
print char,
if isNumber(char) and index2!=len(token)-1:
if index2==len(token)-1:
addToHash(tokens[index+1],all_hash)
else:
addToHash(token[index2+1],all_hash)
print ""
return all_hash
################################
all_hash = {}
text_list = exec_sql("SELECT * from posts ORDER BY RAND()")
for text in text_list:
analyzeText(text[5],all_hash)
f = codecs.open("result_0819.txt",'w','utf-8')
for (k,v) in sorted(all_hash.iteritems(), key=lambda (k,v): (v,k)):
f.write(k+","+str(v)+"\n")
print k,v
f.close()
| d4f5881741c2fc6879f9c91aca8bf9fc2d8665ae | [
"Markdown",
"Python"
] | 2 | Markdown | vixuowis/1gwords-python | 5a00579447b92dc6bcdca788e3988d47e0b42773 | e8e7cf9b37f24fb4b0103a85e4920c7253cd82e2 |
refs/heads/master | <repo_name>jauhari-i/NodeJs-Express-Template<file_sep>/src/models/index.js
// place mongoose Model here
<file_sep>/src/helpers/error.js
export default class ErrorConstructor extends Error {
constructor(code, message) {
super()
this.code = code
this.message = message
}
}
export const handleError = (err, res) => {
const { code, message } = err
if (!code) {
return res.status(500).json({
code: 500,
message: 'Internal server error',
success: false,
})
} else {
return res.status(code).json({
success: false,
code,
message,
})
}
}
<file_sep>/src/bin/app.js
import express from 'express'
import configureApp from '../config/configureApp'
import { getConfig } from '../config/global_config'
import connectMongo from '../db/mongoConnection'
// import { db as mysqlConnection } from '../db/mysqlConnection'
import mongoose from 'mongoose'
const port = getConfig('/port')
const app = express()
configureApp(app)
connectMongo(mongoose)
// use for mysql database
// mysqlConnection.getConnection((err,connection) => {
// if(connection){
// console.log('Connected to mysql database')
// }else{
// console.log(err)
// }
// })
app.listen(port, () => {
console.log('Server is running on port ' + port)
})
<file_sep>/src/auth/jwt_auth_instance.js
import jsonwebtoken from 'jsonwebtoken'
import fs from 'fs'
import { getConfig } from '../config/global_config'
import { handleError } from '../helpers/error'
import { UNAUTHORIZED } from 'http-status'
const jwt = jsonwebtoken
const getKey = keyPath => fs.readFileSync(keyPath, 'utf-8')
export const generateToken = async payload => {
let privateKey = getKey(getConfig('/privateKey'))
const verifyOptions = {
algorithm: 'RS256',
expiresIn: '24h',
}
const token = await jwt.sign(payload, privateKey, verifyOptions)
return token
}
export const getToken = headers => {
if (
headers &&
headers.authorization &&
headers.authorization.includes('Bearer')
) {
const parted = headers.authorization.split(' ')
if (parted.length === 2) {
return parted[1]
}
}
return undefined
}
export const verifyToken = async (req, res, next) => {
const publicKey = fs.readFileSync(getConfig('/publicKey'), 'utf8')
const verifyOptions = {
algorithm: 'RS256',
}
const token = getToken(req.headers)
if (!token) {
return handleError(
{ code: UNAUTHORIZED, message: 'Token is not valid!' },
res
)
}
let decodedToken
try {
decodedToken = await jwt.verify(token, publicKey, verifyOptions)
} catch (error) {
if (error instanceof jwt.TokenExpiredError) {
return handleError(
{ code: UNAUTHORIZED, message: 'Access token expired!' },
res
)
}
return handleError(
{ code: UNAUTHORIZED, message: 'Token is not valid!' },
res
)
}
const userId = decodedToken.sub
req.userId = userId
next()
}
<file_sep>/src/db/mongoConnection.js
import { getConfig } from '../config/global_config'
export default function connectMongo(mongoose) {
const mongoURI = getConfig('/mongoDbUrl')
mongoose.connect(
mongoURI,
{
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
},
err => {
if (err) {
console.error(err)
console.log('Failed to connect database')
} else {
console.log('Connected to Mongo database')
}
}
)
}
<file_sep>/.env.example
PORT=9000
# ------------------------------------------------------------------
# Auth
# ------------------------------------------------------------------
BASIC_AUTH_USERNAME=yourname
BASIC_AUTH_PASSWORD=<PASSWORD>
PUBLIC_KEY_PATH=public.pem
PRIVATE_KEY_PATH=private.pem
# ------------------------------------------------------------------
# DB
# ------------------------------------------------------------------
MONGO_DATABASE_URL=mongodb://localhost:27017/yourdb
MYSQL_CONNECTION_LIMIT=100
MYSQL_HOST=localhost
MYSQL_USER=root
MYSQL_PASSWORD=
MYSQL_DATABASE=dbname
<file_sep>/src/config/global_config.js
import Confidence from 'confidence'
import dotenv from 'dotenv'
dotenv.config()
const config = {
port: process.env.PORT,
basicAuthApi: [
{
username: process.env.BASIC_AUTH_USERNAME,
password: process.env.BASIC_AUTH_PASSWORD,
},
],
publicKey: process.env.PUBLIC_KEY_PATH,
privateKey: process.env.PRIVATE_KEY_PATH,
mongoDbUrl: process.env.MONGO_DATABASE_URL,
mysqlConfig: {
connectionLimit: process.env.MYSQL_CONNECTION_LIMIT,
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: <PASSWORD>,
database: process.env.MYSQL_DATABASE,
},
}
const store = new Confidence.Store(config)
export const getConfig = key => {
return store.get(key)
}
| 0eefd00a32fa89a7c936735b9f62d1526aee0a62 | [
"JavaScript",
"Shell"
] | 7 | JavaScript | jauhari-i/NodeJs-Express-Template | 0d5c616c9a3aa2919b5a5c43ea1d80e68b663fff | 5fc5d3a0dc125ada0ef13bb36d89dc8a8cef248d |
refs/heads/master | <repo_name>vanzheng/Backbone-demo<file_sep>/_static/js/config.js
// none RESTful api
// Backbone.emulateHTTP = true;<file_sep>/_static/js/views/CommentListView.js
var CommentListView = Backbone.View.extend({
initialize: function() {
this.listenTo(this.collection, 'add', this.addComment);
this.listenTo(this.collection, 'remove', this.removeComment);
this.render();
},
render: function() {
this.collection.each(function(item) {
this.addComment(item);
}, this);
},
addComment: function(item) {
var commentView = new CommentView({
model: item
});
this.$el.append(commentView.render().el);
},
removeComment: function(item) {
var commentView = new CommentView({
model: item
});
commentView.remove();
}
});
<file_sep>/_static/js/app.js
(function($) {
$(function(){
var collection = new CommentCollection();
new FormView({collection: collection, el: $('.comment-form')});
var commentListView = new CommentListView({collection:collection, el: $('.comment-list')});
//commentListView.render();
});
})(jQuery);
<file_sep>/_static/js/views/FormView.js
var FormView = Backbone.View.extend({
events: {
'click #SubmitComment': 'submitComment'
},
submitComment: function() {
var _this = this;
var comment = new CommentModel();
var nickname = this.$el.find('input[name="nickname"]').val();
var message = this.$el.find('textarea').val();
comment.set({
nickname: nickname,
message: message
});
this.collection.addComment(comment);
}
});
<file_sep>/_static/js/models/CommentModel.js
var CommentModel = Backbone.Model.extend({
idAttribute: 'commentid'
});
<file_sep>/server.js
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var _ = require('underscore');
//var multer = require('multer');
var app = express();
var router = express.Router();
var dataFolder = './data';
var jsonPath = './data/comments.json';
if (!fs.existsSync(dataFolder)) {
fs.mkdirSync(dataFolder);
}
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({
extended: true
})); // for parsing application/x-www-form-urlencoded
//app.use(multer()); // for parsing multipart/form-data
app.engine('jade', require('jade').__express);
app.set('view engine', 'jade');
app.get('/', function(req, res) {
res.render('index');
});
// RESTful API
router.route('/comments/:id?')
.all(function(req, res, next) {
console.log(req.method, req.url);
next();
})
.get(function(req, res, next) {
var data = '';
if (fs.existsSync(jsonPath)) {
data = fs.readFileSync(jsonPath);
res.send(data);
}
else {
res.send('');
}
})
.post(function(req, res, next) {
var data = req.body;
var result = [data];
var dataStr, dataJson, maxComment, maxId, comments;
try {
// 存在文件, 则读取数据
if (fs.existsSync(jsonPath)) {
dataStr = fs.readFileSync(jsonPath);
if (dataStr !== '') {
dataJson = JSON.parse(dataStr);
maxComment = _.max(dataJson, function (obj) {
return obj.commentid;
});
maxId = maxComment.commentid + 1;
result[0].commentid = maxId;
comments = dataJson.concat(result);
fs.writeFileSync(jsonPath, JSON.stringify(comments));
}
}
else {
result[0].commentid = 1;
fs.writeFileSync(jsonPath, JSON.stringify(result));
}
res.json({
'success': true,
'errorCode': 0,
'data': result[0]
});
}
catch(e) {
res.json({
'success': false,
'errorCode': 101
});
}
})
.put(function(req, res, next) {
var data = res.body;
var result = [data];
var dataStr, dataJson, comment;
try {
// 存在文件, 则读取数据
if (fs.existsSync(jsonPath)) {
dataStr = fs.readFileSync(jsonPath);
if (dataStr !== '') {
dataJson = JSON.parse(dataStr);
comment = _.find(dataJson, function(obj) {
return obj.commentid == data.commentid;
});
if (comment) {
fs.writeFileSync(jsonPath, JSON.stringify(dataJson));
res.json({
'success': true,
'errorCode': 0,
'data': dataJson
});
}
else {
res.json({
'success': false,
'errorCode': 1
});
}
}
}
}
catch(e) {
res.json({
'success': false,
'errorCode': 101
});
}
})
.delete(function(req, res, next) {
var id = req.params.id;
var dataStr, dataJson, commentsData, commentsStr;
try {
if (fs.existsSync(jsonPath)) {
dataStr = fs.readFileSync(jsonPath);
if (dataStr !== '') {
dataJson = JSON.parse(dataStr);
comments = _.reject(dataJson, function (obj) {
return obj.commentid == id;
});
if (comments) {
commentsStr = JSON.stringify(comments);
fs.writeFileSync(jsonPath, commentsStr);
res.json({
'success': true,
'errorCode': 0
});
}
else {
res.json({
'success': false,
'errorCode': 1
});
}
}
}
}
catch (e) {
res.json({
'success': false,
'errorCode': 101
});
}
})
// use router
app.use('/api', router);
// static css, js, images
app.use(express.static('_static'));
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
<file_sep>/_static/js/views/CommentView.js
var CommentView = Backbone.View.extend({
tagName: 'div',
className: 'comment-item',
events: {
'click .delete-comment': 'delete',
'click .edit-comment': 'renderEditForm',
'click .edit-comment-btn': 'update'
},
initialize: function() {
this.itemTemplate = _.template($('#CommentItem').html());
this.editFormTemplate = _.template($('#EditCommentForm').html());
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
},
render: function() {
this.$el.html(this.itemTemplate({
data: this.model.toJSON()
}));
this.$el.data('commentid', this.model.id);
return this;
},
renderEditForm: function() {
this.$el.append(this.editFormTemplate({
data: this.model.toJSON()
}));
},
delete: function() {
this.model.destroy();
},
update: function() {
var _this = this;
this.model.set({
commentid: parseInt(this.$el.find('input[name="commentid"]').val()),
nickname: this.$el.find('input[name="nickname"]').val(),
message: this.$el.find('textarea').val()
});
this.model.save();
}
});
<file_sep>/_static/js/models/CommentCollection.js
var CommentCollection = Backbone.Collection.extend({
url: '/api/comments',
model: CommentModel,
initialize: function() {
this.fetch();
},
addComment: function(model) {
var _this = this;
this.create({
'nickname': model.get('nickname'),
'message': model.get('message')
}, {
success: function(comment, res) {
if (res.success) {
comment.set('commentid', res.data.commentid);
}
}
});
}
});
| f0bfaeb1601ca4aafad92ee1f6e1abbb503aac63 | [
"JavaScript"
] | 8 | JavaScript | vanzheng/Backbone-demo | 990ee71ace68c8c2f6c9850b210fcb12a26f87fc | d694da01610c1f6cd9f0098b36d8ea857f3ba09b |
refs/heads/master | <repo_name>bmosigisi/generator-redux-saga-material<file_sep>/generators/app/templates/src/theme/index.js
import red from '@material-ui/core/colors/red';
import lightGreen from '@material-ui/core/colors/lightGreen';
import pink from '@material-ui/core/colors/pink';
import { createMuiTheme } from '@material-ui/core/styles';
export default createMuiTheme({
palette: {
primary: lightGreen,
secondary: pink,
error: red,
},
space: {
unit: 4,
},
typography: {
fontFamily: [
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
].join(','),
},
});
<file_sep>/generators/component/templates/component.js
import { withStyles } from '@material-ui/core/styles';
import React from 'react';
import PropTypes from 'prop-types';
const styles = () => ({
root: {},
});
const <%= componentName %> = ({ classes, children }) => {
return <div className={classes.root}>{children}</div>;
};
<%= componentName %>.propTypes = {
children: PropTypes.node.isRequired,
classes: PropTypes.objectOf(PropTypes.string).isRequired,
};
export default withStyles(styles)(<%= componentName %>);
<file_sep>/generators/app/templates/src/services/httpClient.js
import axios from 'axios';
import { stringify } from 'querystring';
const defaultOptions = {
headers: {},
queryParams: null,
};
export default function httpClient(
url = '',
options = defaultOptions,
) {
const rootPath = 'https://api.todo.io';
let fullPath = `${rootPath}${url}`;
if (options.queryParams) {
const queryString = stringify(options.queryParams);
fullPath = `${fullPath}?${queryString}`;
}
return axios({
url: fullPath,
method: options.method || 'GET',
headers: options.headers,
}).then(response => ({
data: response.data,
success: response.status === 200,
})).catch(err => ({
data: null,
success: false,
message: err.message,
}));
}
<file_sep>/README.md
# Generator-React-Redux-Saga-MaterialUI
[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][daviddm-image]][daviddm-url]
**generator-redux-saga-material**
A bare-bones yeoman generator built from [create-react-app](https://github.com/facebook/create-react-app) with some additions to make it easy to kick-start and manage projects that use:
- [React](https://reactjs.org/) for building the UI.
- [Redux](https://github.com/reduxjs/redux) for state management.
- [Redux Saga](https://github.com/redux-saga/redux-saga) redux middleware for handling side effects.
- [Material-UI](https://github.com/mui-org/material-ui) for react components based on google's material design.
- [JSS](https://github.com/cssinjs/jss) for css in js styling.
- [Immutable JS](https://github.com/facebook/immutable-js/) for immutable data in stores.
### Also contains:
- Linting using eslint
- Precommit hooks that run the linter.
## Installation and usage
Prerequisites:
- [Node.js](https://nodejs.org/) version >=8.0.0. You can use [nvm](https://github.com/creationix/nvm) to manage different node versions.
- Install yeoman and generator-redux-saga-material globally.
```bash
npm install -g yo
npm install -g generator-redux-saga-material
```
Then to set up a new project:
```bash
# Create a directory and cd into it
mkdir web-app && cd web-app
# To create a new project in the current directory, run the generator
yo redux-saga-material
# Start the project
yarn start
# Generating a new component
yo redux-saga-material:component SomeComponentName
# Generating a new container
yo redux-saga-material:container SomeContainerName
```
## Contribute
Contributions are welcome. Create issues for errors and requests, submit PRs against the *develop* branch.
## License
[MIT license](http://opensource.org/licenses/MIT)
[npm-image]: https://badge.fury.io/js/generator-redux-saga-material.svg
[npm-url]: https://npmjs.org/package/generator-redux-saga-material
[travis-image]: https://travis-ci.org/bmosigisi/generator-redux-saga-material.svg?branch=master
[travis-url]: https://travis-ci.org/bmosigisi/generator-redux-saga-material
[daviddm-image]: https://david-dm.org/bmosigisi/generator-redux-saga-material.svg?theme=shields.io
[daviddm-url]: https://david-dm.org/bmosigisi/generator-redux-saga-material
<file_sep>/generators/app/templates/src/services/todo.js
import httpClient from './httpClient';
/**
* @param {String} category
*
* @return Promise
*/
export const show = (category) => {
return httpClient('/todo', {
queryParams: {
category,
},
});
};
<file_sep>/generators/app/templates/src/index.js
/* eslint-disable */
import { create } from 'jss';
import { MuiThemeProvider, jssPreset } from '@material-ui/core/styles';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { JssProvider } from 'react-jss';
import { Provider } from 'react-redux';
import App from './containers/App';
import rootSaga from './sagas';
import buildStore from './store';
import theme from './theme';
const jss = create(jssPreset());
jss.setup({ insertionPoint: document.head });
class Root extends Component {
render() {
const { store } = this.props;
return (
<Provider store={store}>
<JssProvider jss={jss}>
<MuiThemeProvider theme={theme}>
<App />
</MuiThemeProvider>
</JssProvider>
</Provider>
);
}
}
const store = buildStore();
store.runSaga(rootSaga);
ReactDOM.render(
<Root
store={store}
/>,
document.getElementById('root'),
);
<file_sep>/generators/container/templates/container.js
import CircularProgress from '@material-ui/core/CircularProgress';
import Typography from '@material-ui/core/Typography';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { isLoading } from '../selectors';
const mapStateToProps = (state) => {
return {
loading: isLoading(state),
};
};
class <%= containerName %> extends Component {
static propTypes = {
loading: PropTypes.bool.isRequired,
};
render() {
const { loading } = this.props;
return (
<div>
{ loading && <CircularProgress /> }
{ !loading && <Typography variant="body2"><%= containerName %></Typography> }
</div>
);
}
}
export default connect(mapStateToProps)(<%= containerName %>);
<file_sep>/generators/app/templates/src/containers/App.js
import CircularProgress from '@material-ui/core/CircularProgress';
import Typography from '@material-ui/core/Typography';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { isLoading } from '../selectors';
const mapStateToProps = (state) => {
return {
loading: isLoading(state),
};
};
class App extends Component {
static propTypes = {
loading: PropTypes.bool.isRequired,
};
render() {
const { loading } = this.props;
return (
<div>
{ loading && <CircularProgress /> }
{ !loading && <Typography variant="body2">Welcome to redux-saga-material!</Typography> }
</div>
);
}
}
export default connect(mapStateToProps)(App);
<file_sep>/generators/container/index.js
'use strict';
const Generator = require('yeoman-generator');
const humps = require('humps');
const path = require('path');
module.exports = class extends Generator {
constructor(args, opts) {
super(args, opts);
this.argument('name', { type: String, required: false });
this.containerName = this._capitalize(
humps.camelize(this.options.name)
);
}
writing() {
const destination = path.join(
this.destinationRoot(),
'src',
'containers',
`${this.containerName}.js`
);
this.fs.copyTpl(
this.templatePath('container.js'),
this.destinationPath(destination),
{ containerName: this.containerName }
);
}
// Helpers
_capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
};
<file_sep>/generators/app/templates/src/sagas/index.js
import { takeEvery, all, fork } from 'redux-saga/effects';
import { actionTypes } from '../actions';
// ------ Helpers ---------=
function* upstart() {
yield true;
}
// ------ Handlers --------
function* handleFetchTodos() {
yield true;
}
// ------ Watchers --------
function* watchFetchTodos() {
yield takeEvery(actionTypes.FETCH_TODOS.BEGIN, handleFetchTodos);
}
export default function* root() {
yield* upstart();
yield all([
fork(watchFetchTodos),
]);
}
<file_sep>/generators/app/index.js
'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const ncp = require('ncp').ncp;
const fs = require('fs');
module.exports = class extends Generator {
prompting() {
this.log(
yosay(
`Welcome to the smashing ${chalk.red('react redux redux-saga material-ui')} generator!`
)
);
}
async writing() {
return new Promise(
(resolve, reject) => {
// First, check if the current directory is empty.
fs.readdir(this.destinationRoot(), (err, files) => {
if (err) {
this.log('Could not read current directory');
reject();
} else if (files.length) {
this.log('Sorry, this directory is not empty');
reject();
} else {
ncp(
this.templatePath(),
this.destinationPath(),
(err) => {
if (err) {
this.log(err);
reject();
}
resolve();
}
);
}
})
}
);
}
install() {
this.installDependencies({
yarn: {force: true},
npm: false,
bower: false,
});
}
};
<file_sep>/generators/app/templates/src/reducers/index.js
import { combineReducers } from 'redux-immutable';
import todo from './todo';
const reducers = combineReducers({
todo,
});
export default reducers;
| 45bf0d0715266607ec7b0d7c03c8bf627acb7a9c | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | bmosigisi/generator-redux-saga-material | 5c1ba66fce3a5aa070df46f61bdaae31ed9d1140 | 42829e5547de4a9b7e8c1a422ed2299711312116 |
refs/heads/master | <repo_name>PeiKaLunCi/EP_Collapsed_Gibbs<file_sep>/ep_clustering/data/_gibbs_data.py
#!/usr/bin/env python
"""
Gibbs Sampler Data Class
"""
import numpy as np
import pandas as pd
import logging
from ep_clustering._utils import Map
# Author Information
__author__ = "<NAME>"
# Modify the root logger
logger = logging.getLogger(name=__name__)
class GibbsData(Map):
""" Data for GibbsSampler
Must contain `num_obs` and `num_dim` attributes
See ep_clustering.data.generate_data to generate data
Methods:
_validate_data(self): check that object has proper attributes
"""
def __init__(self, *args, **kwargs):
super(GibbsData, self).__init__(*args, **kwargs)
self._validate_data()
return
def _validate_data(self):
# Check Gibbs Data has required attributes
if "num_obs" not in self:
raise ValueError("`num_obs` must be defined in GibbsData")
if "num_dim" not in self:
raise ValueError("`num_dim` must be defined in GibbsData")
return
def _categorical_sample(probs):
""" Draw a categorical random variable over {0,...,K-1}
Args:
probs (K ndarray) - probability of each value
Returns:
draw (int) - random outcome
"""
return int(np.sum(np.random.rand(1) > np.cumsum(probs)))
# EOF
<file_sep>/ep_clustering/__init__.py
import ep_clustering._utils
import ep_clustering.kalman_filter
import ep_clustering.likelihoods
import ep_clustering.evaluator
import ep_clustering.data
from ep_clustering.gibbs import (
GibbsSampler,
random_init_z,
)
from ep_clustering.likelihoods import (
construct_likelihood,
)
from ep_clustering.data import (
MixtureDataGenerator,
TimeSeriesDataGenerator,
)
from ep_clustering.evaluator import (
GibbsSamplerEvaluater,
)
from ep_clustering.exp_family import(
ExponentialFamily,
construct_exponential_family,
)
from ep_clustering.approx_algorithm import(
EPAlgorithm,
construct_approx_algorithm
)
<file_sep>/experiments/synthetic_timeseries_compare_samplers.py
# Compare the EP Gibbs sampler to classic Gibbs Samplers
# Print (Warning this is a long)
import matplotlib as mpl
mpl.use('Agg')
import os
import time
import numpy as np
import pandas as pd
import joblib
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import ep_clustering as ep
from tqdm import tqdm # Progress Bar
# Make Paths to output/figures
path_to_fig = "output/synth_ts_compare_examples/figures"
path_to_data = "output/synth_ts_compare_examples/data"
if not os.path.isdir(path_to_fig):
os.makedirs(path_to_fig)
if not os.path.isdir(path_to_data):
os.makedirs(path_to_data)
######################################################
# Generate Synthetic Data (Robust Clustering)
######################################################
np.random.seed(12345)
data_param = dict(
num_dim=200, # Length of each time series
num_obs=300, # Number of time series
K=20, # Number of clusters
sigma2_x = 0.01, # Latent noise variance
#missing_obs = 0.05, # Fraction of observations missing (i.e. NaNs)
)
data_param['A'] = 0.95 * np.ones(data_param['num_obs'])
data_gen = ep.data.TimeSeriesDataGenerator(**data_param)
data = data_gen.generate_data()
## Plot and Save Data
def plot_truth_data(data):
fig, ax = plt.subplots(1,1)
plot_df = data.df.reset_index()
z_df = pd.DataFrame({'truth': data.z,
'observation': np.arange(len(data.z))})
plot_df = pd.merge(plot_df, z_df)
sns.lineplot(x='dimension', y='y', hue='truth',
palette=sns.color_palette('deep', data['K']),
alpha=0.5,
units='observation', estimator=None, data=plot_df,
ax=ax)
return fig, ax
# Plot Data
fig, ax = plot_truth_data(data)
fig.savefig(os.path.join(path_to_fig, "true_data.png"))
# Save Data
joblib.dump(data, filename=os.path.join(path_to_data, "data.p"))
######################################################
# Define Samplers to Fit
######################################################
# TimeSeries Likelihood
likelihood = ep.construct_likelihood(
name="TimeSeries",
data=data,
)
# Number of Clusters to infer
K=data['K']
# Shared Random Init
init_z = ep.gibbs.random_init_z(N=data['num_obs'], K=K)
# Naive Gibbs
print("Setup Naive Gibbs Sampler")
naive_alg = ep.construct_approx_algorithm(
name="naive",
)
naive_sampler = ep.GibbsSampler(
data=data,
likelihood=likelihood.deepcopy(),
approx_alg=naive_alg,
K=K,
z_prior_type="fixed",
init_z=init_z,
)
# Blocked Gibbs
print("Setup Collapsed Gibbs Sampler")
collapsed_alg = ep.construct_approx_algorithm(
name="collapsed",
)
collapsed_sampler = ep.GibbsSampler(
data=data,
likelihood=likelihood.deepcopy(),
approx_alg=collapsed_alg,
K=K,
z_prior_type="fixed",
init_z=init_z,
)
# EP Gibbs
print("Setup EP Gibbs Sampler")
EP_alg = ep.construct_approx_algorithm(
name="EP",
exp_family=ep.exp_family.DiagNormalFamily,
)
EP_sampler = ep.GibbsSampler(
data=data,
likelihood=likelihood.deepcopy(),
approx_alg=EP_alg,
K=K,
z_prior_type="fixed",
init_z=init_z,
)
######################################################
# Define Evaluation
######################################################
metric_functions = [
ep.evaluator.metric_function_from_sampler("eval_loglikelihood"),
ep.evaluator.metric_function_from_state("z", data.z, "nvi"),
ep.evaluator.metric_function_from_state("z", data.z, "nmi"),
ep.evaluator.metric_function_from_state("z", data.z, "precision"),
ep.evaluator.metric_function_from_state("z", data.z, "recall"),
]
evaluators = [
ep.GibbsSamplerEvaluater(
sampler=naive_sampler,
metric_functions=metric_functions,
sampler_name="NaiveGibbs",
data_name="simple_example",
),
ep.GibbsSamplerEvaluater(
sampler=collapsed_sampler,
metric_functions=metric_functions,
sampler_name="CollapsedGibbs",
data_name="simple_example",
),
ep.GibbsSamplerEvaluater(
sampler=EP_sampler,
metric_functions=metric_functions,
sampler_name="EPGibbs",
data_name="simple_example",
),
]
######################################################
# Comparison Plot Helper Functions
######################################################
def plot_metric_vs_iteration(evaluators, metric="nmi"):
fig, ax = plt.subplots(1,1)
max_iter = []
for evaluator in evaluators:
nmi = evaluator.metrics.query('metric == "nmi"')
ax.plot(nmi.iteration, nmi.value, label=evaluator.sampler_name)
max_iter.append(nmi.iteration.max())
ax.set_xlim([0, min(max_iter)])
ax.set_xlabel('Iteration (epoch)')
ax.set_ylabel(metric)
ax.legend()
return fig, ax
def plot_metric_vs_time(evaluators, metric="nmi"):
fig, ax = plt.subplots(1,1)
max_time = []
for evaluator in evaluators:
nmi = evaluator.metrics.query('metric == "nmi"')
time = evaluator.metrics.query('metric == "time"')
ax.plot(time.value.cumsum(), nmi.value, label=evaluator.sampler_name)
max_time.append(time.value.sum())
ax.set_xlim([0, min(max_time)])
ax.set_xlabel('Time (sec)')
ax.set_ylabel(metric)
ax.legend()
return fig, ax
######################################################
# Run Each Method
######################################################
MAX_TIME = 3600 # Max time for each algorithm (1 hour)
EVAL_TIME = 120 # Time between evaluations (2 min)
evaluator_times = [0 for _ in evaluators]
print("Running Each Sampler")
while np.any([evaluator_time < MAX_TIME for evaluator_time in evaluator_times]):
for ii in range(len(evaluators)):
if evaluator_times[ii] >= MAX_TIME:
continue
start_time = time.time()
while (time.time() - start_time) < EVAL_TIME:
evaluators[ii].evaluate_sampler_step(['one_step'])
evaluator_times[ii] += time.time()-start_time
inference_time = evaluators[ii].metrics.query("metric == 'time'")['value'].sum()
print("Sampler {0}, inference time {1}, total time {2}".format(
evaluators[ii].sampler_name, inference_time, evaluator_times[ii])
)
evaluators[ii].get_metrics().to_pickle(os.path.join(path_to_data,
"{0}_metrics.p".format(evaluators[ii].sampler_name)))
# Comparision Plots
plt.close('all')
plot_metric_vs_time(evaluators, metric='nmi')[0].savefig(
os.path.join(path_to_fig, 'nmi_vs_time.png'))
plot_metric_vs_iteration(evaluators, metric='nmi')[0].savefig(
os.path.join(path_to_fig, 'nmi_vs_iter.png'))
<file_sep>/ep_clustering/approx_algorithm.py
#!/usr/bin/env python
"""
Approximate Algorithm Classes for Gibbs Sampler
"""
# Import Modules
import logging
import ep_clustering as ep_clustering
import numpy as np
from ep_clustering._utils import fix_docs, Map
logger = logging.getLogger(name=__name__)
# Author Information
__author__ = "<NAME>"
# Construct Approx Algorithm
def construct_approx_algorithm(name, **kwargs):
""" Construct ApproxAlgorithm by name
Args:
name (string): name of likelihood
'naive': naive Gibbs
'collapsed': collapsed Gibbs
'EP': EP
separate_likeparams (bool)
**kwargs (kwargs): additional arguments (e.g. exp_family)
Examples:
ep_alg = construct_approx_algorithm('EP', exp_family=NormalFamily)
Returns:
approx_alg (ApproxAlgorithm): approximate algorithmm for sampling z
"""
if(name == "naive"):
return NaiveAlgorithm(**kwargs)
elif(name == "collapsed"):
return CollapsedAlgorithm(**kwargs)
elif(name == "EP"):
return EPAlgorithm(**kwargs)
else:
raise ValueError("Unrecognized name {0}".format(name))
# Abstract Class for Likelihood
class ApproxAlgorithm(object):
""" Algorithm Class for GibbsSampler
Args:
**kwargs
Attributes:
name (string): name of algorithm
parameters (Map): approximation parameters
separate_likeparams (bool)
Methods:
init_approx(sampler): initializes the approx algorithm
loglikelihood_z(index, state): return approx loglikelihoods of z[index]
update_approx(index, old_z, new_z): update approximation for z[index]
"""
name = "BaseClass"
def __init__(self, separate_likeparams=False, debug=False, **kwargs):
self.parameters = Map()
self.debug = debug
self.separate_likeparams = separate_likeparams
return
def init_approx(self, sampler, init_likelihood=True):
""" Initialize (or reset) ApproxAlgorithm
Args:
sampler (GibbsSampler): GibbsSampler
"""
if not isinstance(sampler, ep_clustering.GibbsSampler):
raise TypeError("likelihood must be Likelihood object")
self.K = sampler.K
if init_likelihood:
if self.separate_likeparams:
self.likelihood = [sampler.likelihood.deepcopy()
for k in range(self.K)]
sampler.state.likelihood_parameter = [
likelihood.parameter
for likelihood in self.likelihood]
else:
self.likelihood = sampler.likelihood
sampler.sample_theta()
return
def get_likelihood(self, k=0):
""" Return likelihood for cluster k """
if self.separate_likeparams:
return self.likelihood[k]
else:
return self.likelihood
def loglikelihood_z(self, index, state):
""" Calculate the loglikelihoods of z[index]
Args:
index (int): index of z
state (Map): map of sampler state
Returns:
loglikelihood_z (ndarray): K likelihood values
"""
raise NotImplementedError()
def update_approx(self, index, old_z, new_z):
""" Update the ApproxAlgorithm for new assignment z[index] = new_z """
return
def sample_theta(self, state):
""" Return a sample from the posterior given z, y """
sampled_theta = np.array([
self.get_likelihood(k).sample(
indices = np.where(state.z == k)[0],
prior_parameter=self.get_likelihood(k).theta_prior,
)
for k in range(0, self.K) ])
return sampled_theta
def sample_likelihood_parameters(self, state, parameter_name = None):
if self.separate_likeparams:
for k in range(self.K):
self.get_likelihood(k).update_local_parameters(
k = k,
z = state.z,
theta = state.theta,
parameter_name = parameter_name)
else:
self.get_likelihood().update_parameters(
z = state.z,
theta = state.theta,
parameter_name = parameter_name)
return
@fix_docs
class NaiveAlgorithm(ApproxAlgorithm):
name = "naive"
def loglikelihood_z(self, index, state):
loglikelihood_z = np.zeros(self.K)
for k in range(0, self.K):
loglikelihood_z[k] = \
self.get_likelihood(k).loglikelihood(index, state.theta[k])
return loglikelihood_z
@fix_docs
class CollapsedAlgorithm(ApproxAlgorithm):
name = "collapsed"
def loglikelihood_z(self, index, state):
loglikelihood_z = np.zeros(self.K)
for k in range(0, self.K):
subset_indices = _get_cluster(index=index, cluster=k, state=state)
loglikelihood_z[k] = \
self.get_likelihood(k).collapsed(index,
subset_indices,
self.get_likelihood(k).theta_prior)
return loglikelihood_z
def _get_cluster(index, cluster, state, max_size=np.inf):
""" Get Cluster Indices
Args:
index (int): observation index
cluster (int): cluster index
max_size (int): maximum cluster size (ignoring the observation)
state (Map): state of GibbsSampler
Returns:
subset_indices (max_size ndarray): indices of data sampled
"""
subset_indices = np.where(state.z == cluster)[0]
if state.z[index] == cluster:
subset_indices = subset_indices[subset_indices != index]
if np.size(subset_indices) > max_size:
subset_indices = np.sort(np.random.choice(subset_indices,
size=max_size, replace=False))
return subset_indices
@fix_docs
class EPAlgorithm(ApproxAlgorithm):
""" EP Algorithm Class for GibbsSampler
Args:
exp_family (ExponentialFamily): exponential family of approx
damping_factor (double): damped updates (default = 0.0)
Attributes:
name (string): name of algorithm
likelihood (Likelihood): model likelihood
parameters (Map): approximation parameters
'site_approx': likelihood site approximations
'post_approx': posterior approx to theta
Methods:
init_approx(sampler)
loglikelihood_z(index, state): return approx loglikelihoods of z[index]
update_approx(index, new_z): update approximation
"""
name = "EP"
def __init__(self, exp_family, damping_factor=0.0, **kwargs):
super(EPAlgorithm, self).__init__(**kwargs)
# exp_family
if not issubclass(exp_family, ep_clustering.ExponentialFamily):
raise ValueError("exp_family must be an ExponentialFamily Class")
self.exp_family = exp_family
# damping_factor
if not isinstance(damping_factor, float):
raise TypeError("damping_factor {0} must be float".format(
damping_factor))
if damping_factor < 0.0 or damping_factor >= 1.0:
raise ValueError("damping_factor {0} must be in [0,1)".format(
damping_factor))
self.damping_factor = damping_factor
return
def init_approx(self, sampler, init_likelihood=True):
if not isinstance(sampler, ep_clustering.GibbsSampler):
raise TypeError("likelihood must be Likelihood object")
self.K = sampler.K
if init_likelihood:
if self.separate_likeparams:
self.likelihood = [sampler.likelihood.deepcopy()
for k in range(self.K)]
sampler.state.likelihood_parameter = [
likelihood.parameter
for likelihood in self.likelihood]
else:
self.likelihood = sampler.likelihood
theta_prior = self.get_likelihood().theta_prior
if not isinstance(theta_prior, self.exp_family):
raise TypeError("likelihood prior does not match EP exp_family")
parameters = Map(
post_approx = [ theta_prior.copy()
for k in range(0, self.K) ],
site_approx = [ self.exp_family(num_dim = sampler.num_dim)
for ii in range(0, sampler.num_obs) ],
)
self.parameters.update(parameters)
sampler.sample_theta()
sampler.update_approx_alg()
self._sampler = sampler
return
def loglikelihood_z(self, index, state):
loglikelihood_z = np.zeros(self.K)
z_index = state.z[index]
cavity_approx = self._calc_cavity_approx(index, z_index)
try:
for k in range(0, self.K):
loglikelihood_z[k] = self.get_likelihood(k).ep_loglikelihood(
index=index,
theta_parameter=cavity_approx[k],
)
if np.any(np.isnan(loglikelihood_z)):
raise RuntimeError("nan in loglikelihood_z")
except:
logger.warning("EP cavity for site index {0} was invalid".format(index))
loglikelihood_z = -100*np.ones(self.K)
loglikelihood_z[z_index] = 0.0
return loglikelihood_z
def reset_cluster(self, k, recurse=True):
""" Reset EP approximation for cluster k """
if not recurse or self.debug:
raise RuntimeError("EP approximation is no longer valid")
theta_prior = self.get_likelihood().theta_prior
self.parameters.post_approx[k] = theta_prior.copy()
z = self._sampler.state.z
cluster_indices = np.where(z == k)[0]
for ii in cluster_indices:
self.parameters.site_approx[ii] = self.exp_family(
num_dim = self._sampler.num_dim)
np.random.shuffle(cluster_indices)
for ii in cluster_indices:
self.update_approx(index=ii,
old_z=k, new_z=k)
return
def _update_approx(self, index, old_z, new_z):
# Cavity Distribution
new_post_for_old_z = (self.parameters.post_approx[old_z] - \
self.parameters.site_approx[index])
if not new_post_for_old_z.is_valid_density():
logger.warning("Invalid Density when updating index {0}".format(
index))
self.reset_cluster(old_z, recurse=True)
else:
self.parameters.post_approx[old_z] = new_post_for_old_z.normalize()
# Get moments of the tilted distribution
unnormalized_post_approx = \
self.get_likelihood(new_z).moment(
index=index,
theta_parameter=self.parameters.post_approx[new_z],
)
if self.damping_factor == 0.0:
# Calculate Site Approx
self.parameters.site_approx[index] = \
unnormalized_post_approx - self.parameters.post_approx[new_z]
# Correct log_scaling_coef of site_approx
# See bottom of page 6 of "EP for Exp Families" by Seeger 2007
self.parameters.site_approx[index].log_scaling_coef += \
self.parameters.post_approx[new_z].logpartition() \
- unnormalized_post_approx.logpartition()
if np.isnan(self.parameters.site_approx[index].log_scaling_coef):
raise ValueError("Log Scaling Coef is Nan -> Something Broke")
# Set new posterior approximation
self.parameters.post_approx[new_z] = \
unnormalized_post_approx.normalize()
else:
# Partial Damped Update
new_site = \
unnormalized_post_approx - self.parameters.post_approx[new_z]
new_site.log_scaling_coef += \
self.parameters.post_approx[new_z].logpartition() \
- unnormalized_post_approx.logpartition()
if np.isnan(new_site.log_scaling_coef):
raise ValueError("Log Scaling Coef is Nan -> Something Broke")
self.parameters.site_approx[index] *= self.damping_factor
new_site *= (1.0-self.damping_factor)
self.parameters.site_approx[index] += new_site
# Set new posterior approximation
self.parameters.post_approx[new_z] = (
self.parameters.post_approx[new_z] + \
self.parameters.site_approx[index]
).normalize()
return
def update_approx(self, index, old_z, new_z):
if old_z == new_z and not self.debug:
try:
self._update_approx(index, old_z, new_z)
except Exception as error:
logger.warning("EP update for site {0} had an error".format(index))
logger.warning(error)
else:
self._update_approx(index, old_z, new_z)
return
def _calc_cavity_approx(self, index, cluster):
# Helper function for removing (index) from (cluster)'s approximation
cavity_approx = [None]*self.K
for k in range(0, self.K):
if cluster == k:
cavity_approx[k] = \
self.parameters.post_approx[k] - \
self.parameters.site_approx[index]
else:
cavity_approx[k] = self.parameters.post_approx[k].copy()
return cavity_approx
# Need to fix timeseries_likelihood to not need `.sample` theta to update x
def sample_theta(self, state):
""" Return a sample from the posterior given z, y """
try:
return super(EPAlgorithm, self).sample_theta(state)
except NotImplementedError:
sampled_theta = np.array([
self.parameters.post_approx[k].sample()
for k in range(0, self.K) ])
return sampled_theta
else:
raise
# EOF
<file_sep>/ep_clustering/data/_mixture_data.py
#!/usr/bin/env python
"""
Create Mixture Model Data
"""
import numpy as np
import pandas as pd
import logging
from scipy.stats import invwishart, gamma
from ep_clustering._utils import Map, fix_docs
from ep_clustering.data._gibbs_data import (
GibbsData, _categorical_sample
)
# Author Information
__author__ = "<NAME>"
# Modify the root logger
logger = logging.getLogger(name=__name__)
# Mixture Model Data
@fix_docs
class MixtureData(GibbsData):
""" Data for Mixture Model Sampler
Must contain `num_obs` and `num_dim` attributes
Additional Attributes:
matrix (ndarray): num_obs by num_dim data matrix
"""
def _validate_data(self):
super(MixtureData, self)._validate_data()
if "matrix" not in self:
raise ValueError("`matrix` must be defined for MixtureData")
if not isinstance(self.matrix, np.ndarray):
raise TypeError("`matrix` must be an ndarray")
if self.matrix.shape != (self.num_obs, self.num_dim):
raise ValueError("matrix.shape must match num_obs num_dim")
return
# Mixture Model Data Generation
class MixtureDataGenerator(object):
""" Mixture Model Data Generator
Args:
num_obs (int): number of observations
num_dim (int): number of dimensions
K (int): number clusters
component_type (string): name (see create_mixture_component)
component_options (dict): optional kwargs args for
create_mixture_component
**kwargs (dict):
`Cluster Proportion Probabilities
cluster_proportions (ndarray): cluster proportion probabilities
or
proportion_prior (ndarray): parameter for Dirichlet prior
`Cluster Component Parameters`
cluster_parameters (list of dict): parameters for component
or
component_prior (dict): args for `generate_component_parameters`
Examples:
my_data = MixtureDataGenerator(num_obs=100, num_dim=2, K=3)
my_data_2 = MixtureDataGenerator(num_obs=100, num_dim=2, K=3,
component_type = "gaussian")
my_data_3 = MixtureDataGenerator(num_obs=100, num_dim=2, K=3,
component_prior = {'mean_sd': 10})
my_data_4 = MixtureDataGenerator(num_obs=100, num_dim=1, K=10,
component_parameters = [
{'mean': np.array([10]), 'variance': np.array([1])},
{'mean': np.array([-10]), 'variance': np.array([1])},
])
Methods:
generate_cluster_proportions(proportion_prior): cluster_proportions
generate_cluster_parameters(component_prior): component_parameters
generate_data(): returns data
"""
def __init__(self, num_obs, num_dim, K, component_type = 'diag_gaussian',
component_options = {}, **kwargs):
self.num_obs = num_obs
self.num_dim = num_dim
self.K = K
self.param = Map(
component_type = component_type,
component_options = component_options,
**kwargs)
self.component = create_mixture_component(component_type, num_dim,
**component_options)
return
def generate_cluster_proportions(self, proportion_prior=None):
if proportion_prior is not None:
self.param.proportion_prior = proportion_prior
if 'proportion_prior' not in self.param:
self.param.proportion_prior = 100 * np.ones(self.K)
cluster_proportions = np.random.dirichlet(
alpha = self.param.proportion_prior, size=1)
return cluster_proportions
def generate_cluster_parameters(self, component_prior=None):
if component_prior is not None:
self.param.component_prior = component_prior
cluster_parameters = \
[self.component.sample_parameters(
self.param.get('component_prior', {})
) for k in range(self.K)]
return cluster_parameters
def generate_data(self):
""" Generate Data
Returns:
data (MixtureData)
"""
# Get Proportions
if 'cluster_proportions' not in self.param:
self.param.cluster_proportions = self.generate_cluster_proportions()
# Get Component Parameters
if 'cluster_parameters' not in self.param:
self.param.cluster_parameters = self.generate_cluster_parameters()
else:
self.param.cluster_parameters = [
Map(cluster_parameter)
for cluster_parameter in self.param.cluster_parameters
]
# Generate Data
z = np.array(
[ _categorical_sample(probs=self.param.cluster_proportions)
for i in range(0,self.num_obs)],
dtype=int)
matrix = np.zeros((self.num_obs, self.num_dim))
for ii, z_ii in enumerate(z):
matrix[ii,:] = self.component.sample_observation(
self.param.cluster_parameters[z_ii])
# Format Output
data = MixtureData(
matrix = matrix,
z = z,
num_obs = self.num_obs,
num_dim = self.num_dim,
K = self.K,
parameters = self.param,
)
return data
def create_mixture_component(name, num_dim, **kwargs):
""" Return Component Object
Args:
name (string): type of component
'diag_gaussian' - Diagonal Gaussian
'gaussian' - Gaussian
'mix_diag_gaussian' - Mixture of Diagonal Gaussian
'mix_gaussian' - Mixture of Gaussians
'student_t' - Student-T
'von_mises_fisher' - Von Mises Fisher Distribution
num_dim (int): dimension of component
**kwargs: additional args for Component constructor
Returns:
component (Component): mixture component object
"""
if name.lower() == "diag_gaussian":
return DiagGaussianComponent(num_dim)
elif name.lower() == "gaussian":
return GaussianComponent(num_dim)
elif name.lower() == "mix_diag_gaussian":
return MixDiagGaussianComponent(num_dim, **kwargs)
elif name.lower() == "mix_gaussian":
return MixGaussianComponent(num_dim, **kwargs)
elif name.lower() == "student_t":
return StudentTComponent(num_dim, **kwargs)
elif name.lower() == "von_mises_fisher":
return VonMisesFisherComponent(num_dim, **kwargs)
else:
raise ValueError("Unrecognized component name '{0}'".format(name))
class Component(object):
""" Mixture Component Distribution Object
Args:
num_dim (int)
**kwargs
Methods:
sample_parameters(prior): return Map of parameters
sample_observation(parameters): returns ndarray sample
"""
def __init__(self, num_dim, **kwargs):
self.num_dim = num_dim
self._process_kwargs(**kwargs)
def _process_kwargs(self, **kwargs):
return
def sample_parameters(self, prior):
""" Sample parameters
Args:
prior (dict): (optional)
"""
raise NotImplementedError()
def sample_observation(self, parameters):
""" Sample observations
Args:
parameters (Map):
Returns:
obs (ndarray)
"""
raise NotImplementedError()
@fix_docs
class DiagGaussianComponent(Component):
def sample_parameters(self, prior={}):
""" Sample parameters
Args:
prior (dict): (optional)
mean_mean (double or ndarray): mean for mean
mean_sd (double or ndarray): standard deviation for mean
variance_alpha (double or ndarray):
shape parameter for inverse Gamma
variance_beta (double or ndarray):
rate parameter for inverse Gamma
"""
if not isinstance(prior, dict):
raise TypeError("Prior must be dict not '{0}'".format(type(prior)))
mean_mean = prior.get("mean_mean", 0.0)
mean_sd = prior.get("mean_sd", 2.0)
variance_alpha = prior.get("sd_alpha", 5.0)
variance_beta = prior.get("sd_beta", 5.0)
mean = np.random.normal(size = self.num_dim) * mean_sd + mean_mean
variance = 1.0/np.random.gamma(
shape = variance_alpha,
scale = 1.0/variance_beta,
size = self.num_dim,
)
parameters = Map(mean = mean, variance = variance)
return parameters
def sample_observation(self, parameters):
""" Sample observations
Args:
parameters (Map):
mean (double or ndarray)
variance (double or ndarray)
Returns:
obs (ndarray)
"""
obs = parameters.mean + \
np.random.normal(size = self.num_dim) * \
np.sqrt(parameters.variance)
return obs
@fix_docs
class GaussianComponent(Component):
def sample_parameters(self, prior={}):
""" Sample parameters
Args:
prior (dict): (optional)
mean_mean (ndarray): mean for mean
mean_sd (ndarray): standard deviation for mean
cov_psi (ndarray): scale matrix parameter for inverse Wishart
cov_nu (double): df parameter for inverse Wishart
"""
if not isinstance(prior, dict):
raise TypeError("Prior must be dict not '{0}'".format(type(prior)))
mean_mean = prior.get("mean_mean", np.zeros(self.num_dim))
mean_sd = prior.get("mean_sd", np.ones(self.num_dim))
cov_psi = prior.get("cov_psi", np.eye(self.num_dim))
cov_nu = prior.get("cov_nu", self.num_dim + 2)
mean = np.random.normal(size = self.num_dim) * mean_sd + mean_mean
cov = invwishart.rvs(df = cov_nu, scale = cov_psi)
parameters = Map(mean = mean, cov = cov)
return parameters
def sample_observation(self, parameters):
""" Sample observations
Args:
parameters (Map):
mean (ndarray)
cov (ndarray)
Returns:
obs (ndarray)
"""
if self.num_dim > 1:
obs = np.random.multivariate_normal(parameters.mean, parameters.cov)
return obs
else:
obs = parameters.mean + \
np.random.normal(size = self.num_dim) * np.sqrt(parameters.cov)
return obs
@fix_docs
class MixDiagGaussianComponent(Component):
""" Mixture of Scale Normals """
__doc__ += Component.__doc__
def sample_parameters(self, prior):
raise NotImplementedError(
"MixDiagGaussianComponent requires parameters to be specified")
def sample_observation(self, parameters):
""" Sample observations
Args:
parameters (Map):
mean (ndarray): length num_dim
variance (double or ndarray): length num_dim
proportions (ndarray): length num_scale_components
scales (ndarray): length num_scale_components
(!!Note!! that this scales the variance)
Returns:
obs (ndarray)
"""
if np.size(parameters.proportions) != np.size(parameters.scales):
raise ValueError(
"scale mixture proportion and scale size must match")
scale = np.random.choice(parameters.scales, size=1,
p=parameters.proportions)[0]
obs = parameters.mean + \
np.random.normal(size = self.num_dim) * \
np.sqrt(parameters.variance * scale)
return obs
@fix_docs
class MixGaussianComponent(Component):
""" Mixture of Scale Normals """
__doc__ += Component.__doc__
def sample_parameters(self, prior):
raise NotImplementedError(
"MixGaussianComponent requires parameters to be specified"
)
def sample_observation(self, parameters):
""" Sample observations
Args:
parameters (Map):
mean (ndarray): length num_dim
cov (ndarray): shape (num_dim, num_dim)
proportions (ndarray): length num_scale_components
scales (ndarray): length num_scale_components, nonnegative
(!!Note!! that this scales the variance)
Returns:
obs (ndarray)
"""
if np.size(parameters.proportions) != np.size(parameters.scales):
raise ValueError(
"scale mixture proportion and scale size must match")
scale = np.random.choice(parameters.scales, size=1,
p=parameters.proportions)[0]
if self.num_dim > 1:
obs = np.random.multivariate_normal(parameters.mean,
parameters.cov*np.sqrt(scale))
else:
obs = parameters.mean + \
np.random.normal(size = self.num_dim) * \
np.sqrt(parameters.cov * scale)
return obs
@fix_docs
class VonMisesFisherComponent(Component):
""" Von Mises Fisher Distribution """
def sample_parameters(self, prior):
raise NotImplementedError(
"VonMiseFisherComponent requires parameters to be specified"
)
def sample_observation(self, parameters):
""" Sample observations
Args:
parameters (Map):
normalized_mean (ndarray): lenth num_dim, l2 norm = 1
concentration (double): positive
Returns:
obs (ndarray)
"""
from spherecluster import sample_vMF
if not np.isclose(np.linalg.norm(parameters.normalized_mean), 1.0):
raise ValueError("normalized_mean must have l2 norm = 1.0")
if parameters.concentration < 1e-16:
raise ValueError("concentration must be positive")
obs = sample_vMF(
mu=parameters.normalized_mean,
kappa=parameters.concentration,
num_samples=1)[0]
return obs
@fix_docs
class StudentTComponent(Component):
""" Student T Distribution """
def sample_parameters(self, prior={}):
""" Sample parameters
Args:
prior (dict): (optional)
mean_mean (ndarray): mean for mean
mean_sd (ndarray): standard deviation for mean
cov_psi (ndarray): scale matrix parameter for inverse Wishart
cov_nu (double): df parameter for inverse Wishart
df_alpha (double): shape for Gamma
df_beta (double): rate for Gamma
"""
if not isinstance(prior, dict):
raise TypeError("Prior must be dict not '{0}'".format(type(prior)))
mean_mean = prior.get("mean_mean", np.zeros(self.num_dim))
mean_sd = prior.get("mean_sd", np.ones(self.num_dim))
cov_psi = prior.get("cov_psi", np.eye(self.num_dim))
cov_nu = prior.get("cov_nu", self.num_dim + 2)
df_alpha = prior.get("df_alpha", 8.0)
df_beta = prior.get("df_beta", 4.0)
mean = np.random.normal(size = self.num_dim) * mean_sd + mean_mean
cov = invwishart.rvs(df = cov_nu, scale = cov_psi)
df = gamma.rvs(a=df_alpha, scale=1.0/df_beta)
parameters = Map(mean=mean, cov=cov, df=df)
return parameters
def sample_observation(self, parameters):
""" Sample observations
Args:
parameters (Map):
mean (ndarray): vector of mean
cov (ndarray): matrix of covariance
df (double): positive degrees of freedom for t-distribution
Returns:
obs (ndarray)
"""
u = gamma.rvs(a=parameters.df/2.0, scale=2.0/parameters.df)
scaled_cov = parameters.cov / u
if self.num_dim > 1:
obs = np.random.multivariate_normal(parameters.mean, scaled_cov)
return obs
else:
obs = parameters.mean + \
np.random.normal(size = self.num_dim) * np.sqrt(scaled_cov)
return obs
return obs
# Example Script
if __name__ == "__main__":
print("Example Create Mixture Model Data")
data_generator = MixtureDataGenerator(
num_obs = 30,
num_dim = 2,
K = 3)
my_data = data_generator.generate_data()
#EOF
<file_sep>/ep_clustering/likelihoods/_gaussian_likelihood.py
#!/usr/bin/env python
"""
Gaussian Likelihood
"""
# Import Modules
import numpy as np
import logging
from ep_clustering._utils import fix_docs
from ep_clustering.likelihoods._likelihoods import Likelihood
from ep_clustering.exp_family._normal_mean import (
NormalFamily,
DiagNormalFamily
)
logger = logging.getLogger(name=__name__)
LOGGING_FORMAT = '%(levelname)s: %(asctime)s - %(name)s: %(message)s ...'
logging.basicConfig(
level = logging.INFO,
format = LOGGING_FORMAT,
)
@fix_docs
class GaussianLikelihood(Likelihood):
""" Gaussian Likelihood Object
Args:
**kwargs :
variance (double) - cluster noise
"""
# Inherit Docstrings
__doc__ += Likelihood.__doc__
# Class Variables
name = "Gaussian"
def __init__(self, data, **kwargs):
self.y = data.matrix
self.num_dim = data.num_dim
super(GaussianLikelihood, self).__init__(data, **kwargs)
return
def _get_default_prior(self):
theta_prior = DiagNormalFamily(num_dim = self.num_dim,
precision=np.ones(self.num_dim)/100.0)
return theta_prior
def _get_default_parameters(self):
"""Returns default parameters dict"""
default_parameter = {
"variance": np.ones(self.num_dim),
}
return default_parameter
def _get_default_parameters_prior(self):
"""Returns default parameters prior dict"""
prior = {
"alpha_variance0": 3.0,
"beta_variance0": 2.0,
}
return prior
def _sample_from_prior(self):
parameter = {
"variance": 1.0/np.random.gamma(
shape=self.prior.alpha_variance0,
scale=self.prior.beta_variance0,
size=self.num_dim)
}
return parameter
def loglikelihood(self, index, theta):
y = self.y[index]
loglikelihood = -0.5*((y-theta)/self.parameter.variance).dot(y-theta) +\
-0.5*self.num_dim*np.log(2*np.pi) + \
-0.5*np.sum(np.log(self.parameter.variance))
return loglikelihood
def collapsed(self, index, subset_indices, theta_parameter):
posterior = theta_parameter
for s_index in subset_indices:
s_y = self.y[s_index]
posterior = (posterior +
DiagNormalFamily.from_mean_variance(
mean=s_y,
variance=self.parameter.variance)
)
mean = posterior.get_mean()
variance = posterior.get_variance() + self.parameter.variance
y = self.y[index]
loglikelihood = -0.5*((y-mean)/variance).dot(y-mean) + \
-0.5*self.num_dim*np.log(2*np.pi) + \
-0.5*np.sum(np.log(variance))
return loglikelihood
def moment(self, index, theta_parameter):
y = self.y[index]
site = DiagNormalFamily.from_mean_variance(
mean=y,
variance=self.parameter.variance,
)
unnormalized_post_approx = (theta_parameter + site)
unnormalized_post_approx.log_scaling_coef = \
unnormalized_post_approx.logpartition() - \
(theta_parameter.logpartition() + site.logpartition())
return unnormalized_post_approx
def sample(self, indices, prior_parameter):
posterior = prior_parameter
for index in indices:
y = self.y[index]
posterior = (posterior +
DiagNormalFamily.from_mean_variance(
mean=y,
variance=self.parameter.variance)
)
mean = posterior.get_mean()
variance = posterior.get_variance()
return np.random.randn(posterior.num_dim)*np.sqrt(variance) + mean
def update_parameters(self, z, theta, parameter_name = None):
if parameter_name is None:
self._update_variance(z, theta)
elif parameter_name == "variance":
self._update_variance(z, theta)
else:
raise ValueError("Unrecognized parameter_name: " + parameter_name)
return
def _update_variance(self, z, theta, k_list=None):
if k_list is None:
k_list = range(np.shape(theta)[0])
sse = 0
N = 0
for k in k_list:
ind = (z == k)
N += np.sum(ind)
sse += np.sum((self.y[ind,:] - theta[k]) ** 2)
alpha_variance = self.prior.alpha_variance0 + N/2.0
beta_variance = self.prior.beta_variance0 + sse/2.0
self.parameter.variance = 1.0/np.random.gamma(shape = alpha_variance,
scale = 1.0/beta_variance, size = self.num_dim)
return
def update_local_parameters(self, k, z, theta, parameter_name = None):
if parameter_name is None:
self._update_variance(z, theta, k_list[k])
elif parameter_name == "variance":
self._update_variance(z, theta, k_list[k])
else:
raise ValueError("Unrecognized parameter_name: " + parameter_name)
return
# EOF
<file_sep>/ep_clustering/likelihoods/_timeseries_regression_likelihood.py
#!/usr/bin/env python
"""
Timeseries Likelihood with Regression
"""
# Import Modules
import numpy as np
import pandas as pd
import logging
from ep_clustering._utils import (
fix_docs, convert_matrix_to_df, convert_df_to_matrix)
from ep_clustering.likelihoods._likelihoods import Likelihood
from ep_clustering.likelihoods._timeseries_likelihood import (
TimeSeriesLikelihood, _fix_pandas_index)
from ep_clustering.kalman_filter import KalmanFilter, _cpp_available
## Try Importing C++ Implementation
if _cpp_available:
from ep_clustering.kalman_filter.c_kalman_filter import CKalmanFilter
logger = logging.getLogger(name=__name__)
@fix_docs
class TimeSeriesRegressionLikelihood(TimeSeriesLikelihood):
""" Correlated Time Series with regression Object
Args:
covariate_names (list of string): name of regression covariates
There are `H` covariates
use_cpp (boolean): whether to use the C++ implementation of the
Kalman Filter (default = False)
use_old_update (boolean): whether to use the old (incorrect) EP update
For comparison purposes only (default = False)
**kwargs:
- x (N by T ndarray) - latent time series
- A (N ndarray) - AR Coefficients
- lambduh (N ndarray) - Factor Loadings
- sigma2_x (double) - Covariance of latent errors
- sigma2_y (N ndarray) - Variance of observation errors
- covariate_coeff (N by H ndarray) - regression coefficients
Attributes:
residuals (pd.DataFrame) - columns are
original - observed data
_ts_resid - observed data - estimated time series
_reg - estimated regression
_reg_resid -
Note that `x` is updated when sampling `theta` using `sample()`.
"""
__doc__ += Likelihood.__doc__
name = "TimeSeriesRegression"
def __init__(self, data, covariate_names, **kwargs):
if len(covariate_names) == 0:
raise ValueError("No covariates listed in covariate_name")
for name in covariate_names:
if name not in data.df.columns:
raise ValueError(
"covariate_name {0} not found in data.df".format(name)
)
self.covariate_names = covariate_names
self.covariates = data.df[covariate_names]
self.residuals = pd.DataFrame(
data = np.zeros((len(self.covariates.index), 4)),
index = data.df.index.copy(),
columns = ['original', '_ts_resid', '_reg', '_reg_resid'],
)
self.residuals['original'] = data.df[data.observation_name]
self.residuals['_reg_resid'] = data.df[data.observation_name]
super(TimeSeriesRegressionLikelihood, self).__init__(data, **kwargs)
self._update_covariate_coeff()
return
def _get_default_parameters_prior(self):
prior = {
"mu_A0": 0.0,
"sigma2_A0": 100.0,
"mu_lambduh0": 0.0,
"sigma2_lambduh0": 100.0,
"alpha_x0": 3.0,
"beta_x0": 2.0,
"alpha_y0": 3.0,
"beta_y0": 2.0,
"mu_coeff_mean_0": 0.0,
"sigma2_coeff_mean_0": 1.0,
"alpha_coeff_var_0": 3.0,
"beta_coeff_var_0": 2.0,
}
return prior
def _get_default_parameters(self):
N = np.shape(self.y)[0]
H = len(self.covariate_names)
default_parameter = {
"x": np.zeros(np.shape(self.y)),
"A": 0.9 * np.ones(N),
"lambduh": np.ones(N),
"sigma2_x": 1.0,
"sigma2_y": np.ones(N),
"covariate_coeff": np.zeros((N, H)),
"mu_coeff": np.zeros(H),
"sigma2_coeff": np.ones(H),
}
return default_parameter
def _sample_from_prior(self):
N = np.shape(self.y)[0]
H = length(self.covariate_names)
logger.warning("Sampling from prior is not recommended")
parameter = {
"x": np.zeros(np.shape(self.y)),
"A": np.random.normal(
loc=self.prior.mu_A0,
scale=np.sqrt(self.prior.sigma2_A0),
size=N),
"lambduh": np.random.normal(
loc=self.prior.mu_lambduh0,
scale=np.sqrt(self.prior.sigma2_lambduh0),
size=N),
"sigma2_x": 1.0/np.random.gamma(
shape=self.prior.alpha_x0,
scale=self.prior.beta_x0,
size=1)[0],
"sigma2_y": 1.0/np.random.gamma(
shape=self.prior.alpha_y0,
scale=self.prior.beta_y0,
size=N),
"mu_coeff": np.random.normal(
loc=self.prior.mu_coeff_mean_0,
scale=np.sqrt(self.prior.sigma2_coeff_mean_0),
size=H),
"sigma2_coeff": 1.0/np.random.gamma(
shape=self.prior.alpha_coeff_var_0,
scale=self.prior.beta_coeff_var_0,
size=H),
}
parameter['covariate_coeff'] = np.random.normal(
loc=parameter['mu_coeff'],
scale=np.sqrt(parameter['sigma2_coeff']),
size=(N, H))
return parameter
def predict(self, new_data, prior_parameter, num_samples):
sample_ys = []
indices = np.array(new_data.df.index.levels[0])
# Regression Component
covariates_df = new_data.df[self.covariate_names]
def to_apply(row):
coeff = self.parameter.covariate_coeff[row.index.to_numpy()[0][0]]
row['_reg'] = np.dot(row[self.covariate_names], coeff)
return(row)
y_reg = covariates_df.groupby(level="observation").apply(to_apply)['_reg']
y_reg.index = _fix_pandas_index(y_reg.index)
# Time Series Component
kalman = self.Filter(
y=self.y[indices],
A=self.parameter.A[indices],
lambduh=self.parameter.lambduh[indices],
sigma2_x=self.parameter.sigma2_x,
sigma2_y=self.parameter.sigma2_y[indices],
eta_mean=prior_parameter.get_mean(),
eta_var=prior_parameter.get_variance(),
y_count=self.y_count[indices],
)
for s in range(0, num_samples):
y = kalman.sample_y(x = self.parameter.x[indices].T)
y_df = convert_matrix_to_df(y.T, '_prediction')['_prediction']
y_df.index = y_df.index.set_levels(indices, level='observation')
y_filtered = (y_reg + y_df).dropna()
sample_ys.append(y_filtered.values)
sampled_y = np.array(sample_ys)
return sampled_y
def update_parameters(self, z, theta, parameter_name = None):
if(parameter_name is None):
self._update_A(z, theta)
self._update_lambduh(z, theta)
self._update_sigma2_y()
self._update_sigma2_x(z, theta)
self._update_covariate_coeff()
elif(parameter_name == "A"):
self._update_A(z, theta)
elif(parameter_name == "lambduh"):
self._update_lambduh(z, theta)
elif(parameter_name == "sigma2_y"):
self._update_sigma2_y(z, theta)
elif(parameter_name == "sigma2_x"):
self._update_sigma2_x(z, theta)
elif(parameter_name == "covariate_coeff"):
self._update_covariate_coeff()
elif(parameter_name == "mu_coeff"):
raise ValueError("mu_coeff is updated sampling covariate_coeff")
elif(parameter_name == "sigma2_coeff"):
raise ValueError("sigma2_coeff is updated sampling covariate_coeff")
elif(parameter_name == "x"):
raise ValueError("x is updated when sampling theta using `sample`")
else:
raise ValueError("Unrecognized parameter_name: " + parameter_name)
return
def _update_covariate_coeff(self):
# Update ts_resid
self._update_ts_resid()
# Update covariate coeff
N, H = np.shape(self.parameter.covariate_coeff)
for index in range(0, N):
# X is times by covariates matrix
X = self.covariates.loc[index].values
# target is times by 1 vector
target = (self.residuals['_ts_resid'].loc[index]).values
sigma2_y = self.parameter.sigma2_y[index]
coeff = self.parameter.covariate_coeff[index]
# Prior
precision_coeff = np.diag(self.parameter.sigma2_coeff ** -1.0)
mean_precision_coeff = \
self.parameter.mu_coeff / self.parameter.sigma2_coeff
# Add Likelihood
XtX = X.T.dot(X)
precision_coeff += XtX / sigma2_y
mean_precision_coeff += np.dot(X.T, target) / sigma2_y
# Sample Posterior
L = np.linalg.cholesky(precision_coeff)
self.parameter.covariate_coeff[index,:] = \
np.linalg.solve(L.T, np.random.normal(size = H) +
np.linalg.solve(L, mean_precision_coeff))
# Update Hyperpriors
self._update_mu_coeff()
self._update_sigma2_coeff()
# Update reg_resid
self._update_reg_resid()
return
def _update_mu_coeff(self):
N, H = np.shape(self.parameter.covariate_coeff)
for index in range(0, H):
coeff = self.parameter.covariate_coeff[:, index]
precision = self.prior.sigma2_coeff_mean_0
mean_precision = self.prior.mu_coeff_mean_0 * precision
precision += N / self.parameter.sigma2_coeff[index]
mean_precision += np.sum(coeff / self.parameter.sigma2_coeff[index])
self.parameter.mu_coeff[index] = np.random.normal(
loc = mean_precision/precision,
scale = precision ** -0.5)
return
def _update_sigma2_coeff(self):
N, H = np.shape(self.parameter.covariate_coeff)
for index in range(0, H):
# TODO: This can be vectorized
coeff = self.parameter.covariate_coeff[:, index]
coeff_mean = self.parameter.mu_coeff[index]
alpha_sigma2_coeff = self.prior.alpha_coeff_var_0
beta_sigma2_coeff = self.prior.beta_coeff_var_0
alpha_sigma2_coeff += N/2.0
beta_sigma2_coeff += np.sum((coeff - coeff_mean)**2) / 2.0
self.parameter.sigma2_coeff[index] = \
1.0 / np.random.gamma(shape = alpha_sigma2_coeff,
scale = 1.0/ beta_sigma2_coeff,
size = 1)
return
def _update_ts_resid(self):
# Update data.df['_ts_resid']
x_df = convert_matrix_to_df(self.parameter.x, observation_name='_x')
observed_data = self.residuals['original']
observed_data.index = _fix_pandas_index(observed_data.index)
_ts_resid = (observed_data - x_df['_x']).dropna()
self.residuals['_ts_resid'] = _ts_resid.tolist()
return
def _update_reg_resid(self):
# Update data.df['_reg_resid'] and y
def to_apply(row):
coeff = self.parameter.covariate_coeff[row.index.to_numpy()[0][0]]
row['_reg'] = np.dot(row[self.covariate_names], coeff)
return(row)
self.residuals['_reg'] = \
self.covariates.groupby(level="observation").apply(to_apply)['_reg']
self.residuals['_reg_resid'] = \
self.residuals['original'] - self.residuals['_reg']
self.y = \
convert_df_to_matrix(self.residuals, value_name = "_reg_resid")[0]
return
<file_sep>/ep_clustering/evaluator/_metric_functions.py
"""
Gibbs Sampler Metric Functions
"""
import numpy as np
import ep_clustering._utils as _utils
from sklearn.metrics import confusion_matrix, normalized_mutual_info_score
def metric_function_from_sampler(sampler_func_name, metric_name=None,
**sampler_func_kwargs):
""" Returns metric function that evaluates sampler_func_name
Example:
metric_function_of_sampler(sampler_func_name = "loglikelihood",
kind = "naive")
"""
if metric_name is None:
metric_name = sampler_func_name
def custom_metric_function(sampler):
sampler_func = getattr(sampler, sampler_func_name, None)
if sampler_func is None:
raise ValueError(
"sampler_func_name `{}` is not in sampler".format(
sampler_func_name)
)
else:
metric_value = sampler_func(**sampler_func_kwargs)
metric = {'variable': 'sampler',
'metric': metric_name,
'value': metric_value}
return metric
return custom_metric_function
def metric_function_from_state(state_variable_name, target_value, metric_name,
return_variable_name=None, state_variable_func=None, log_level=None):
""" Returns metric function that compares samplers' state to a target
If the variable is a list of variables, then
Args:
state_variable_name (string, list): name of variable in sampler.state
(e.g. 'z' or ['likelihood_parameter', 'A'])
target_value (ndarray or list of ndarrays):
target value(s) for sampler.state.variable_name
metric_name (string): name of a metric function
* 'nvi': normalized variation of information
* 'nmi': normalized mutual information
* 'precision': cluster precision
* 'recall': cluster recall
* 'mse': mean squared error
* 'mae': mean absolute error
* 'l2_percent_error': percent_error
(see construct_metric_function)
return_variable_name (string, optional): name of metric return name
default is `state_variable_name` (concat by "_" if list)
state_variable_func (func, optional):
function to get variable of interest from state
(e.g. state_variable_func = lambda state: state.z)
Default is inferred from `state_variable_name`
log_level (int, optional): logging level (e.g. logging.INFO)
Returns:
A function that returns dictionary of
return_variable_name, metric, value
If comparing list of values,
then the returnvariable name has suffix `_[#]` for its position
"""
metric_func = construct_metric_function(metric_name)
if return_variable_name is None:
if isinstance(state_variable_name, list):
return_variable_name = "_".join(state_variable_name)
else:
return_variable_name = state_variable_name
if state_variable_func is not None:
if not callable(state_variable_func):
raise ValueError("`state_variable_func` must be callable")
def custom_metric_function(sampler):
if state_variable_func is not None:
state_variable = state_variable_func(sampler.state)
else:
if isinstance(state_variable_name, list):
state_variable = _utils.getFromNestDict(sampler.state,
state_variable_name)
else:
state_variable = sampler.state[state_variable_name]
if isinstance(state_variable, list):
if not isinstance(target_value, list):
raise TypeError(
"target_value must be a list to match {0}".format(
str(state_variable_name))
)
metric = []
for ii, (state_var, target_var) in enumerate(zip(
state_variable, target_value)):
metric_value = metric_func(state_var, target_var)
metric.append(
{'variable': return_variable_name + "_" + str(ii),
'metric': metric_name,
'value': metric_value,
})
else:
metric_value = metric_func(state_variable, target_value)
metric = {'variable': return_variable_name,
'metric': metric_name,
'value': metric_value
}
return metric
# Helper to assign log_level
if log_level is not None:
custom_metric_function.log_level = log_level
return custom_metric_function
def construct_metric_function(metric_name):
""" Return a metric function
Args:
metric_name (string): name of metric. Must be one of
* 'nvi': normalized variation of information
* 'nmi': normalized mutual information
* 'precision': cluster precision
* 'recall': cluster recall
* 'mse': mean squared error
* 'mae': mean absolute error
* 'l2_percent_error': percent_error
Returns:
metric_function (function):
function of two inputs (result, expected)
"""
if(metric_name == "mse"):
def metric_function(result, expected):
return np.mean((result - expected)**2)
return metric_function
elif(metric_name == "nvi"):
def metric_function(result, expected):
return var_info(result, expected, normalized=True)
return metric_function
elif(metric_name == "nmi"):
def metric_function(predict, truth):
return normalized_mutual_info_score(truth, predict, average_method='geometric')
return metric_function
elif(metric_name == "precision"):
def metric_function(predict, truth):
cm = confusion_matrix(truth, predict)
return np.sum(np.max(cm, axis=0))/(np.sum(cm)*1.0)
return metric_function
elif(metric_name == "recall"):
def metric_function(predict, truth):
cm = confusion_matrix(truth, predict)
return np.sum(np.max(cm, axis=1))/(np.sum(cm)*1.0)
return metric_function
elif(metric_name == "mae"):
def metric_function(result, expected):
return np.mean(np.abs(result - expected))
return metric_function
elif(metric_name == "l2_percent_error"):
def metric_function(result, expected):
return np.linalg.norm(result-expected)/np.linalg.norm(expected)*100
return metric_function
else:
raise ValueError("Unrecognized metric name = %s" % metric_name)
def heldout_loglikelihood(test_set, variable_name = 'test_set'):
""" Returns metric function that evaluates heldout_likelihood of test_set
Args:
test_set (array-like): data to evaluate
variable_name (string): name of `variable` in returned dict
Returns:
metric_function (function):
function of sampler that returns dict
Example:
heldout_loglikelihood(test_set)
"""
def heldout_loglikelihood_metric_func(sampler):
heldout_loglikelihood = 0.0
for test_data in test_set:
for k in range(sampler.K):
#TODO FIX THIS HACK
likelihood = sampler.approx_alg.get_likelihood(k)
original_data = likelihood.y[0] + 0.0
likelihood.y[0] = test_data
component_loglikelihood = \
sampler.approx_alg.get_likelihood(k).loglikelihood(
index = -1,
theta = sampler.state.theta[k],
)
likelihood.y[0] = original_data
heldout_loglikelihood += (
component_loglikelihood * np.mean(sampler.state.z == k)
)
heldout_loglikelihood *= 1.0/len(test_set)
metric = {
'metric':'heldout_loglikelihood',
'variable': variable_name,
'value': heldout_loglikelihood}
return metric
return heldout_loglikelihood_metric_func
# HELPER FUNCTIONS
def var_info(z1, z2, normalized=False):
""" Variation of Information
Args:
z1 (N ndarray): cluster assignments
z2 (N ndarray): cluster assignments
normalized (bool): normalize by joint entropy (default false)
Returns:
vi (double >= 0): divergence between the two assignments
"""
n = len(z1)
p1 = np.unique(z1)
p2 = np.unique(z2)
r = np.zeros((len(p1), len(p2)))
for i1, v1 in enumerate(p1):
for i2, v2 in enumerate(p2):
r[i1,i2] = np.sum((z1 == v1) & (z2 == v2))*1.0/n
r1 = np.sum(r, axis=1)
r2 = np.sum(r, axis=0)
entropy_1 = -1.0*np.sum(r1[r1 > 0] * np.log(r1[r1 > 0]))
entropy_2 = -1.0*np.sum(r2[r2 > 0] * np.log(r2[r2 > 0]))
prod = np.outer(r1, r2)
mutual_info = np.sum(r[r>0] * (np.log(r[r > 0]) - np.log(prod[r > 0])))
vi = entropy_1 + entropy_2 - 2.0*mutual_info
if not normalized:
return vi
else:
joint_entropy = -1.0*np.sum(r[r > 0] * np.log(r[r>0]))
nvi = vi/joint_entropy
return nvi
<file_sep>/ep_clustering/likelihoods/__init__.py
from ._likelihoods import Likelihood
from ._constructor import construct_likelihood
from ._gaussian_likelihood import GaussianLikelihood
from ._mix_gaussian_likelihood import MixDiagGaussianLikelihood
from ._student_t_likelihood import StudentTLikelihood
from ._timeseries_likelihood import TimeSeriesLikelihood
from ._timeseries_regression_likelihood import TimeSeriesRegressionLikelihood
from ._ar_likelihood import ARLikelihood
#from ._von_mises_fisher_likelihood import (
# FixedVonMisesFisherLikelihood,
# VonMisesFisherLikelihood,
# )
<file_sep>/ep_clustering/data/_timeseries_data.py
#!/usr/bin/env python
"""
Create TimeSeries Model Data
"""
import numpy as np
import pandas as pd
import logging
from ep_clustering._utils import (
Map, fix_docs, convert_matrix_to_df, convert_df_to_matrix
)
from ep_clustering.data._gibbs_data import (
GibbsData, _categorical_sample
)
# Author Information
__author__ = "<NAME>"
# Modify the root logger
logger = logging.getLogger(name=__name__)
# TimeSeries Model Data
@fix_docs
class TimeSeriesData(GibbsData):
""" Data for TimeSeries GibbsSampler
Additional Attributes:
df (pd.DataFrame): data frame with data with columns
(observation, dimension, ...)
observation_name (string): name of observation column in df
Additional Methods:
get_matrix(column_name)
subset(indices)
"""
def __init__(self, df, *args, **kwargs):
df = df.sort_index()
super(TimeSeriesData, self).__init__(df=df, *args, **kwargs)
return
def _validate_data(self):
super(TimeSeriesData, self)._validate_data()
if "df" not in self:
raise ValueError("`df` must be defined for TimeSeriesData")
if "observation_name" not in self:
raise ValueError(
"`observation_name` must be defined for TimeSeriesData")
if "observation" not in self.df.index.names:
raise ValueError("row_index 'observation' not in df index")
if "dimension" not in self.df.index.names:
raise ValueError("col_index 'dimension' not in df index")
if self.observation_name not in self.df.columns:
raise ValueError("observation_name {0} not in df".format(
observation_name))
def get_matrix(self, column_name=None):
""" Return mean and count matrix (observation x dim) of column_name"""
if column_name is None:
column_name = self.observation_name
if column_name not in self.df.columns:
raise ValueError("column_name {0} not in df".format(column_name))
return convert_df_to_matrix(self.df, value_name = column_name,
row_index="observation", col_index="dimension")
def subset(self, indices):
if isinstance(indices, np.ndarray):
indices = indices.tolist()
if len(indices) == 1:
# Bug with Pandas when indices is length 1 w/ 1 observation
subset_df = self.df.loc[
self.df.index.get_level_values('observation').isin(indices)
]
else:
subset_df = self.df.loc[
self.df.index.get_level_values('observation').isin(indices)
]
subset_data = type(self)(**self.copy()) # Copy Self
subset_data.df = subset_df
subset_data.num_obs = \
subset_df.index.get_level_values('observation').max() + 1
subset_data.num_dims = \
subset_df.index.get_level_values('dimension').max() + 1
subset_data._validate_data()
return subset_data
# TimeSeries Model Data Generation
class TimeSeriesDataGenerator(object):
""" TimeSeries Model Data Generator
Args:
num_obs (int): number of observations
num_dim (int): number of dimensions
K (int): number clusters
**kwargs (dict):
`Cluster Proportion Probabilities`
cluster_proportions (ndarray): cluster proportion probabilities
or
proportion_prior (ndarray): parameter for Dirichlet prior
`Cluster Parameter`
sigma2_x (double): latent process noise variance (default 1.0)
`Series-Specific Parameters`
A (ndarray): AR coefficients (default 0.99 * np.ones(N))
sigma2_y (ndarray): obs noise variance (default np.ones(N))
lambduh (ndarray): latent factor loadings (default np.ones(N))
x0 (ndarray): latent process initialization
`Options`
missing_obs (double or ndarray): probability of missing obs
regression (boolean): whether to include dummy covariates
covariate_coeff (ndarray, optional): regression covariates
must by num_dim by num_coeff
Methods:
generate_cluster_proportions(proportion_prior): cluster_proportions
generate_data(): returns data
"""
def __init__(self, num_obs, num_dim, K, **kwargs):
self.num_obs = num_obs
self.num_dim = num_dim
self.K = K
self._parse_param(**kwargs)
if kwargs.get('regression', False):
self.param.covariate_coeff = kwargs.get('covariate_coeff',
np.zeros((self.num_obs, 2)))
return
def _parse_param(self, **kwargs):
# Defines self.param
default = {
'sigma2_x': 1.0,
'A': None,
'sigma2_y': None,
'sigma2_theta': 1.0,
'lambduh': None,
'missing_obs': 0.0,
'x_0': None,
}
for key, value in kwargs.items():
if key in default.keys():
default[key] = value
param = Map(default)
# Handle variable arg defaults
if param.A is None:
param.A = 0.99 * np.ones(self.num_obs)
if param.lambduh is None:
param.lambduh = np.ones(self.num_obs)
if param.sigma2_y is None:
param.sigma2_y = np.ones(self.num_obs)
if param.x_0 is None:
var_0 = param.sigma2_x * (1.0/(1.0 - param.A**2))
param.x_0 = np.random.normal(0,1,self.num_obs)*np.sqrt(var_0)
self.param = param
return
def generate_cluster_proportions(self, proportion_prior=None):
if proportion_prior is not None:
self.param.proportion_prior = proportion_prior
if 'proportion_prior' not in self.param:
self.param.proportion_prior = 100 * np.ones(self.K)
cluster_proportions = np.random.dirichlet(
alpha = self.param.proportion_prior, size=1)
return cluster_proportions
def generate_data(self):
# Get Proportions
if 'cluster_proportions' not in self.param:
self.param.cluster_proportions = self.generate_cluster_proportions()
# Generate Data
z = np.array(
[ _categorical_sample(probs=self.param.cluster_proportions)
for i in range(0,self.num_obs)],
dtype=int)
x = np.zeros((self.num_dim, self.num_obs))
y = np.zeros((self.num_dim, self.num_obs))
theta = np.zeros((self.num_dim, self.K))
x_t = self.param.x_0
for t in range(0,self.num_dim):
theta_t = np.random.normal(0,1,self.K)
theta[t,:] = theta_t
x_t = self.param.A * x_t
x_t += (np.random.normal(0,1,self.num_obs) *
np.sqrt(self.param.sigma2_x))
x_t += (self.param.lambduh *
_one_hot(z, self.K).dot(theta_t))
x[t,:] = x_t
y[t,:] = x_t + (np.random.normal(0,1,self.num_obs) *
np.sqrt(self.param.sigma2_y))
if self.param.missing_obs > 0.0:
missing = np.random.rand(self.num_obs) < self.param.missing_obs
y[t,missing] = np.nan
df = convert_matrix_to_df(y.T, observation_name = "y")
# Add Regression + Covariates
if 'covariate_coeff' in self.param:
# TODO: REFACTOR THIS
covariate_coeff = self.param.covariate_coeff
num_coeff = covariate_coeff.shape[1]
for ii in range(num_coeff):
df['cov_{0}'.format(ii)] = np.random.normal(size=df.shape[0])
df['y_resid'] = df['y'] + 0.0
y_new = df.reset_index().apply(lambda row: row['y_resid'] +
np.sum([
row['cov_{0}'.format(ii)] *
covariate_coeff[int(row['observation']), ii]
for ii in range(num_coeff)
]), axis=1)
df['y'] = y_new.values
# Format Output
self.param['x'] = x.T
data = TimeSeriesData(
df = df,
observation_name = "y",
theta = theta.T,
z = z,
num_obs = self.num_obs,
num_dim = self.num_dim,
K = self.K,
parameters = self.param,
)
return data
def _one_hot(z, K):
""" Convert z into a one-hot bit vector representation """
z_one_hot = np.zeros((z.size, K))
z_one_hot[np.arange(z.size), z] = 1
return z_one_hot
# Example Script
if __name__ == "__main__":
print("Example Create TimeSeries Model Data")
data_generator = TimeSeriesDataGenerator(
num_obs = 50,
num_dim = 100,
K = 3,
sigma2_x = 0.01)
my_data = data_generator.generate_data()
#EOF
<file_sep>/ep_clustering/exp_family/_von_mises_fisher.py
#!/usr/bin/env python
"""
Von Mises Fisher Exponential Family Helper Class
"""
# Import Modules
import numpy as np
import logging
import scipy.stats
from ep_clustering._utils import fix_docs, logsumexp
from ._exponential_family import ExponentialFamily
from spherecluster import sample_vMF
from scipy.special import iv
logger = logging.getLogger(name=__name__)
LOGGING_FORMAT = '%(levelname)s: %(asctime)s - %(name)s: %(message)s ...'
logging.basicConfig(
level = logging.INFO,
format = LOGGING_FORMAT,
)
# VonMisesFisher Exponential Family
@fix_docs
class VonMisesFisherFamily(ExponentialFamily):
""" Von Mises Fisher Site Approximation Class
This is the likelihood for the mean, treating the concentration as fixed.
Natural Parameters:
'mean': (num_dim ndarray)
Helper Functions:
get_normalized_mean(): return mean
get_concentration(): return variance
"""
def __init__(self, num_dim, log_scaling_coef=0.0, mean=None):
# Set default mean
if mean is None:
#mean = np.ones(num_dim)/np.sqrt(num_dim) * count
mean = np.zeros(num_dim)
# Check Dimensions
if np.size(mean) != num_dim:
raise ValueError("mean must be size num_dim")
super(VonMisesFisherFamily, self).__init__(
num_dim=num_dim,
log_scaling_coef=log_scaling_coef,
mean=mean,
)
return
def is_valid_density(self):
if np.linalg.norm(self.natural_parameters['mean']) < 1e-16:
return False
return True
def sample(self):
self._check_is_valid_density()
sample = sample_vMF(
mu=self.get_normalized_mean(),
kappa=self.get_concentration(),
num_samples=1)[0]
return sample
def logpartition(self):
self._check_is_valid_density()
concentration = self.get_concentration()
order = (0.5 * self.num_dim - 1)
log_partition = 0.5 * self.num_dim * np.log(2*np.pi)
log_partition -= order * np.log(concentration)
log_partition += amos_asymptotic_log_iv(order, concentration)
return log_partition
def get_normalized_mean(self):
""" Return mean a.k.a. mu (on unit ball) """
mean = self.natural_parameters['mean']
norm = np.linalg.norm(mean)
if norm > 0:
normalized_mean = mean / norm
else:
raise RuntimeError("mean is zero-vector")
return normalized_mean
def get_concentration(self):
""" Return concentration a.k.a. kappa """
concentration = np.linalg.norm(self.natural_parameters['mean'])
return concentration
# VonMisesFisherProdGamma Exponential Family
@fix_docs
class VonMisesFisherProdGammaFamily(ExponentialFamily):
""" Von Mises Fisher Product Gamma Site Approximation Class
This is the likelihood for the mean and concentration parameter of the vMF.
Natural Parameters:
'mean': (num_dim ndarray) mean parameter for vMF mean
'alpha_minus_one': (double) shape parameter for vMF concentration
'beta': (double) rate parameter for vMF scale
Helper Functions:
get_normalized_mean(): return mean
"""
def __init__(self, num_dim, log_scaling_coef=0.0, mean=None,
alpha_minus_one=0.0, beta=0.0):
# Set default mean
if mean is None:
#mean = np.ones(num_dim)/np.sqrt(num_dim) * count
mean = np.zeros(num_dim)
# Check Dimensions
if np.size(mean) != num_dim:
raise ValueError("mean must be size num_dim")
super(VonMisesFisherProdGammaFamily, self).__init__(
num_dim=num_dim,
log_scaling_coef=log_scaling_coef,
mean=mean,
alpha_minus_one=alpha_minus_one,
beta=beta,
)
return
def _get_concentration_quantiles(self, breaks=20):
q = (np.arange(0, breaks) + 0.5)/(breaks*1.0)*0.98 + 0.01
q = np.concatenate((
np.logspace(-5, -2, 5),
q,
1.0-np.logspace(-5, -2, 5)[::-1],
))
alpha = self.natural_parameters['alpha_minus_one'] + 1.0
beta = self.natural_parameters['beta']
kappas = scipy.stats.gamma.ppf(q=q, a=alpha, scale=1.0/beta)
return kappas
def _get_concentration_quantile_weights(self, kappas):
alpha = self.natural_parameters['alpha_minus_one'] + 1.0
beta = self.natural_parameters['beta']
mid_points = (kappas[1:]+kappas[:-1])/2.0
cdf = np.concatenate(
(np.zeros(1),
scipy.stats.gamma.cdf(x=mid_points, a=alpha, scale=1.0/beta),
np.ones(1),
)
)
weights = cdf[1:] - cdf[:-1]
return weights
def _get_concentration_logpartitions(self, kappas):
order = (0.5 * self.num_dim - 1)
log_partitions = np.zeros_like(kappas)
log_partitions += 0.5 * self.num_dim * np.log(2*np.pi)
log_partitions -= order * np.log(kappas)
log_partitions += amos_asymptotic_log_iv(order, kappas)
return log_partitions
def is_valid_density(self):
if np.linalg.norm(self.natural_parameters['mean']) < 1e-16:
return False
if (self.natural_parameters['alpha_minus_one'] + 1.0) < 1e-16:
return False
if self.natural_parameters['beta'] < 1e-16:
return False
return True
def sample(self):
self._check_is_valid_density()
alpha = self.natural_parameters['alpha_minus_one'] + 1.0
beta = self.natural_parameters['beta']
sample_concentration = scipy.stats.gamma.rvs(
a=alpha, scale=1.0/beta, size=1)[0]
sample_mean = sample_vMF(
mu=self.get_normalized_mean(),
kappa=sample_concentration,
num_samples=1)[0]
return dict(
mean=sample_mean,
concentration=sample_concentration,
)
def logpartition(self):
self._check_is_valid_density()
kappas = self._get_concentration_quantiles()
weights = self._get_concentration_quantile_weights(kappas)
log_partitions = self._get_concentration_logpartitions(
kappas * np.linalg.norm(self.natural_parameters['mean'])
)
log_partition = logsumexp(log_partitions, weights)
return log_partition
def get_normalized_mean(self):
""" Return mean a.k.a. mu (on unit ball) """
mean = self.natural_parameters['mean']
norm = np.linalg.norm(mean)
if norm > 0:
normalized_mean = mean / norm
else:
raise RuntimeError("mean is zero-vector")
return normalized_mean
def get_mean_variance_concentration(self):
""" Return mean and variance of concentration """
alpha = self.natural_parameters['alpha_minus_one'] + 1.0
beta = self.natural_parameters['beta']
mean = alpha/beta
variance = alpha/(beta**2)
return dict(mean=mean, variance=variance)
# Helper Functions
def hankle_asymptotic_log_iv(order, z):
""" Asymptotic Expansion of the modified Bessel function
Asymptotic form by Hankle (see http://dlmf.nist.gov/10.40)
Using the first three terms
(see https://en.wikipedia.org/wiki/Bessel_function#Asymptotic_forms)
Do not use! (Only good for small order + very large z, z >> order**2)
"""
log_iv = z + 0.0
log_iv -= 0.5 * np.log(2*np.pi*z)
log_iv += np.log(1 +
-(4*order**2 -1)/(8*z) +
(4*order**2-1)*(4*order**2-9)/(2*(8*z)**2) +
-(4*order**2-1)*(4*order**2-9)*(4*order**2-25)/(6*(8*z)**3))
return log_iv
def amos_asymptotic_log_iv(order, z):
""" Asymptotic Expansion of the modified Bessel function
Asymptotic form by spherecluster using `_log_H_asymptotic`
(See utility function implementation notes in movMF.R from
https://cran.r-project.org/web/packages/movMF/index.html)
"""
# The approximation from spherecluster is good up to a constant
log_iv = np.log(iv(order, 100)) - (
_log_H_asymptotic(order, 100) + order*np.log(100)
)
log_iv += _log_H_asymptotic(order, z) + order*np.log(z)
return log_iv
def _log_H_asymptotic(nu, kappa):
"""Compute the Amos-type upper bound asymptotic approximation on H where
log(H_\nu)(\kappa) = \int_0^\kappa R_\nu(t) dt.
See "lH_asymptotic <-" in movMF.R and utility function implementation notes
from https://cran.r-project.org/web/packages/movMF/index.html
"""
beta = (nu + 0.5)
kappa_l = np.min(np.array([kappa,
np.sqrt((3. * nu + 11. / 2.) * (nu + 3. / 2.))*np.ones_like(kappa)]),
axis=0)
return (
_S(kappa, nu + 0.5, beta) +
(_S(kappa_l, nu, nu + 2.) - _S(kappa_l, nu + 0.5, beta))
)
def _S(kappa, alpha, beta):
"""Compute the antiderivative of the Amos-type bound G on the modified
Bessel function ratio.
See "S <-" in movMF.R and utility function implementation notes from
https://cran.r-project.org/web/packages/movMF/index.html
"""
kappa = 1. * np.abs(kappa)
alpha = 1. * alpha
beta = 1. * np.abs(beta)
a_plus_b = alpha + beta
u = np.sqrt(kappa**2 + beta**2)
if alpha == 0:
alpha_scale = 0
else:
alpha_scale = alpha * np.log((alpha + u) / a_plus_b)
return u - beta - alpha_scale
<file_sep>/ep_clustering/evaluator/__init__.py
from ._gibbs_evaluater import GibbsSamplerEvaluater
from ._metric_functions import (
metric_function_from_sampler,
metric_function_from_state,
heldout_loglikelihood,
var_info
)
from ._timeseries_prediction_metric import (
TimeSeriesPredictionEvaluator)
<file_sep>/ep_clustering/likelihoods/_student_t_likelihood.py
#!/usr/bin/env python
"""
Student T Likelihood
"""
# Import Modules
import numpy as np
import scipy
import logging
from scipy.stats import wishart, gamma
from scipy.special import gammaln
from scipy.optimize import brentq
from ep_clustering._utils import fix_docs, logsumexp
from ep_clustering.likelihoods._likelihoods import Likelihood
from ep_clustering.exp_family._mean_variance import (
NormalWishartFamily, multidigamma
)
logger = logging.getLogger(name=__name__)
LOGGING_FORMAT = '%(levelname)s: %(asctime)s - %(name)s: %(message)s ...'
logging.basicConfig(
level = logging.INFO,
format = LOGGING_FORMAT,
)
@fix_docs
class StudentTLikelihood(Likelihood):
""" Student T Likelihood Object
Args:
moment_update (string):
'exact' - use root finding to match sufficient statistics
breaks (int): number of points used in numerical integration
**kwargs :
df (double) - degrees of freedom (default = 3.0)
u (N ndarray) - auxiliary scale parameter for t-distribution
"""
# Inherit Docstrings
__doc__ += Likelihood.__doc__
# Class Variables
name = "StudentT"
def __init__(self, data, moment_update='exact', breaks=20, **kwargs):
self.y = data.matrix
self.num_dim = data.num_dim
self.moment_update = moment_update
if not isinstance(breaks, int):
raise TypeError("breaks must be an int")
self.breaks = breaks
super(StudentTLikelihood, self).__init__(data, **kwargs)
return
def deepcopy(self):
""" Return a copy """
other = type(self)(data = self.data,
moment_update=self.moment_update,
breaks=self.breaks,
theta_prior=self.theta_prior)
other.parameter = self.parameter.deepcopy()
other.prior = self.prior.deepcopy()
return other
def _get_default_prior(self):
theta_prior = NormalWishartFamily(num_dim = self.num_dim,
kappa = 0.1,
nu_minus = 1.0,
zeta=np.eye(self.num_dim)*(self.num_dim),
)
return theta_prior
def _get_default_parameters(self):
"""Returns default parameters dict"""
default_parameter = {
"df": 3.0,
"u": np.ones(np.shape(self.y)[0]),
}
return default_parameter
def _get_default_parameters_prior(self):
"""Returns default parameters prior dict"""
prior = {"df_prior": 3.0}
return prior
def _sample_from_prior(self):
parameter = {
"df": self.prior.df_prior,
"u": np.random.gamma(
shape=self.prior.df_prior/2.0,
scale=2.0/self.prior.df_prior,
size=self.num_dim)
}
return parameter
def loglikelihood(self, index, theta):
y_index = self.y[index]
# Conditioned on mean, precision, and u_index -> likelihood is Gaussian
mean = theta['mean']
precision = theta['precision']
u_index = self.parameter.u[index]
scaled_precision = u_index * precision
loglikelihood = -0.5*self.num_dim*np.log(2*np.pi) + \
-0.5*(y_index-mean).dot(scaled_precision.dot(y_index-mean)) + \
0.5*self.num_dim*np.log(u_index) + \
0.5*np.linalg.slogdet(precision)[1]
return loglikelihood
def collapsed(self, index, subset_indices, theta_parameter):
kappa, nu, mu, psi = theta_parameter.get_kappa_nu_mu_psi()
y_indices = self.y[subset_indices]
u_indices = self.parameter.u[subset_indices]
uy_indices = np.outer(u_indices, np.ones(self.num_dim)) * y_indices
u_sum = np.sum(u_indices)
uy_sum = np.sum(uy_indices, axis=0)
uyy_sum = y_indices.T.dot(uy_indices)
kappa_post = kappa + u_sum
nu_post = nu + len(subset_indices)
mu_post = (kappa * mu + uy_sum)/(kappa + u_sum)
psi_post = psi + uyy_sum + (
kappa*np.outer(mu, mu) - kappa_post*np.outer(mu_post, mu_post)
)
y_index = self.y[index]
u_index = self.parameter.u[index]
# Generalization of t-Distribution predictive posterior
loglikelihood = -0.5*self.num_dim*np.log(np.pi) + \
0.5*self.num_dim*np.log(u_index) + \
0.5*self.num_dim*(np.log(kappa_post)-np.log(kappa_post+u_index)) + \
scipy.special.gammaln((nu_post + 1.0)/2.0) + \
-scipy.special.gammaln((nu_post - self.num_dim + 1.0)/2.0) + \
-0.5*np.linalg.slogdet(psi_post)[1] + \
-0.5*(nu_post + 1.0)*np.log(1 +
(kappa_post*u_index)/(kappa_post + u_index) *
(y_index-mu_post).dot(
np.linalg.solve(psi_post, y_index-mu_post))
)
return loglikelihood
def _get_u_grid(self, recalculate=False):
# Create Grid of numerical values for moment_update
# Grid is based on Gamma(alpha=df/2, beta=df/2)
if not hasattr(self, "_u_grid") or recalculate:
# Define _u_grid
q = (np.arange(0, self.breaks) + 0.5)/(self.breaks*1.0)*0.98 + 0.01
q = np.concatenate((
np.logspace(-5, -2, 5),
q,
1.0-np.logspace(-5, -2, 5)[::-1],
))
alpha = self.parameter.df/2.0
beta = self.parameter.df/2.0
self._u_grid = gamma.ppf(q=q, a=alpha, scale=1.0/beta)
# Define _u_weights
mid_points = (self._u_grid[1:]+self._u_grid[:-1])/2.0
cdf = np.concatenate((
np.zeros(1),
gamma.cdf(x=mid_points, a=alpha, scale=1.0/beta),
np.ones(1),
))
self._u_weights = cdf[1:] - cdf[:-1]
return self._u_grid, self._u_weights
def moment(self, index, theta_parameter):
# Need to numpy vectorize this
y_index = self.y[index]
kappa, nu, mu, psi = theta_parameter.get_kappa_nu_mu_psi()
# Helper constants
V = np.linalg.inv(psi)
logdetpsi = np.linalg.slogdet(psi)[1]
delta = y_index - mu
V_delta = np.linalg.solve(psi, delta)
VdeltadeltaTV = np.outer(V_delta, V_delta)
deltaTVdelta = delta.dot(V_delta)
u_grid, u_weights = self._get_u_grid()
# Calculate loglikelihood
logpartitions = 0.5*self.num_dim*np.log(u_grid/np.pi) + \
0.5*self.num_dim*np.log(kappa) + \
-0.5*self.num_dim*np.log(kappa+u_grid) + \
gammaln((nu+1.0)/2.0) - gammaln((nu-self.num_dim+1.0)/2.0) + \
-0.5*logdetpsi + \
-0.5*(nu+1.0)*np.log(
1.0 + (kappa*u_grid)/(kappa+u_grid) * deltaTVdelta
)
logpartition = logsumexp(logpartitions, u_weights)
# Calculate Moments of Titled Distribution
expect_mean_precision_mean = 0.0
expect_mean_precision = np.zeros(self.num_dim)
expect_precision = np.zeros((self.num_dim, self.num_dim))
expect_log_precision = (
multidigamma((nu+1.0)/2.0, self.num_dim) + \
self.num_dim * np.log(2) - logdetpsi
)
moment_weights = u_weights * np.exp(logpartitions-logpartition)
for u, weight in zip(u_grid, moment_weights):
psi_post_inv = (
V - (kappa * u)/(kappa + u) * (VdeltadeltaTV) / \
(1 + (kappa * u)/(kappa + u) * deltaTVdelta)
)
mu_post = (kappa * mu + u * y_index)/(kappa + u)
expect_mean_precision_mean += weight * (
(nu+1) * mu_post.dot(psi_post_inv.dot(mu_post)) +
self.num_dim/(kappa + u)
)
expect_mean_precision += weight * (nu+1) * psi_post_inv.dot(mu_post)
expect_precision += weight * (nu+1) * psi_post_inv
expect_log_precision += weight * (
-1.0 * np.log(1 + (kappa * u)/(kappa+u) * deltaTVdelta)
)
# Project into NormalWishartFamily
if self.moment_update == 'exact':
constant = (expect_log_precision - self.num_dim * np.log(2) - \
np.linalg.slogdet(expect_precision)[1])
d = self.num_dim
def fun(x):
obj = multidigamma(x/2.0, d) - d*np.log(x) - constant
return obj
nu_proj = brentq(fun, d, (nu+1)*10.0)
L_V_proj = np.linalg.cholesky(expect_precision / nu_proj)
psi_proj = np.linalg.solve(L_V_proj.T,
np.linalg.solve(L_V_proj, np.eye(self.num_dim)))
mu_proj = np.linalg.solve(expect_precision, expect_mean_precision)
kappa_proj = self.num_dim * (expect_mean_precision_mean - \
mu_proj.dot(expect_mean_precision))**-1.0
else:
raise ValueError("Unrecognized moment_update `{0}`".format(
self.moment_update))
unnormalized_post_approx = NormalWishartFamily.from_mu_kappa_nu_psi(
mu=mu_proj, kappa=kappa_proj,
nu=nu_proj, psi=psi_proj,
)
unnormalized_post_approx.log_scaling_coef = logpartition
return unnormalized_post_approx
def ep_loglikelihood(self, index, theta_parameter):
# Copied from self.moment()
y_index = self.y[index]
kappa, nu, mu, psi = theta_parameter.get_kappa_nu_mu_psi()
# Helper constants
logdetpsi = np.linalg.slogdet(psi)[1]
delta = y_index - mu
deltaTVdelta = delta.dot(np.linalg.solve(psi, delta))
u_grid, u_weights = self._get_u_grid()
# Calculate loglikelihood
logpartitions = 0.5*self.num_dim*np.log(u_grid/np.pi) + \
0.5*self.num_dim*np.log(kappa) + \
-0.5*self.num_dim*np.log(kappa+u_grid) + \
gammaln((nu+1.0)/2.0) - gammaln((nu-self.num_dim+1.0)/2.0) + \
-0.5*logdetpsi + \
-0.5*(nu+1.0)*np.log(
1.0 + (kappa*u_grid)/(kappa+u_grid) * deltaTVdelta
)
logpartition = logsumexp(logpartitions, u_weights)
return logpartition
def sample(self, indices, prior_parameter):
kappa, nu, mu, psi = prior_parameter.get_kappa_nu_mu_psi()
y_indices = self.y[indices]
u_indices = self.parameter.u[indices]
uy_indices = np.outer(u_indices, np.ones(self.num_dim)) * y_indices
u_sum = np.sum(u_indices)
uy_sum = np.sum(uy_indices, axis=0)
uyy_sum = y_indices.T.dot(uy_indices)
kappa_post = kappa + u_sum
nu_post = nu + len(indices)
mu_post = (kappa * mu + uy_sum)/(kappa + u_sum)
psi_post = psi + uyy_sum + (
kappa*np.outer(mu, mu) - kappa_post*np.outer(mu_post, mu_post)
)
precision = wishart(df=nu_post,
scale=np.linalg.inv(psi_post)).rvs()
L = np.linalg.cholesky(precision) * \
np.sqrt(kappa_post)
mean = mu_post + np.linalg.solve(L.T,
np.random.normal(size=self.num_dim))
return dict(mean=mean, precision=precision)
def update_parameters(self, z, theta, parameter_name = None):
if parameter_name is None:
self._update_u(z, theta)
elif parameter_name == "u":
self._update_u(z, theta)
else:
raise ValueError("Unrecognized parameter_name: " + parameter_name)
return
def _update_u(self, z, theta, k=None):
df = self.parameter.df
for ii, z_i in enumerate(z):
if (k is None) or (z_i == k):
# Condition on Y_i
delta = self.y[ii] - theta[z_i]['mean']
alpha_u = df/2.0 + self.num_dim/2.0
beta_u = df/2.0 + 0.5 * np.dot(
delta, np.dot(theta[z_i]['precision'], delta)
)
self.parameter.u[ii] = gamma(a=alpha_u, scale=1.0/beta_u).rvs()
else:
# Sample from Prior
self.parameter.u[ii] = gamma(a=df/2.0, scale=2.0/df).rvs()
return
def update_local_parameters(self, k, z, theta, parameter_name = None):
if parameter_name is None:
self._update_u(z, theta, k=k)
elif parameter_name == "u":
self._update_u(z, theta, k=k)
else:
raise ValueError("Unrecognized parameter_name: " + parameter_name)
return
# EOF
<file_sep>/experiments/synthetic_timeseries_clustering_example.py
# Refresher script to get familiar with the code-base API
import matplotlib as mpl
mpl.use('Agg')
import os
import numpy as np
import pandas as pd
import joblib
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import ep_clustering as ep
from tqdm import tqdm # Progress Bar
# Make Paths to output/figures
path_to_fig = "output/synth_ts_examples/figures"
path_to_data = "output/synth_ts_examples/data"
if not os.path.isdir(path_to_fig):
os.makedirs(path_to_fig)
if not os.path.isdir(path_to_data):
os.makedirs(path_to_data)
######################################################
# Generate Synthetic Data
######################################################
np.random.seed(12345)
data_param = dict(
num_dim=100, # Length of each time series
num_obs=50, # Number of time series
K=3, # Number of clusters
sigma2_x = 0.01, # Latent noise variance
#missing_obs = 0.05, # Fraction of observations missing (i.e. NaNs)
)
data_gen = ep.data.TimeSeriesDataGenerator(**data_param)
data = data_gen.generate_data()
# 'data' is a dict containing observations, cluster labels, latent variables and parameters
print(data['df']) # Data as a pd.Series in tall-format
# To convert data['df'] to a matrix, use 'ep._utils.convert_df_to_matrix'
Y_mat, missing_mat = ep._utils.convert_df_to_matrix(data['df'])
print(Y_mat)
# Convert back with 'ep._utils.convert_matrix_to_df'
df = ep._utils.convert_matrix_to_df(Y_mat)
print(df)
print(data['z']) # True Cluster Assignments
print(data['theta']) # Cluster Means / Latent Factor Means
print(data['parameters'].keys()) # Dictionary of other parameters
print(data['parameters']['x']) # Latent time series
## Plot and Save Data
def plot_truth_data(data):
fig, ax = plt.subplots(1,1)
plot_df = data.df.reset_index()
z_df = pd.DataFrame({'truth': data.z,
'observation': np.arange(len(data.z))})
plot_df = pd.merge(plot_df, z_df)
sns.lineplot(x='dimension', y='y', hue='truth',
palette=sns.color_palette('deep', data['K']),
alpha=0.5,
units='observation', estimator=None, data=plot_df,
ax=ax)
return fig, ax
# Plot Data
fig, ax = plot_truth_data(data)
fig.savefig(os.path.join(path_to_fig, "true_data.png"))
# Save Data
joblib.dump(data, filename=os.path.join(path_to_data, "data.p"))
######################################################
# Define Model to Fit
######################################################
## Likelihood
likelihood = ep.construct_likelihood(name="TimeSeries", data=data)
# See likelihood? for more details (or print(likelihood.__doc__))
## Approximation Algorithm
alg_name = 'EP' # 'naive' or 'collapsed' are the other options
approx_alg = ep.construct_approx_algorithm(
name=alg_name,
exp_family=ep.exp_family.DiagNormalFamily,
)
# See approx_alg? for more details (or print(approx_alg.__doc__))
## Number of Clusters to Infer
Kinfer = 3
## Setup Approx Gibbs Sampler
sampler = ep.GibbsSampler(
data=data,
likelihood=likelihood,
K=Kinfer,
approx_alg=approx_alg,
)
# See ep.GibbsSampler? for more details on how to set prior and other algorithm options
# See sampler? for more details (or print(sampler.__doc__))
print(sampler.state) # Initial state of latent vars 'z' and parameters
print(sampler.options) # Gibbs sampling options (including prior)
# Randomly initialize the inital_state
sampler.init_state()
# sampler.init_state(z=data['z']) # init from ground truth labels
# Sample z from the posterior (based on alg_name)
print(sampler.sample_z())
# Only sample z[5] from the posterior, returns [5], old_z[5], new_z[5]
print(sampler.sample_one_z(5))
# Note, the EP approx parameters are updated automatically whenever z is sampled
# Sample Theta
print(sampler.sample_theta())
# Sample Other Likelihood Parameters
sampler.sample_likelihood_parameters()
# Helper Function to Sample Z, Theta, and Likelihood Parameters using Blocked Gibbs
sampler.one_step(full_mcmc=True)
# If full_mcmc is False, then the likelihood_parameters will not be sampled
# Manually update all EP Approximation Parameters (for Full, exact EP)
sampler.update_approx_alg()
# Evaluate log Pr(y | z, theta, likelihood parameters) of data
print(sampler.eval_loglikelihood(kind='naive'))
# Evaluate log Pr(y | z, likelihood parameters) of data
print(sampler.eval_loglikelihood(kind='collapsed'))
######################################################
# Define Evaluation Metrics
######################################################
## Metrics to track
# -Loglikelihood
# -NVI (normalized variation of information) a divergence metric between clusters
# -MSE of parameters likelihood parameters and latent series x
my_metric_functions = [
ep.evaluator.metric_function_from_sampler("eval_loglikelihood"),
ep.evaluator.metric_function_from_state("z", data.z, "nvi"),
ep.evaluator.metric_function_from_state(
['likelihood_parameter', "A"],
data.parameters.A, "mse"),
ep.evaluator.metric_function_from_state(
['likelihood_parameter', "x"],
data.parameters.x, "mse"),
ep.evaluator.metric_function_from_state(
['likelihood_parameter', "lambduh"],
data.parameters.lambduh, "mse"),
ep.evaluator.metric_function_from_state(
['likelihood_parameter', "sigma2_x"],
data.parameters.sigma2_x, "mse"),
ep.evaluator.metric_function_from_state(
['likelihood_parameter', "sigma2_y"],
data.parameters.sigma2_y, "mse"),
]
## Samples to track
# Keep track of theta and cluster assignments z
my_sample_functions = {
'theta': lambda sampler: sampler.state.theta,
'z': lambda sampler: sampler.state.z,
}
## Construct Sampler Wrapper
my_evaluator = ep.GibbsSamplerEvaluater(
sampler=sampler,
metric_functions=my_metric_functions,
sample_functions=my_sample_functions,
sampler_name="example",
)
######################################################
# Run Sampler with Online Evaluation
######################################################
from tqdm import tqdm # Progress Bar
for _ in tqdm(range(10)):
my_evaluator.evaluate_sampler_step()
metric_df = my_evaluator.get_metrics()
sample_df = my_evaluator.get_samples()
print(metric_df) # Metrics for first iterations are pd.DataFrame
print(sample_df) # Samples for first iterations are pd.DataFrame
# For example to look at just the loglikelihood
print(metric_df.query('metric == "eval_loglikelihood"'))
# Metric Plotter
def plot_metrics(metric_df):
metric_df['variable'] = metric_df['variable'].apply(
lambda x: x.strip('likelihood_parameter'))
metric_df['metric_var'] = metric_df['metric'] + "_" + metric_df['variable']
g = sns.FacetGrid(
data=metric_df, col="metric_var", col_wrap=4, sharey=False,
)
g = g.map(plt.plot, "iteration", "value")
return g
# Run for 100 EPOCHs
num_epochs = 100 # number of iterations (passes over the data set)
for _ in tqdm(range(num_epochs)):
my_evaluator.evaluate_sampler_step()
# Checkpoint Metrics + Samples every 10 Epochs
if _ % 10 == 0:
metric_df = my_evaluator.get_metrics()
sample_df = my_evaluator.get_samples()
# Plot Metrics over time
plot_metrics(metric_df).savefig(os.path.join(path_to_fig, 'metrics.png'))
# Save Metrics + Samples
metric_df.to_pickle(os.path.join(path_to_data, "metrics.p"))
sample_df.to_pickle(os.path.join(path_to_data, "samples.p"))
######################################################
# Full Example of TS with regression covariates
######################################################
data_param = dict(
num_dim=150, # Length of each time series
num_obs=100, # Number of time series
K=4, # Number of clusters
sigma2_x = 0.01, # Latent noise variance
#missing_obs = 0.05, # Fraction of observations missing (i.e. NaNs)
A=np.ones(100) * 0.95,
regression=True, # Include Covariates
covariate_coeff=10*np.ones((100, 3)), # Covariates
)
data_gen = ep.data.TimeSeriesDataGenerator(**data_param)
data = data_gen.generate_data()
print(data['df'].head())
# Save Data
joblib.dump(data, filename=os.path.join(path_to_data, "tsreg_data.p"))
Kinfer = 4
covariate_names = [col for col in data['df'].columns if "cov" in col]
likelihood = ep.construct_likelihood(name="TimeSeriesRegression",
data=data, covariate_names=covariate_names)
approx_alg = ep.construct_approx_algorithm(
name='EP',
exp_family=ep.exp_family.DiagNormalFamily,
)
sampler = ep.GibbsSampler(
data=data,
likelihood=likelihood,
K=Kinfer,
approx_alg=approx_alg,
)
sampler.init_state()
my_metric_functions = [
ep.evaluator.metric_function_from_sampler("eval_loglikelihood"),
]
my_metric_functions += [
ep.evaluator.metric_function_from_state("z", data.z, "nvi"),
ep.evaluator.metric_function_from_state("z", data.z, "nmi"),
ep.evaluator.metric_function_from_state("z", data.z, "precision"),
ep.evaluator.metric_function_from_state("z", data.z, "recall"),
]
my_metric_functions += [
ep.evaluator.metric_function_from_state(
['likelihood_parameter', "A"],
data.parameters.A, "mse"),
ep.evaluator.metric_function_from_state(
['likelihood_parameter', "x"],
data.parameters.x, "mse"),
ep.evaluator.metric_function_from_state(
['likelihood_parameter', "lambduh"],
data.parameters.lambduh, "mse"),
ep.evaluator.metric_function_from_state(
['likelihood_parameter', "sigma2_x"],
data.parameters.sigma2_x, "mse"),
ep.evaluator.metric_function_from_state(
['likelihood_parameter', "sigma2_y"],
data.parameters.sigma2_y, "mse"),
ep.evaluator.metric_function_from_state(
['likelihood_parameter', "covariate_coeff"],
data.parameters.covariate_coeff, "mse"),
]
my_sample_functions = {
'theta': lambda sampler: sampler.state.theta,
'z': lambda sampler: sampler.state.z,
}
# Construct Evaluator
evaluator = ep.GibbsSamplerEvaluater(
sampler=sampler,
metric_functions=my_metric_functions,
sample_functions=my_sample_functions,
sampler_name="regression_example",
)
# Run for 100 EPOCHs
num_epochs = 100 # number of iterations (passes over the data set)
for _ in tqdm(range(num_epochs)):
evaluator.evaluate_sampler_step(['one_step'])
# Checkpoint Metrics + Samples every 10 Epochs
if _ % 10 == 0:
metric_df = evaluator.get_metrics()
sample_df = evaluator.get_samples()
# Plot Metrics over time
plt.close('all')
plot_metrics(metric_df).savefig(os.path.join(path_to_fig, 'tsreg_metrics.png'))
# Save Metrics + Samples
metric_df.to_pickle(os.path.join(path_to_data, "tsreg_metrics.p"))
sample_df.to_pickle(os.path.join(path_to_data, "tsreg_samples.p"))
<file_sep>/ep_clustering/exp_family/_normal_mean.py
#!/usr/bin/env python
"""
Natural Parameters Helper
"""
# Import Modules
import numpy as np
from ep_clustering._utils import fix_docs
from ._exponential_family import ExponentialFamily
# Author Information
__author__ = "<NAME>"
# Normal Exponential Family
@fix_docs
class NormalFamily(ExponentialFamily):
""" Normal Family Site Approximation Class
Natural Parameters:
'mean_precision': (num_dim ndarray)
'precision': (num_dim by num_dim ndarray)
(__init__ will cast input to matrix if diagonal matrix)
Helper Functions:
get_mean(): return mean
get_variance(): return variance
"""
def __init__(self, num_dim, log_scaling_coef=0.0, mean_precision=None,
precision=None):
# Set Default mean_precision and precision
if mean_precision is None:
mean_precision = np.zeros(num_dim)
if precision is None:
precision = np.zeros((num_dim, num_dim))
# Check Dimensions
if np.size(mean_precision) != num_dim:
raise ValueError("mean_precision must be size num_dim")
if np.shape(precision) != (num_dim, num_dim):
if np.size(precision) == num_dim:
precision = np.diag(precision)
else:
raise ValueError("precision must be size num_dim by num_dim")
super(NormalFamily, self).__init__(
num_dim=num_dim,
log_scaling_coef=log_scaling_coef,
mean_precision=mean_precision,
precision=precision
)
return
def is_valid_density(self):
eigvals = np.linalg.eigvals(self.natural_parameters['precision'])
if np.any(eigvals < 1e-12):
return False
return True
def sample(self):
self._check_is_valid_density()
L = np.linalg.cholesky(self.natural_parameters['precision'])
z = np.random.normal(size = self.num_dim)
sample = np.linalg.solve(L.T, z + np.linalg.solve(L.T,
self.natural_parameters['mean_precision']))
return sample
def logpartition(self):
self._check_is_valid_density()
sign, logdet_precision = np.linalg.slogdet(
self.natural_parameters['precision'])
log_partition = 0.5 * self.num_dim * np.log(2 * np.pi)
log_partition -= 0.5 * logdet_precision
log_partition += 0.5 * self.natural_parameter['mean_precision'].dot(
np.linalg.solve(self.natural_parameters['precision'],
self.natural_parameters['mean_precision']))
return log_partition
def get_mean(self):
""" Return the mean """
mean = self.natural_parameters['mean_precision'] / \
self.natural_parameters['precision']
return mean
def get_variance(self):
""" Return the variance """
variance = self.natural_parameters['precision'] ** -1
return variance
@fix_docs
class DiagNormalFamily(ExponentialFamily):
""" Normal Family Site Approximation Class (with diag variance)
Natural Parameters Args:
'mean_precision' (num_dim ndarray): precision * mean
'precision' (num_dim ndarray): diagonal precision
Helper Functions:
get_mean(): return mean
get_variance(): return variance
"""
def __init__(self, num_dim, log_scaling_coef=0.0, mean_precision=None,
precision=None):
# Set Default mean_precision and precision
if mean_precision is None:
mean_precision = np.zeros(num_dim)
if precision is None:
precision = np.zeros(num_dim)
# Check Dimensions
if np.size(mean_precision) != num_dim:
raise ValueError("mean_precision must be size num_dim")
if np.size(precision) != num_dim:
raise ValueError("precision must be size num_dim")
super(DiagNormalFamily, self).__init__(
num_dim=num_dim,
log_scaling_coef=log_scaling_coef,
mean_precision=mean_precision,
precision=precision
)
return
def is_valid_density(self):
if np.any(self.natural_parameters['precision'] < 1e-12):
return False
return True
def sample(self):
self._check_is_valid_density()
sample = self.get_mean() + \
np.random.normal(size = self.num_dim) * \
np.sqrt(self.get_variance())
return sample
def logpartition(self):
self._check_is_valid_density()
logdet_precision = np.sum(np.log(self.natural_parameters['precision']))
log_partition = 0.5 * self.num_dim * np.log(2 * np.pi)
log_partition -= 0.5 * logdet_precision
log_partition += 0.5 * np.sum(
self.natural_parameters['mean_precision'] ** 2 /
self.natural_parameters['precision'])
return log_partition
def get_mean(self):
""" Return the mean """
mean = self.natural_parameters['mean_precision'] / \
self.natural_parameters['precision']
return mean
def get_variance(self):
""" Return the variance """
variance = self.natural_parameters['precision'] ** -1
return variance
@staticmethod
def from_mean_variance(mean, variance):
""" Helper function for constructing DiagNormalFamily from
mean and variance
Args:
mean (ndarray): mean (size num_dim)
variance (ndarray): variance (size num_dim)
"""
num_dim = np.size(mean)
if np.size(variance) != num_dim:
raise ValueError("mean and variance dimensions do not match")
precision = 1.0/variance
mean_precision = mean * precision
return DiagNormalFamily(
num_dim=num_dim,
mean_precision=mean_precision,
precision=precision,
)
<file_sep>/ep_clustering/likelihoods/_timeseries_likelihood.py
#!/usr/bin/env python
"""
Timeseries Likelihood
"""
# Import Modules
import numpy as np
import pandas as pd
import logging
from ep_clustering._utils import fix_docs, convert_matrix_to_df
from ep_clustering.likelihoods._likelihoods import Likelihood
from ep_clustering.kalman_filter import KalmanFilter, _cpp_available
from ep_clustering.exp_family import DiagNormalFamily
## Try Importing C++ Implementation
if _cpp_available:
from ep_clustering.kalman_filter.c_kalman_filter import CKalmanFilter
logger = logging.getLogger(name=__name__)
@fix_docs
class TimeSeriesLikelihood(Likelihood):
""" Correlated Time Series Object
Args:
use_cpp (boolean): whether to use the C++ implementation of the
Kalman Filter (default = False)
use_old_update (boolean): whether to use the old (incorrect) EP update
For comparison purposes only (default = False)
**kwargs:
- x (N by T ndarray) - latent time series
- A (N ndarray) - AR Coefficients
- lambduh (N ndarray) - Factor Loadings
- sigma2_x (double) - Covariance of latent errors
- sigma2_y (N ndarray) - Variance of observation errors
Note that `x` is updated when sampling `theta` using `sample()`.
"""
__doc__ += Likelihood.__doc__
name = "TimeSeries"
def __init__(self, data, use_cpp = False,
use_old_update = False, **kwargs):
self.y, self.y_count = data.get_matrix()
self.num_dim = data.num_dim
super(TimeSeriesLikelihood, self).__init__(data, **kwargs)
if use_cpp:
if _cpp_available:
self.Filter = CKalmanFilter
self.name = "CppTimeSeries"
else:
logger.warning("C++ Implementation not found.\n " +
"Have you called 'python setup.py build_ext -i' from src/ ?")
logger.info("Using Python Kalman Filter Implementation")
self.Filter = KalmanFilter
else:
self.Filter = KalmanFilter
self._use_cpp = use_cpp
self._use_old_update = use_old_update
return
def _get_default_prior(self):
theta_prior = DiagNormalFamily(
num_dim=self.num_dim,
precision=np.ones(self.num_dim)/100,
)
return theta_prior
def _get_default_parameters(self):
default_parameter = {
"x": np.zeros(np.shape(self.y)) * np.nan,
"A": 0.9 * np.ones(np.shape(self.y)[0]),
"lambduh": np.ones(np.shape(self.y)[0]),
"sigma2_x": 1.0,
"sigma2_y": np.ones(np.shape(self.y)[0]),
}
return default_parameter
def _get_default_parameters_prior(self):
prior = {
"mu_A0": 0.0,
"sigma2_A0": 100.0,
"mu_lambduh0": 0.0,
"sigma2_lambduh0": 100.0,
"alpha_x0": 3.0,
"beta_x0": 2.0,
"alpha_y0": 3.0,
"beta_y0": 2.0,
}
return prior
def _sample_from_prior(self):
N = np.shape(self.y)[0]
logger.warning("Sampling from prior is not recommended")
parameter = {
"x": np.zeros(np.shape(self.y)) * np.nan,
"A": np.random.normal(
loc=self.prior.mu_A0,
scale=np.sqrt(self.prior.sigma2_A0),
size=N),
"lambduh": np.random.normal(
loc=self.prior.mu_lambduh0,
scale=np.sqrt(self.prior.sigma2_lambduh0),
size=N),
"sigma2_x": 1.0/np.random.gamma(
shape=self.prior.alpha_x0,
scale=self.prior.beta_x0,
size=1)[0],
"sigma2_y": 1.0/np.random.gamma(
shape=self.prior.alpha_y0,
scale=self.prior.beta_y0,
size=N),
}
return parameter
def loglikelihood(self, index, theta):
kalman = self.Filter(y=np.array([self.y[index]]),
A=self.parameter.A[index],
lambduh=self.parameter.lambduh[index],
sigma2_x=self.parameter.sigma2_x,
sigma2_y=self.parameter.sigma2_y[index],
eta_mean=theta,
eta_var=np.zeros(np.size(theta)),
y_count=np.array([self.y_count[index]]),
)
loglikelihood = kalman.calculate_log_likelihood()
return loglikelihood
def cluster_loglikelihood(self, indices, theta_parameter):
if theta_parameter is None:
theta_parameter = self._get_default_prior()
if len(indices) == 0:
return 0.0
kalman = self.Filter(
y = np.vstack([self.y[indices]]),
A = np.hstack([self.parameter.A[indices]]),
lambduh = np.hstack([self.parameter.lambduh[indices]]),
sigma2_x=self.parameter.sigma2_x,
sigma2_y=np.hstack([self.parameter.sigma2_y[indices]]),
eta_mean=theta_parameter.get_mean(),
eta_var=theta_parameter.get_variance(),
y_count=np.vstack(
[self.y_count[indices]]),
)
loglikelihood = kalman.calculate_log_likelihood()
return loglikelihood
def collapsed(self, index, subset_indices, theta_parameter):
if theta_parameter is None:
theta_parameter = self._get_default_prior()
kalman = self.Filter(
y=np.vstack([self.y[index], self.y[subset_indices]]),
A=np.hstack([self.parameter.A[index],
self.parameter.A[subset_indices]]),
lambduh=np.hstack([self.parameter.lambduh[index],
self.parameter.lambduh[subset_indices]]),
sigma2_x=self.parameter.sigma2_x,
sigma2_y=np.hstack([self.parameter.sigma2_y[index],
self.parameter.sigma2_y[subset_indices]]),
eta_mean=theta_parameter.get_mean(),
eta_var=theta_parameter.get_variance(),
y_count=np.vstack(
[self.y_count[index], self.y_count[subset_indices]]),
)
loglikelihood = kalman.calculate_cond_log_likelihood(i=0)
return loglikelihood
def ep_loglikelihood(self, index, theta_parameter):
approx_loglikelihood = self.collapsed(index=index, subset_indices=[],
theta_parameter=theta_parameter)
return approx_loglikelihood
def moment(self, index, theta_parameter):
#kalman = self.Filter( # TO FIX need to implement Cython Version
kalman = KalmanFilter(
y=np.array([self.y[index]]),
A=self.parameter.A[index],
lambduh=self.parameter.lambduh[index],
sigma2_x=self.parameter.sigma2_x,
sigma2_y=self.parameter.sigma2_y[index],
eta_mean=theta_parameter.get_mean(),
eta_var=theta_parameter.get_variance(),
y_count=np.array([self.y_count[index]]),
)
log_scaling_coef = self.ep_loglikelihood(index, theta_parameter)
if self._use_old_update and not self._use_cpp:
likelihood_mean, likelihood_variance = kalman._old_moment_eta()
else:
likelihood_mean, likelihood_variance = kalman.moment_eta()
site = DiagNormalFamily.from_mean_variance(
mean=likelihood_mean,
variance=likelihood_variance,
)
post_approx = theta_parameter + site
post_approx.log_scaling_coef = log_scaling_coef
return post_approx
def sample(self, indices, prior_parameter):
if len(indices) == 0:
return np.random.randn(prior_parameter.num_dim)*np.sqrt(
prior_parameter.get_variance()) + prior_parameter.get_mean()
kalman = self.Filter(
y=self.y[indices],
A=self.parameter.A[indices],
lambduh=self.parameter.lambduh[indices],
sigma2_x=self.parameter.sigma2_x,
sigma2_y=self.parameter.sigma2_y[indices],
eta_mean=prior_parameter.get_mean(),
eta_var=prior_parameter.get_variance(),
y_count=self.y_count[indices],
)
x = kalman.sample_x() # Updates x through sampling theta
self.parameter.x[indices] = x.T
sampled_theta = kalman.sample_eta(x = np.copy(x))
return sampled_theta
def predict(self, new_data, prior_parameter, num_samples):
sample_ys = []
indices = np.unique(new_data.df.index.get_level_values('observation'))
y_reg = pd.Series(np.zeros(new_data.df.shape[0]),
index = _fix_pandas_index(new_data.df.index)
)
kalman = self.Filter(
y=self.y[indices],
A=self.parameter.A[indices],
lambduh=self.parameter.lambduh[indices],
sigma2_x=self.parameter.sigma2_x,
sigma2_y=self.parameter.sigma2_y[indices],
eta_mean=prior_parameter.get_mean(),
eta_var=prior_parameter.get_variance(),
y_count=self.y_count[indices],
)
for s in range(0, num_samples):
y = kalman.sample_y(x = self.parameter.x[indices].T)
y_df = convert_matrix_to_df(y.T, '_prediction')['_prediction']
y_df.index = y_df.index.set_levels(indices, level='observation')
y_filtered = (y_reg + y_df).dropna()
sample_ys.append(y_filtered.values)
sampled_y = np.array(sample_ys)
return sampled_y
def update_parameters(self, z, theta, parameter_name = None):
if(parameter_name is None):
self._update_A(z, theta)
self._update_lambduh(z, theta)
self._update_sigma2_y()
self._update_sigma2_x(z, theta)
elif(parameter_name == "A"):
self._update_A(z, theta)
elif(parameter_name == "lambduh"):
self._update_lambduh(z, theta)
elif(parameter_name == "sigma2_y"):
self._update_sigma2_y()
elif(parameter_name == "sigma2_x"):
self._update_sigma2_x(z, theta)
elif(parameter_name == "x"):
raise ValueError("x is updated when sampling theta using `sample`")
else:
raise ValueError("Unrecognized parameter_name: " + parameter_name)
return
def _update_A(self, z, theta):
""" Update the AR coefficients A """
N, T = np.shape(self.parameter.x)
for index in range(0, N):
x = self.parameter.x[index]
lambduh = self.parameter.lambduh[index]
eta = theta[z[index]]
sigma2_x = self.parameter.sigma2_x
# Calculate posterior natural parameter (from sufficient statistics)
precision = self.prior.sigma2_A0 ** -1
mean_precision = self.prior.mu_A0 * precision
## TODO: Handle t = 0
## (for now assume sigma2_0 is very large, so precision is zero)
precision_t = (x[0:(T-1)] ** 2)/sigma2_x
mean_precision_t = (x[1:T] - lambduh * eta[1:T])*x[0:(T-1)]/sigma2_x
precision += np.sum(precision_t)
mean_precision += np.sum(mean_precision_t)
# Update A[index] by sampling from posterior
sampled_A = np.random.normal(loc = mean_precision / precision,
scale = precision ** -0.5)
# Restrict A <= 0.999
if sampled_A > 0.999:
logger.warning(
"Sampled AR coefficient A is %f, which is > 0.999",
sampled_A)
sampled_A = 0.999
# Restrict A >= -0.999
if sampled_A < -0.999:
logger.warning(
"Sampled AR coefficient A is %f, which is < -0.999",
sampled_A)
sampled_A = -0.999
self.parameter.A[index] = sampled_A
return
def _update_lambduh(self, z, theta):
""" Update the factor loading lambduh """
N, T = np.shape(self.parameter.x)
for index in range(0, N):
x = self.parameter.x[index]
a = self.parameter.A[index]
eta = theta[z[index]]
sigma2_x = self.parameter.sigma2_x
# Calculate posterior natural parameter (from sufficient statistics)
precision = self.prior.sigma2_lambduh0 ** -1
mean_precision = self.prior.mu_lambduh0 * precision
## TODO: Handle t = 0
## (for now assume sigma2_0 is very large, so precision is zero)
precision_t = (eta[1:T] ** 2)/sigma2_x
mean_precision_t = (x[1:T] - a * x[0:(T-1)])*eta[1:T]/sigma2_x
precision += np.sum(precision_t)
mean_precision += np.sum(mean_precision_t)
# Update lambduh[index] by sampling from posterior
self.parameter.lambduh[index] = np.random.normal(
loc = mean_precision / precision,
scale = precision ** -0.5)
return
def _update_sigma2_x(self, z, theta):
N, T = np.shape(self.parameter.x)
alpha_x = self.prior.alpha_x0
beta_x = self.prior.beta_x0
for index in range(0, N):
x = self.parameter.x[index]
a = self.parameter.A[index]
lambduh = self.parameter.lambduh[index]
eta = theta[z[index]]
## TODO: Handle t = 0
## (for now assume sigma2_0 is very large, so precision is zero)
# Calculate posterior natural parameter (from sufficient statistics)
alpha_x += (T-1)/2.0
beta_x += np.sum((x[1:T] - a*x[0:(T-1)] - lambduh*eta[1:T])**2)/2
# Update sigma2_x
self.parameter.sigma2_x = 1.0/np.random.gamma(shape = alpha_x,
scale = 1.0/beta_x,
size = 1)[0]
return
def _update_sigma2_y(self):
N, T = np.shape(self.parameter.x)
for index in range(0, N):
x = self.parameter.x[index]
y = self.y[index]
y_count = self.y_count[index]
is_obs = y_count > 0
# Calculate posterior natural parameter (from sufficient statistics)
alpha_y = self.prior.alpha_y0
beta_y = self.prior.beta_y0
alpha_y += np.sum(y_count[is_obs]) / 2.0
beta_y += np.sum((y[is_obs] - x[is_obs])**2 * y_count[is_obs]) / 2.0
# Sample sigma2_y
self.parameter.sigma2_y[index] = \
1.0 / np.random.gamma(shape = alpha_y,
scale = 1.0 / beta_y,
size = 1)
return
def update_local_parameters(self, k, z, theta, parameter_name = None):
raise RuntimeError("Do not use 'separate_likeparams' argument with timeseries_likelihood")
def _fix_pandas_index(index):
# Only keep the 'observation' and 'dimension' index
index = index.droplevel(
[name for name in index.names
if name not in ['observation', 'dimension'] ]
)
return index
<file_sep>/ep_clustering/gibbs.py
#!/usr/bin/env python
"""
Gibbs Sampler
"""
# Import Modules
import numpy as np
import pandas as pd
import logging
from ._utils import Map
from copy import deepcopy
from tqdm import tqdm
# Author Information __author__ = "<NAME>"
logger = logging.getLogger(name=__name__)
# Code Implementation
def random_init_z(N, K, z_prior = None):
""" Draw Z for N assignments, K cluster/groups """
if z_prior is None:
z_prior = np.ones(K)/K
z = np.random.multinomial(
n=1,
pvals=z_prior/np.sum(z_prior),
size=N,
).dot(np.arange(0, K))
return z
class GibbsSampler(object):
""" GibbsSampler
N observations, T dimensions
Args:
data (GibbsData): data
likelihood (Likelihood or string): likelihood object with functions for
K (int): number of latent clusters
approx_alg (ApproxAlgorithm or string)
**kwargs (kwargs): keyword arguments for options
alg_type (string): algorithm to use when sampling z
"naive" : Naive Gibbs (default)
"collapsed" : Collapsed Gibbs
"EP" : EP Gibbs
"subsampled" : Subsampled Collapsed Gibbs
"EP_subsampled" : EP Gibbs w/Subsampling
max_subsample_size (int): max subsample size (default: np.inf)
theta_prior (NaturalParameters): theta prior (default: std norm)
theta_prior_variance (double): prior variance (default: 100)
z_prior_type (string): whether to use a fixed prior over z ("fixed")
or a dirichlet prior ("dirichlet") (default "fixed")
z_prior (K ndarray): dirichlet prior for Pr(z) (default: 1/K)
track_ep (bool): whether to compute EP likelihood approximations
(default True for EP, False otherwise)
full_mcmc (bool): whether to sample all parameters (default True)
shuffle (bool): whether to shuffle scan order over z (default True)
Attributes:
num_obs (int): number of observations
num_dim (int): number of dimensions
likelihood(Likelihood): likelihood object
K (int): number of latent clusters
approx_alg (ApproxAlgorithm)
state (Map): state of sampler consists of:
z (N ndarray): latent cluster assignment
theta (K by T ndarray): cluster parameters
likelihood_parameters (Map): map of likelihood parameters
approx_parameters (Map): map of approx algorithm parameters
options (Map): algorithm options
Methods:
- init_state() -> randomly select initial state
- one_step() -> one step of GibbSampler
- sample_z() -> sample z
- sample_theta() -> sample theta condition on z
- eval_loglikelihood() -> return loglikelihood
- sample_likelihood_parameters() -> sample likelihood parameters
- get_state() -> return dictionary with current state
- set_state() -> set current state with a dictionary
"""
def __init__(self, data, likelihood, K, approx_alg, **kwargs):
self.num_obs = data.num_obs
self.num_dim = data.num_dim
self.K = K
self.likelihood = likelihood
self.approx_alg = approx_alg
self.options = self._process_options(**kwargs)
self._set_prior()
self.init_state(init_z = self.options.init_z)
return
@staticmethod
def _process_options(**kwargs):
# Default Options
options = {
"max_subsample_size": np.inf,
"theta_prior": None,
"theta_prior_variance": 1.0,
"z_prior": None,
"z_prior_type": "fixed",
"init_z": None,
"full_mcmc": True,
"shuffle": True,
"verbosity": logging.INFO,
"log_file": None,
}
# Parse Input
for key, value in kwargs.items():
if key in options.keys():
options[key] = value
else:
print("Ignoring unrecognized kwarg: {0}".format(key))
return Map(options)
def _set_prior(self):
# Set Default Priors
if self.options.z_prior is None:
self.options.z_prior = np.ones(self.K)/self.K
elif np.size(self.options.z_prior) == 1:
self.options.z_prior = np.ones(self.K) * self.options.z_prior
return
def init_state(self, init_z = None):
""" Initialize State """
self.state = Map()
if init_z is None:
self.state['z'] = \
random_init_z(self.num_obs, self.K, self.options.z_prior)
else:
self.state['z'] = np.copy(init_z)
self.state['theta'] = np.zeros((self.K, self.num_dim))
self.state['likelihood_parameter'] = self.likelihood.parameter
self.state['approx_parameters'] = self.approx_alg.parameters
self.approx_alg.init_approx(sampler=self)
return
def get_state(self):
""" Return a deepcopy of state """
state = Map(deepcopy(self.state))
return state
def save_state(self, filename, filetype=None):
""" Save state to file (see Map.save) """
self.state.save(filename, filetype)
return
def load_state(self, filename, filetype=None):
""" Load state from file (see Map.load) """
self.state.load(filename, filetype)
self.likelihood.parameter = self.state.likelihood_parameter
self.approx_alg.parameters = self.state.approx_parameters
return
def set_state(self, **kwargs):
""" Set state """
for key, value in kwargs.items():
if key in self.state.keys():
if isinstance(value, Map):
self.state[key].update(deepcopy(value))
else:
self.state[key] = deepcopy(value)
else:
logger.warning("Unrecognized key '%s' for state", key)
#self._check_state()
return
def one_step(self, full_mcmc=None):
self.sample_z()
self.sample_theta()
if full_mcmc is None:
full_mcmc = self.options.full_mcmc
if full_mcmc:
self.sample_likelihood_parameters()
return
def sample_theta(self):
""" Return a sample from posterior given z,y """
self.state.theta = self.approx_alg.sample_theta(self.state)
return self.state.theta
def _create_scan_order_gen(self):
""" Generator for the next observation """
while(True):
scan_order = range(0, self.num_obs)
if self.options.shuffle:
np.random.shuffle(list(scan_order))
for ii in scan_order:
yield ii
def sample_one_z(self, ii=None):
""" Update a single observation's cluster assignment z_i
Args:
ii (int): index of observation to sample cluster assignments
If not specified, will update in scan_order
Returns:
out (tuple): [ii, old_z_i, new_z_i]
"""
if ii is None:
if not hasattr(self, "_scan_order_gen"):
self._scan_order_gen = self._create_scan_order_gen()
ii = next(self._scan_order_gen)
logging.debug("Sampling z[%u]", ii)
# Calculate Log Posterior
if self.options.z_prior_type == "fixed":
logprior = np.log(self.options.z_prior)
elif self.options.z_prior_type == "dirichlet":
dir_post_alpha = np.bincount(self.state.z) + self.options.z_prior
logprior = np.log(dir_post_alpha) - np.log(np.sum(dir_post_alpha))
else:
raise ValueError("z_prior_type unrecognized {0}".format(
self.options.z_prior_type))
loglikelihood = \
self.approx_alg.loglikelihood_z(index=ii, state=self.state)
logposterior = logprior+loglikelihood
logposterior -= np.max(logposterior)
posterior = np.exp(logposterior)
posterior = posterior / np.sum(posterior)
# Sample new_z_i (int)
new_z_i = np.random.multinomial(1,posterior,1).dot(
np.arange(0, self.K))[0]
# Update approx + state
old_z_i = self.state.z[ii]
self.approx_alg.update_approx(index=ii,
old_z=old_z_i, new_z=new_z_i)
self.state.z[ii] = new_z_i
out = [ii, old_z_i, new_z_i]
return out
def sample_z(self):
""" Return a sample of z from the posterior
Also updates approx_alg based on new samples
Returns:
sampled_z (N ndarray): latent cluster assignments
"""
scan_order = range(0, self.num_obs)
if self.options.shuffle:
np.random.shuffle(list(scan_order))
for ii in scan_order:
self.sample_one_z(ii)
return self.state.z
def update_approx_alg(self, scan_order=None):
""" Updates approx_alg """
logger.info("Updating Approx Alg")
if scan_order is None:
scan_order = range(0, self.num_obs)
if self.options.shuffle:
np.random.shuffle(list(scan_order))
for ii in scan_order:
self.approx_alg.update_approx(
index=ii,
old_z=self.state.z[ii],
new_z=self.state.z[ii])
return
def reset_approx_alg(self):
""" Reset approx_alg """
logger.info("Resetting Approx Alg")
self.approx_alg.init_approx(self, init_likelihood=False)
return
def sample_likelihood_parameters(self, parameter_name = None):
likeparams = self.approx_alg.sample_likelihood_parameters(
self.state, parameter_name=parameter_name)
return likeparams
def eval_loglikelihood(self, kind="naive"):
""" Return the loglikelihood of the current state
Args:
kind (string):
'naive': loglikelihood(y | z, theta)
'collapsed': loglikelihood(y | z)
"""
# TODO: ADD 'alg_estimate': alg's estimate for loglikelihood(y | z)
loglikelihood = 0.0
if kind == "naive":
for ii in range(0, self.num_obs):
z_ii = self.state.z[ii]
likelihood = self.approx_alg.get_likelihood(z_ii)
loglikelihood += likelihood.loglikelihood(
index=ii, theta=self.state.theta[z_ii])
elif kind == "collapsed":
for cluster in range(0, self.K):
cluster_indices = np.where(self.state.z == cluster)[0]
likelihood = self.approx_alg.get_likelihood(cluster)
loglikelihood += likelihood.cluster_loglikelihood(
indices=cluster_indices,
theta_parameter=self.options.theta_prior)
else:
raise ValueError("Unrecognized kind={0}".format(kind))
return loglikelihood
# Code to execute if called from command-line
if __name__ == '__main__':
print("gibbs")
# EOF
<file_sep>/ep_clustering/kalman_filter/__init__.py
from ._kalman_filter import KalmanFilter
## Try Importing C++ Implementation
try:
from ep_clustering.kalman_filter.c_kalman_filter import CKalmanFilter
_cpp_available = True
except ImportError:
_cpp_available = False
CKalmanFilter = None
<file_sep>/ep_clustering/exp_family/__init__.py
from ._constructor import construct_exponential_family
from ._exponential_family import ExponentialFamily
from ._normal_mean import NormalFamily, DiagNormalFamily
from ._mean_variance import NormalInverseWishartFamily, NormalWishartFamily
#from ._von_mises_fisher import (
# VonMisesFisherFamily,
# VonMisesFisherProdGammaFamily,
# )
<file_sep>/ep_clustering/likelihoods/_constructor.py
import ep_clustering.likelihoods
def construct_likelihood(name, data, **kwargs):
""" Construct likelihood function by name
Args:
name (string): name of likelihood. One of
* "Gaussian"
* "MixDiagGaussian"
* "TimeSeries"
* "AR"
* "FixedVonMisesFisher"
data (GibbsData): data
**kwargs: arguments to pass to likelihood constructor
Returns:
likelihood (Likelihood): the appropriate likelihood subclass
"""
if(name == "Gaussian"):
return ep_clustering.likelihoods.GaussianLikelihood(data, **kwargs)
elif(name == "MixDiagGaussian"):
return ep_clustering.likelihoods.MixDiagGaussianLikelihood(data, **kwargs)
elif(name == "TimeSeries"):
return ep_clustering.likelihoods.TimeSeriesLikelihood(data, **kwargs)
elif(name == "TimeSeriesRegression"):
return ep_clustering.likelihoods.TimeSeriesRegressionLikelihood(data, **kwargs)
elif(name == "AR"):
return ep_clustering.likelihoods.ARLikelihood(data, **kwargs)
elif(name == "StudentT"):
return ep_clustering.likelihoods.StudentTLikelihood(data, **kwargs)
elif(name == "FixedVonMisesFisher"):
return ep_clustering.likelihoods.FixedVonMisesFisherLikelihood(data, **kwargs)
elif(name == "VonMisesFisher"):
return ep_clustering.likelihoods.VonMisesFisherLikelihood(data, **kwargs)
else:
raise ValueError("Unrecognized name {0}".format(name))
return
<file_sep>/ep_clustering/data/__init__.py
from ._gibbs_data import GibbsData
from ._mixture_data import (
create_mixture_component,
MixtureData,
MixtureDataGenerator,
)
from ._timeseries_data import (
TimeSeriesData,
TimeSeriesDataGenerator,
)
<file_sep>/README.md
# Approximate Collapsed Gibbs Sampling with Expectation Propagation
> This is Python 3 code for clustering latent variable models with approximate Gibbs sampling.
This repo contains example python code for the paper [Approximate Collapsed Gibbs Clustering with Expectation Propagation](https://arxiv.org/abs/1807.07621) and [Scalable Clustering of Correlated Time Series using Expectation Propagation](https://aicherc.github.io/pdf/aicherc2016scalable.pdf)
## Overview
* The `experiments` folder stores example python scripts for both correlated time series clustering and robust mixture modeling.
* The `output` folder stores output for the example python scripts.
* The `ep_clustering` folder stores the python module code for the various Gibbs sampling methods for a variety of models. See `ep_clustering/README.md` for additional details
## Installation
Install add the `ep_clustering/` folder to the python path.
Requirements:
`python 3+`, `matplotlib`, `ipython`, `joblib`, `numpy`, `scipy`, `pandas`, `scikit-learn`, `tqdm`, `seaborn`
## Usage Example
For *correlated time series clustering*:
* Walk through `experiments/synthetic_timeseries_clustering_example.py` for an overview of the API
* Run `experiments/synthetic_timeseries_compare_example.py` to compare naive, collapsed, and approx-EP Gibbs. (This script takes a while).
Below is example output comparing normalized mutual information (NMI) of each sampler's inferred clustering compared to the truth
NMI vs Iteration | NMI vs Time
:---------------:|:------------:
 | 
For *robust mixture modeling* with the Student's-$t$ distribution:
* Walk through `experiments/synthetic_mixture_clustering_example.py` for an overview of the API
* Run `experiments/synthetic_mixture_compare_example.py` to compare naive, blocked, and approx-EP Gibbs.
NMI vs Iteration | NMI vs Time
:---------------:|:------------:
 | 
## Release History / Changelog
* 0.1.0
* The first release (Dec 2019)
* Over-engineered code from the beginning of my PhD
## Meta
<NAME> - <EMAIL>
Distributed under the MIT license. See ``LICENSE`` for more information.
<file_sep>/ep_clustering/_utils.py
"""
Utilities functions
"""
import joblib
import os
import errno
import numpy as np
import pandas as pd
import logging
import types
from copy import deepcopy
logger = logging.getLogger(name=__name__)
# Handling Doc-string inheritance
def fix_docs(cls):
"""
This will copy missing documentation from parent classes.
Arguments:
cls (class): class to fix up.
Returns:
cls (class): the fixed class.
"""
for name, func in vars(cls).items():
if isinstance(func, types.FunctionType) and not func.__doc__:
for parent in cls.__bases__:
parfunc = getattr(parent, name, None)
if parfunc and getattr(parfunc, '__doc__', None):
func.__doc__ = parfunc.__doc__
break
elif isinstance(func, property) and not func.fget.__doc__:
for parent in cls.__bases__:
parprop = getattr(parent, name, None)
if parprop and getattr(parprop.fget, '__doc__', None):
newprop = property(fget=func.fget,
fset=func.fset,
fdel=func.fdel,
__doc__=parprop.fget.__doc__)
setattr(cls, name, newprop)
break
return cls
# Custom Dictionary Class with additional functionality
@fix_docs
class Map(dict):
"""
Customized dict class
"""
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
self.__dict__ = self
def copy(self):
return Map(super(Map, self).copy())
def deepcopy(self):
return Map(deepcopy(super(Map,self).copy()))
def save(self, filename, filetype = None, compress=0):
""" Save dictionary to file """
if filetype is None:
filetype = filename.split(".")[-1]
if filetype == "p":
joblib.dump(self.__dict__, filename, compress=compress)
else:
raise ValueError("Unrecognized filetype '{0}'".format(filetype))
return
def load(self, filename, filetype = None):
""" Load dictionary from file """
if filetype is None:
filetype = filename.split(".")[-1]
if filetype == "p":
obj = joblib.load(filename)
else:
raise ValueError("Unrecognized filetype '{0}'".format(filetype))
if isinstance(obj, dict):
for key, value in obj.items():
super(Map, self).__setitem__(key, value)
self.__dict__.update({key: value})
else:
raise ValueError(
"Unrecognized obj type '{0}'".format(type(obj)))
return self
def getFromNestDict(dataDict, mapList):
for k in mapList:
dataDict = dataDict[k]
return dataDict
def setFromNestDict(dataDict, mapList, value):
getFromNestDict(dataDict, mapList[:-1])[mapList[-1]] = value
return
def logsumexp(x, weights=None):
""" LogSumExp trick with optional weights
Args:
x (ndarray): input
weights (ndarray): weight
Returns:
out (double): log(sum(weights * exp(x)))
"""
if weights is None:
weights = np.ones_like(x)
a = np.max(x)
out = np.log(np.sum(weights * np.exp(x-a))) + a
return out
# This should really be in a dataset 'class'
def convert_df_to_matrix(df, value_name = "y",
row_index="observation",
col_index="dimension"):
""" Converts df to y matrix and y_counts matrix
Args:
df (pd.DataFrame): raw data with
index (row_index, col_index) and column value_name
value_name (string): name column in df for output mean and count
row_index (int): name of df index for rows for output
col_index (int): name of df index for columns of output
Returns:
mean_matrix (np.ndarray): row by column mean values (nan for missing)
count_matrix (np.ndarray): row by column count of values
"""
if value_name not in df.columns:
raise ValueError("value_name {0} not in df".format(value_name))
if row_index not in df.index.names:
raise ValueError("row_index {0} not in df index".format(row_index))
if col_index not in df.index.names:
raise ValueError("col_index {0} not in df index".format(col_index))
agg_df = df.groupby(level=[row_index, col_index])[value_name].aggregate(
mean=np.mean, count=np.size,
)
mean_matrix = agg_df['mean'].reset_index().pivot(
index = row_index,
columns = col_index,
values = 'mean').values
count_matrix = agg_df['count'].reset_index().pivot(
index = row_index,
columns = col_index,
values = 'count').values
count_matrix = np.nan_to_num(count_matrix)
return mean_matrix, count_matrix
def convert_matrix_to_df(y, observation_name = "y"):
""" Converts y matrix to df format
Args:
y (np.ndarray): observation by dimension matrix of values
"""
n_rows, n_cols = np.shape(y)
row_index = pd.Index(np.arange(n_rows), name = 'observation')
col_index = pd.Index(np.arange(n_cols), name = 'dimension')
out = pd.DataFrame(y, index=row_index, columns=col_index).stack()
out_df = pd.DataFrame(out)
out_df.columns = [observation_name]
return out_df
def make_path(path):
""" Helper function for making directories """
if path is not None:
if not os.path.isdir(path):
if os.path.exists(path):
raise ValueError(
"path {0} is any existing file location!".format(path)
)
else:
try:
os.makedirs(path)
except OSError as e:
logger.warning(e.args)
if e.errno != errno.EEXIST:
raise e
return
<file_sep>/ep_clustering/exp_family/_mean_variance.py
#!/usr/bin/env python
"""
Natural Parameters Helper for Mean + Variance Exp Families
"""
# Import Modules
import numpy as np
from ep_clustering._utils import fix_docs
from ._exponential_family import ExponentialFamily
from scipy.special import digamma, multigammaln
from scipy.stats import invwishart, wishart
# Author Information
__author__ = "<NAME>"
# Helper function for Inverse Wishart
def multidigamma(a, d):
""" Returns psi_d(a), where psi_d is the multivariate digamma of d
Calculation exploits the recursion:
psi_d(a) = \sum_{i=1}^d psi_1(a + (1-i)/2)
where psi_1 is the digamma function
"""
if np.isscalar(a):
return np.sum(digamma(a - 0.5*np.arange(d)),
axis=-1)
else:
return np.sum(digamma(a[...,None] - 0.5*np.arange(d)),
axis=-1)
@fix_docs
class NormalInverseWishartFamily(ExponentialFamily):
""" Normal Inverse Wishart Family Site Approximation Class
Natural Parameters:
lambduh (double):
mean_lambduh (num_dim ndarray):
nu (double):
psi_plus (num_dim by num_dim ndarray):
Helper Functions:
get_mean(): return expected mean
get_mean_precision(): return expected mean-precision
get_variance(): return expected variance
get_precision(): return expected precision
get_log_variance(): return expected log variance
"""
def __init__(self, num_dim, log_scaling_coef=0.0,
lambduh=0.0, mean_lambduh=None,
nu=0.0, psi_plus=None):
# Set Default mean_precision and precision
if mean_lambduh is None:
mean_lambduh = np.zeros(num_dim)
if psi_plus is None:
psi_plus = np.zeros((num_dim, num_dim))
# Check Dimensions
if np.size(mean_lambduh) != num_dim:
raise ValueError("mean_lambduh must be size num_dim")
if np.shape(psi_plus) != (num_dim, num_dim):
if np.size(psi_plus) == num_dim:
psi_plus = np.diag(psi_plus)
else:
raise ValueError("psi_plus must be size num_dim by num_dim")
super(NormalInverseWishartFamily, self).__init__(
num_dim=num_dim,
log_scaling_coef=log_scaling_coef,
lambduh=lambduh,
mean_lambduh=mean_lambduh,
nu=nu,
psi_plus=psi_plus,
)
return
def get_mean(self):
""" Return the expected mean """
if not self.is_valid_density():
return np.NaN
mean = self.natural_parameters['mean_lambduh'] / \
self.natural_parameters['lambduh']
return mean
def get_mean_precision(self):
""" Return the expected mean precision """
if not self.is_valid_density():
return np.NaN
mean_precision = self.natural_parameters['nu'] * np.linalg.solve(
self._get_psi(), self.get_mean())
return mean_precision
def get_variance(self):
""" Return the expected variance (returns NaN if variance DNE)"""
if not self.is_valid_density():
return np.NaN
nu = self.natural_parameters['nu']
if nu - self.num_dim - 1 <= 0:
variance = np.NaN
else:
variance = self._get_psi() / (nu - self.num_dim - 1)
return variance
def get_precision(self):
""" Return the expected precision """
if not self.is_valid_density():
return np.NaN
precision = self.natural_parameters['nu'] * \
np.linalg.inv(self._get_psi())
return precision
def get_log_variance(self):
""" Return the expected log det of variance """
if not self.is_valid_density():
return np.NaN
log_det_psi = np.linalg.slogdet(self._get_psi())[1]
log_det_var = log_det_psi - self.num_dim * np.log(2) - \
multidigamma(a=self.natural_parameters['nu']/2.0, p=self.num_dim)
return log_det_var
def _get_psi(self):
psi = self.natural_parameters['psi_plus'] - \
np.outer(self.natural_parameters['mean_lambduh'],
self.natural_parameters['mean_lambduh']) / \
self.natural_parameters['lambduh']
return psi
def is_valid_density(self):
if self.natural_parameters['lambduh'] < 1e-12:
return False
if self.natural_parameters['nu'] < self.num_dim - 1 + 1e-12:
return False
eigvals = np.linalg.eigvals(self._get_psi())
if np.any(eigvals < 1e-12):
return False
return True
def sample(self):
self._check_is_valid_density()
variance = invwishart(df=self.natural_parameters['nu'],
scale=self._get_psi()).rvs()
mean = np.random.multivariate_normal(mean=self.get_mean(),
cov=variance/self.natural_parameters['lambduh'])
return dict(mean=mean, variance=variance)
@fix_docs
class NormalWishartFamily(ExponentialFamily):
""" Normal Wishart Family Site Approximation Class
Canonical Parameters:
mu (num_dim ndarray):
psi (num_dim by num_dim ndarray):
kappa (double): pseudo count on mu observations
nu (double): pseudo count on psi observations
Natural Parameters:
kappa (double): kappa
nu_minus (double): nu - num_dim
eta (num_dim ndarray): kappa * mu
zeta (num_dim by num_dim ndarray): psi + kappa * mu * mu.T
Helper Functions:
get_mean(): return expected mean
get_mean_precision(): return expected mean-precision
get_variance(): return expected variance
get_precision(): return expected precision
get_log_variance(): return expected log variance
"""
def __init__(self, num_dim, log_scaling_coef=0.0,
kappa=0.0, nu_minus=0.0, eta=None, zeta=None):
# Set Default mean_precision and precision
if eta is None:
eta = np.zeros(num_dim)
if zeta is None:
zeta = np.zeros((num_dim, num_dim))
# Check Dimensions
if np.size(eta) != num_dim:
raise ValueError("mean_lambduh must be size num_dim")
if np.shape(zeta) != (num_dim, num_dim):
if np.size(zeta) == num_dim:
zeta = np.diag(zeta)
else:
raise ValueError("zeta must be size num_dim by num_dim")
super(NormalWishartFamily, self).__init__(
num_dim=num_dim,
log_scaling_coef=log_scaling_coef,
kappa=kappa,
nu_minus=nu_minus,
eta=eta,
zeta=zeta,
)
return
@staticmethod
def from_mu_kappa_nu_psi(mu, kappa, nu, psi):
""" Helper function for constructing from canonical parameters """
num_dim = np.size(mu)
if np.shape(psi) != (num_dim, num_dim):
raise ValueError("psi must be size num_dim by num_dim")
eta = kappa * mu
zeta = psi + kappa * np.outer(mu, mu)
return NormalWishartFamily(
num_dim=num_dim,
kappa=kappa,
nu_minus=nu - num_dim,
eta=eta,
zeta=zeta,
)
def get_mean(self):
""" Return the expected mean """
if not self.is_valid_density():
return np.NaN
mean = self.natural_parameters['eta'] / \
self.natural_parameters['kappa']
return mean
def get_mean_precision(self):
""" Return the expected mean precision """
if not self.is_valid_density():
return np.NaN
mean_precision = self._get_nu() * np.linalg.solve(
self._get_psi(), self.get_mean())
return mean_precision
def get_variance(self):
""" Return the expected variance (returns NaN if variance DNE)"""
if not self.is_valid_density():
return np.NaN
nu = self._get_nu()
if nu - self.num_dim - 1 <= 0:
variance = np.NaN
else:
variance = self._get_psi() / (nu - self.num_dim - 1)
return variance
def get_precision(self):
""" Return the expected precision """
if not self.is_valid_density():
return np.NaN
precision = self._get_nu() * \
np.linalg.inv(self._get_psi())
return precision
def get_log_precision(self):
""" Return the expected log det of precision """
if not self.is_valid_density():
return np.NaN
log_det_psi = np.linalg.slogdet(self._get_psi())[1]
log_det_precision = -log_det_psi + self.num_dim * np.log(2) + \
multidigamma(a=self._get_nu()/2.0, p=self.num_dim)
return log_det_precision
def get_log_variance(self):
""" Return the expected log det of variance """
if not self.is_valid_density():
return np.NaN
log_det_var = -1.0 * self.get_log_variance()
return log_det_var
def get_kappa_nu_mu_psi(self):
""" Return Canonical parametrization """
kappa = self.natural_parameters['kappa']
mu = self.natural_parameters['eta'] / \
self.natural_parameters['kappa']
nu = self._get_nu()
psi = self._get_psi()
return [kappa, nu, mu, psi]
def _get_psi(self):
psi = self.natural_parameters['zeta'] - \
np.outer(self.natural_parameters['eta'],
self.natural_parameters['eta']) / \
self.natural_parameters['kappa']
return psi
def _get_nu(self):
return self.natural_parameters['nu_minus'] + self.num_dim
def is_valid_density(self):
if self.natural_parameters['kappa'] < 1e-12:
return False
if self.natural_parameters['nu_minus'] < 1e-12:
return False
eigvals = np.linalg.eigvals(self._get_psi())
if np.any(eigvals < 1e-12):
return False
return True
def logpartition(self):
self._check_is_valid_density()
nu = self._get_nu()
psi = self._get_psi()
kappa = self.natural_parameters['kappa']
log_partition = 0.5 * self.num_dim * np.log(2*np.pi)
log_partition += 0.5 * self.num_dim * nu * np.log(2)
log_partition -= 0.5 * nu * np.linalg.slogdet(psi)[1]
log_partition -= 0.5 * self.num_dim * np.log(kappa)
log_partition += multigammaln(nu/2.0, self.num_dim)
return log_partition
def sample(self):
self._check_is_valid_density()
precision = wishart(df=self._get_nu(),
scale=np.linalg.inv(self._get_psi())).rvs()
L = np.linalg.cholesky(precision) * \
np.sqrt(self.natural_parameters['kappa'])
mean = self.get_mean() + \
np.linalg.solve(L.T, np.random.normal(size=self.num_dim))
return dict(mean=mean, precision=precision)
<file_sep>/ep_clustering/likelihoods/_likelihoods.py
#!/usr/bin/env python
"""
Likelihood Objects for Gibbs Sampler
"""
# Import Modules
import logging
import ep_clustering._utils as _utils
logger = logging.getLogger(name=__name__)
# Author Information
__author__ = "<NAME>"
# Abstract Class for Likelihood
class Likelihood(object):
""" Likelihood function for GibbsSampler
Likelihood function of theta
Args:
data (GibbsData): the data
prior (ExponentialFamily): the prior for theta
sample_prior (bool): whether to initalize parameters from prior
**kwargs (kwargs): additional likelihood arguments
likelihood_prior_kwargs,
default_likelihood_parameters,
Attributes:
theta_prior (ExponentialFamily): prior for theta
parameter (Map): likelihood parameters
prior (Map): likelihood prior parameters
name (string): name of likelihood function
Methods:
- loglikelihood(index, theta): return loglikelihood
- init_parameters(sample_prior, **kwargs): initialize parameters
- collapsed(index, subset_indices, theta_parameter):
return conditional loglikelihood
- ep_loglikelihood(index, theta): return ep approx to loglikelihood
- moment(index, theta_parameter): return moment for EP
- sample(indices, prior_parameter): return sample from posterior
- predict(indices, prior_parameter, num_samples, **kwargs): returns
posterior predictions for observations
- update_parameters(z, theta): update parameters via Gibbs sampling
"""
name = "Likelihood"
def __init__(self, data, theta_prior=None, **kwargs):
self.data = data
if theta_prior is None:
theta_prior = self._get_default_prior()
self.theta_prior = theta_prior
kwargs = self._set_parameters_prior(**kwargs)
kwargs = self._set_default_parameters(**kwargs)
self.init_parameters(sample_prior=kwargs.pop("sample_prior",False))
self._process_kwargs(**kwargs)
return
def deepcopy(self):
""" Return a copy """
other = type(self)(data = self.data, theta_prior=self.theta_prior)
other.parameter = self.parameter.deepcopy()
other.prior = self.prior.deepcopy()
return other
def _get_default_prior(self):
""" Returns default theta prior ExponentialFamily object """
raise NotImplementedError()
def _get_default_parameters(self):
"""Returns default parameters dict"""
raise NotImplementedError()
def _get_default_parameters_prior(self):
"""Returns default parameters prior dict"""
raise NotImplementedError()
def _set_parameters_prior(self, **kwargs):
""" Set prior of likelihood parameters """
prior = self._get_default_parameters_prior()
for key in list(kwargs.keys()):
if key in prior.keys():
prior[key] = kwargs.pop(key) + 0.0
self.prior = _utils.Map(prior)
return kwargs
def _set_default_parameters(self, **kwargs):
""" Set default_parameter """
default_parameter = self._get_default_parameters()
for key in list(kwargs.keys()):
if key in default_parameter.keys():
default_parameter[key] = kwargs.pop(key) + 0.0
self._default_parameter = _utils.Map(default_parameter)
return kwargs
def _process_kwargs(self, **kwargs):
""" Process remaining kwargs """
for key in kwargs.keys():
logger.info("Ignoring unrecognized kwarg: {0}".format(key))
return
def _sample_from_prior(self):
""" Sample initial likelihood parameter setting from prior """
raise NotImplementedError()
def init_parameters(self, sample_prior=False, **kwargs):
""" Initialize the likelihood parameters
Args:
sample_prior (bool): whether to sample from prior or use defaults
**kwargs:
likelihood parameter initialization
"""
if sample_prior:
# Sample parameter from prior
parameter = self._sample_from_prior()
else:
# Use default parameter
parameter = self._default_parameter
# Override any specified parameters
for key, value in kwargs.items():
if key in parameter.keys():
parameter[key] = value + 0.0
else:
logging.info("Ignoring unrecognized kwarg: {0}".format(key))
# Set parameter
self.parameter = _utils.Map(parameter)
return
def loglikelihood(self, index, theta):
""" Calculate the loglikelihood for a single series.
Calculates the loglikelihood for y[index] for cluster parameter theta
Args:
index (int): index of series
theta (ndarray): cluster parameter
Returns:
loglikelihood (double): loglikelihood of y[index] for theta
"""
raise NotImplementedError()
def cluster_loglikelihood(self, indices, theta_parameter):
""" Calculate the collapsed loglikelihood for an entire cluster. """
raise NotImplementedError()
def collapsed(self, index, subset_indices, theta_parameter):
""" Calculate the collapsed loglikelihood for a series
Calculates the collapsed loglikelihood for y[index] for a cluster
given the other series y[subset_indices] and prior theta_parameter
Args:
index (int): index of series
subset_indices (list): indices of other series assigned to cluster
theta_parameter (ExponentialFamily): cavity prior for cluster parameter
Returns:
loglikelihood (double): collapsed loglikelihood of y[index]
"""
raise NotImplementedError()
def ep_loglikelihood(self, index, theta_parameter):
""" Calculate the EP approximation to the loglikelihood
Calculate the log of the integral of the unnormalized
tilted distribution (i.e. the log_scaling_coef)
"""
approx_loglikelihood = self.moment(
index=index,
theta_parameter=theta_parameter,
).log_scaling_coef
return approx_loglikelihood
def moment(self, index, theta_parameter):
""" Calculate the ExponentialFamily approx to the tilted distribution.
Calculates the approximate moments and log_scaling_coef of
the tilted distribution for theta_parameter's exponential family
Args:
index (int): index of series
theta_parameter (ExponentialFamily):
cavity distribution
Returns:
unnormalized_post_approx (ExponetialFamily):
"""
raise NotImplementedError()
def sample(self, indices, prior_parameter):
""" Sample cluster parameter from posterior
Samples cluster parameter theta conditioning on
series in cluster y[indices] and prior
Args:
indices (list): indices of series in cluster
prior_parameter (ExponentialFamily): prior for cluster parameter
Returns:
theta (T ndarray): random sample of cluster parameter from posterior
"""
raise NotImplementedError()
def predict(self, new_data, prior_parameter, num_samples, **kwargs):
""" Sample observations from predictive posterior
Args:
new_data (GibbsData): new data to predict
prior_parameter (ExponentialFamily): prior for cluster parameter
num_samples (int): number of samples
**kwargs: additional arguments
Returns:
sampled_y (np.ndarray): num_samples by num_rows(new_data)
"""
raise NotImplementedError()
return
def update_parameters(self, z, theta, parameter_name = None):
""" Update likelihood based on cluster assignments and parameters
Args:
z (num_obs ndarray):
cluster assignments
theta (K by num_dim ndarray):
cluster parameters
parameter_name(string, optional):
parameter to update, default updates all parameters
Returns:
None: updates likelihood.parameter
"""
raise NotImplementedError()
return
def update_local_parameters(self, k, z, theta, parameter_name = None):
""" Update likelihood parameters based only on cluster k
Args:
k (int): cluster
z (num_obs ndarray):
cluster assignments
theta (K by num_dim ndarray):
cluster parameters
parameter_name(string, optional):
parameter to update, default updates all parameters
Returns:
None: updates likelihood.parameter
"""
raise NotImplementedError()
return
#EOF
<file_sep>/experiments/synthetic_mixture_clustering_example.py
# Script to get familiar with the code-base API
import matplotlib as mpl
mpl.use('Agg')
import os
import numpy as np
import pandas as pd
import joblib
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import ep_clustering as ep
from tqdm import tqdm # Progress Bar
# Make Paths to output/figures
path_to_fig = "output/synth_mixture_examples/figures"
path_to_data = "output/synth_mixture_examples/data"
if not os.path.isdir(path_to_fig):
os.makedirs(path_to_fig)
if not os.path.isdir(path_to_data):
os.makedirs(path_to_data)
######################################################
# Generate Synthetic Data (Robust Clustering)
######################################################
np.random.seed(1234)
mean_scale=3
df=5
df_scale=0.001
data_param = dict(
num_dim=2, # Number of dimensions
num_obs=100, # Number of observations
K=3, # Number of clusters
component_type='student_t', # e.g. 'diag_gaussian', 'mix_gaussian', etc
component_prior={'mean_sd': np.ones(2)* mean_scale,
'df_alpha': df/df_scale, 'df_beta': 1.0/df_scale},
)
data_gen = ep.data.MixtureDataGenerator(**data_param)
data = data_gen.generate_data()
# 'data' is a dict containing observations, cluster labels, latent variables and parameters
print(data['matrix']) # Data as a matrix
print(data['z']) # True Cluster Assignments
print(data['parameters'].keys()) # Dictionary of other parameters
print(data['parameters']['cluster_parameters']) # List of dicts of cluster parameters
## Plot and Save Data
def plot_2d_data(data, z=None, x0=0, x1=1, ax=None):
cp = sns.color_palette("husl", n_colors=data.K)
if ax is None:
fig = plt.figure()
ax = plt.subplot(1,1,1)
if z is None:
z = data.z
for k in range(data.K):
ind = (z == k)
ax.plot(data.matrix[ind,x0], data.matrix[ind,x1], "o",
alpha=0.5, color=cp[k], label="z={0}".format(k))
ax.legend()
ax.set_title("X{1} vs X{0}".format(x0, x1))
return ax
# Plot Data
fig, ax = plt.subplots(1,1)
plot_2d_data(data, ax=ax)
fig.savefig(os.path.join(path_to_fig, "true_data.png"))
# Save Data
joblib.dump(data, filename=os.path.join(path_to_data, "data.p"))
######################################################
# Define Model to Fit
######################################################
## Likelihood
likelihood = ep.construct_likelihood(name="StudentT", data=data)
# See likelihood? for more details (or print(likelihood.__doc__))
## Approximation Algorithm
alg_name = 'EP' # 'naive' or 'collapsed' are the other options
approx_alg = ep.construct_approx_algorithm(
name=alg_name,
exp_family=ep.exp_family.NormalWishartFamily,
damping_factor=0.0, #0.0001,
separate_likeparams=True,
)
# See approx_alg? for more details (or print(approx_alg.__doc__))
## Number of Clusters to Infer
Kinfer = 3
## Setup Approx Gibbs Sampler
sampler = ep.GibbsSampler(
data=data,
likelihood=likelihood,
K=Kinfer,
approx_alg=approx_alg,
)
# See ep.GibbsSampler? for more details on how to set prior and other algorithm options
# See sampler? for more details (or print(sampler.__doc__))
print(sampler.state) # Initial state of latent vars 'z' and parameters
print(sampler.options) # Gibbs sampling options (including prior)
# Randomly initialize the inital_state
sampler.init_state()
# sampler.init_state(z=data['z']) # init from ground truth labels
# Sample z from the posterior (based on alg_name)
print(sampler.sample_z())
# Only sample z[5] from the posterior
print(sampler.sample_one_z(5))
# Note, the EP approx parameters are updated automatically whenever z is sampled
# Sample Theta
print(sampler.sample_theta())
# Sample Other Likelihood Parameters
sampler.sample_likelihood_parameters()
# Helper Function to Sample Z, Theta, and Likelihood Parameters using Blocked Gibbs
sampler.one_step(full_mcmc=True)
# If full_mcmc is False, then the likelihood_parameters will not be sampled
# Manually update all EP Approximation Parameters (for Full, exact EP)
sampler.update_approx_alg()
# Evaluate log Pr(y | z, theta, likelihood parameters) of data
print(sampler.eval_loglikelihood(kind='naive'))
# Evaluate log Pr(y | z, likelihood parameters) of data
# print(sampler.eval_loglikelihood(kind='collapsed')) # Not conjugate so does not exist in closed form
######################################################
# Define Evaluation Metrics
######################################################
## Metrics to track
# -Loglikelihood
# -NVI (normalized variation of information) a divergence metric between clusters
# -MSE of parameters likelihood parameters and latent series x
my_metric_functions = [
ep.evaluator.metric_function_from_sampler("eval_loglikelihood"),
ep.evaluator.metric_function_from_state("z", data.z, "nvi"),
ep.evaluator.metric_function_from_state("z", data.z, "nmi"),
ep.evaluator.metric_function_from_state("z", data.z, "precision"),
ep.evaluator.metric_function_from_state("z", data.z, "recall"),
]
## Samples to track
# Keep track of theta and cluster assignments z
my_sample_functions = {
'mean0': lambda sampler: sampler.state.theta[0]['mean'],
'mean1': lambda sampler: sampler.state.theta[1]['mean'],
'mean2': lambda sampler: sampler.state.theta[2]['mean'],
'prec0': lambda sampler: sampler.state.theta[0]['precision'],
'prec1': lambda sampler: sampler.state.theta[1]['precision'],
'prec2': lambda sampler: sampler.state.theta[2]['precision'],
'z': lambda sampler: sampler.state.z,
}
## Construct Sampler Wrapper
my_evaluator = ep.GibbsSamplerEvaluater(
sampler=sampler,
metric_functions=my_metric_functions,
sample_functions=my_sample_functions,
sampler_name="example",
)
######################################################
# Run Sampler with Online Evaluation
######################################################
from tqdm import tqdm # Progress Bar
for _ in tqdm(range(10)):
my_evaluator.evaluate_sampler_step()
metric_df = my_evaluator.get_metrics()
sample_df = my_evaluator.get_samples()
print(metric_df) # Metrics for first iterations are pd.DataFrame
print(sample_df) # Samples for first iterations are pd.DataFrame
# For example to look at just the loglikelihood
print(metric_df.query('metric == "eval_loglikelihood"'))
# Metric Plotter
def plot_metrics(metric_df):
metric_df['variable'] = metric_df['variable'].apply(
lambda x: x.strip('likelihood_parameter'))
metric_df['metric_var'] = metric_df['metric'] + "_" + metric_df['variable']
g = sns.FacetGrid(
data=metric_df, col="metric_var", col_wrap=4, sharey=False,
)
g = g.map(plt.plot, "iteration", "value")
return g
# Run for 100 EPOCHs
num_epochs = 100 # number of iterations (passes over the data set)
for _ in tqdm(range(num_epochs)):
my_evaluator.evaluate_sampler_step()
# Checkpoint Metrics + Samples every 10 Epochs
if _ % 10 == 0:
metric_df = my_evaluator.get_metrics()
sample_df = my_evaluator.get_samples()
# Plot Metrics over time
plt.close('all')
plot_metrics(metric_df).savefig(os.path.join(path_to_fig, 'metrics.png'))
# Save Metrics + Samples
metric_df.to_pickle(os.path.join(path_to_data, "metrics.p"))
sample_df.to_pickle(os.path.join(path_to_data, "samples.p"))
## Reload Metrics
#metric_df = pd.read_pickle(os.path.join(path_to_data, "metrics.p"))
#sample_df = pd.read_pickle(os.path.join(path_to_data, "samples.p"))
<file_sep>/ep_clustering/kalman_filter/_kalman_filter.py
#!/usr/bin/env python
"""
Likelihood Objects for Gibbs Sampler
"""
# Import Modules
import numpy as np
# Author Information
__author__ = "<NAME>"
class KalmanFilter(object):
""" Kalman Filter Object
N - dimension of state vector
T - number of time points
Args:
y (N by T ndarray): observations
y_count (N by T ndarray): counts of observations (0 indicates missing)
A (N ndarray): AR Coefficients (diagonal matrix)
lambduh (N ndarray): factor loadings
sigma2_x (double): variance of latent process
sigma2_y (N ndarray): variance of observation errors (diagonal matrix)
eta_mean (T ndarray): latent cluster mean
eta_var (T ndarray): latent cluster variance
mu_0 (N ndarray): prior mean for x at time -1
V_0 (N by N ndarray): prior variance for x at time -1
Attributes:
y_T (T by N ndarray): observations
y_count_T (T by N ndarray): counts of observations (0 indicates missing)
A (N ndarray): AR Coefficients (diagonal matrix)
lambduh (N ndarray): factor loadings
sigma2_x (double): variance of latent process
sigma2_y (N ndarray): variance of observation errors (diagonal matrix)
eta_mean (T ndarray): latent cluster mean eta_var (T ndarray): latent cluster variance
Methods:
- kalman_filter_step
- filter_pass
- smoothing_pass
- calculate_log_likelihood
- calculate_cond_log_likelihood
- sample_x
- sample_eta
"""
def __init__(self, y, A, lambduh, sigma2_x, sigma2_y, eta_mean, eta_var,
mu_0=None, V_0=None, y_count=None):
if np.isscalar(A):
A = np.array([A])
if np.isscalar(lambduh):
lambduh = np.array([lambduh])
if np.isscalar(sigma2_y):
sigma2_y = np.array([sigma2_y])
self.y_T = y.T
self.T, self.N = np.shape(self.y_T)
self.A = A
self.lambduh = lambduh
self.sigma2_x = sigma2_x
self.sigma2_y = sigma2_y
self.eta_mean = eta_mean
self.eta_var = eta_var
if mu_0 is None:
self.mu_0 = np.zeros(self.N)
if V_0 is None:
self.V_0 = np.ones(self.N)
self.V_0 *= self.sigma2_x/(1.0-self.A**2)
self.V_0 = np.diag(self.V_0)
if y_count is None:
y_count = 1.0 - np.isnan(y)
y_count[np.isnan(y)] = 0
self.y_count_T = y_count.T
# Scalar Division is much more efficient that np.linalg.solve
if self.N == 1:
self.linalg_solve = lambda a, x: x/a
else:
self.linalg_solve = np.linalg.solve
self._check_attrs()
return
def _check_attrs(self):
""" Check that attrs are valid """
if np.size(self.A) != self.N:
raise ValueError("A must be a N ndarray")
if np.size(self.lambduh) != self.N:
raise ValueError("lambduh must be a N ndarray")
if np.size(self.sigma2_y) != self.N:
raise ValueError("sigma2_y must be a N ndarray")
if np.any(self.sigma2_y < 0):
raise ValueError("sigma2_y must be nonnegative")
if self.sigma2_x < 0:
raise ValueError("sigma2_x must be nonnegative")
if np.size(self.eta_mean) != self.T:
raise ValueError("eta_mean must be a T ndarray")
if np.size(self.eta_var) != self.T:
raise ValueError("eta_var must be a T ndarray")
if np.any(self.eta_var < 0):
raise ValueError("eta_var must be nonnegative")
if np.size(self.mu_0) != self.N:
raise ValueError("mu_0 must be a N ndarray")
if np.shape(self.V_0) != (self.N, self.N):
raise ValueError("V_0 must be a N by N ndarray")
if np.any(np.linalg.eigvals(self.V_0) < 0):
raise ValueError("V_0 must be nonnegative")
if np.shape(self.y_count_T) != np.shape(self.y_T):
raise ValueError("y_count and y do not have the same shape")
if np.any(self.y_count_T < 0):
raise ValueError("y_count must be nonnegative")
return
def kalman_filter_step(self, t, mu_prev, V_prev):
""" Apply Kalman Filter to new observation at time t
Args:
t (int): time index t
mu_prev (N ndarray): filtered mean at time t-1
V_prev (N by N ndarray): filtered variance at time t-1
Returns:
out (dict): dictionary containing
- mu_filter (N ndarray) - filtered mean at time t
- V_filter (N by N ndarray) - filtered variance at time t
- S_t (N by N ndarray) - predictive variance for observation y_t
- mu_predict (N ndarray) - predictive mean for time t
- V_predict (N by N ndarray) - predictive variance for time t
"""
# Predict
y_t = self.y_T[t]
y_count_t = self.y_count_T[t]
mu_predict = self.A * mu_prev + self.lambduh * self.eta_mean[t]
Q = (np.eye(self.N)*self.sigma2_x +
np.outer(self.lambduh, self.lambduh)*self.eta_var[t])
V_predict = _mult_diag_matrix(self.A,
_mult_diag_matrix(self.A, V_prev, on_right=True)) + Q
is_obs = y_count_t > 0
V_yx = V_predict[is_obs,:]
V_yy = V_yx[:,is_obs]
if np.any(is_obs):
# Observation Variance
S_t = V_yy + np.diag(self.sigma2_y[is_obs] / y_count_t[is_obs])
if np.any(np.isnan(S_t)):
raise ValueError("DEBUG")
# Gain Matrix
K_t = self.linalg_solve(S_t, V_yx).T
# Filter
mu_filter = mu_predict + K_t.dot(y_t[is_obs] - mu_predict[is_obs])
V_filter = V_predict - K_t.dot(V_yx)
else:
# No observations -> No filter update step
S_t = np.array([])
mu_filter = mu_predict
V_filter = V_predict
out = {
'mu_predict': mu_predict,
'V_predict': V_predict,
'S_t': S_t,
'mu_filter': mu_filter,
'V_filter': V_filter, }
return out
def filter_pass(self):
""" One pass of the Kalman Filter
Returns:
out (list of T dicts): containing
- mu_filter (N ndarray) - filtered mean at time t
- V_filter (N by N ndarray) - filtered variance at time t
- S_t (N by N ndarray) - predictive variance for observation y_t
- mu_predict (N ndarray) - predictive mean for time t
- V_predict (N by N ndarray) - predictive variance for time t
"""
mu = self.mu_0
V = self.V_0
out = [None]*self.T
for t in range(0, self.T):
out[t] = self.kalman_filter_step(t, mu, V)
mu, V = out[t]['mu_filter'], out[t]['V_filter']
return out
def calculate_log_likelihood(self):
""" Calculate the log-likelihood of y
Returns:
log_like (double): log-likelihood of observations
"""
log_like = 0.0
mu = self.mu_0
V = self.V_0
for t in range(0, self.T):
kalman_result = self.kalman_filter_step(t, mu, V)
y_t = self.y_T[t]
y_count_t = self.y_count_T[t]
is_obs = y_count_t > 0
log_like += _gaussian_log_likelihood(y_t[is_obs],
mean=kalman_result['mu_predict'][is_obs],
variance=kalman_result['S_t'])
mu, V = kalman_result['mu_filter'], kalman_result['V_filter']
return np.asscalar(log_like)
def calculate_cond_log_likelihood(self, i):
""" Calculate the conditional log-likelihood of y_i given other y
Args:
i (int): index of stream
Returns:
cond_log_like (double): conditional log-likelihood of stream i
"""
cond_log_like = 0.0
mu = self.mu_0
V = self.V_0
for t in range(0, self.T):
kalman_result = self.kalman_filter_step(t, mu, V)
y_t = self.y_T[t]
y_count_t = self.y_count_T[t]
is_obs = y_count_t > 0
if is_obs[i]:
cond_log_like += _gaussian_cond_log_likelihood(
x=y_t[is_obs],
mean=kalman_result['mu_predict'][is_obs],
variance=kalman_result['S_t'],
i=(np.cumsum(is_obs)[i] - 1),
)
mu, V = kalman_result['mu_filter'], kalman_result['V_filter']
return cond_log_like
def smoothing_pass(self, filter_out=None, calc_prev=False):
""" One pass of the Kalman Smoothing
Args:
filter_out (list of dicts): output of filter_pass (optional)
Will call `filter_pass` if not supplied
calc_prev (bool): calculate smoothed posterior for t=-1
Returns:
out (list of T dicts): containing
- mu_smoothed (N ndarray) - filtered mean at time t
- V_smoothed (N by N ndarray) - filtered variance at time t
- J_t (N by N ndarray) - backward filter matrix
If calc_prev is True, then smoothing_pass() will also return
the dict prev (for t=-1)
"""
out = [None]*self.T
# Forward Kalman Filter
if filter_out is None:
filter_out = self.filter_pass()
# Backward Smoothing Pass
mu_smoothed = filter_out[self.T-1]['mu_filter']
V_smoothed = filter_out[self.T-1]['V_filter']
out[self.T-1] = {'mu_smoothed': mu_smoothed,
'V_smoothed': V_smoothed,
'J_t': None}
for t in reversed(range(0, self.T-1)):
mu_filter = filter_out[t]['mu_filter']
V_filter = filter_out[t]['V_filter']
mu_predict_next = filter_out[t+1]['mu_predict']
V_predict_next = filter_out[t+1]['V_predict']
J_t = self.linalg_solve(V_predict_next,
_mult_diag_matrix(self.A, V_filter)).T
mu_smoothed = mu_filter + J_t.dot(mu_smoothed-mu_predict_next)
V_smoothed = (V_filter +
J_t.dot(V_smoothed - V_predict_next).dot(J_t.T))
out[t] = {'mu_smoothed': mu_smoothed,
'V_smoothed': V_smoothed,
'J_t': J_t}
if not calc_prev:
return out
else:
# Handle t = -1
mu_filter = self.mu_0
V_filter = self.V_0
mu_predict_next = filter_out[0]['mu_predict']
V_predict_next = filter_out[0]['V_predict']
J_t = self.linalg_solve(V_predict_next,
_mult_diag_matrix(self.A, V_filter)).T
mu_smoothed = mu_filter + J_t.dot(mu_smoothed-mu_predict_next)
V_smoothed = (V_filter +
J_t.dot(V_smoothed - V_predict_next).dot(J_t.T))
prev = {'mu_smoothed': mu_smoothed,
'V_smoothed': V_smoothed,
'J_t': J_t}
return out, prev
def _backward_pass(self, filter_out = None, smoothing_out = None):
""" Helper function for moments of G(X_t) ~ Pr(Y_{t:T} | X_t)
G(X_t) ~ Pr(X_t | Y_{1:T}) / Pr(X_t | Y_{1:t-1})
Returns:
out (list of T dicts): containing
- mu_beta (N ndarray) - backward filtered mean at time t
- V_beta (N by N ndarray) - backward filtered variance at time t
"""
out = [None]*self.T
# Perform Filter and Smoother if necessary
if filter_out is None:
filter_out = self.filter_pass()
if smoothing_out is None:
smoothing_out = self.smoothing_pass(filter_out = filter_out)
for t in range(0, self.T):
mu_predict = filter_out[t]['mu_predict']
V_predict = filter_out[t]['V_predict']
mu_smoothed = smoothing_out[t]['mu_smoothed']
V_smoothed = smoothing_out[t]['V_smoothed']
if np.allclose(V_smoothed, V_predict):
# If Pr(Y_{s:T} | X_s) = 1, e.g. no observations in s:T
# Then set V_beta = Inf
V_beta = np.diag(np.inf * np.ones(self.N))
mu_beta = np.zeros(self.N)
else:
V_beta = V_smoothed.dot(
np.eye(self.N) +
self.linalg_solve(V_predict - V_smoothed, V_smoothed)
)
mu_beta = V_beta.dot(
self.linalg_solve(V_smoothed, mu_smoothed) -
self.linalg_solve(V_predict, mu_predict)
)
out[t] = {
"mu_beta": mu_beta,
"V_beta": V_beta,
}
return out
def moment_eta(self):
""" Return the mean and (diag) variance of the latent process given Y.
Returns the marginal moments of likelihood fo the latent process for EP.
Note that eta_mean, eta_variance are the parameters of [Pr(Y | \eta_s)]
Returns:
eta_mean (T ndarray): mean of eta likelihood
eta_variance (T ndarray): variance of eta likelihood
"""
eta_mean = np.zeros(self.T)
eta_variance = np.zeros(self.T)
filter_out = self.filter_pass()
smoothing_out = self.smoothing_pass(filter_out = filter_out)
beta_out = self._backward_pass(
filter_out = filter_out,
smoothing_out = smoothing_out
)
# Constants
sigma2_eta = (self.lambduh.dot(self.lambduh))**-1 * self.sigma2_x
p_beta = (self.lambduh.dot(self.lambduh))**-1 * self.lambduh
p_alpha = -1.0 * p_beta * self.A
for t in range(0, self.T):
# alpha(X_{t-1}) ~ Pr(X_{t-1} | Y_{1:t-1})
if t == 0:
mu_alpha = self.mu_0
V_alpha = self.V_0
else:
mu_alpha = filter_out[t-1]["mu_filter"]
V_alpha = filter_out[t-1]["V_filter"]
# beta(X_t) ~ Pr(Y_{t:T} | X_t)
mu_beta = beta_out[t]["mu_beta"]
V_beta = beta_out[t]["V_beta"]
eta_mean[t] = p_alpha.dot(mu_alpha) + p_beta.dot(mu_beta)
eta_variance[t] = (
p_alpha.dot(V_alpha.dot(p_alpha)) +
p_beta.dot(V_beta.dot(p_beta)) +
sigma2_eta
)
return eta_mean, eta_variance
def _old_moment_eta(self):
""" Old (incorrect) EP moment update step
Use `moment_eta` instead.
Return the mean and variance of the likelihood of the
latent process given Y (integrating out X).
Returns:
eta_mean (T ndarray): mean of eta
eta_variance (T ndarray): variance of eta
"""
eta_mean = np.zeros(self.T)
eta_variance = np.zeros(self.T)
smoothing_out, prev = self.smoothing_pass(calc_prev=True)
# Handle t = 0
J_prev = prev['J_t']
mu_prev = prev['mu_smoothed']
V_prev = prev['V_smoothed']
mu = smoothing_out[0]['mu_smoothed']
V = smoothing_out[0]['V_smoothed']
eta_mean[0] = (mu - self.A * mu_prev) / self.lambduh
eta_variance[0] = (self.sigma2_x +
(V + self.A**2 * V_prev - 2 * V * J_prev * self.A) /
(self.lambduh**2))
# Handle t = 1:T-1
for t in range(1, self.T):
J_prev = smoothing_out[t-1]['J_t']
mu_prev = mu
V_prev = V
mu = smoothing_out[t]['mu_smoothed']
V = smoothing_out[t]['V_smoothed']
eta_mean[t] = (mu - self.A * mu_prev) / self.lambduh
eta_variance[t] = (self.sigma2_x +
(V + self.A**2 * V_prev - 2 * V * J_prev * self.A) /
(self.lambduh**2))
return eta_mean, eta_variance
def sample_x(self, filter_out=None):
""" Sample latent process using forward filter backward sampler
Args:
filter_out (list of dicts): output of filter_pass (optional)
Will call filter_pass if not supplied
Returns:
x (T by N ndarray): sample from latent state conditioned on y
"""
x = np.zeros((self.T,self.N))
# Forward Kalman Filter
if filter_out is None:
filter_out = self.filter_pass()
# Backwards Sampler
mu = filter_out[self.T-1]['mu_filter']
V = filter_out[self.T-1]['V_filter']
#x_next = np.random.multivariate_normal(mean=mu, cov=V)
x_next = _sample_multivariate_normal(mu, V)
x[self.T-1,:] = x_next
for t in reversed(range(0, self.T-1)):
mu_filter = filter_out[t]['mu_filter']
V_filter = filter_out[t]['V_filter']
mu_predict_next = filter_out[t+1]['mu_predict']
V_predict_next = filter_out[t+1]['V_predict']
J_t = self.linalg_solve(V_predict_next,
_mult_diag_matrix(self.A, V_filter)).T
mu = mu_filter + J_t.dot(x_next - mu_predict_next)
V = V_filter - J_t.dot(_mult_diag_matrix(self.A, V_filter))
# x_next = np.random.multivariate_normal(mu, V)
x_next = _sample_multivariate_normal(mu, V)
x[t,:] = x_next
return x
def sample_eta(self, x=None):
""" Sample latent process
Args:
x (T by N ndarray): sampled x (optional)
Returns:
eta (T ndarray): sampled eta
"""
if x is None:
x = self.sample_x()
eta = np.zeros(self.T)
# Handle t = 0
mean_1 = self.eta_mean[0]
var_1 = self.eta_var[0]
mean_2 = np.sum(
self.lambduh * (x[0] - self.A * self.mu_0)
) / np.sum(self.lambduh ** 2)
var_2 = np.sum(
self.lambduh ** 2 /
(self.sigma2_x + self.A**2 * np.diag(self.V_0))
) ** -1
var = 1.0/(1.0/var_1 + 1.0/var_2)
mean = (mean_1/var_1 + mean_2/var_2) * var
eta[0] = np.random.randn(1)*np.sqrt(var) + mean
# Handle t = 1:T-1
for t in range(1, self.T):
mean_1 = self.eta_mean[t]
var_1 = self.eta_var[t]
mean_2 = np.sum(
self.lambduh * (x[t] - self.A * x[t-1])
) / np.sum(self.lambduh ** 2)
var_2 = self.sigma2_x / np.sum(self.lambduh ** 2)
var = 1.0/(1.0/var_1 + 1.0/var_2)
mean = (mean_1/var_1 + mean_2/var_2) * var
eta[t] = np.random.randn(1)*np.sqrt(var) + mean
return eta
def sample_y(self, x=None, filter_out=None):
""" Sample new observations based on latent process conditioned on y
Args:
x (T by N ndarray): sample from latent state conditioned on y
filter_out (list of dicts): output of filter_pass (optional)
Only used if x is not supplied
Returns:
y (T by N ndarray): sample of observations conditioned on y
"""
y = np.zeros((self.T, self.N))
# Draw X is not supplied
if x is None:
x = self.sample_x(filter_out=filter_out)
# Y is a noisy version of X
y = x + _mult_diag_matrix(self.sigma2_y,
np.random.normal(size=np.shape(x)),
on_right = True)
return y
#UTILITY FUNCTION
def _mult_diag_matrix(D, mtx, on_right=False):
""" Multiply diagonal matrix D to mtx
Args:
D (N ndarray) - diagonal matrix
mtx (ndarray) - matrix to multiply
on_right (bool) - whether to return D * mtx (False) or mtx * D (True)
"""
if not on_right:
return (D*mtx.T).T
else:
return D*mtx
def _sample_multivariate_normal(mean, cov):
""" Alternative to numpy.random.multivariate_normal """
if np.size(mean) == 1:
x = np.random.normal(loc = mean, scale = np.sqrt(cov))
return x
else:
L = np.linalg.cholesky(cov)
x = L.dot(np.random.normal(size = np.size(mean))) + mean
return x
def _gaussian_log_likelihood(x, mean, variance):
""" Calculate the log-likelihood of multivariate Gaussian """
N = np.size(x)
log_like = - N/2.0 * np.log(2*np.pi)
if N == 1:
log_like += - 0.5 * np.log(variance)
log_like += - 0.5 * (x-mean)**2/variance
elif N == 0:
log_like = 0.0
else:
log_like += - 0.5 * np.linalg.slogdet(variance)[1]
log_like += - 0.5 * np.sum((x-mean)*np.linalg.solve(variance, x-mean))
return log_like
def _gaussian_cond_log_likelihood(x, mean, variance, i):
""" Calculate the conditional log-likelihood of multivariate Gaussian """
N = np.size(x)
if i >= N:
raise ValueError("Index i is too large for x")
if N == 1:
return _gaussian_log_likelihood(x, mean, variance)
j = np.arange(N) != i
V_ii = variance[i,i]
V_ij = variance[i,j]
V_jj = variance[np.ix_(j,j)]
mu_i = mean[i]
mu_j = mean[j]
K_ij = np.linalg.solve(V_jj, V_ij.T).T
cond_mean = mean[i] + K_ij.dot(x[j] - mu_j)
cond_variance = V_ii - K_ij.dot(V_ij.T)
cond_log_like = _gaussian_log_likelihood(x[i], cond_mean, cond_variance)
return cond_log_like
def _categorical_sample(probs):
""" Draw a categorical random variable over {0,...,K-1}
Args:
probs (K ndarray) - probability of each value
Returns:
draw (int) - random outcome
"""
return int(np.sum(np.random.rand(1) > np.cumsum(probs)))
#EOF
<file_sep>/ep_clustering/likelihoods/_slice_sampler.py
#!/usr/bin/env python
"""
Slice Sampler for vMF likelihood
"""
# Import Modules
import numpy as np
import logging
logger = logging.getLogger(name=__name__)
LOGGING_FORMAT = '%(levelname)s: %(asctime)s - %(name)s: %(message)s ...'
logging.basicConfig(
level = logging.INFO,
format = LOGGING_FORMAT,
)
def bounded(func, lower_bound, upper_bound, out_of_bound_value=-np.inf):
""" Wrap logf with bounds """
def bounded_func(x):
if x < lower_bound:
return out_of_bound_value
if x > upper_bound:
return out_of_bound_value
else:
return func(x)
return bounded_func
class SliceSampler(object):
""" One Dimensional Slice Sampler
Based on 'Slice Sampling' by Neal (2003)
https://projecteuclid.org/download/pdf_1/euclid.aos/1056562461
Args:
logf (func): log of target density (up to a constant)
lower_bound (double): lower bound
upper_bound (double): upper bound
interval_method (string): "stepout" or "doubling" (default doubling)
num_steps (int): number of slice sampler steps for each call to `sample`
typical_slice_size (double): guess of slice size
max_interval_size (double): maximum interval size
"""
def __init__(self, logf, lower_bound=-np.inf, upper_bound=np.inf,
interval_method="doubling", num_steps=1,
typical_slice_size=1.0, max_inteval_size=10e5,
):
self.logf = bounded(logf, lower_bound, upper_bound)
self.lower_bound = lower_bound
self.upper_bound = upper_bound
self.num_steps = num_steps
self.typical_slice_size = typical_slice_size
self.max_inteval_size = max_inteval_size
self.interval_method = interval_method
return
def sample(self, x_init, num_steps=None):
if num_steps is None:
num_steps = self.num_steps
x_cur = x_init + 0.0
for step in range(num_steps):
# Draw Height of slice
logf_cur = self.logf(x_cur)
logy = logf_cur + np.log(np.random.rand())
# Get Interval around slice
x_l, x_r = self._get_interval(x_cur, logy)
# Draw New X from Interval containing slice
x_new = self._draw_from_interval(x_cur, x_l, x_r, logy)
# Repeat
x_cur = x_new
return x_new
def _get_interval(self, x_cur, logy):
if self.interval_method == "stepout":
return self._stepout_interval(x_cur, logy)
elif self.interval_method == "doubling":
return self._doubling_interval(x_cur, logy)
else:
raise ValueError("Unrecognized interval_method")
def _stepout_interval(self, x_cur, logy):
# See Fig. 3 in Slice Sampling by Neal (2003)
x_l = x_cur - self.typical_slice_size * np.random.rand()
x_r = x_l + self.typical_slice_size
m = np.ceil(self.max_inteval_size / self.typical_slice_size)
J = np.floor(m * np.random.rand())
K = (m-1)-J
while (J > 0) and logy < self.logf(x_l):
x_l = x_l - self.typical_slice_size
J -= 1
while (K > 0) and logy < self.logf(x_r):
x_r = x_r + self.typical_slice_size
K -= 1
if J <= 0 or K <= 0:
logging.warning("inteval may not contain slice")
return x_l, x_r
def _doubling_interval(self, x_cur, logy):
# See Fig. 4 in Slice Sampling by Neal (2003)
p = np.ceil(np.log2(self.max_inteval_size / self.typical_slice_size))
x_l = x_cur - self.typical_slice_size * np.random.rand()
x_r = x_l + self.typical_slice_size
while((p > 0) and ((logy < self.logf(x_l)) or (logy < self.logf(x_r)))):
# Expanding either side equally is important for correctness
if np.random.rand() < 0.5:
x_l = x_l - (x_r - x_l)
else:
x_r = x_r + (x_r - x_l)
p -= 1
if p <= 0:
logging.warning("inteval may not contain slice")
return x_l, x_r
def _draw_from_interval(self, x_cur, x_l, x_r, logy):
""" Draw x_new with logf(x_new) > logy from interval [x_l, x_r] """
x_new = None
for _ in range(1000):
x_candidate = np.random.rand() * (x_r - x_l) + x_l
logf_candidate = self.logf(x_candidate)
# If candidate is on slice
if logf_candidate >= logy:
x_new = x_candidate
break
# Otherwise Shrink Interval
if x_candidate > x_cur:
x_r = x_candidate
elif x_candidate < x_cur:
x_l = x_candidate
else:
raise RuntimeError("Slice shrunk too far")
if x_new is None:
raise RuntimeError("Could not find sample on slice")
return x_new
<file_sep>/ep_clustering/evaluator/_timeseries_prediction_metric.py
"""
Time Series Prediction Metric Function
"""
import numpy as np
import pandas as pd
import logging
logger = logging.getLogger(name=__name__)
class TimeSeriesPredictionEvaluator(object):
""" Class for keeping track of GibbsSampler posterior predictions
Args:
new_data (TimeSeriesData): data to predict
num_samples (int): number of samples to use each evaluation call
variable_name (string): string of variable name for output
transformer (func): function to postprocess predictions
"""
def __init__(self, new_data, num_samples = 5, variable_name = "predict",
transformer = None):
self.new_data = new_data
self.num_samples = num_samples
self.variable_name = variable_name
if transformer is not None:
if not callable(transformer):
raise ValueError("transfomer must be a callable function")
self.transformer = transformer
# Initialize Mean Predict + Number of Observations
columns = ['mean_predict', 'mean_predict_sq']
self.predict_df = pd.DataFrame(0.0, columns=columns,
index=new_data.df.index)
self.num_obs = 0.0
self.variable_name = variable_name
self.metrics = ['rmse', 'mape', 'median ape', '90th ape']
return
def sample_predictions(self, sampler):
""" Use GibbsSampler to generate predictions
Returns:
sample_predictions (ndarray): num_rows by num_samples
"""
sample_predictions = \
pd.DataFrame(index = self.predict_df.index,
columns = pd.Index(np.arange(self.num_samples), name="sample"))
for cluster in range(0, sampler.K):
# Get cluster membership
cluster_indices = np.where(sampler.state.z == cluster)[0]
if cluster_indices.size == 0: # No indices in cluster
continue
# Subset series in new_data
cluster_new_data = self.new_data.subset(cluster_indices)
row_indices = sample_predictions.index.get_level_values(
'observation').isin(cluster_indices)
if sum(row_indices) == 0: # No rows in new_data
continue
# Otherwise Use likelihood to predict
sampled_y = sampler.likelihood.predict(
new_data = cluster_new_data,
prior_parameter=sampler.likelihood.theta_prior,
num_samples=self.num_samples,
)
sample_predictions.iloc[row_indices] = sampled_y.T
return sample_predictions
def _update_mean_prediction(self, samples):
""" Use GibbsSampler to update mean_predict """
# Note: mean_predict is of the resid = y - yhat
n_old = self.num_obs
n_new = n_old + self.num_samples
mean_predict = self.predict_df['mean_predict'] * n_old / n_new
mean_predict += np.sum(samples, axis=1) / n_new
mean_predict_sq = self.predict_df['mean_predict_sq'] * n_old / n_new
mean_predict_sq += np.sum(samples**2, axis=1) / n_new
self.num_obs = n_new
self.predict_df['mean_predict'] = mean_predict
self.predict_df['mean_predict_sq'] = mean_predict_sq
return
def evaluate(self, sampler):
""" Metric Function to pass to GibbsSamplerEvaluater
Returns:
list of dicts - metrics on the time-series prediction
"""
logger.info("Sampling Predictions")
samples = self.sample_predictions(sampler)
logger.info("Updating Predictions")
self._update_mean_prediction(samples)
truth = self.new_data.df[self.new_data.observation_name]
prediction = self.predict_df['mean_predict']
if self.transformer is not None:
truth = self.transformer(truth)
prediction = self.transformer(prediction)
resid = prediction - truth
percent_resid = (prediction - truth) / truth * 100
metrics = []
if 'rmse' in self.metrics:
metrics.append({
'variable': self.variable_name,
'metric': 'rmse',
'value': np.sqrt(np.mean(resid ** 2)),
})
if 'mape' in self.metrics:
metrics.append({
'variable': self.variable_name,
'metric': 'mape',
'value': np.mean(np.abs(percent_resid)),
})
if 'median ape' in self.metrics:
metrics.append({
'variable': self.variable_name,
'metric': 'median ape',
'value': np.median(np.abs(percent_resid)),
})
if '90th ape' in self.metrics:
metrics.append({
'variable': self.variable_name,
'metric': '90th ape',
'value': np.percentile(np.abs(percent_resid), 90),
})
return metrics
if __name__ == "__main__":
print("TimeSeries Prediction Evaluation")
#EOF
<file_sep>/ep_clustering/likelihoods/_mix_gaussian_likelihood.py
#!/usr/bin/env python
"""
Mixture of Scale Gaussians Likelihood
"""
# Import Modules
import numpy as np
import logging
from scipy.special import logsumexp
from ep_clustering._utils import fix_docs
from ep_clustering.likelihoods._likelihoods import Likelihood
from ep_clustering.exp_family._normal_mean import (
NormalFamily,
DiagNormalFamily
)
logger = logging.getLogger(name=__name__)
@fix_docs
class MixDiagGaussianLikelihood(Likelihood):
""" Mixture of Scale Gaussian Likelihood Object
Args:
**kwargs : parameters
variance (double or ndarray): clutter noise, length num_dim
proportions (ndarray): length num_scale_components
scales (ndarray): length num_scale_components
(!!Note!! that this scales the variance)
"""
# Inherit Docstrings
__doc__ += Likelihood.__doc__
# Class Variables
name = "MixScaleDiagGaussian"
def __init__(self, data, **kwargs):
self.y = data.matrix
self.num_dim = data.num_dim
super(MixDiagGaussianLikelihood, self).__init__(data, **kwargs)
self.num_scale_components = np.size(self.parameter.proportions)
return
def _get_default_prior(self):
theta_prior = DiagNormalFamily(num_dim = self.num_dim,
precision=np.ones(self.num_dim)/100.0)
return theta_prior
def _get_default_parameters(self):
"""Returns default parameters dict"""
default_parameter = {
"variance": np.ones(self.num_dim),
"proportions": np.ones(2)/2.0,
"scales": np.array([0.5, 1.5]),
}
return default_parameter
def _get_default_parameters_prior(self):
"""Returns default parameters prior dict"""
prior = {}
return prior
def _sample_from_prior(self):
raise NotImplementedError(
"Parameter prior not implemented for MixDiagGaussian")
def loglikelihood(self, index, theta):
y = self.y[index]
component_loglikelihood = np.zeros(self.num_scale_components)
for c in range(self.num_scale_components):
variance = self.parameter.variance * self.parameter.scales[c]
component_loglikelihood[c] = \
-0.5*((y-theta)/variance).dot(y-theta) + \
-0.5*self.num_dim*np.sqrt(2*np.pi) + \
-0.5*np.sum(np.log(variance))
component_loglikelihood[c] += \
np.log(self.parameter.proportions[c])
loglikelihood = logsumexp(component_loglikelihood)
return loglikelihood
def collapsed(self, index, subset_indices, theta_parameter):
raise NotImplementedError("collapsed likelihood not implemented")
def moment(self, index, theta_parameter):
y = self.y[index]
theta_parameter_log_partition = theta_parameter.logpartition()
# Calculate Moments of Individual Components
logZs = np.zeros(self.num_scale_components)
means = np.zeros((self.num_scale_components, self.num_dim))
second_moments = np.zeros((self.num_scale_components, self.num_dim))
for c in range(self.num_scale_components):
site_c = DiagNormalFamily.from_mean_variance(
mean=y,
variance=self.parameter.variance*self.parameter.scales[c],
)
post_approx_c = (theta_parameter + site_c)
logZs[c] = post_approx_c.logpartition() - \
(theta_parameter_log_partition + site_c.logpartition())
means[c] = post_approx_c.get_mean()
second_moments[c] = \
post_approx_c.get_variance() + post_approx_c.get_mean()**2
# Aggregate Moments
weights = np.exp(logZs) * self.parameter.proportions
Z = np.sum(weights)
mean = np.sum(
means * np.outer(weights, np.ones(self.num_dim)),
axis=0,
) / Z
second_moment = np.sum(
second_moments * np.outer(weights, np.ones(self.num_dim)),
axis=0,
) / Z
variance = second_moment - mean**2
# Construct and return the unnormalized_post_approx
unnormalized_post_approx = DiagNormalFamily.from_mean_variance(
mean = mean,
variance = variance,
)
unnormalized_post_approx.log_scaling_coef = np.log(Z)
return unnormalized_post_approx
def sample(self, indices, prior_parameter):
raise NotImplementedError("sample theta not implemented")
def update_parameters(self, z, theta, parameter_name = None):
raise NotImplementedError("update parameters not implemented")
# EOF
<file_sep>/ep_clustering/exp_family/_exponential_family.py
#!/usr/bin/env python
"""
Exponential Family Class
"""
# Import Modules
import numpy as np
from ep_clustering._utils import fix_docs
from copy import deepcopy
# Author Information
__author__ = "<NAME>"
class ExponentialFamily(object):
""" Exponential Family Site Approximation Class
Let X be a r.v.
Pr(X) \propto \exp(natural_parameters*sufficient statistics - logpartition)
Args:
num_dim (int): dimension of random variable
**kwargs: additional key-word args
initialization of a natural_parameters by key name
Attributes:
natural_parameters (dict): natural parameters
log_scaling_coef (double): scaling coeffient for site approximations
Methods:
copy()
sample()
logpartition()
is_valid_density()
normalize()
__add__ and __sub__
"""
def __init__(self, num_dim, log_scaling_coef=0.0,
**kwargs):
self.num_dim = num_dim
self.log_scaling_coef = log_scaling_coef
self.natural_parameters = dict(**kwargs)
self._is_known_valid_density = False
return
def copy(self):
""" Return a copy of the object """
cls = type(self)
my_copy = cls(num_dim = self.num_dim,
log_scaling_coef = self.log_scaling_coef,
**deepcopy(self.natural_parameters)
)
return my_copy
def is_valid_density(self):
""" Check if the object is a valid probability density """
raise NotImplementedError()
def _check_is_valid_density(self):
if self._is_known_valid_density:
return
else:
self._is_known_valid_density = self.is_valid_density()
if not self._is_known_valid_density:
raise RuntimeError("ExponentialFamily is not a valid density")
return
def sample(self):
""" Return a sample draw from the ExponentialFamily """
raise NotImplementedError()
def logpartition(self):
""" Evaluates the logpartition function for current parameters """
raise NotImplementedError()
def normalize(self):
""" Set log_scaling_coef so the ExponentialFamily integrates to 1
Must be a valid density
"""
self._check_is_valid_density()
self.log_scaling_coef = 0.0
return self
def __add__(self, right):
result = self.copy()
result += right
return result
def __iadd__(self, right):
cls = type(self)
if not isinstance(right, cls):
raise TypeError("RHS must be type {0}".format(cls))
if self.num_dim != right.num_dim:
raise ValueError(
"Dimensions of LHS and RHS do not match: {0} != {1}".format(
self.num_dim, right.num_dim)
)
for key in self.natural_parameters.keys():
self.natural_parameters[key] += right.natural_parameters[key]
self.log_scaling_coef += right.log_scaling_coef
self._is_known_valid_density = False
return self
def __sub__(self, right):
result = self.copy()
result -= right
return result
def __isub__(self, right):
cls = type(self)
if not isinstance(right, cls):
raise TypeError("RHS must be type {0}".format(cls))
if self.num_dim != right.num_dim:
raise ValueError(
"Dimensions of LHS and RHS do not match: {0} != {1}".format(
self.num_dim, right.num_dim)
)
for key in self.natural_parameters.keys():
self.natural_parameters[key] -= right.natural_parameters[key]
self.log_scaling_coef -= right.log_scaling_coef
self._is_known_valid_density = False
return self
def __mul__(self, right):
result = self.copy()
result *= right
return result
def __rmul__(self, left):
result = self.copy()
result *= left
return result
def __imul__(self, right):
if not isinstance(right, float):
raise TypeError(
"Multiplication only defined for floats not {0}".format(right)
)
for key in self.natural_parameters.keys():
self.natural_parameters[key] *= right
self.log_scaling_coef *= right
self._is_known_valid_density = False
return self
def __repr__(self):
obj_repr = super(ExponentialFamily, self).__repr__()
obj_repr += "\nnum_dim: " + str(self.num_dim)
obj_repr += "\nlog_scale_coef: " + str(self.log_scaling_coef)
for para_name, para_value in self.natural_parameters.items():
obj_repr += "\n{0}:\n{1}".format(para_name, para_value)
obj_repr += "\n"
return obj_repr
def as_vector(self):
""" Return vector of log_scaling_coef and natural_parameters """
vector_list = [np.array([self.log_scaling_coef])]
for key, value in self.natural_parameters.items():
vector_list.append(value.flatten())
vector = np.concatenate(vector_list)
return vector
<file_sep>/ep_clustering/likelihoods/_ar_likelihood.py
#!/usr/bin/env python
"""
AR Likelihood
"""
# Import Modules
import numpy as np
import logging
from ep_clustering._utils import fix_docs
#from ep_clustering._natural_parameters import NaturalParameters
from ep_clustering.likelihoods._likelihoods import Likelihood
logger = logging.getLogger(name=__name__)
@fix_docs
class ARLikelihood(Likelihood):
""" AR Likelihood
Model: y_t = a y_{t-1} + lambduh theta_t + \epsilon_x
Note: the first element of `theta`, `theta[k,0]`, should be ignored as it
has no meaning for this model
Args:
**kwargs :
- A (N ndarray): AR coefficient
- lambduh (N ndarray): latent factor loadings
- sigma2_x (double): white noise variance
"""
# Inherit docstrings
__doc__ += Likelihood.__doc__
prior = {
"mu_A0": 0.0,
"sigma2_A0": 100.0,
"mu_lambduh0": 0.0,
"sigma2_lambduh0": 100.0,
"alpha_x0": 3.0,
"beta_x0": 2.0,
}
name = "AR"
def __init__(self, data, sample_prior = False, **kwargs):
raise NotImplementedError("This no longer works properly due to refactorization")
self.y = data.get_matrix()[0]
self._set_prior()
self._default_parameter = {
"A": 0.9 * np.ones(np.shape(self.y)[0]),
"lambduh": np.ones(np.shape(self.y)[0]),
"sigma2_x": 1.0,
}
self._set_default_parameters(**kwargs)
self.init_parameters(sample_prior)
return
def _sample_from_prior(self):
N = np.shape(self.y)[0]
logger.warning("Sampling from prior is not recommended")
parameter = {
"A": np.random.normal(
loc=self.prior.mu_A0,
scale=np.sqrt(self.prior.sigma2_A0),
size=N),
"lambduh": np.random.normal(
loc=self.prior.mu_lambduh0,
scale=np.sqrt(self.prior.sigma2_lambduh0),
size=N),
"sigma2_x": 1.0/np.random.gamma(
shape=self.prior.alpha_x0,
scale=self.prior.beta_x0,
size=1)[0],
}
return parameter
def loglikelihood(self, index, theta):
u = self.y[index, 1:] - self.parameter.A[index] * self.y[index, 0:-1]
mean = self.parameter.lambduh[index] * theta[1:]
variance = self.parameter.sigma2_x
loglikelihood = -0.5*((u - mean)/variance).dot(u - mean)
return loglikelihood
def collapsed(self, index, subset_indices, theta_parameter):
posterior = theta_parameter
for s_index in subset_indices:
s_mean = np.append(
np.zeros(1),
(self.y[s_index, 1:] -
self.parameter.A[s_index] * self.y[s_index, 0:-1]) /
self.parameter.lambduh[s_index])
s_variance = (self.parameter.sigma2_x /
(self.parameter.lambduh[s_index] ** 2))
posterior = (posterior +
NaturalParameters(mean=s_mean, variance=s_variance))
u_mean = self.parameter.lambduh[index] * posterior.get_mean()[1:]
u_variance = (self.parameter.sigma2_x +
self.parameter.lambduh[index] ** 2 *
posterior.get_variance()[1:])
u = self.y[index, 1:] - self.parameter.A[index] * self.y[index, 0:-1]
loglikelihood = -0.5*((u - u_mean) / u_variance).dot(u - u_mean)
return loglikelihood
def moment(self, index, theta_parameter):
mean = np.append(
np.zeros(1),
(self.y[index, 1:] -
self.parameter.A[index] * self.y[index, 0:-1]) /
self.parameter.lambduh[index])
variance = (self.parameter.sigma2_x /
(self.parameter.lambduh[index] ** 2))
posterior = (theta_parameter +
NaturalParameters(mean=mean,
variance=variance))
return posterior
def sample(self, indices, prior_parameter):
posterior = prior_parameter
for s_index in indices:
s_mean = np.append(
np.zeros(1),
(self.y[s_index, 1:] -
self.parameter.A[s_index] * self.y[s_index, 0:-1]) /
self.parameter.lambduh[s_index])
s_variance = (self.parameter.sigma2_x /
(self.parameter.lambduh[s_index] ** 2))
posterior = (posterior +
NaturalParameters(mean=s_mean, variance=s_variance))
theta_mean = posterior.get_mean()
theta_variance = posterior.get_variance()
return np.random.randn(posterior.T)*np.sqrt(theta_variance) + theta_mean
def update_parameters(self, z, theta, parameter_name = None):
if(parameter_name is None):
self._update_A(z, theta)
self._update_lambduh(z, theta)
self._update_sigma2_x(z, theta)
elif(parameter_name == "A"):
self._update_A(z, theta)
elif(parameter_name == "lambduh"):
self._update_lambduh(z, theta)
elif(parameter_name == "sigma2_x"):
self._update_sigma2_x(z, theta)
else:
raise ValueError("Unrecognized parameter_name: " + parameter_name)
return
def _update_A(self, z, theta):
""" Update the AR coefficients A """
N, T = np.shape(self.y)
for index in range(0, N):
x = self.y[index]
lambduh = self.parameter.lambduh[index]
eta = theta[z[index]]
sigma2_x = self.parameter.sigma2_x
# Calculate posterior natural parameter (from sufficient statistics)
precision = self.prior.sigma2_A0 ** -1
mean_precision = self.prior.mu_A0 * precision
## TODO: Handle t = 0
## (for now assume sigma2_0 is very large, so precision is zero)
precision_t = (x[0:(T-1)] ** 2)/sigma2_x
mean_precision_t = (x[1:T] - lambduh * eta[1:T])*x[0:(T-1)]/sigma2_x
precision += np.sum(precision_t)
mean_precision += np.sum(mean_precision_t)
# Update A[index] by sampling from posterior
sampled_A = np.random.normal(loc = mean_precision / precision,
scale = precision ** -0.5)
# Restrict A <= 0.999
if sampled_A > 0.999:
logger.warning(
"Sampled AR coefficient A is %f, which is > 0.999",
sampled_A)
sampled_A = 0.999
self.parameter.A[index] = sampled_A
# Restrict A >= -0.999
if sampled_A < -0.999:
logger.warning(
"Sampled AR coefficient A is %f, which is < -0.999",
sampled_A)
sampled_A = -0.999
self.parameter.A[index] = sampled_A
return
def _update_lambduh(self, z, theta):
""" Update the factor loading lambduh """
N, T = np.shape(self.y)
for index in range(0, N):
x = self.y[index]
a = self.parameter.A[index]
eta = theta[z[index]]
sigma2_x = self.parameter.sigma2_x
# Calculate posterior natural parameter (from sufficient statistics)
precision = self.prior.sigma2_lambduh0 ** -1
mean_precision = self.prior.mu_lambduh0 * precision
## TODO: Handle t = 0
## (for now assume sigma2_0 is very large, so precision is zero)
precision_t = (eta[1:T] ** 2)/sigma2_x
mean_precision_t = (x[1:T] - a * x[0:(T-1)])*eta[1:T]/sigma2_x
precision += np.sum(precision_t)
mean_precision += np.sum(mean_precision_t)
# Update lambduh[index] by sampling from posterior
self.parameter.lambduh[index] = np.random.normal(
loc = mean_precision / precision,
scale = precision ** -0.5)
return
def _update_sigma2_x(self, z, theta):
N, T = np.shape(self.y)
alpha_x = self.prior.alpha_x0
beta_x = self.prior.beta_x0
for index in range(0, N):
x = self.y[index]
a = self.parameter.A[index]
lambduh = self.parameter.lambduh[index]
eta = theta[z[index]]
## TODO: Handle t = 0
## (for now assume sigma2_0 is very large, so precision is zero)
# Calculate posterior natural parameter (from sufficient statistics)
alpha_x += (T-1)/2.0
beta_x += np.sum((x[1:T] - a*x[0:(T-1)] - lambduh*eta[1:T])**2)/2
# Update sigma2_x
self.parameter.sigma2_x = 1.0/np.random.gamma(shape = alpha_x,
scale = 1.0/beta_x,
size = 1)[0]
return
<file_sep>/ep_clustering/evaluator/_gibbs_evaluater.py
"""
Gibbs Sampler Evaluation Wrapper
"""
import pandas as pd
import time
import logging
logger = logging.getLogger(name=__name__)
class GibbsSamplerEvaluater(object):
""" Wrapper to handle measuring a GibbsSampler's performance
Example:
Args:
sampler (GibbsSampler): the Gibbs sampler
metric_functions (func or list of funcs): evaluation functions
Each function takes a sampler and returns a dict (or list of dict)
{metric, variable, value} for each
See ep_clustering.evaluator.metric_function_from_state or
ep_clustering.evaluator.metric_function_from_sampler
sample_functions (dict of funcs, optional): samples to save
`key` is the name of column, `value` is a function with
input: sampler
output: obj saved under column `key`
sampler_name (string, optional): name for sampler
data_name (string, optional): name for data
Attributes:
metrics (pd.DataFrame): output data frame with columns
* metric (string)
* variable (string)
* value (double)
* iteration (int)
Methods:
get_metrics(self, **kwargs)
reset_metrics(self)
save_metrics(self, file_name)
get_samples(self)
reset_samples(self)
save_samples(self, file_name)
evaluate_sampler_step(self, sampler_func_name, sampler_func_kwargs)
evaluate_metric_functions(self)
"""
def __init__(self, sampler, metric_functions,
sample_functions = {},
sampler_name = None, data_name = None,
metric_log_level = logging.INFO):
self.sampler = sampler
self.metric_log_level = metric_log_level
# Check metric Functions
self._process_metric_functions(metric_functions)
self.metric_functions = metric_functions
if not isinstance(sample_functions, dict):
raise ValueError("sample_functions must be a dict of str:func")
self.sample_functions = sample_functions
if sampler_name is None:
sampler_name = sampler.name
self.sampler_name = sampler_name
if data_name is None:
data_name = sampler.likelihood.data.get("name", "")
self.data_name = data_name
self.iteration = 0
self._start_time = time.time()
self._init_metrics()
self._init_samples()
return
@staticmethod
def _process_metric_functions(metric_functions):
if callable(metric_functions):
metric_functions = [metric_functions]
elif isinstance(metric_functions, list):
for metric_function in metric_functions:
if not callable(metric_function):
raise ValueError("metric_functions must be list of funcs")
else:
ValueError("metric_functions should be list of funcs")
def _init_metrics(self):
self.metrics = pd.DataFrame()
self.eval_metric_functions()
init_metric = {
"variable": "time",
"metric": "time",
"value": 0.0,
"iteration": self.iteration,
}
self.metrics = self.metrics.append(init_metric, ignore_index = True)
return
def get_metrics(self, extra_columns={}):
""" Return a pd.DataFrame copy of metrics
Args:
extra_columns (dict): extra metadata to add as columns
Returns:
pd.DataFrame with columns
metric, variable, value, iteration, sampler, data, extra_columns
"""
metrics = self.metrics.copy()
metrics["sampler"] = self.sampler_name
metrics["data"] = self.data_name
for k,v in extra_columns.items():
metrics[k] = v
return metrics
def reset_metrics(self):
""" Reset self.metrics """
logger.info("Resetting metrics")
self.iteration = 0
self._init_metrics()
return
def save_metrics(self, filename, extra_columns = {}):
""" Save a pd.DataFrame to filename + '.csv' """
metrics = self.get_metrics(extra_columns)
logger.info("Saving metrics to file %s", filename)
metrics.to_csv(filename + ".csv", index = False)
return
def evaluate_sampler_step(self, sampler_func_name = "one_step",
sampler_func_kwargs = None):
""" Evaluate the performance of the sampler steps
Args:
sampler_func_name (string or list of strings):
name(s) of sampler member functions
(e.g. `one_step` or `['sample_z', 'sample_z']`)
sampler_func_kwargs (kwargs or list of kwargs):
options to pass to sampler_func_name
"""
logger.info("Sampler %s, Iteration %d",
self.sampler_name, self.iteration+1)
# Single Function
if isinstance(sampler_func_name, str):
sampler_func = getattr(self.sampler, sampler_func_name, None)
if sampler_func is None:
raise ValueError(
"sampler_func_name `{}` is not in sampler".format(
sampler_func_name)
)
if sampler_func_kwargs is None:
sampler_func_kwargs = {}
sampler_start_time = time.time()
sampler_func(**sampler_func_kwargs)
sampler_step_time = time.time() - sampler_start_time
# Multiple Steps
elif isinstance(sampler_func_name, list):
sampler_funcs = [getattr(self.sampler, func_name, None)
for func_name in sampler_func_name]
if None in sampler_funcs:
raise ValueError("Invalid sampler_func_name")
if sampler_func_kwargs is None:
sampler_func_kwargs = [{} for _ in sampler_funcs]
if not isinstance(sampler_func_kwargs, list):
raise TypeError("sampler_func_kwargs must be a list of dicts")
if len(sampler_func_kwargs) != len(sampler_func_name):
raise ValueError("sampler_func_kwargs must be same length " +
"as sampler_func_name")
sampler_start_time = time.time()
for sampler_func, kwargs in zip(sampler_funcs, sampler_func_kwargs):
sampler_func(**kwargs)
sampler_step_time = time.time() - sampler_start_time
else:
raise TypeError("Invalid sampler_func_name")
self.iteration += 1
time_metric = {
"variable": "time",
"metric": "time",
"value": sampler_step_time,
"iteration": self.iteration,
}
self.metrics = self.metrics.append(time_metric, ignore_index = True)
self.eval_metric_functions()
# Save Samples
if self.sample_functions:
self._eval_samples()
return
def eval_metric_functions(self, metric_functions = None):
""" Evaluate the state of the sampler
Args:
metric_functions (list of funcs): evaluation functions
Defaults to metric functions defined in __init__
"""
if metric_functions is None:
metric_functions = self.metric_functions
self._process_metric_functions(metric_functions)
iter_metrics = []
for metric_function in metric_functions:
metric = metric_function(self.sampler)
log_level = getattr(metric_function, "log_level",
self.metric_log_level)
if isinstance(metric, dict):
logger.log(log_level, "Metric: %s", str(metric))
iter_metrics.append(metric)
elif isinstance(metric, list):
for met in metric:
if not isinstance(met, dict):
raise TypeError("Metric must be dict or list of dict")
logger.log(log_level, "Metric: %s", str(met))
iter_metrics.append(met)
else:
raise TypeError("Metric must be dict or list of dict")
iter_metrics = pd.DataFrame(iter_metrics)
iter_metrics["iteration"] = self.iteration
self.metrics = self.metrics.append(iter_metrics, ignore_index = True)
return
def _init_samples(self):
columns = ["iteration"]
columns.extend(self.sample_functions.keys())
self.samples = pd.DataFrame(columns = columns)
self._eval_samples()
return
def get_samples(self):
""" Return a pd.DataFrame of samples """
if not self.sample_functions:
logger.warning("No sample functions were provided to track!!!")
samples = self.samples.copy()
samples["sampler"] = self.sampler_name
samples["data_name"] = self.data_name
return samples
def reset_samples(self):
""" Reset self.metrics """
logger.info("Resetting samples")
self._init_samples()
return
def save_samples(self, filename):
""" Save a pd.DataFrame to filename + '.csv' """
samples = self.get_samples()
logger.info("Saving samples to file %s", filename)
samples.to_csv(filename + ".csv", index = False)
return
def _eval_samples(self):
# Return a dict of current tracked samples
samples = { key : value(self.sampler) + 0.0
for key, value in self.sample_functions.items() }
samples.update({"iteration": self.iteration})
self.samples = self.samples.append(samples, ignore_index=True)
return
<file_sep>/ep_clustering/likelihoods/_von_mises_fisher_likelihood.py
#!/usr/bin/env python
"""
Von Mises Fisher Likelihood
"""
# Import Modules
import numpy as np
import scipy.special
from scipy.optimize import root
import logging
from ep_clustering._utils import fix_docs, logsumexp
from ep_clustering.likelihoods._likelihoods import Likelihood
from ep_clustering.likelihoods._slice_sampler import SliceSampler
from ep_clustering.exp_family._von_mises_fisher import (
VonMisesFisherFamily,
VonMisesFisherProdGammaFamily,
amos_asymptotic_log_iv,
)
from spherecluster import sample_vMF
MAX_CONCENTRATION = 10.0**9
MIN_CONCENTRATION = 10**-3
logger = logging.getLogger(name=__name__)
LOGGING_FORMAT = '%(levelname)s: %(asctime)s - %(name)s: %(message)s ...'
logging.basicConfig(
level = logging.INFO,
format = LOGGING_FORMAT,
)
@fix_docs
class FixedVonMisesFisherLikelihood(Likelihood):
""" Von Mises Fisher Likelihood with fixed concentration
Args:
concentration_update (string): method for updating concentration
"map": (default) use the MAP estimator
"slice_sampler": slow
num_slice_steps (int): number of slice sampler steps
**kwargs:
concentration (double) - concentration (a.k.a. kappa)
"""
# Inherit Docstrings
__doc__ += Likelihood.__doc__
# Class Variables
name = "FixedVonMisesFisher"
def __init__(self, data, concentration_update="map",
num_slice_steps=5, **kwargs):
self.y = data.matrix
self.num_dim = data.num_dim
super(FixedVonMisesFisherLikelihood, self).__init__(data, **kwargs)
self.concentration_update = concentration_update
self.num_slice_steps = num_slice_steps
return
def deepcopy(self):
""" Return a copy """
other = type(self)(data = self.data,
concentration_update=self.concentration_update,
num_slice_steps=self.num_slice_steps,
theta_prior=self.theta_prior)
other.parameter = self.parameter.deepcopy()
other.prior = self.prior.deepcopy()
return other
def _get_default_prior(self):
theta_prior = VonMisesFisherFamily(
num_dim = self.num_dim,
mean=np.ones(self.num_dim)/np.sqrt(self.num_dim) * 1e-9)
return theta_prior
def _get_default_parameters(self):
"""Returns default parameters dict"""
default_parameter = {
"concentration": 1.0,
}
return default_parameter
def _get_default_parameters_prior(self):
"""Returns default parameters prior dict"""
prior = {
"alpha_concentration0": 2.0,
"beta_concentration0": 0.1,
}
return prior
def _sample_from_prior(self):
parameter = {
"concentration": 1.0/np.random.gamma(
shape=self.prior.alpha_concentration0,
scale=self.prior.beta_concentration0,
size=1)
}
return parameter
def loglikelihood(self, index, theta):
y_index = self.y[index]
order = (0.5 * self.num_dim - 1)
loglikelihood = self.parameter.concentration * theta.dot(y_index) + \
order * np.log(self.parameter.concentration) + \
-0.5*self.num_dim*np.sqrt(2*np.pi) + \
-amos_asymptotic_log_iv(order, self.parameter.concentration)
return loglikelihood
def collapsed(self, index, subset_indices, theta_parameter):
loglikelihood = 0.0
cavity_posterior = theta_parameter
for s_index in subset_indices:
s_y = self.y[s_index]
cavity_posterior = (cavity_posterior + VonMisesFisherFamily(
num_dim=self.num_dim,
mean=s_y*self.parameter.concentration,
))
loglikelihood -= cavity_posterior.logpartition()
y = self.y[index]
likelihood = VonMisesFisherFamily(
num_dim=self.num_dim,
mean=y*self.parameter.concentration,
)
loglikelihood -= likelihood.logpartition()
posterior = cavity_posterior + likelihood
loglikelihood += posterior.logpartition()
return loglikelihood
def moment(self, index, theta_parameter):
y_index = self.y[index]
site = VonMisesFisherFamily(
num_dim=self.num_dim,
mean=y_index * self.parameter.concentration,
)
unnormalized_post_approx = (theta_parameter + site)
unnormalized_post_approx.log_scaling_coef = \
unnormalized_post_approx.logpartition() - \
(theta_parameter.logpartition() + site.logpartition())
return unnormalized_post_approx
def sample(self, indices, prior_parameter):
posterior = prior_parameter
for index in indices:
y_index = self.y[index]
posterior = posterior + VonMisesFisherFamily(
num_dim=self.num_dim,
mean=y_index * self.parameter.concentration,
)
return posterior.sample()
def update_parameters(self, z, theta, parameter_name = None):
if parameter_name is None:
self._update_concentration(z, theta)
elif parameter_name == "variance":
self._update_concentration(z, theta)
else:
raise ValueError("Unrecognized parameter_name: " + parameter_name)
return
def _update_concentration(self, z, theta, k_list=None):
if k_list is None:
k_list = range(np.shape(theta)[0])
if self.concentration_update == "map":
# MAP Estimator Update from
# http://www.jmlr.org/papers/volume6/banerjee05a/banerjee05a.pdf
kappa, n = 0.0, 0.0
for k in k_list:
ind = (z == k)
n_k = (np.sum(ind)*1.0)
r_bar_k = np.linalg.norm(np.sum(self.y[ind,:], axis=0))/n_k
r_bar_k *= (1-1e-6)
kappa_k = (r_bar_k*self.num_dim - r_bar_k**3)/(1.0 - r_bar_k**2)
if kappa_k > MAX_CONCENTRATION:
kappa_k = MAX_CONCENTRATION
kappa += n_k * kappa_k
n += n_k
self.parameter.concentration = kappa/n
if n == 0:
self.parameter.concentration = MIN_CONCENTRATION
if (np.isinf(self.parameter.concentration) or
np.isnan(self.parameter.concentration)):
raise ValueError("concentration is invalid")
elif self.concentration_update == "slice_sampler":
# Slice Sampler Update
logprior = lambda kappa: scipy.stats.gamma.logpdf(
kappa, a=self.prior.alpha_concentration0,
scale=1.0/self.prior.beta_concentration0,
)
n = 0.0
mu_T_x = 0.0
for k in k_list:
ind = (z == k)
n += (np.sum(ind)*1.0)
mu_T_x += np.dot(theta[k], np.sum(self.y[ind,:], axis=0))
order = self.num_dim/2.0 - 1.0
def logf(kappa):
logf = logprior(kappa)
logf += kappa * mu_T_x
logf += n * order * np.log(kappa)
logf -= n * amos_asymptotic_log_iv(order, kappa)
return logf
slice_sampler = SliceSampler(
logf=logf, lower_bound=0.0,
num_steps=self.num_slice_steps)
self.parameter.concentration = slice_sampler.sample(
x_init = self.parameter.concentration,
)
if (np.isinf(self.parameter.concentration) or
np.isnan(self.parameter.concentration)):
raise ValueError("concentration is invalid")
else:
raise NotImplementedError(
"Unrecognized `concentration_update`={0}".format(
self.concentration_update,
))
return
def update_local_parameters(self, k, z, theta, parameter_name = None):
if parameter_name is None:
self._update_concentration(z, theta, k_list=[k])
elif parameter_name == "concentration":
self._update_concentration(z, theta, k_list=[k])
else:
raise ValueError("Unrecognized parameter_name: " + parameter_name)
return
@fix_docs
class VonMisesFisherLikelihood(Likelihood):
""" Von Mises Fisher Likelihood
Args:
moment_update (string):
'exact' - use root finding to match sufficient statistics
'variance' - use algebra to match first two moments (faster)
decay_factor (double):
decay factor for posterior moment natural parameters
breaks (int): number of points used in numerical integration
**kwargs:
"""
# Inherit Docstrings
__doc__ += Likelihood.__doc__
# Class Variables
name = "VonMisesFisher"
def __init__(self, data, moment_update='exact', decay_factor=1.0, breaks=20,
**kwargs):
self.y = data.matrix
self.num_dim = data.num_dim
self.moment_update = moment_update
self.decay_factor = decay_factor
if not isinstance(breaks, int):
raise TypeError("breaks must be an int")
self.breaks = breaks
super(VonMisesFisherLikelihood, self).__init__(data, **kwargs)
return
def deepcopy(self):
""" Return a copy """
other = type(self)(data = self.data,
moment_update=self.moment_update,
decay_factor=self.decay_factor,
breaks=self.breaks,
theta_prior=self.theta_prior)
other.parameter = self.parameter.deepcopy()
other.prior = self.prior.deepcopy()
return other
def _get_default_prior(self):
theta_prior = VonMisesFisherProdGammaFamily(
num_dim = self.num_dim,
mean=np.ones(self.num_dim)/np.sqrt(self.num_dim) * 1e-9,
alpha_minus_one=1.0,
beta=0.1,
)
return theta_prior
def _get_default_parameters(self):
"""Returns default parameters dict"""
default_parameter = {}
return default_parameter
def _get_default_parameters_prior(self):
"""Returns default parameters prior dict"""
prior = {}
return prior
def _sample_from_prior(self):
parameter = {}
return parameter
def loglikelihood(self, index, theta):
y_index = self.y[index]
order = (0.5 * self.num_dim - 1)
loglikelihood = theta['concentration'] * theta['mean'].dot(y_index) + \
order * np.log(theta['concentration']) + \
-0.5*self.num_dim*np.sqrt(2*np.pi) + \
-amos_asymptotic_log_iv(order, theta['concentration'])
return loglikelihood
def collapsed(self, index, subset_indices, theta_parameter):
raise NotImplementedError("collapsed likelihood not implemented")
def ep_loglikelihood(self, index, theta_parameter):
approx_loglikelihood = 0.0
y_index = self.y[index]
cavity_posterior = theta_parameter
kappas = cavity_posterior._get_concentration_quantiles(
breaks=self.breaks)
weights = cavity_posterior._get_concentration_quantile_weights(kappas)
site_logpart = cavity_posterior._get_concentration_logpartitions(kappas)
cavity_logpart = cavity_posterior._get_concentration_logpartitions(
kappas * np.linalg.norm(
cavity_posterior.natural_parameters['mean']
)
)
post_approx_logpart = cavity_posterior._get_concentration_logpartitions(
kappas * np.linalg.norm(
y_index + cavity_posterior.natural_parameters['mean']
)
)
approx_loglikelihood = logsumexp(
post_approx_logpart - site_logpart - cavity_logpart,
weights)
return approx_loglikelihood
def moment(self, index, theta_parameter):
y_index = self.y[index]
kappas = theta_parameter._get_concentration_quantiles(
breaks=self.breaks)
weights = theta_parameter._get_concentration_quantile_weights(kappas)
site_logpart = theta_parameter._get_concentration_logpartitions(kappas)
cavity_logpart = theta_parameter._get_concentration_logpartitions(
kappas * np.linalg.norm(
theta_parameter.natural_parameters['mean']
)
)
post_approx_logpart = theta_parameter._get_concentration_logpartitions(
kappas * np.linalg.norm(
y_index + theta_parameter.natural_parameters['mean']
)
)
logparts = post_approx_logpart - site_logpart - cavity_logpart
# Calculate Sufficient Statistic Moments
logpartition = logsumexp(logparts, weights)
mean_kappa = np.exp(
logsumexp(logparts, weights * kappas) -
logpartition
)
mean_kappa_2 = np.exp(
logsumexp(logparts, weights * kappas**2) -
logpartition
)
var_kappa = mean_kappa_2 - mean_kappa**2
if np.isnan(mean_kappa) or mean_kappa < 0:
raise ValueError("Invalid Mean_Kappa")
# Convert Moments to Alpha + Beta
if self.moment_update == 'exact':
mean_log_kappa = np.exp(
logsumexp(logparts, weights * np.log(kappas)) -
logpartition
)
beta0 = mean_kappa / var_kappa
alpha0 = mean_kappa * beta0
def fun(x):
return (scipy.special.digamma(x) - np.log(x) +
np.log(mean_kappa) - mean_log_kappa)
alpha = root(fun, alpha0).x[0]
beta = alpha/mean_kappa
elif self.moment_update == 'variance':
beta = mean_kappa / var_kappa
alpha = mean_kappa * beta
else:
raise ValueError("Unrecognized moment_update `{0}`".format(
self.moment_update))
# Apply Decay Factor
if self.decay_factor < 1.0:
alpha_minus_one_diff = (alpha - 1) - \
theta_parameter.natural_parameters['alpha_minus_one']
beta_diff = beta - \
theta_parameter.natural_parameters['beta']
alpha = (self.decay_factor * alpha_minus_one_diff) + 1 + \
theta_parameter.natural_parameters['alpha_minus_one']
beta = (self.decay_factor * beta_diff) + \
theta_parameter.natural_parameters['beta']
# Return post approx
unnormalized_post_approx = theta_parameter.copy()
unnormalized_post_approx.natural_parameters['mean'] += y_index
unnormalized_post_approx.natural_parameters['alpha_minus_one'] = \
(alpha - 1.0) * self.decay_factor
unnormalized_post_approx.natural_parameters['beta'] = \
beta * self.decay_factor
unnormalized_post_approx.log_scaling_coef = logpartition
return unnormalized_post_approx
def sample(self, indices, prior_parameter):
raise NotImplementedError("sample theta not implemented")
def update_parameters(self, z, theta, parameter_name = None):
if parameter_name is not None:
raise ValueError("Unrecognized parameter_name: " + parameter_name)
return
def update_local_parameters(self, k, z, theta, parameter_name = None):
if parameter_name is not None:
raise ValueError("Unrecognized parameter_name: " + parameter_name)
return
<file_sep>/ep_clustering/exp_family/_constructor.py
import ep_clustering.exp_family
def construct_exponential_family(name, num_dim, **kwargs):
""" Construct exponential family site approximation by name
Args:
name (string): name of exponential family:
* NormalFamily
* DiagNormalFamily
num_dim (int): dimension of exponential family
**kwargs: arguments to pass to the exponential family constructor
Returns:
expfam (ExponentialFamily): the appropriate exponential family subclass
"""
if(name == "NormalFamily"):
return exp_family.NormalFamily(num_dim=num_dim, **kwargs)
elif(name == "DiagNormalFamily"):
return exp_family.DiagNormalFamily(num_dim=num_dim, **kwargs)
else:
raise ValueError("Unrecognized name {0}".format(name))
return
<file_sep>/experiments/synthetic_mixture_compare_example.py
# Script to get familiar with the code-base API
import matplotlib as mpl
mpl.use('Agg')
import os
import time
import numpy as np
import pandas as pd
import joblib
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import ep_clustering as ep
from tqdm import tqdm # Progress Bar
# Make Paths to output/figures
path_to_fig = "output/synth_mixture_compare_examples/figures"
path_to_data = "output/synth_mixture_compare_examples/data"
if not os.path.isdir(path_to_fig):
os.makedirs(path_to_fig)
if not os.path.isdir(path_to_data):
os.makedirs(path_to_data)
######################################################
# Generate Synthetic Data (Robust Clustering)
######################################################
np.random.seed(1234)
mean_scale=5
df=5
df_scale=0.001
data_param = dict(
num_dim=2, # Number of dimensions
num_obs=600, # Number of observations
K=8, # Number of clusters
component_type='student_t', # e.g. 'diag_gaussian', 'mix_gaussian', etc
component_prior={'mean_sd': np.ones(2)* mean_scale,
'df_alpha': df/df_scale, 'df_beta': 1.0/df_scale},
)
data_gen = ep.data.MixtureDataGenerator(**data_param)
data = data_gen.generate_data()
## Plot and Save Data
def plot_2d_data(data, z=None, x0=0, x1=1, ax=None):
cp = sns.color_palette("husl", n_colors=data.K)
if ax is None:
fig = plt.figure()
ax = plt.subplot(1,1,1)
if z is None:
z = data.z
for k in range(data.K):
ind = (z == k)
ax.plot(data.matrix[ind,x0], data.matrix[ind,x1], "o",
alpha=0.5, color=cp[k], label="z={0}".format(k))
ax.legend()
ax.set_title("X{1} vs X{0}".format(x0, x1))
return ax
# Plot Data
fig, ax = plt.subplots(1,1)
plot_2d_data(data, ax=ax)
fig.savefig(os.path.join(path_to_fig, "true_data.png"))
# Save Data
joblib.dump(data, filename=os.path.join(path_to_data, "data.p"))
######################################################
# Define Samplers to Fit
######################################################
# Student-T-Mixture
likelihood = ep.construct_likelihood(
name="StudentT",
data=data,
df=df,
)
# Number of Clusters to infer
K=data['K']
# Shared Random Init
init_z = ep.gibbs.random_init_z(N=data['num_obs'], K=K)
# Naive Gibbs
print("Setup Naive Gibbs Sampler")
naive_alg = ep.construct_approx_algorithm(
name="naive",
separate_likeparams=True,
)
naive_sampler = ep.GibbsSampler(
data=data,
likelihood=likelihood.deepcopy(),
approx_alg=naive_alg,
K=K,
z_prior_type="fixed",
init_z=init_z,
)
# Blocked Gibbs
print("Setup Blocked Gibbs Sampler")
block_alg = ep.construct_approx_algorithm(
name="collapsed",
separate_likeparams=True,
)
block_sampler = ep.GibbsSampler(
data=data,
likelihood=likelihood.deepcopy(),
approx_alg=block_alg,
K=K,
z_prior_type="fixed",
init_z=init_z,
)
# EP Gibbs
print("Setup EP Gibbs Sampler")
EP_alg = ep.construct_approx_algorithm(
name="EP",
exp_family=ep.exp_family.NormalWishartFamily,
damping_factor=0.0, #0.0001,
separate_likeparams=True,
)
EP_sampler = ep.GibbsSampler(
data=data,
likelihood=likelihood.deepcopy(),
approx_alg=EP_alg,
K=K,
full_mcmc=False, # Do not need to sample latent variables u with EP
z_prior_type="fixed",
init_z=init_z,
)
######################################################
# Define Evaluation
######################################################
metric_functions = [
ep.evaluator.metric_function_from_sampler("eval_loglikelihood"),
ep.evaluator.metric_function_from_state("z", data.z, "nvi"),
ep.evaluator.metric_function_from_state("z", data.z, "nmi"),
ep.evaluator.metric_function_from_state("z", data.z, "precision"),
ep.evaluator.metric_function_from_state("z", data.z, "recall"),
]
evaluators = [
ep.GibbsSamplerEvaluater(
sampler=naive_sampler,
metric_functions=metric_functions,
sampler_name="NaiveGibbs",
data_name="simple_example",
),
ep.GibbsSamplerEvaluater(
sampler=block_sampler,
metric_functions=metric_functions,
sampler_name="BlockedGibbs",
data_name="simple_example",
),
ep.GibbsSamplerEvaluater(
sampler=EP_sampler,
metric_functions=metric_functions,
sampler_name="EPGibbs",
data_name="simple_example",
),
]
######################################################
# Comparison Plot Helper Functions
######################################################
def plot_metric_vs_iteration(evaluators, metric="nmi"):
fig, ax = plt.subplots(1,1)
max_iter = []
for evaluator in evaluators:
nmi = evaluator.metrics.query('metric == "nmi"')
ax.plot(nmi.iteration, nmi.value, label=evaluator.sampler_name)
max_iter.append(nmi.iteration.max())
ax.set_xlim([0, min(max_iter)])
ax.set_xlabel('Iteration (epoch)')
ax.set_ylabel(metric)
ax.legend()
return fig, ax
def plot_metric_vs_time(evaluators, metric="nmi"):
fig, ax = plt.subplots(1,1)
max_time = []
for evaluator in evaluators:
nmi = evaluator.metrics.query('metric == "nmi"')
time = evaluator.metrics.query('metric == "time"')
ax.plot(time.value.cumsum(), nmi.value, label=evaluator.sampler_name)
max_time.append(time.value.sum())
ax.set_xlim([0, min(max_time)])
ax.set_xlabel('Time (sec)')
ax.set_ylabel(metric)
ax.legend()
return fig, ax
######################################################
# Run Each Method
######################################################
MAX_TIME = 300 # Max time for each algorithm
EVAL_TIME = 30 # Time between evaluations
evaluator_times = [0 for _ in evaluators]
print("Running Each Sampler")
while np.any([evaluator_time < MAX_TIME for evaluator_time in evaluator_times]):
for ii in range(len(evaluators)):
if evaluator_times[ii] >= MAX_TIME:
continue
start_time = time.time()
while (time.time() - start_time) < EVAL_TIME:
evaluators[ii].evaluate_sampler_step(['one_step'])
evaluator_times[ii] += time.time()-start_time
inference_time = evaluators[ii].metrics.query("metric == 'time'")['value'].sum()
print("Sampler {0}, inference time {1}, total time {2}".format(
evaluators[ii].sampler_name, inference_time, evaluator_times[ii])
)
evaluators[ii].get_metrics().to_pickle(os.path.join(path_to_data,
"{0}_metrics.p".format(evaluators[ii].sampler_name)))
# Comparision Plots
plt.close('all')
plot_metric_vs_time(evaluators, metric='nmi')[0].savefig(
os.path.join(path_to_fig, 'nmi_vs_time.png'))
plot_metric_vs_iteration(evaluators, metric='nmi')[0].savefig(
os.path.join(path_to_fig, 'nmi_vs_iter.png'))
<file_sep>/ep_clustering/README.md
README for `ep_clustering` python module code.
## Files
* `gibbs.py` provides the `GibbsSampler` class.
* `approx_algorithm.py` provides the `ApproxAlgorithm` base class and `NaiveAlgorithm`, `CollapsedAlgorithm`, and `EPAlgorithm` child classes.
* `likelihoods/` provides the `Likelihood` classes for the various models.
* `data/` provides synthetic dataset generation code.
* `exp_family/` provides exponential family code for Bayesian inference.
* `evaluator/` provides a wrapper class for running and evaluating Gibbs samplers.
* `kalman_filter/` provides Kalman filter code for the time series models.
This is old (over-engineered) code from the beginning of my PhD that has been ported from python2.7 to python 3+.
There are no guarantees that anything beyond the correlated time series clustering and robust mixture model examples work.
## Usage Example
See `experiments/synthetic_timeseries_clustering_example.py` and `experiments/synthetic_mixture_clustering_example.py` for an overview of the API.
| 63df49317f5ef093e572c3cb8cd635c2e74ef09a | [
"Markdown",
"Python"
] | 37 | Python | PeiKaLunCi/EP_Collapsed_Gibbs | 3b2e8c3addeab2343837b9e86e9cb57b00798b9a | e4015b9b1dbef8b80a837146794dd71e32ee2c30 |
refs/heads/master | <repo_name>erjohnso/gcelb-demo<file_sep>/install.sh
#!/bin/bash
# This script assumes that Debian-7 wheezy Compute Engine images are used
#
# Prior to using this install script, please execute
# $ sudo apt-get update && sudo apt-get upgrade -y
# $ sudo apt-get install git apache2 -y
#sudo DEBIAN_FRONTEND=noninteractive apt-get update
#sudo DEBIAN_FRONTEND=noninteractive apt-get upgrade -y >/dev/null 2>&1
pushd `dirname $0` > /dev/null
MY_PATH=`pwd`
popd > /dev/null
NAME=$(hostname -s)
echo "=> Copying HTML files, apache2.conf, enable mod-header, and restarting"
sudo cp $MY_PATH/index.html /var/www/html/
sudo sed -i "s|@MY_INSTANCE_NAME@|$NAME|" /var/www/html/index.html
sudo chmod 644 /var/www/html/index.html
sudo cp $MY_PATH/apache2.conf /etc/apache2/apache2.conf
sudo ln -s /etc/apache2/mods-available/headers.load /etc/apache2/mods-enabled/headers.load
sudo service apache2 restart
exit 0
<file_sep>/README.md
## Google Compute Engine Load-Balancer Demo
This repo is a place to park my GCELB demo code. It requires a bit of
customization for each demo, but I've used it with Puppet and SaltStack.
General idea is to create 4 GCE `Debian-7` instances, install these files
on each instance, put them behind a GCELB, and then hit the LB's public IP
with your browser to test. The page to be fetched again (without caching)
and will flip between the 4 instances (each with it's own Google primary
color).
For this demo to truly work dynamically, it is ideal for each `index.html`
page's title be set to `<title>instance_shortname</title>`. If you use the
actual shortnames of `myinstance{1..4}`, then the `if-else` javascript
statements do not need to be updated.
As an example, during the SaltConf demo, when I dropped down the `index.html`
file, I used `<title>{{ grains.id }}</title>` and as the file was being
written to the instance, the jinja2 processing replace `{{ grains.id }}`
with that instance's short hostname.
The actual title-element for the `index.html` page is @MY_INSTANCE_NAME@
and a sed command can be used to replace that with the local instance's
short hostname. For example,
```sh
NAME=$(hostname -s)
sed -i "s|@MY_INSTANCE_NAME@|$NAME|" /var/www/index.html
```
### Install
1. Make sure your GCE `network` has `tcp:80` open
1. Use some tool-specific (demo) automated way to spin up 4 `Debian-7`
instances, preferably two per zone in the same region.
1. When the instances are created, install apache2 overwrite the package's
`/etc/apache2/apache2.conf` file with this custom `apache2.conf` file.
1. Make sure that the installation of apache also enables `mod_headers`
(e.g. `/etc/apache2/mods-enabled`). The custom `apache2.conf` includes
`mod_header` directives to disable client-side caching with custom
headers (lines 264-272).
1. Next, copy over the `index.html` and `demo.css` files to apache's root
directory, typically `/var/www`.
1. Create the GCELB and place all 4 instances in the GCELB's `TargetPool`.
Set its `ForwardingRule` to forward `tcp:80` traffic to the `TargetPool`.
### Test / Usage
1. Point your browser to `http://a.b.c.d` and you should see a page served
from one of your instances.
1. If all goes well, the javascript `location.reload(true)` function should
be triggered onLoad and you'll see the browser flip between all four
instances with separate Google colors.
### Troubleshooting
1. Check the HTTP headers to ensure that client-side caching is indeed
disabled. Using `curl -I http://a.b.c.d`, you should see headers like
`Cache-Control: "max-age=0, no-cache, no-store, must-revalidate"`,
`Pragma: "no-cache"`, and `Expires: "Wed, 11 Jan 2010 05:00:00 GMT"`.
1. If your instance's background color is white and you are dynamically
updating the `index.html` title, make sure the javascript code's
`if-else` block is using the correct instance names for setting the page
background color. The default is to use `myinstance{1..4}` for the
instance names.
<file_sep>/curl-loop.sh
#!/bin/bash
# usage: curl-loop.sh GCELB-IPAddress
if [ -n "$1" ]; then
while [ 1 ]
do
curl -s http://$1
sleep .5
done
fi
echo "usage: curl-loop.sh IP-address"
exit 1
| 4a8322b42b340a174126a0bf23f255d83c65d0f0 | [
"Markdown",
"Shell"
] | 3 | Shell | erjohnso/gcelb-demo | 5f32bb9a7f8e0c80b8f41d05a79ebdd71ef454ff | 501ecc901810205547bb44a6876207443e855c42 |
refs/heads/master | <repo_name>Dutchman101/mass-trailingspace-trimmer<file_sep>/src/nl/dutchman/spacetrimmer/launcher/Launcher.java
package nl.dutchman.spacetrimmer.launcher;
import nl.dutchman.spacetrimmer.ui.WindowController;
public class Launcher
{
public static void main(String[] args)
{
try
{
WindowController windowController = new WindowController();
windowController.display();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
<file_sep>/README.md
# Trailing space trimmer
This JAVA application allows you to trim trailing spaces and empty tabs over a whole project.
It's able to get rid of all trailing spaces for all code files in a directory and its subdirectories, so you could work on a whole repository at once.
All programming languages are supported, you can input a comma-separated list of code-file extensions into the app's GUI, so that all matching files are included in the operation.
Definition of GUI option 1 ("Remove trailing spaces/tabs"):
- remove whitespaces at the end of a line consisting of empty character spaces (no loss of indent or style)
- actual tabs/spaces content in empty lines (it won't delete the empty lines itself, only bring it back to 0 bytes)
[Example] See below image for the effects of this option:
[img] https://i.imgur.com/7jLMMlk.png
Definition of GUI option 2 ("Remove excessive empty lines"):
- Particular locations with more than 3 empty lines, will be brought back to 2 lines. Such lines are often separator spaces between code/function blocks, and grow inconsistent over the lifespan of a project.
[Example] See below image for the effects of this option:
[img] https://i.imgur.com/cu46f7E.png
The stable, multi-threaded approach and progress bar, should allow you to work on an high amount of files simultaneously and large repositories.
This is freeware and free to use for private and commercial purposes, change the license of, (re)distribute, compile and modify on private and corporate level. There are no restrictions.
GUI interface:
https://i.imgur.com/QL6asxH.png
Processing the 1100 files in above example GUI image, took just under 3 seconds of execution time.
It should speak for itself, but if you have any specific demands, you can simply edit the source and recompile the app.
Also feel free to submit pull requests!<file_sep>/src/nl/dutchman/spacetrimmer/ui/MainWindow.java
package nl.dutchman.spacetrimmer.ui;
import javax.swing.*;
import java.awt.*;
public class MainWindow extends JFrame
{
public static final int WIDTH = 800, HEIGHT = 600;
private JPanel contentPane;
private JPanel consoleContainer;
private JScrollPane consoleScrollContainer;
private JTextPane consoleArea;
private JPanel interfaceContainer;
private JPanel directoryContainer;
private JPanel optionsContainer;
private JPanel utilityContainer;
private JButton directoryButton;
private JTextField directoryField;
private JPanel processContainer;
private JButton processButton;
private JPanel progressContainer;
private JPanel statusContainer;
private JLabel statusLabel;
private JLabel statusIcon;
private JLabel threadsLabel;
private JLabel currentLabel;
private JProgressBar progressBar;
private JCheckBox endTrimCheckbox;
private JCheckBox emptyLineCheckBox;
private JPanel fileFormatContainer;
private JLabel fileFormatLabel;
private JTextField fileFormatField;
public JTextPane getConsoleArea() { return consoleArea; }
public JButton getDirectoryButton() { return directoryButton; }
public JTextField getDirectoryField() { return directoryField; }
public JButton getProcessButton() { return processButton; }
public JLabel getStatusLabel() { return statusLabel; }
public JLabel getStatusIcon() { return statusIcon; }
public JLabel getThreadsLabel() { return threadsLabel; }
public JLabel getCurrentLabel() { return currentLabel; }
public JProgressBar getProgressBar() { return progressBar; }
public JCheckBox getEndTrimCheckbox() { return endTrimCheckbox; }
public JCheckBox getEmptyLineCheckBox() { return emptyLineCheckBox; }
public JTextField getFileFormatField() { return fileFormatField; }
public MainWindow()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(WIDTH, HEIGHT);
this.setLocationRelativeTo(null);
this.setContentPane(contentPane);
this.setIconImage(Toolkit.getDefaultToolkit().getImage(MainWindow.class.getResource("/nl/dutchman/spacetrimmer/resources/icon.png")));
this.setTitle("Space Trimmer - Remove trailing spaces/empty lines");
this.setResizable(false);
this.consoleArea.setFont(new Font("Consolas", Font.PLAIN, 12));
this.consoleArea.setEditable(false);
this.endTrimCheckbox.setSelected(true);
this.emptyLineCheckBox.setSelected(true);
}
}
| 2a86d5e7e36d56ea83267b751a1131217897fb6f | [
"Markdown",
"Java"
] | 3 | Java | Dutchman101/mass-trailingspace-trimmer | 81f1db5c28541ff87a4a63410826f6d60a6c9331 | 4185f69a76e38d31b5b5150294d8af637c2ac9fd |
refs/heads/master | <file_sep><?php
/*
* url format: http://dlevine.us/phptest/numsort/sorter.php?numbers=5,1,2,1,7,3
*
* Compare each number to all other numbers in the array
* Push larger numbers to the end
* Push smaller numbers to the ordered array
* Push the last number to the ordered array (should be the largest)
*/
/*Let's get some stuff straight*/
$numbers = $_GET['numbers'] = isset($_GET['numbers']) ? $_GET['numbers'] : "";
$numbers = str_replace(" ", "", $numbers);
$numbers = explode(",", $numbers);
$numberslength = count($numbers);
$ordered = array();
$counter = 1;
/*Use this to print out to screen*/
function showDebugLog($arrayOne, $arrayTwo){
$numberslength= $GLOBALS['numberslength'];
$counter = $GLOBALS['counter'];
if(!isset($arrayOne[$counter])){$counter=0;}
echo "Input Numbers: <br>";
print_r($arrayOne);
//echo "<br><br>$arrayOne[0] compared to $arrayOne[$counter]";
echo "<br><br>Re-ordered Numbers: <br>";
print_r($arrayTwo);
echo "<!--<br><br>Remaining Numbers: " . --$numberslength . "<br>--><hr>";
}
//showDebugLog($numbers, $ordered); //Print for debugging
foreach ($numbers as $element) {
if (!is_numeric($element)) {
array_push($ordered, "Please enter numbers.");
$ordered = json_encode($ordered);
echo ($ordered);
exit(0);
}
}
/*Here's where the magic happens*/
while($numberslength > 0){
if($numberslength == 1){
array_push($ordered, $numbers[0]);
unset($numbers[0]);
$numbers = array_values($numbers);
} elseif($numbers[0] < $numbers[$counter]){
if($counter < $numberslength-1){
$counter += 1;
} else {
array_push($ordered, $numbers[0]);
unset($numbers[0]);
$numbers = array_values($numbers);
$counter = 1;
//showDebugLog($numbers, $ordered); //Print for debugging
}
}
else{
$moveToEnd = $numbers[0];
unset($numbers[0]);
array_push($numbers, $moveToEnd);
$numbers = array_values($numbers);
}
$numberslength = count($numbers);
}
/*Send final output to json*/
$ordered = json_encode($ordered);
echo ($ordered);
?>
<file_sep># Number_sorter
Ajax and PHP code exercise to sort a set of numbers from the users input by looping through each number and checking if it's the smallest number in the array, if it's not we push it to the end and keep going, if it is we move it to a new array.
<file_sep><?php
// ini_set('display_startup_errors',1);
// ini_set('display_errors',1);
// error_reporting(-1);
/*
* url format: http://dlevine.us/phptest/numsort/sorter.php?numbers=5,1,2,1,7,3
*/
//Get the numbers
$numbers = $_GET['numbers'] = isset($_GET['numbers']) ? $_GET['numbers'] : "";
//Make sure there are no spaces
$numbers = str_replace(" ", ",", $numbers);
//Explore to array
$numbers = explode(",", $numbers);
//How many items are there?
$numberslength = count($numbers);
$ordered = array();
$counter = 1; // count our position
function showDebugLog($arrayOne, $arrayTwo){
$numberslength= $GLOBALS['numberslength'];
$counter = $GLOBALS['counter'];
if(!isset($arrayOne[$counter])){$counter=0;}
echo "Input Numbers: <br>";
print_r($arrayOne);
//echo "<br><br>$arrayOne[0] compared to $arrayOne[$counter]";
echo "<br><br>Re-ordered Numbers: <br>";
print_r($arrayTwo);
echo "<!--<br><br>Remaining Numbers: " . --$numberslength . "<br>--><hr>";
}
//showDebugLog($numbers, $ordered); //Print for debugging
/*
* Compare each number to all other numbers in the array
* Push larger numbers to the end
* Push smaller numbers to the ordered array
* Push the last number to the ordered array (should be the largest)
*/
foreach ($numbers as $element) {
if (!is_numeric($element)) {
array_push($ordered, "Please enter numbers.");
$ordered = json_encode($ordered);
echo ($ordered);
exit(0);
}
}
//Make sure something is in the array
while($numberslength > 0){
//If an array only has one item just push it
if($numberslength == 1){
//Push it to ordered
array_push($ordered, $numbers[0]);
// Remove it from the input array
unset($numbers[0]);
//Evaluate input array (make sure nothing is left)
$numbers = array_values($numbers);
//Break
//If the number is not the last one
//evaluate to see if it's the smallest
} elseif($numbers[0] < $numbers[$counter]){//Is it smaller than the next number
if($counter < $numberslength-1){//If it is check to see if the next number is the last number
$counter += 1; //If there's more than 2 numbers remaining keep checking
//if this number is the smallest in the group push it to the ordered array
} else {
array_push($ordered, $numbers[0]); //Push it
unset($numbers[0]); //Remove from the original array
$numbers = array_values($numbers); //Re-evaluate the original array
$counter = 1; //Reset the counter
//showDebugLog($numbers, $ordered); //Print for debugging
}
}
else{ //If the number is NOT the smallest in the group
//move it to the end
$moveToEnd = $numbers[0]; //Store this number to a variable
unset($numbers[0]); //Remove it from the original array
array_push($numbers, $moveToEnd); //Push it to the end
$numbers = array_values($numbers); //Re-evaluate it
}
$numberslength = count($numbers); //Re-evaluate the length of numbers
}
//echo "<br> Final Order: "; print_r($ordered); echo "<br> Encode as json: ";
$ordered = json_encode($ordered);
echo ($ordered);
?>
| dfb7cfc5d939730e72e25cebd58ef48a065d1aac | [
"Markdown",
"PHP"
] | 3 | PHP | djlevine/Number_sorter | 8a5b5b78d7a4513580f4509dbc682e44aab4450f | b38edd3e0763608b37963240e4d4486a9d06ac66 |
refs/heads/master | <repo_name>anais0210/toovalu<file_sep>/src/Entity/Testimonial.php
<?php
namespace App\Entity;
use App\Repository\TestimonialRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\IdGenerator\UuidV4Generator;
use Symfony\Component\Uid\UuidV4;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Class Testimonial
*
* @author <NAME> <<EMAIL>>
* @ORM\Entity(repositoryClass=TestimonialRepository::class)
*/
class Testimonial
{
/**
* @var string
* @ORM\Id
* @ORM\Column(type="uuid", unique=true)
* @ORM\GeneratedValue(strategy="CUSTOM")
* @ORM\CustomIdGenerator(class=UuidV4Generator::class)
*/
private $id = UuidV4::class;
/**
* @var string
* @ORM\Column(type="string", length=255)
* @Assert\NotNull(
* message = "Ce champ ne peut pas être vide"
* )
* @Assert\Length(
* min = 2,
* max = 255,
* minMessage = "L'entreprise doit avoir au minimum {{ limit }} caractères",
* maxMessage = "L'entreprise doit avoir au maximum {{ limit }} caractères"
* )
*/
private $compagny;
/**
* @var string
* @ORM\Column(type="string", length=255)
* @Assert\NotNull(
* message = "Ce champ ne peut pas être vide"
* )
* @Assert\Length(
* min = 2,
* max = 255,
* minMessage = "Le métier doit avoir au minimum {{ limit }} caractères",
* maxMessage = "Le métier doit avoir au maximum {{ limit }} caractères"
* )
*/
private $job;
/**
* @var string
* @ORM\Column(type="string", length=255)
* @Assert\NotNull(
* message = "Ce champ ne peut pas être vide"
* )
* @Assert\Length(
* min = 2,
* max = 255,
* minMessage = "Le nom doit avoir au minimum {{ limit }} caractères",
* maxMessage = "Le nom doit avoir au maximum {{ limit }} caractères"
* )
*/
private $name;
/**
* @var string
* @ORM\Column(type="text")
* @Assert\NotNull(
* message = "Ce champ ne peut pas être vide"
* )
* @Assert\Length(
* min = 20,
* max = 600,
* minMessage = "Le témoignage doit avoir au minimum {{ limit }} caractères",
* maxMessage = "Le témoignage doit avoir au maximum {{ limit }} caractères"
* )
*/
private $content;
/**
* @return string
*/
public function getId(): string
{
return $this->id;
}
/**
* @return string|null
*/
public function getCompagny(): ?string
{
return $this->compagny;
}
/**
* @param string $compagny
* @return $this
*/
public function setCompagny(string $compagny): self
{
$this->compagny = $compagny;
return $this;
}
/**
* @return string|null
*/
public function getJob(): ?string
{
return $this->job;
}
/**
* @param string $job
* @return $this
*/
public function setJob(string $job): self
{
$this->job = $job;
return $this;
}
/**
* @return string|null
*/
public function getName(): ?string
{
return $this->name;
}
/**
* @param string $name
* @return $this
*/
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* @return string|null
*/
public function getContent(): ?string
{
return $this->content;
}
/**
* @param string $content
* @return $this
*/
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
}
<file_sep>/src/Entity/Author.php
<?php
namespace App\Entity;
use App\Repository\AuthorRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\IdGenerator\UuidV4Generator;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\UuidV4;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Class Author
*
* @author <NAME> <<EMAIL>>
* @ORM\Entity(repositoryClass=AuthorRepository::class)
*/
class Author
{
/**
* @var string
* @ORM\Id
* @ORM\Column(type="uuid", unique=true)
* @ORM\GeneratedValue(strategy="CUSTOM")
* @ORM\CustomIdGenerator(class=UuidV4Generator::class)
*/
private $id = UuidV4::class;
/**
* @var string
* @ORM\Column(type="string", length=255, nullable=false)
* @Assert\Length(
* min = 2,
* max = 255,
* minMessage = "Le nom de l'auteur doit avoir au minimum {{ limit }} caractères",
* maxMessage = "Le nom de l'auteur doit avoir au maximum {{ limit }} caractères"
* )
*/
private string $firstName;
/**
* @var string
* @ORM\Column(type="string", length=255, nullable=false)
* @Assert\Length(
* min = 2,
* max = 255,
* minMessage = "Le prénom de l'auteur doit avoir au minimum {{ limit }} caractères",
* maxMessage = "Le prénom de l'auteur doit avoir au maximum {{ limit }} caractères"
* )
*/
private string $lastName;
/**
* @var ArrayCollection
* @ORM\OneToMany(targetEntity=Article::class, mappedBy="author")
*/
private $article;
/**
* Author constructor.
*/
public function __construct()
{
$this->article = new ArrayCollection();
}
/**
* @return string
*/
public function getId(): string
{
return $this->id;
}
/**
* @return string|null
*/
public function getFirstName(): ?string
{
return $this->firstName;
}
/**
* @param string|null $firstName
* @return $this
*/
public function setFirstName(?string $firstName): self
{
$this->firstName = $firstName;
return $this;
}
/**
* @return string|null
*/
public function getLastName(): ?string
{
return $this->lastName;
}
/**
* @param string|null $lastName
* @return $this
*/
public function setLastName(?string $lastName): self
{
$this->lastName = $lastName;
return $this;
}
/**
* @return Collection|Article[]
*/
public function getArticle(): Collection
{
return $this->article;
}
/**
* @param Article $article
* @return $this
*/
public function addArticle(Article $article): self
{
if (!$this->article->contains($article)) {
$this->article[] = $article;
$article->setAuthor($this);
}
return $this;
}
/**
* @param Article $article
* @return $this
*/
public function removeArticle(Article $article): self
{
if ($this->article->removeElement($article)) {
if ($article->getAuthor() === $this) {
$article->setAuthor(null);
}
}
return $this;
}
/**
* @return string
*/
public function __toString()
{
return $this->getFullUsername();
}
/**
* @return string
*/
public function getFullUsername(): string
{
return $this->firstName . ' ' . ' ' . $this->lastName;
}
}
<file_sep>/Makefile
# --------------------------------------------------------------------
# PROJECT
# --------------------------------------------------------------------
project: composer-install symfony-clear-cache docker-start console-doctrine-database-drop console-doctrine-database-create console-doctrine-schema-update fixtures
project-start: composer-install symfony-clear-cache docker-start
project-stop: docker-stop
project-restart: project-stop project-start
project-rebuild: composer-install symfony-clear-cache docker-rebuild
# --------------------------------------------------------------------
# DOCKER
# --------------------------------------------------------------------
docker-start:
docker-compose -f docker-compose.yml up -d --build
docker-stop:
docker-compose -f docker-compose.yml stop
docker-rebuild: docker-clean-containers docker-start
docker-clean-containers: docker-stop
docker-compose -f docker-compose.yml rm --force
docker-clean-images:
docker rmi $$(docker images -q)
# --------------------------------------------------------------------
# SYMFONY
# --------------------------------------------------------------------
symfony-clear-cache:
rm -rf ./var/cache/*
rm -rf ./var/log/*
php bin/console cache:clear --no-warmup
# --------------------------------------------------------------------
# COMPOSER
# --------------------------------------------------------------------
composer-install:
rm -rf ./vendor/*
composer install
composer:
docker exec -ti php_apache_symfony bash
# --------------------------------------------------------------------
# CONSOLE
# --------------------------------------------------------------------
console-doctrine-database-create:
docker exec -ti php_apache_symfony php bin/console doctrine:database:create
console-doctrine-database-drop:
docker exec -ti php_apache_symfony php bin/console doctrine:database:drop --force
console-doctrine-schema-update:
docker exec -ti php_apache_symfony php bin/console doctrine:schema:update --force
# --------------------------------------------------------------------
# QUALITY
# --------------------------------------------------------------------
phpStan:
docker exec -ti php_apache_symfony vendor/bin/phpstan analyse -l 5 src
phpPsalm:
docker exec -ti php_apache_symfony vendor/bin/psalm
phpCs:
docker exec -ti php_apache_symfony ./vendor/bin/phpcs
phpCbf:
docker exec -ti php_apache_symfony vendor/bin/phpcbf
# --------------------------------------------------------------------
# Fixtures
# --------------------------------------------------------------------
fixtures:
docker exec -ti php_apache_symfony php bin/console doctrine:fixtures:load -q
# --------------------------------------------------------------------
# TESTS BEHAT
# --------------------------------------------------------------------
# LA BASE DE DONNEE DE TEST ET STRICTEMENT LA MÊME QUE DEV
#La commande supprime la base, la recréer, lance les fixtures et les tests behat
behat: console-doctrine-database-drop console-doctrine-database-create console-doctrine-schema-update fixtures
docker exec -ti php_apache_symfony php vendor/bin/behat<file_sep>/src/Controller/Admin/TestimonialCrudController.php
<?php
namespace App\Controller\Admin;
use App\Entity\Testimonial;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
/**
* Class TestimonialCrudController
*
* @author <NAME> <<EMAIL>>
*/
class TestimonialCrudController extends AbstractCrudController
{
/**
* @return string
*/
public static function getEntityFqcn(): string
{
return Testimonial::class;
}
/**
* @param string $pageName
* @return iterable
*/
public function configureFields(string $pageName): iterable
{
return [
TextField::new('compagny', 'Entreprise'),
TextField::new('name', 'Nom et Prénom'),
TextField::new('job', 'Métier'),
TextField::new('content', 'témoignage'),
];
}
/**
* @param Actions $actions
* @return Actions
*/
public function configureActions(Actions $actions): Actions
{
return $actions
->add(Crud::PAGE_INDEX, Action::DETAIL)
->disable(Action::DETAIL, Action::SAVE_AND_ADD_ANOTHER, Action::SAVE_AND_CONTINUE)
->update(Crud::PAGE_INDEX, Action::DELETE, function (Action $action) {
return $action->setIcon('fa fa-trash-alt')->setLabel('supprimer');
})
->update(Crud::PAGE_INDEX, Action::EDIT, function (Action $action) {
return $action->setLabel('editer');
});
}
}
<file_sep>/src/Controller/Admin/EmployeeCrudController.php
<?php
namespace App\Controller\Admin;
use App\Entity\Employee;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Faker\Provider\Text;
/**
* Class EmployeeCrudController
*
* @author <NAME> <<EMAIL>>
*/
class EmployeeCrudController extends AbstractCrudController
{
/**
* @return string
*/
public static function getEntityFqcn(): string
{
return Employee::class;
}
/**
* @param string $pageName
* @return iterable
*/
public function configureFields(string $pageName): iterable
{
return [
TextField::new('firstName', 'Nom'),
TextField::new('lastName', 'Prénom'),
AssociationField::new('job', 'Métier'),
TextField::new('biography', 'Déscription'),
];
}
/**
* @param Actions $actions
* @return Actions
*/
public function configureActions(Actions $actions): Actions
{
return $actions
->disable(Action::DETAIL, Action::SAVE_AND_CONTINUE, Action::SAVE_AND_ADD_ANOTHER)
->update(Crud::PAGE_INDEX, Action::DELETE, function (Action $action) {
return $action->setIcon('fa fa-trash-alt')->setLabel('supprimer');
})
->update(Crud::PAGE_INDEX, Action::EDIT, function (Action $action) {
return $action->setIcon('fa fa-pen')->setLabel('éditer');
})
->update(Crud::PAGE_EDIT, Action::SAVE_AND_RETURN, function (Action $action) {
return $action->setLabel('sauvegarder');
})
;
}
}
<file_sep>/src/Controller/ArticleController.php
<?php
namespace App\Controller;
use App\Entity\Article;
use App\Entity\Comment;
use App\Form\CommentType;
use DateTime;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class ArticleController
*
* @author <NAME> <<EMAIL>>
* @Route("/actualites", name="actualites_")
*/
class ArticleController extends AbstractController
{
/**
* @Route("/{slug}", name="article")
* @param $slug
* @param Request $request
* @return Response
*/
public function index($slug, Request $request): Response
{
$article = $this->getDoctrine()->getRepository(Article::class)->findOneBy(['slug' => $slug]);
$comments = $this->getDoctrine()->getRepository(Comment::class)->findBy([
'article' => $article,
],['createdAt' => 'desc']);
if(!$article){
throw $this->createNotFoundException('L\'article n\'existe pas');
}
$comments = new Comment();
$form = $this->createForm(CommentType::class, $comments);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$comments->setArticle($article);
$comments->setCreatedAt(new DateTime('now'));
$em = $this->getDoctrine()->getManager();
$em->persist($comments);
$em->flush();
}
return $this->render('article/article.html.twig', [
'form' => $form->createView(),
'article' => $article,
'comments' => $comments,
]);
}
}
<file_sep>/src/Controller/Admin/AuthorCrudController.php
<?php
namespace App\Controller\Admin;
use App\Entity\Article;
use App\Entity\Author;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
/**
* Class AuthorCrudController
*
* @author <NAME> <<EMAIL>>
*/
class AuthorCrudController extends AbstractCrudController
{
/**
* @return string
*/
public static function getEntityFqcn(): string
{
return Author::class;
}
/**
* @param string $pageName
* @return iterable
*/
public function configureFields(string $pageName): iterable
{
return [
TextField::new('firstName', 'Nom'),
TextField::new('lastName', 'Prénom'),
];
}
/**
* @param Actions $actions
* @return Actions
*/
public function configureActions(Actions $actions): Actions
{
return $actions
->add(Crud::PAGE_INDEX, Action::DETAIL)
->disable(Action::DETAIL, Action::SAVE_AND_CONTINUE, Action::SAVE_AND_ADD_ANOTHER)
->update(Crud::PAGE_INDEX, Action::DELETE, function (Action $action) {
return $action->setIcon('fa fa-trash-alt')->setLabel('supprimer');
})
->update(Crud::PAGE_INDEX, Action::EDIT, function (Action $action) {
return $action->setIcon('fa fa-pen')->setLabel('éditer');
})
->update(Crud::PAGE_EDIT, Action::SAVE_AND_RETURN, function (Action $action) {
return $action->setLabel('sauvegarder');
})
;
}
/**
* @param EntityManagerInterface $entityManager
* @param $entityInstance
*/
public function deleteEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$articles = $entityManager->getRepository(Article::class)->findBy(
[
'author' => $entityInstance->getId()
]
);
if (count($articles) > 0) {
$session = $this->get('request_stack')->getCurrentRequest()->getSession();
$session->getFlashBag()->add('danger', 'Cette auteur à écrit des articles et ne peut pas être supprimé');
return;
}
parent::deleteEntity($entityManager, $entityInstance);
}
}
<file_sep>/README.md
# Projet réalisé comme "test" pour TOOVALU
### Déscription du projet
* Réalisation du site web de l'entreprise
* One page
* Formulaire de contact
* Back office d'administration
### Setup du projet
* git clone https://github.com/anais0210/toovalu.git
#### Console Command pour démarrer le projet
make project
* Le projet sera accesible à cet URL "http://0.0.0.0/"
#### Back office du site web
* Le back office sera accesible à cet URL "http://0.0.0.0/admin"
* email -> <EMAIL>
* mot de passe -> <PASSWORD>
#### Qualité du code
* make phpCs
* make phpStan
* make phpPsalm
#### Test Behat
* make behat
## TODO
* programmer la publication des articles
* compteur de vue sur les articles et le site web
* gestion des commentaires des articles
* ajout d'une page listant les articles
* lire les articles dans une page dédié
<file_sep>/src/Controller/Admin/ArticleCrudController.php
<?php
namespace App\Controller\Admin;
use App\Entity\Article;
use App\Entity\Contact;
use Doctrine\ORM\Mapping\OneToMany;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\EmailField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Vich\UploaderBundle\Form\Type\VichImageType;
use Vich\UploaderBundle\Mapping\Annotation\UploadableField;
/**
* Class ArticleCrudController
*
* @author <NAME> <<EMAIL>>
*/
class ArticleCrudController extends AbstractCrudController
{
/**
* @return string
*/
public static function getEntityFqcn(): string
{
return Article::class;
}
/**
* @param string $pageName
* @return iterable
*/
public function configureFields(string $pageName): iterable
{
return [
TextField::new('title', 'Titre'),
TextField::new('content', 'Contenu'),
DateField::new('publicationDate', 'Date de publication')
->setFormat('short'),
AssociationField::new('author', 'Auteur'),
AssociationField::new('category', 'Catégorie'),
ImageField::new('featuredImage', 'Nom de l\'image')
->setBasePath('uploads/images/articles')->onlyOnDetail(),
TextareaField::new('imageFile', 'Image')
->setFormType(VichImageType::class),
TextField::new('comment', 'Commentaires'),
];
}
/**
* @param Actions $actions
* @return Actions
*/
public function configureActions(Actions $actions): Actions
{
return $actions
->add(Crud::PAGE_INDEX, Action::DETAIL)
->disable(Action::DETAIL, Action::SAVE_AND_ADD_ANOTHER, Action::SAVE_AND_CONTINUE)
->update(Crud::PAGE_INDEX, Action::DELETE, function (Action $action) {
return $action->setIcon('fa fa-trash-alt')->setLabel('supprimer');
})
->update(Crud::PAGE_INDEX, Action::EDIT, function (Action $action) {
return $action->setLabel('editer');
});
}
}
<file_sep>/src/DataFixtures/AppFixtures.php
<?php
namespace App\DataFixtures;
use App\Entity\Article;
use App\Entity\Author;
use App\Entity\Category;
use App\Entity\Contact;
use App\Entity\Job;
use App\Entity\Employee;
use App\Entity\Testimonial;
use App\Entity\User;
use bheller\ImagesGenerator\ImagesGeneratorProvider;
use DateTime;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Validator\Constraints\Date;
use Faker;
/**
* Class AppFixtures
*
* @author <NAME> <<EMAIL>>
*/
class AppFixtures extends Fixture
{
private $passwordEncoder;
/**
* AppFixtures constructor.
* @param UserPasswordEncoderInterface $passwordEncoder
*/
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
/**
* @param ObjectManager $manager
*/
public function load(ObjectManager $manager): void
{
$faker = Faker\Factory::create('fr_FR');
$contact = [];
for ($i = 0; $i < 8; $i++) {
$contact [$i] = new Contact();
$contact [$i]->setEmail($faker->email);
$contact [$i]->setFirstName($faker->firstName);
$contact [$i]->setLastName($faker->lastName);
$contact [$i]->setMessage($faker->text);
$contact [$i]->setCreatedAt($faker->dateTime);
$manager->persist($contact [$i]);
}
$author = new Author();
$author->setFirstName('Sparesotto');
$author->setLastName('Anais');
$manager->persist($author);
$category = new Category();
$category->setName('Climat');
$manager->persist($category);
$article = [];
for ($i = 0; $i < 10; $i++) {
$article [$i] = new Article();
$article [$i]->setTitle($faker->sentence($nbWords = 6, $variableNbWords = true));
$article [$i]->setContent($faker->text($maxNbChars = 2000));
$article [$i]->setPublicationDate($faker->dateTime);
$article [$i]->setAuthor($author);
$article [$i]->setCategory($category);
$article [$i]->setUpdatedAt($faker->dateTime);
$article [$i]->setFeaturedImage($faker->name);
$article [$i]->setSlug($faker->slug);
$faker->addProvider(new ImagesGeneratorProvider($faker));
$manager->persist($article [$i]);
}
$job = [];
for ($i = 0; $i < 7; $i++) {
$job [$i] = new Job();
$job [$i]->setName($faker->jobTitle);
$manager->persist($job [$i]);
}
$employee = [];
for ($i = 0; $i < 6; $i++) {
$employee [$i] = new Employee();
$employee [$i]->setFirstName($faker->firstName);
$employee [$i]->setLastName($faker->lastName);
$employee [$i]->setBiography($faker->text);
$employee [$i]->setJob($job[rand(0, 6)]);
$manager->persist($employee [$i]);
}
$testimonial = [];
for ($i = 0; $i < 3; $i++) {
$testimonial [$i] = new Testimonial();
$testimonial [$i]->setCompagny($faker->company);
$testimonial [$i]->setName($faker->name);
$testimonial [$i]->setJob($faker->jobTitle);
$testimonial [$i]->setContent($faker->text);
$manager->persist($testimonial [$i]);
}
$user = new User();
$user->setEmail('<EMAIL>');
$user->setPassword($this->passwordEncoder->encodePassword(
$user,
'<PASSWORD>'
));
$user->setRoles(['ROLE_ADMIN']);
$manager->persist($user);
$manager->flush();
}
}
<file_sep>/src/Controller/HomeController.php
<?php
namespace App\Controller;
use App\Entity\Article;
use App\Entity\Employee;
use App\Entity\Testimonial;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class HomeController
*
* @author <NAME> <<EMAIL>>
*/
class HomeController extends AbstractController
{
/**
* @Route("/", name="home")
*/
public function index(): Response
{
$articles = $this->getDoctrine()->getRepository(Article::class)->findBy([], [], 3);
$employees = $this->getDoctrine()->getRepository(Employee::class)->findAll();
$testimonials = $this->getDoctrine()->getRepository(Testimonial::class)->findAll();
return $this->render('base.html.twig', [
'articles' => $articles,
'employees' => $employees,
'testimonials' => $testimonials,
]);
}
}
<file_sep>/src/Entity/Category.php
<?php
namespace App\Entity;
use App\Repository\CategoryRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Bridge\Doctrine\IdGenerator\UuidV4Generator;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\UuidV4;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Class Category
*
* @author <NAME> <<EMAIL>>
* @ORM\Entity(repositoryClass=CategoryRepository::class)
*/
class Category
{
/**
* @var string
* @ORM\Id
* @ORM\Column(type="uuid", unique=true)
* @ORM\GeneratedValue(strategy="CUSTOM")
* @ORM\CustomIdGenerator(class=UuidV4Generator::class)
*/
private $id = UuidV4::class;
/**
* @var string
* @ORM\Column(type="string", length=255, nullable=false)
* @Assert\NotNull(
* message = "La catégorie doit avoir un nom"
* )
* @Assert\Length(
* min = 2,
* max = 255,
* minMessage = "Le nom de la catégorie doit avoir au minimum {{ limit }} caractères",
* maxMessage = "Le nom de la catégorie doit avoir au maximum {{ limit }} caractères"
* )
*/
private $name;
/**
* @var ArrayCollection
* @ORM\OneToMany(targetEntity=Article::class, mappedBy="category")
*/
private $article;
/**
* Category constructor.
*/
public function __construct()
{
$this->article = new ArrayCollection();
}
/**
* @return string
*/
public function getId(): string
{
return $this->id;
}
/**
* @return string|null
*/
public function getName(): ?string
{
return $this->name;
}
/**
* @param string $name
* @return $this
*/
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* @return Collection|Article[]
*/
public function getArticle(): Collection
{
return $this->article;
}
/**
* @param Article $article
* @return $this
*/
public function addArticle(Article $article): self
{
if (!$this->article->contains($article)) {
$this->article[] = $article;
$article->setCategory($this);
}
return $this;
}
/**
* @param Article $article
* @return $this
*/
public function removeArticle(Article $article): self
{
if ($this->article->removeElement($article)) {
if ($article->getCategory() === $this) {
$article->setCategory(null);
}
}
return $this;
}
/**
* @return string
*/
public function __toString()
{
return $this->name;
}
}
<file_sep>/docker-compose.yml
version: '3.7'
services:
php_apache_symfony:
build:
context: ./
dockerfile: docker/php/dockerfile
container_name: php_apache_symfony
ports:
- 80:80
environment:
SERVICE_NAME: php_apache_symfony
volumes:
- .:/var/www/html
links:
- postgres_symfony
postgres_symfony:
build:
context: ./
dockerfile: docker/postgres/dockerfile
container_name: postgres_symfony
env_file:
- .env
environment:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_USER: ${POSTGRES_USER}
SERVICE_NAME: postgres_symfony
ports:
- 5432:5432
volumes:
- ./logs/postgres:/var/log/postgresql
adminer:
image: adminer
restart: always
ports:
- 8080:8080
links:
- postgres_symfony
<file_sep>/src/Entity/Employee.php
<?php
namespace App\Entity;
use App\Repository\EmployeeRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\IdGenerator\UuidV4Generator;
use Symfony\Component\Uid\UuidV4;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Class Employee
*
* @author <NAME> <<EMAIL>>
* @ORM\Entity(repositoryClass=EmployeeRepository::class)
*/
class Employee
{
/**
* @var string
* @ORM\Id
* @ORM\Column(type="uuid", unique=true)
* @ORM\GeneratedValue(strategy="CUSTOM")
* @ORM\CustomIdGenerator(class=UuidV4Generator::class)
*/
private $id = UuidV4::class;
/**
* @var string
* @ORM\Column(type="string", length=255)
* @Assert\NotNull
* @Assert\Length(
* min = 2,
* max = 255,
* minMessage = "Le nom du salarié doit avoir au minimum {{ limit }} caractères",
* maxMessage = "Le nom du salarié doit avoir au maximum {{ limit }} caractères"
* )
*/
private $firstName;
/**
* @var string
* @ORM\Column(type="string", length=255)
* @Assert\NotNull
* @Assert\Length(
* min = 2,
* max = 255,
* minMessage = "Le prénom du salarié doit avoir au minimum {{ limit }} caractères",
* maxMessage = "Le prénom du salarié doit avoir au maximum {{ limit }} caractères"
* )
*/
private $lastName;
/**
* @var string
* @ORM\Column(type="text")
* @Assert\NotNull(
* message = "Vous devez renseigner une descritpion"
* )
* @Assert\Length(
* min = 2,
* max = 800,
* minMessage = "Le texte doit avoir au minimum {{ limit }} caractères",
* maxMessage = "Le texte doit avoir au maximum {{ limit }} caractères"
* )
*/
private $biography;
/**
* @var Job|null
* @ORM\ManyToOne(targetEntity=Job::class, inversedBy="employee")
* @ORM\JoinColumn(nullable=false)
* @Assert\NotNull(
* message = "Vous devez choisir un métier"
* )
*/
private ?Job $job;
/**
* @return string
*/
public function getId(): string
{
return $this->id;
}
/**
* @return string|null
*/
public function getFirstName(): ?string
{
return $this->firstName;
}
/**
* @param string $firstName
* @return $this
*/
public function setFirstName(string $firstName): self
{
$this->firstName = $firstName;
return $this;
}
/**
* @return string|null
*/
public function getLastName(): ?string
{
return $this->lastName;
}
/**
* @param string $lastName
* @return $this
*/
public function setLastName(string $lastName): self
{
$this->lastName = $lastName;
return $this;
}
/**
* @return string|null
*/
public function getBiography(): ?string
{
return $this->biography;
}
/**
* @param string $biography
* @return $this
*/
public function setBiography(string $biography): self
{
$this->biography = $biography;
return $this;
}
/**
* @return Job|null
*/
public function getJob(): ?Job
{
return $this->job;
}
/**
* @param Job|null $job
* @return $this
*/
public function setJob(?Job $job)
{
$this->job = $job;
return $this;
}
}
<file_sep>/src/Controller/Admin/ContactCrudController.php
<?php
namespace App\Controller\Admin;
use App\Entity\Contact;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\EmailField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
/**
* Class ContactCrudController
*
* @author <NAME> <<EMAIL>>
*/
class ContactCrudController extends AbstractCrudController
{
/**
* @return string
*/
public static function getEntityFqcn(): string
{
return Contact::class;
}
/**
* @param string $pageName
* @return iterable
*/
public function configureFields(string $pageName): iterable
{
return [
EmailField::new('email'),
TextField::new('firstName', 'Nom'),
TextField::new('lastName', 'Prénom'),
DateField::new('createdAt', 'Date de réception')->setFormat('short'),
TextField::new('message', 'Message'),
];
}
/**
* @param Actions $actions
* @return Actions
*/
public function configureActions(Actions $actions): Actions
{
return $actions
->add(Crud::PAGE_INDEX, Action::DETAIL)
->disable(Action::NEW, Action::EDIT)
->update(Crud::PAGE_INDEX, Action::DELETE, function (Action $action) {
return $action->setIcon('fa fa-trash-alt')->setLabel('supprimer');
})
->update(Crud::PAGE_INDEX, Action::DETAIL, function (Action $action) {
return $action->setIcon('fa fa-eye')->setLabel('lire');
});
}
}
<file_sep>/src/Entity/Article.php
<?php
namespace App\Entity;
use App\Repository\ArticleRepository;
use DateTime;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\IdGenerator\UuidV4Generator;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Uid\UuidV4;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Class Article
* @author <NAME> <<EMAIL>>
* @ORM\Entity(repositoryClass=ArticleRepository::class)
* @Vich\Uploadable
*/
class Article
{
/**
* @var string
* @ORM\Id
* @ORM\Column(type="uuid", unique=true)
* @ORM\GeneratedValue(strategy="CUSTOM")
* @ORM\CustomIdGenerator(class=UuidV4Generator::class)
*/
private $id = UuidV4::class;
/**
* @var string
* @ORM\Column(type="string", length=255)
* @Assert\Type(type="string")
* @Assert\NotBlank
* @Assert\Length(
* min = 2,
* max = 255,
* minMessage = "Le titre doit avoir au minimum {{ limit }} caractères",
* maxMessage = "Le titre doit avoir au maximum {{ limit }} caractères"
* )
*/
private string $title;
/**
* @var string
* @ORM\Column(type="text")
* @Assert\NotBlank
* @Assert\Length(
* min = 2,
* max = 2000,
* minMessage = "L'article doit avoir au minimum {{ limit }} caractères",
* maxMessage = "L'article doit avoir au maximum {{ limit }} caractères"
* )
*/
private string $content;
/**
* @var DateTime
* @ORM\Column(type="datetime")
*/
private DateTime $publicationDate;
/**
* @var DateTime | null
* @ORM\Column(type="datetime")
*/
private ?DateTime $updatedAt;
/**
* @var string
* @ORM\Column(type="string", length=255, nullable=true)
* @Assert\Length(
* min = 1,
* max = 255,
* minMessage = "Le nom de l'image doit avoir au minimum {{ limit }} caractères",
* maxMessage = "Le nom de l'image doit avoir au maximum {{ limit }} caractères"
* )
*/
private $featuredImage;
/**
* @var file
* @Vich\UploadableField(mapping="featured_image", fileNameProperty="featuredImage")
* @Assert\File(
* mimeTypes = {"image/jpeg", "image/gif", "image/png", "image/svg"},
* mimeTypesMessage = "Le format de l'image est incorect (jpg,gif,png,svg)"
* )
*/
private $imageFile;
/**
* @var Author
* @ORM\ManyToOne(targetEntity=Author::class, inversedBy="article")
* @ORM\JoinColumn(nullable=false)
* @Assert\NotNull
*/
private $author;
/**
* @var Category
* @ORM\ManyToOne(targetEntity=Category::class, inversedBy="article")
* @ORM\JoinColumn(nullable=false)
* @Assert\NotNull
*/
private Category $category;
/**
* @ORM\OneToMany(targetEntity=Comment::class, mappedBy="article")
*/
private $comments;
/**
* @ORM\Column(type="string", length=255)
*/
private $slug;
/**
* Article constructor.
*/
public function __construct()
{
$this->updatedAt = new DateTime();
$this->comments = new ArrayCollection();
}
/**
* @return string
*/
public function getId(): ?string
{
return $this->id;
}
/**
* @return string|null
*/
public function getTitle(): ?string
{
return $this->title;
}
/**
* @param string $title
* @return $this
*/
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
/**
* @return DateTime | null
*/
public function getUpdatedAt(): ?DateTime
{
return $this->updatedAt;
}
/**
* @param DateTime|null $updatedAt
*/
public function setUpdatedAt(?DateTime $updatedAt): void
{
$this->updatedAt = $updatedAt;
}
/**
* @return string|null
*/
public function getContent(): ?string
{
return $this->content;
}
/**
* @param string $content
* @return $this
*/
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
/**
* @return DateTime|null
*/
public function getPublicationDate(): ?DateTime
{
return $this->publicationDate;
}
/**
* @param DateTime $publicationDate
* @return $this
*/
public function setPublicationDate(DateTime $publicationDate): self
{
$this->publicationDate = $publicationDate;
return $this;
}
/**
* @return File | null
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* @param File|null $image
* @return $this
*/
public function setImageFile($image = null): self
{
$this->imageFile = $image;
if ($image) {
$this->updatedAt = new DateTime();
}
return $this;
}
/**
* @return string | null
*/
public function getFeaturedImage(): ?string
{
return $this->featuredImage;
}
/**
* @param string|null $featuredImage
* @return $this
*/
public function setFeaturedImage(?string $featuredImage): self
{
$this->featuredImage = $featuredImage;
return $this;
}
/**
* @return Author|null
*/
public function getAuthor(): ?Author
{
return $this->author;
}
/**
* @param Author|null $author
* @return $this
*/
public function setAuthor(?Author $author): self
{
$this->author = $author;
return $this;
}
/**
* @return Category|null
*/
public function getCategory(): ?Category
{
return $this->category;
}
/**
* @param Category|null $category
* @return $this
*/
public function setCategory(?Category $category): self
{
$this->category = $category;
return $this;
}
/**
* @return Collection|Comment[]
*/
public function getComments(): Collection
{
return $this->comments;
}
public function addComment(Comment $comment): self
{
if (!$this->comments->contains($comment)) {
$this->comments[] = $comment;
$comment->setArticle($this);
}
return $this;
}
public function removeComment(Comment $comment): self
{
if ($this->comments->removeElement($comment)) {
if ($comment->getArticle() === $this) {
$comment->setArticle(null);
}
}
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
}
<file_sep>/src/Controller/Admin/DashboardController.php
<?php
namespace App\Controller\Admin;
use App\Entity\Article;
use App\Entity\Author;
use App\Entity\Category;
use App\Entity\Contact;
use App\Entity\Job;
use App\Entity\Employee;
use App\Entity\Testimonial;
use EasyCorp\Bundle\EasyAdminBundle\Config\Dashboard;
use EasyCorp\Bundle\EasyAdminBundle\Config\MenuItem;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class DashboardController
*
* @author <NAME> <<EMAIL>>
*/
class DashboardController extends AbstractDashboardController
{
/**
* @return Response
* @Route("/admin", name="admin")
*/
public function index(): Response
{
{
$contact = $this->getDoctrine()->getRepository(Contact::class)->count([]);
$author = $this->getDoctrine()->getRepository(Author::class)->count([]);
$employee = $this->getDoctrine()->getRepository(Employee::class)->count([]);
$articles = $this->getDoctrine()->getRepository(Article::class)->count([]);
$category = $this->getDoctrine()->getRepository(Category::class)->count([]);
$testimonial = $this->getDoctrine()->getRepository(Testimonial::class)->count([]);
$job = $this->getDoctrine()->getRepository(Job::class)->count([]);
return $this->render('Dashboard/index.html.twig', [
'contact' => $contact,
'author' => $author,
'employee' => $employee,
'articles' => $articles,
'category' => $category,
'testimonial' => $testimonial,
'job' => $job,
]);
}
}
/**
* @return Dashboard
*/
public function configureDashboard(): Dashboard
{
return Dashboard::new()
->setTitle('Kiribati Toovalu')
->setTranslationDomain('admin');
}
/**
* @return iterable
*/
public function configureMenuItems(): iterable
{
return [
MenuItem::linkToDashboard('Dashboard', 'fa fa-home'),
MenuItem::section('Email de contact'),
MenuItem::linkToCrud('Email', 'fa fa-envelope-open-text', Contact::class),
MenuItem::section('Blog'),
MenuItem::linkToCrud('Auteurs', 'fa fa-user', Author::class),
MenuItem::linkToCrud('Categories', 'fa fa-list-alt', Category::class),
MenuItem::linkToCrud('Articles', 'fa fa-book', Article::class),
MenuItem::section('Entreprise'),
MenuItem::linkToCrud('Salariés', 'fa fa-users', Employee::class),
MenuItem::linkToCrud('Métier', 'fa fa-briefcase', Job::class),
MenuItem::section('Témoignages'),
MenuItem::linkToCrud('Témoignage', 'fa fa-comments', Testimonial::class),
];
}
}
| a0cc6da9d51b28d18be14a0a540945ffa8cb926c | [
"Markdown",
"Makefile",
"YAML",
"PHP"
] | 17 | PHP | anais0210/toovalu | dbcd3927915bf8814aab8447775e8b1621afd608 | 047a943043e18387799faaa749e3b1e439328c5c |
refs/heads/main | <repo_name>charlotte-on/exquisite-game<file_sep>/js/index.js
import { initEmojis } from "./emoji.js";
const sendBtn = document.querySelector(".send");
const textInput = document.querySelector("#words");
const textWritten = document.querySelector("#written-text");
const emojiBtn = document.querySelector(".trigger");
const warningMsg = document.querySelector(".message");
initEmojis();
let functionCalls = 0;
function sendText() {
if (textInput.value.length < 30) {
warningMsg.textContent = "Your text should be at least 30 characters long";
warningMsg.classList.toggle("warning");
warning();
return;
}
if (textInput.value.length > 50) {
warningMsg.textContent = "Your text should be less than 50 characters long";
warningMsg.classList.toggle("warning");
warning();
return;
}
if (textWritten.textContent === "") {
textWritten.textContent += textInput.value;
hideText();
let start = revealLastWord();
functionCalls++;
return (textInput.value = `${start}`);
} else {
let string = textInput.value.split(" ");
let firstWord = string.splice(0, 3);
let withoutFirstWord = string.join(" ");
textWritten.textContent += ` ${withoutFirstWord}`;
hideText();
let start = revealLastWord();
functionCalls++;
console.log(functionCalls);
if (functionCalls === 9) {
changeButton();
return (textInput.value = `${start}`);
} else if (functionCalls === 10) {
removeInputs();
return revealText();
} else {
return (textInput.value = `${start}`);
}
}
}
function hideText() {
textWritten.classList.add("hidden-text");
}
function revealLastWord() {
let string = textInput.value.split(" ");
let lastWords =
string[string.length - 3] +
" " +
string[string.length - 2] +
" " +
string[string.length - 1] +
" ";
return lastWords;
}
function changeButton() {
sendBtn.value = "REVEAL";
sendBtn.classList.toggle("reveal");
}
function removeInputs() {
sendBtn.remove();
textInput.remove();
emojiBtn.remove();
}
function revealText() {
textWritten.classList.remove("hidden-text");
}
sendBtn.onclick = sendText;
textInput.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
sendBtn.click();
}
});
function warning() {
setTimeout(() => {
warningMsg.classList.toggle("warning");
}, 3000);
}
// textInput.onkeydown = () => {
// removeEmojis(textInput.value);
// };
<file_sep>/js/emoji.js
import { EmojiButton } from "./emoji.lib.js";
const textInput = document.querySelector("#words");
export function initEmojis() {
const picker = new EmojiButton();
const trigger = document.querySelector(".trigger");
picker.on("emoji", (selection) => {
textInput.value += selection.emoji;
console.log(selection);
});
trigger.addEventListener("click", () => picker.togglePicker(trigger));
}
| d2004db63aedb493ac60dc6f0ba2b8e7c30a1bc8 | [
"JavaScript"
] | 2 | JavaScript | charlotte-on/exquisite-game | 545dd99e7f5afc1f1707b38bb7c023ac90cb828a | d3b77246c9f8842aa7112650a34e1acbed994c9b |
refs/heads/master | <repo_name>RainerTodtenhoefer/WS2018GitDemo<file_sep>/README.md
# WS2018GitDemo
My tutorial
<file_sep>/FromClient.js
# Some code from my MacBook
| 4e3d784bb5e0fad72299f7c42c48f2488e61f433 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | RainerTodtenhoefer/WS2018GitDemo | 5673d668c3b11716974fd58d1185323cfe08c870 | b908e180721c86f1524fa46203b009adb048ca69 |
refs/heads/master | <repo_name>JoistApp/CreditCardForm-iOS<file_sep>/Example/Demo2-CreditCardFormLibarary/Demo/ViewController.swift
//
// ViewController.swift
// Demo
//
// Created by <NAME> on 11/29/16.
// Copyright © 2016 Veriloft. All rights reserved.
//
import UIKit
import Stripe
import CreditCardForm
class ViewController: UIViewController, STPPaymentCardTextFieldDelegate {
@IBOutlet weak var creditCardView: CreditCardFormView!
let paymentTextField = STPPaymentCardTextField()
private var cardHolderNameTextField: TextField!
private var cardParams: STPPaymentMethodCardParams!
override func viewDidLoad() {
super.viewDidLoad()
creditCardView.cardHolderString = "<NAME>"
creditCardView.cardGradientColors[Brands.Amex.rawValue] = [UIColor.red, UIColor.black]
creditCardView.cardNumberFont = UIFont(name: "HelveticaNeue", size: 20)!
creditCardView.cardPlaceholdersFont = UIFont(name: "HelveticaNeue", size: 10)!
creditCardView.cardTextFont = UIFont(name: "HelveticaNeue", size: 12)!
paymentTextField.postalCodeEntryEnabled = false
createTextField()
cardParams = STPPaymentMethodCardParams()
cardParams.number = "375987654321111"
cardParams.expMonth = 03
cardParams.expYear = 23
cardParams.cvc = "7997"
self.paymentTextField.cardParams = cardParams
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// load saved card params
creditCardView.paymentCardTextFieldDidChange(cardNumber: cardParams.number, expirationYear: cardParams!.expYear as? UInt, expirationMonth: cardParams!.expMonth as? UInt, cvc: cardParams.cvc)
}
func createTextField() {
cardHolderNameTextField = TextField(frame: CGRect(x: 15, y: 199, width: self.view.frame.size.width - 30, height: 44))
cardHolderNameTextField.placeholder = "CARD HOLDER"
cardHolderNameTextField.delegate = self
cardHolderNameTextField.translatesAutoresizingMaskIntoConstraints = false
cardHolderNameTextField.setBottomBorder()
cardHolderNameTextField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged)
view.addSubview(cardHolderNameTextField)
paymentTextField.frame = CGRect(x: 15, y: 199, width: self.view.frame.size.width - 30, height: 44)
paymentTextField.delegate = self
paymentTextField.translatesAutoresizingMaskIntoConstraints = false
paymentTextField.borderWidth = 0
let border = CALayer()
let width = CGFloat(1.0)
border.borderColor = UIColor.darkGray.cgColor
border.frame = CGRect(x: 0, y: paymentTextField.frame.size.height - width, width: paymentTextField.frame.size.width, height: paymentTextField.frame.size.height)
border.borderWidth = width
paymentTextField.layer.addSublayer(border)
paymentTextField.layer.masksToBounds = true
view.addSubview(paymentTextField)
NSLayoutConstraint.activate([
cardHolderNameTextField.topAnchor.constraint(equalTo: creditCardView.bottomAnchor, constant: 20),
cardHolderNameTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
cardHolderNameTextField.widthAnchor.constraint(equalToConstant: self.view.frame.size.width-25),
cardHolderNameTextField.heightAnchor.constraint(equalToConstant: 44)
])
NSLayoutConstraint.activate([
paymentTextField.topAnchor.constraint(equalTo: cardHolderNameTextField.bottomAnchor, constant: 20),
paymentTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
paymentTextField.widthAnchor.constraint(equalToConstant: self.view.frame.size.width-20),
paymentTextField.heightAnchor.constraint(equalToConstant: 44)
])
}
func paymentCardTextFieldDidChange(_ textField: STPPaymentCardTextField) {
creditCardView.paymentCardTextFieldDidChange(cardNumber: textField.cardNumber, expirationYear: textField.expirationYear, expirationMonth: textField.expirationMonth, cvc: textField.cvc)
}
func paymentCardTextFieldDidEndEditingExpiration(_ textField: STPPaymentCardTextField) {
creditCardView.paymentCardTextFieldDidEndEditingExpiration(expirationYear: textField.expirationYear)
}
func paymentCardTextFieldDidBeginEditingCVC(_ textField: STPPaymentCardTextField) {
creditCardView.paymentCardTextFieldDidBeginEditingCVC()
}
func paymentCardTextFieldDidEndEditingCVC(_ textField: STPPaymentCardTextField) {
creditCardView.paymentCardTextFieldDidEndEditingCVC()
}
}
extension ViewController: UITextFieldDelegate {
@objc func textFieldDidChange(_ textField: UITextField) {
creditCardView.cardHolderString = textField.text!
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == cardHolderNameTextField {
textField.resignFirstResponder()
paymentTextField.becomeFirstResponder()
} else if textField == paymentTextField {
textField.resignFirstResponder()
}
return true
}
}
extension UITextField {
func setBottomBorder() {
self.borderStyle = UITextField.BorderStyle.none
let border = CALayer()
let width = CGFloat(1.0)
border.borderColor = UIColor.darkGray.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
border.borderWidth = width
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
}
| 1fa62dfb2bf115e8a08624bfb3713161ec2ffade | [
"Swift"
] | 1 | Swift | JoistApp/CreditCardForm-iOS | f22ab22f292e942d3498bc41921ba0cf9b5adee0 | e2d68be5a295edf4de03af41ed9d1e70eb007b11 |
refs/heads/master | <repo_name>DEARTSV/FirstTask<file_sep>/FirstTask/FirstTask/FirstTask.cpp
#include "stdafx.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <math.h>
int main(int argc, char* argv[])
{
IplImage* src = 0;
IplImage* dst = 0;
IplImage* color_dst = 0;
// имя картинки задаётся первым параметром
char* filename = argc >= 2 ? argv[1] : "Image0.jpg";
// получаем картинку (в градациях серого)
src = cvLoadImage(filename, CV_LOAD_IMAGE_GRAYSCALE);
if (!src){
printf("[!] Error: cant load image: %s \n", filename);
return -1;
}
printf("[i] image: %s\n", filename);
// хранилище памяти для хранения найденных линий
CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* lines = 0;
int i, p, i0;
double angle = CV_PI / 2, phi = 0, tetta, b, k;
dst = cvCreateImage(cvGetSize(src), 8, 1);
color_dst = cvCreateImage(cvGetSize(src), 8, 3);
// детектирование границ
cvCanny(src, dst, 50, 70, 3);
// конвертируем в цветное изображение
cvCvtColor(dst, color_dst, CV_GRAY2BGR);
// нахождение линий
lines = cvHoughLines2(dst, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI/180, 100, 50, 10);
// ищем нужную линию по углу наклона(ось x и данная линия), её угол наклона
for (i = 0; i < lines->total; i++)
{
CvPoint* line = (CvPoint*)cvGetSeqElem(lines, i);
//check for correct finding tg
if (line[0].x >= line[1].x)
{
p = line[0].x;
line[0].x = line[1].x;
line[1].x = p;
p = line[0].y;
line[0].y = line[1].y;
line[1].y = p;
}
tetta = atan((double)(line[1].y - line[0].y) / (double)(line[1].x - line[0].x));
if (abs(angle - abs(tetta)) < abs(angle - abs(phi)))
{
phi = tetta;
i0 = i;
}
}
//Преобразуем нашу линию в прямую y=kx+b
k = tan(phi);
CvPoint* line = (CvPoint*)cvGetSeqElem(lines, i0);
b = line[0].y - k*line[0].x;
line[0].y = 0;
line[0].x = (line[0].y - b) / k;
line[1].y = color_dst->height;
line[1].x = (line[1].y - b) / k;
//Строим прямую
cvLine(color_dst, line[0], line[1], CV_RGB(255, 0, 0), 3, CV_AA, 0);
// показываем
cvNamedWindow("Source", 1);
cvShowImage("Source", src);
cvNamedWindow("Hough", 1);
cvShowImage("Hough", color_dst);
// ждём нажатия клавиши
cvWaitKey(0);
// освобождаем ресурсы
cvReleaseMemStorage(&storage);
cvReleaseImage(&src);
cvReleaseImage(&dst);
cvReleaseImage(&color_dst);
cvDestroyAllWindows();
return 0;
} | 18bfba5d19026ba510ba3986da8eb6263150c79e | [
"C++"
] | 1 | C++ | DEARTSV/FirstTask | 76a46dc8c011c2ed79a95395fda2dd5c82ec111f | e7b8b51a225dd5aab23ad98e505c7075095c3d01 |
refs/heads/master | <repo_name>SiweiYang/siwei.review<file_sep>/_posts/2018-07-17-cli-stuff.markdown
---
layout: single
title: "Make CLI great again"
subtitle: "command line utilities"
navcolor: "invert"
date: 2018-07-17
author: "Siwei"
catalog: true
tags:
- Coding
- System admin
---
> common CLI tools you may need
### admin
+ `!!` and its derivatives
+ `column -t` or `alias ct='column -t'`
+ `sudo lsof -Pni` `sudo netstat -nutlp`
+ `nohup`
+ `ssh -ND PORT` for creating a SOCK
+ `ProxyCommand` in ssh config
+ `ps aux | sort -nk 3` for CPU `ps aux | sort -nk 4` for MEM
+ `multitail`
+ `at` `atq` `atrm`
### editing
+ sshfs
+ vim over scp
### shells
+ `zsh` `fish`<file_sep>/_posts/2017-11-08-boosting.markdown
---
layout: single
title: "Machine Learning Concepts"
subtitle: "primitive building blocks"
navcolor: "invert"
date: 2017-11-08
author: "Siwei"
catalog: true
tags:
- Concept
- Machine Learning
- Reflection
---
> TL; DR
## Boosting
+ AdaBoost
+ Gradient Boosting
+ Newton Boosting
## Attention
## MultiTask(side objective)
<file_sep>/_posts/2018-07-27-kubernetes-concepts.markdown
---
layout: single
title: "Kubernetes concepts"
subtitle: "how to program kubernetes"
navcolor: "invert"
date: 2018-07-17
author: "Siwei"
catalog: true
tags:
- System admin
- Container
- DevOps
---
Pod + replicas + label(selector) = Deployment
automatic rolling update: new replica set and incrementally roll over
Pod + label(selector) = Service connection
e.g. canary and grey-scale and blue-green<file_sep>/_posts/2018-08-05-technical-interview.markdown
#
+ linear structure
+ graph structure
+ sorting, graph
+ backtrcking, DP, backtracking tree
+ design
+ system design primer
+ perspective companty blog
+ TinyURL
+ Netflix
+ MySQL
+ GFS
+ FB
+ Big Data plat
+ LinkedIn
+ Uber
+ exp
+ role/contribution
+ used what
+ achieved what
+ OOD
+ multi-thread
+ linear structure
+ binary tree and tree
+ DP and greedy
#######################################################
kafka -> spark(hadoop, hive) -> cassandra + Maria + ElasticDB
什么是系统设计?
设计一个Netflix:
宏观设计(snake五步系统设计):
scenario,necessary,application,kilobit,evolve,
微观设计:
如何设计推荐模块?(snake五步系统设计)<file_sep>/res/code/falcon-resources.py
#!/usr/bin/env python3
import io
import sys
import gzip
import json
import click
import traceback
import logging
import falcon
from falcon_cors import CORS
from wsgiref import simple_server
logger = logging.getLogger(__name__)
supported_methods = ['GET', 'POST', 'PUT', 'DELETE']
class GzipMiddleware:
def process_request(self, req, resp):
#print(req.headers)
if 'CONTENT-ENCODING' in req.headers and 'gzip' == req.headers['CONTENT-ENCODING']:
logger.info('using gzip middleware to decompress')
req.stream = gzip.GzipFile(fileobj=req.stream)
def process_response(self, req, resp, resource, req_succeeded):
if req.method not in supported_methods:
return
if 'ACCEPT-ENCODING' in req.headers and 'gzip' in req.headers['ACCEPT-ENCODING']:
logger.info('using gzip middleware to compress')
if type(resp.body) == str:
resp.body = resp.body.encode('utf8')
resp.body = gzip.compress(resp.body)
resp.set_header('CONTENT-ENCODING', 'gzip')
pass
class ResourceBasedMiddleware:
def process_resource(self, req, resp, resource, params):
if req.method not in supported_methods:
raise falcon.HTTPInternalServerError()
try:
req.data = None
if type(resource) == DATAResources:
if req.method in ['GET', 'DELETE']:
req.data = {}
if req.method in ['POST', 'PUT', 'DELETE']:
try:
req.data = req.stream.read()
req.data = json.loads(req.data.decode('utf8'))
except:
req.data = {}
if type(resource) == RAWResources:
req.data = req.stream.read()
if req.data == None:
raise Exception(f'request {req} cannot be processed for resource {resource}')
except:
logger.warn('Failed to preprocess:')
logger.warn(req)
exc_type, exc_value, exc_traceback = sys.exc_info()
stacktrace = ''.join(traceback.format_exception(
exc_type,
exc_value,
exc_traceback))
logger.warn(stacktrace)
raise falcon.HTTPInternalServerError()
def process_response(self, req, resp, resource, req_succeeded):
if req.method not in supported_methods:
raise falcon.HTTPInternalServerError()
if resp.data == None:
raise falcon.HTTPInternalServerError()
if type(resource) == DATAResources:
resp.body = json.JSONEncoder().encode(resp.data).encode('utf8')
resp.content_length = len(resp.body)
resp.content_type = 'application/json'
if type(resource) == RAWResources:
if not resp.data:
raise falcon.HTTPInternalServerError()
resp.body = resp.data
resp.content_length = len(resp.body)
resp.content_type = resource.content_type
if not resp.content_type:
resp.content_type = req.content_type
public_cors = CORS(allow_all_origins=True, allow_all_methods=True, allow_all_headers=True)
def CORSMiddleware():
return public_cors.middleware
class DATAResources():
def __init__(self, processor, failsafe):
self.processor = processor
if type(self.processor) != dict:
self.processor = {
'default': self.processor,
}
self.failsafe = failsafe
self.on_get = self.process
self.on_put = self.process
self.on_post = self.process
self.on_delete = self.process
def resolve_processor(self, req, **kwargs):
if req.method in self.processor:
return self.processor[req.method]
else:
return self.processor['default']
def process(self, req, resp, **kwargs):
try:
processor = self.resolve_processor(req)
try:
resp.data = processor(req.data, kwargs, req.params)
except TypeError as e:
resp.data = processor(req.data)
except (falcon.HTTPError, falcon.HTTPStatus) as e:
resp.data = {}
raise e
except Exception as e:
logger.error('something went wrong with RPC:')
logger.error(req.data)
exc_type, exc_value, exc_traceback = sys.exc_info()
stacktrace = ''.join(traceback.format_exception(
exc_type,
exc_value,
exc_traceback
))
logger.error(stacktrace)
raise falcon.HTTPInternalServerError()
class RAWResources():
def __init__(self, processor, content_type):
self.processor = processor
self.content_type = content_type
def on_post(self, req, resp, **kwargs):
self.on_get(req, resp, **kwargs)
def on_get(self, req, resp, **kwargs):
try:
try:
resp.data = self.processor(req.data, kwargs, req.params)
except TypeError as e:
resp.data = self.processor(req.data)
except Exception as e:
logger.error('something went wrong with RPC:')
logger.error(req.data)
exc_type, exc_value, exc_traceback = sys.exc_info()
stacktrace = ''.join(traceback.format_exception(exc_type,
exc_value,
exc_traceback))
logger.error(stacktrace)
raise falcon.HTTPInternalServerError()
def make_service(pairs, middlewares=[]):
service = falcon.API(middleware=middlewares)
health_resources = RAWResources(lambda data: {'health': True}, 'text/html')
service.add_route('/health', health_resources)
for path, resource in pairs:
service.add_route(path, resource)
return service
def run_service(port, service):
print('running services at port %d' % port)
httpd = simple_server.make_server('0.0.0.0', port, service)
httpd.serve_forever()
<file_sep>/_posts/2018-08-01-design-for-cloud.markdown
+ requirement
+ measure
+ design
+ stateless is good, but what about state
+ hotspot
+ re-provision time
+ dimension
+ in general, dumb components, smart orchastrating
+ component easy to test, integration can be hard
+ typically useful when services are provided in various packages
+ needs messaging, sometimes protocol needs designing
+ shared storage
+ how much control? we can trade control for productivity
+ should some components be treated differently
+ 12 factor, but with tradeoff
+ config injection is almost always necessary
+ start thinking early e.g. scaling, but iterate over the design
+ security
+ regular rotation
+ maybe there's trails for audit
+ isolation
+ capacity planning
+ leave margin of err and refine with iterations
+ initial load v.s. stable load
+ os and hardware can make a difference
+ pricing of different instance types
+ pricing of traffic: ingress, egress, between zones, between regions<file_sep>/_posts/2017-10-30-management-101.markdown
---
layout: single
title: "Management 101"
subtitle: "organization development in action"
navcolor: "invert"
date: 2017-10-30
author: "Siwei"
catalog: true
tags:
- Management
- Reflection
- Problem Solving
---
> TL; DR
## defining management
incentive:
needs to work
## reflecting on traditional management
traditional:
personnel centric
position centric
project centric
modern:
priority
deal making
naturing
## 5 aspects of management
### Planning: matching resources and objectives
### Workflow: building specializations and coordination
### Organization: defining power and responsibilities
### Strategy: realizing core competences
### Culture: motivating personnel
planning: resources and objective
workflow: who does what
incentive
empowerment
organization: power and responsibility
professionalism
distribution of power
temporary v.s. permanent
strategy: core competence
potential
high value
barrier
vest extra effort
culture
influencer
team
brand
community
<file_sep>/publish.sh
#!/usr/bin/env bash
jekyll build && gsutil -m -o rsync -r _site/ gs://siwei.review
| 79c18e23fc9ea16afe22b591f1c358aa3e8117a4 | [
"Markdown",
"Python",
"Shell"
] | 8 | Markdown | SiweiYang/siwei.review | ec1108e27d72a10296dd24adab6fe7869231bc6c | 916c18c4904282157a030990618b064a7df84887 |
refs/heads/master | <file_sep>require("dotenv").config();
var keys = require("./keys.js");
var Spotify = require("node-spotify-api");
var axios = require("axios");
var moment = require("moment");
var fs = require("fs");
var spotify = new Spotify(keys.spotify);
//concert-this
var concertThis = function (band) {
var url = "https://rest.bandsintown.com/artists/" + band + "/events?app_id=codingbootcamp"
axios.get(url).then(function (response) {
for (var i = 0; i < response.data.length && i < 3; i++) {
console.log(
"Venue: " + response.data[i].venue.name + "\n",
"City: " + response.data[i].venue.city + "\n",
"Time: " + moment(response.data[i].datetime).format('MM/DD/YYYY') + "\n",
);
}
});
}
//movie-this
var movieThis = function (movie) {
//sets the default as The Sign by Ace of Base if no input
if (movie === null || movie.trim().length === 0) {
movie = "Mr. Nobody";
}
var url = "http://www.omdbapi.com/?t=" + movie + "&y=&plot=short&apikey=trilogy"
axios.get(url).then(function (response) {
var movie = response.data;
console.log(
" Movie: " + movie.Title + "\n",
"Year: " + movie.Year + "\n",
"Rating: " + movie.Ratings[1].Value + "\n",
"Country: " + movie.Country + "\n",
"Language: " + movie.Language + "\n",
"Plot: " + movie.Plot + "\n",
"Actors: " + movie.Actors + "\n",
);
})
}
//spotify-this-song
var spotifyThis = function (song) {
//sets the default as The Sign by Ace of Base if no input
if (song === null || song.trim().length === 0) {
song = "The Sign ace of base";
}
spotify.search({ type: "track", query: song },
function (err, data) {
if (err) {
return console.log("Error occurred" + err);
};
// debugger;
console.log(
" Song: " + data.tracks.items[0].name + "\n",
"Artist: " + data.tracks.items[0].artists[0].name + "\n",
"Preview: " + data.tracks.items[0].preview_url + "\n",
"Album: " + data.tracks.items[0].album.name + "\n",
);
});
}
//do-what-it-says
var doWhatItSays = function () {
fs.readFile("random.txt", "utf8", function (error, data) {
if (error) {
return console.log(error);
} console.log(data);
//set a var to the text & have it call the appropriate function
})
}
//user input & what is output
var whichCommand = function(action,value){
if(action==="concert-this"){
concertThis(value)
}else if(action==="spotify-this-song"){
spotifyThis(value);
} else if(action === "movie-this"){
movieThis(value);
}
//this needs sets what the output would be "I want it that way"
// else if(action === "do-what-it-says"){
// doWhatItSays(value);
// }
else {
console.log("Unrecognized action. Format needed: node liri.js concert-this, spotify-this-song, movie-this ");
}
}
var userCommand = process.argv[2];
var userValue = process.argv.splice(3).join("+");
whichCommand(userCommand,userValue);<file_sep># LIRI-node-app
LIRI is a node app that allows users to search for a song, movie, or concert. LIRI uses different APIs to retrieve data and output to the user.
## Technology Used
* Node-Spotify-API
* Axios, which is used to get data from the following:
* OMDB API
* Bands In Town API
* Moment
* DotEnv
## Launch
In order to use LIRI, you must have the technologies mentioned above. Once installed, LIRI can be accessed by going to liri.js and inputing one of the following commands:
* node liri.js spotify-this-song <song name>
* node liri.js movie-this <movie title>
* node liri.js concert-this <artist name>
If you choose to simply enter the command without your choice of song or movie, LIRI will happily display its choice.
## Video
The following videos are demonstrations of the LIRI app in action. You will notice that the corresponding code is above the terminal.
This video shows LIRI working with the spotify-this-song command:
* https://drive.google.com/file/d/1gkk3Kf9O_lhiJ-44abT2AQcZYw8XDCr9/view
This video shows LIRI working with the movie-this command:
* https://drive.google.com/file/d/1gsTilHgQ_ebGfVVEf4zozAjUYuiGNgQV/view
This video shows LIRI working with the concert-this command:
* https://drive.google.com/file/d/1HP889BCys7sxadZK_RcVpc92347hjgWl/view
This video shows the code for the LIRI app:
* https://drive.google.com/file/d/12EfKqbNniiGBsUU3IPahuwKEEkFR4WDc/view
## Project Status
In progress
| f2deb4351cd03b30333fdb4588c8e9d357f95357 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | abzamer/liri-node-app | b957a2d73df216b540e7a716c5b389a2226cf8a9 | ca9f3a2d791a3459f6d7e8f2257543f3d8d31f13 |
refs/heads/master | <file_sep>require 'CSV'
CSV.open("new_numbers.csv", "w", :headers => true) do |csv|
CSV.foreach("numbers.csv", headers: :true, converters: :numeric) do |obj|
csv << obj.headers.sort
csv << Hash[obj.sort].values
end
end
<file_sep>**Code Test Problem - CSV**
1. Download a zip and navigate to the folder in terminal
2. Run 'ruby csv\_example.rb' in terminal. This code will take the 'numbers.csv' file, transform it by taking out leading zero's and sorting by header, and output a new file called 'new\_numbers.csv', or rewrite the existing file.
| eacf72e625a0247aae88df1da0a95baa6677b13d | [
"Markdown",
"Ruby"
] | 2 | Ruby | ebrohman/csv | 3c0d55c28eeddd35394f7715d5006af0e9b48eca | 208553aee8be79e378067b538255e8851ec5e9a4 |
refs/heads/master | <file_sep>package com.example.moviedb.data;
import androidx.room.Database;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
import com.example.moviedb.model.Result;
@Database(entities = {Result.class},version = 2, exportSchema = false)
@TypeConverters({Converter.class})
public abstract class MovieDB extends RoomDatabase {
public abstract MovieDao movieDao();
}
| 5bb2c7b5729e8cfbd654e28d708cc176bf66d107 | [
"Java"
] | 1 | Java | Juliardi16/STUDI-INDEPENDENT_TUGAS12 | 6a24e6ee6b74b820ea208275e7f51c9603e5ee48 | 30d9952bf2736caa93a19941f67678f1aa9b3fd0 |
refs/heads/master | <repo_name>Javagic/Smart_Alarm_Clock<file_sep>/app/src/main/java/com/me/ilya/smartalarmclock/AlarmEditActivity.java
package com.me.ilya.smartalarmclock;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import com.me.ilya.smartalarmclock.main.AlarmClockApplication;
import com.me.ilya.smartalarmclock.music.Song;
import com.me.ilya.smartalarmclock.music.SongListActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by Ilya on 6/17/2016.
*/
public class AlarmEditActivity extends AppCompatActivity {
AlarmItem alarmItem;
Song song;
@BindView(R.id.chk_mond)
DaySwitcher chekMonday;
@BindView(R.id.chk_tue)
DaySwitcher chekTuesday;
@BindView(R.id.chk_wed)
DaySwitcher chekWednesday;
@BindView(R.id.chk_thur)
DaySwitcher chekThursday;
@BindView(R.id.chk_frid)
DaySwitcher chekFriday;
@BindView(R.id.chk_sat)
DaySwitcher chekSaturday;
@BindView(R.id.chk_sun)
DaySwitcher chekSunday;
@BindView(R.id.alarm_name)
EditText alarmNameEditText;
TimePicker tp;
@BindView(R.id.accept_button)
ImageView acceptButton;
private final static String EXTRA_ALARM_ID = "alarm_id";
public static Intent intent(Context context) {
return new Intent(context, AlarmEditActivity.class);
}
public static Intent intent(Context context, int alarmId) {
Intent intent = new Intent(context, AlarmEditActivity.class);
intent.putExtra(EXTRA_ALARM_ID, alarmId);
return intent;
}
private int alarmId;
@BindView(R.id.edit_song_name)
TextView editSongName;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
song= (Song) data.getSerializableExtra("song");
editSongName.setText(song.getName());
}
//if(AlarmClockApplication.getDataSource().getAlarmById(alarmId).getSong()!=null)
//editSongName.setText(AlarmClockApplication.getDataSource().getAlarmById(alarmId).getSong().getName());
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm_edit_activity);
ButterKnife.bind(this);
alarmId = getIntent().getIntExtra(EXTRA_ALARM_ID, -1);//notSet
tp = (TimePicker) findViewById(R.id.timePicker);
tp.setIs24HourView(true);
if (alarmId != -1) {
alarmItem = AlarmClockApplication.getDataSource().getAlarmById(alarmId);
if (alarmItem != null) {
song=alarmItem.getSong();
alarmNameEditText.setText(alarmItem.getName());
tp.setCurrentMinute(alarmItem.getTimeMinute());
tp.setCurrentHour(alarmItem.getTimeHour());
editSongName.setText(alarmItem.getSong().getName());
}
} else {
alarmItem = new AlarmItem(alarmId, "", tp.getCurrentHour(), tp.getCurrentMinute(), Song.DEFAULT());
song = Song.DEFAULT();
editSongName.setText("Default(" + RingtoneManager.getRingtone(this, Uri.parse(Song.DEFAULT_URI)).getTitle(this) + ")");
}
setDays();
ImageView imageView = (ImageView) findViewById(R.id.song_list);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startAct();
}
});
}
private void setDays(){
chekMonday.setChecked(alarmItem.getDay(AlarmItem.MONDAY));
chekTuesday.setChecked(alarmItem.getDay(AlarmItem.TUESDAY));
chekWednesday.setChecked(alarmItem.getDay(AlarmItem.WEDNESDAY));
chekThursday.setChecked(alarmItem.getDay(AlarmItem.THURSDAY));
chekFriday.setChecked(alarmItem.getDay(AlarmItem.FRDIAY));
chekSaturday.setChecked(alarmItem.getDay(AlarmItem.SATURDAY));
chekSunday.setChecked(alarmItem.getDay(AlarmItem.SUNDAY));
}
private void startAct() {
startActivityForResult(SongListActivity.intent(AlarmEditActivity.this, alarmId), 0);
}
@OnClick(R.id.accept_button)
public void accept() {
AlarmItem newAlarmItem = new AlarmItem(alarmId, alarmNameEditText.getText().toString(), tp.getCurrentHour(), tp.getCurrentMinute(), song);
newAlarmItem.setDay(AlarmItem.MONDAY, chekMonday.isChecked());
newAlarmItem.setDay(AlarmItem.TUESDAY, chekTuesday.isChecked());
newAlarmItem.setDay(AlarmItem.WEDNESDAY, chekWednesday.isChecked());
newAlarmItem.setDay(AlarmItem.THURSDAY, chekThursday.isChecked());
newAlarmItem.setDay(AlarmItem.FRDIAY, chekFriday.isChecked());
newAlarmItem.setDay(AlarmItem.SATURDAY, chekSaturday.isChecked());
newAlarmItem.setDay(AlarmItem.SUNDAY, chekSunday.isChecked());
AlarmClockApplication.getDataSource().alarmItemChange(newAlarmItem);
setResult(RESULT_OK);
finish();
}
}
<file_sep>/app/src/main/java/com/me/ilya/smartalarmclock/main/AlarmListFragment.java
package com.me.ilya.smartalarmclock.main;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.me.ilya.smartalarmclock.AlarmEditActivity;
import com.me.ilya.smartalarmclock.AlarmItem;
import com.me.ilya.smartalarmclock.CursorAdapter;
import com.me.ilya.smartalarmclock.R;
import com.me.ilya.smartalarmclock.Titleable;
import java.text.SimpleDateFormat;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Ilya on 6/15/2016.
*/
public class AlarmListFragment extends Fragment implements Titleable {
AlarmItem deletedAlarm;
Adapter adapter;
@Override
public String getTitle(Context context) {
return "Alarm Clock Application";
}
public static AlarmListFragment create() {
return new AlarmListFragment();
}
RecyclerView alarmListRecycleView;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ImageView addButton;
View v = inflater.inflate(R.layout.alarm_list_fragment, container, false);
alarmListRecycleView = (RecyclerView) v.findViewById(R.id.alarm_list);
addButton = (ImageView) v.findViewById(R.id.btn_addAlarm);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(AlarmEditActivity.intent(getContext()), 0);
}
});
return v;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
adapter.swapCursor(AlarmClockApplication.getDataSource().alarmItemsGet());
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
adapter = new Adapter(getContext(), AlarmClockApplication.getDataSource().alarmItemsGet());
alarmListRecycleView.setAdapter(adapter);
alarmListRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
}
class ViewHolder extends RecyclerView.ViewHolder {
AlarmItem alarmItem;
@BindView(R.id.unabled_tv_days)
TextView unabledDays;
@BindView(R.id.unabled_tv_name)
TextView unabledName;
@BindView(R.id.tv_time_unabled)
TextView unabledTime;
@BindView(R.id.turnOffImage)
OnButton turnOffButton;
@BindView(R.id.tv_name)
TextView nameTextView;
@BindView(R.id.tv_days)
TextView daysTextView;
@BindView(R.id.tv_time)
TextView timeTextView;
@BindView(R.id.show_context_menu)
ImageView contextMenuImageView;
@BindView(R.id.turnOnImage)
OnButton onButton;
public ViewHolder(ViewGroup root) {
super(LayoutInflater.from(getContext()).inflate(R.layout.alarm_custom_item, root, false));
ButterKnife.bind(this, itemView);
}
public void bind(final AlarmItem alarmItem) {
this.alarmItem = alarmItem;
if (alarmItem.isEnabled()) {//TODO оптимизировать
unabledDays.setVisibility(View.INVISIBLE);
unabledTime.setVisibility(View.INVISIBLE);
unabledName.setVisibility(View.INVISIBLE);
turnOffButton.setVisibility(View.INVISIBLE);
nameTextView.setVisibility(View.VISIBLE);
daysTextView.setVisibility(View.VISIBLE);
timeTextView.setVisibility(View.VISIBLE);
onButton.setVisibility(View.VISIBLE);
FrameLayout frameLayout = (FrameLayout) itemView.findViewById(R.id.item_back);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
frameLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.list_item_background));
} else {
frameLayout.setBackground(getResources().getDrawable(R.drawable.list_item_background));
}
nameTextView.setText(this.alarmItem.getName());
timeTextView.setText(String.format(getString(R.string.alarm_time), alarmItem.getTimeHour(), alarmItem.getTimeMinute()));
} else {
nameTextView.setVisibility(View.INVISIBLE);
daysTextView.setVisibility(View.INVISIBLE);
timeTextView.setVisibility(View.INVISIBLE);
onButton.setVisibility(View.INVISIBLE);
unabledDays.setVisibility(View.VISIBLE);
unabledTime.setVisibility(View.VISIBLE);
unabledName.setVisibility(View.VISIBLE);
turnOffButton.setVisibility(View.VISIBLE);
FrameLayout frameLayout = (FrameLayout) itemView.findViewById(R.id.item_back);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
frameLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.list_item_background_unabled));
} else {
frameLayout.setBackground(getResources().getDrawable(R.drawable.list_item_background_unabled));
}
unabledName.setText(this.alarmItem.getName());
unabledTime.setText(String.format(getString(R.string.alarm_time), alarmItem.getTimeHour(), alarmItem.getTimeMinute()));
}
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(AlarmEditActivity.intent(getContext(), alarmItem.getId()), 0);
}
});
contextMenuImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(getContext(), v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_alarm_edit, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
deletedAlarm = AlarmClockApplication.getDataSource().getAlarmById(alarmItem.getId());
deletedAlarm.setDays(alarmItem.getDays());
AlarmClockApplication.getDataSource().deleteAlarmItem(alarmItem.getId());
adapter.swapCursor(AlarmClockApplication.getDataSource().alarmItemsGet());
Snackbar mSnackBar = Snackbar.make(itemView, "Будильник " + alarmItem.getName() + " удален", Snackbar.LENGTH_LONG);
mSnackBar.setAction("Отменить", new View.OnClickListener() {
@Override
public void onClick(View v) {
AlarmClockApplication.getDataSource().alarmItemChange(deletedAlarm);
deletedAlarm = null;
adapter.swapCursor(AlarmClockApplication.getDataSource().alarmItemsGet());
}
});
mSnackBar.show();
return true;
}
});
}
});
setDays();
}
private void setDays() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = AlarmItem.MONDAY; i <= AlarmItem.SUNDAY; i++) {
if (alarmItem.getDay(i)) {
switch (i) {
case 0:
stringBuilder.append(getString(R.string.monday)).append(" ");
break;
case 1:
stringBuilder.append(getString(R.string.tuesday)).append(" ");
break;
case 2:
stringBuilder.append(getString(R.string.wednesday)).append(" ");
break;
case 3:
stringBuilder.append(getString(R.string.thursday)).append(" ");
break;
case 4:
stringBuilder.append(getString(R.string.friday)).append(" ");
break;
case 5:
stringBuilder.append(getString(R.string.saturday)).append(" ");
break;
case 6:
stringBuilder.append(getString(R.string.sunday)).append(" ");
break;
}
}
}
daysTextView.setText(stringBuilder.toString());
unabledDays.setText(stringBuilder.toString());
}
}
class Adapter extends CursorAdapter<ViewHolder> {
// ViewGroup parent;
public Adapter(Context context, Cursor cursor) {
super(context, cursor);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// this.parent=parent;
return new ViewHolder(parent);
}
@Override
public void onBindViewHolder(final ViewHolder viewHolder, final Cursor cursor) {
final AlarmItem alarmItem = AlarmItem.fromCursor(cursor);//как
// if(alarmItem.isEnabled()){
// }
viewHolder.bind(alarmItem);
viewHolder.onButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlarmItem newAlarmItem = new AlarmItem(alarmItem.getId(), alarmItem.getName(), alarmItem.getTimeHour(), alarmItem.getTimeMinute(), alarmItem.getSong(), alarmItem.getDays(), !alarmItem.isEnabled());
AlarmClockApplication.getDataSource().alarmItemChange(newAlarmItem);
swapCursor(AlarmClockApplication.getDataSource().alarmItemsGet());
}
});
viewHolder.turnOffButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlarmItem newAlarmItem = new AlarmItem(alarmItem.getId(), alarmItem.getName(), alarmItem.getTimeHour(), alarmItem.getTimeMinute(), alarmItem.getSong(), alarmItem.getDays(), !alarmItem.isEnabled());
AlarmClockApplication.getDataSource().alarmItemChange(newAlarmItem);
swapCursor(AlarmClockApplication.getDataSource().alarmItemsGet());
}
});
}
}
}
<file_sep>/app/src/main/java/com/me/ilya/smartalarmclock/AlarmScreen.java
package com.me.ilya.smartalarmclock;
import android.app.Activity;
/**
* Created by Ilya on 6/26/2016.
*/
public class AlarmScreen extends Activity {
}
<file_sep>/app/src/main/java/com/me/ilya/smartalarmclock/DaySwitcher.java
package com.me.ilya.smartalarmclock;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.me.ilya.smartalarmclock.R;
/**
* Created by Ilya on 6/24/2016.
*/
public class DaySwitcher extends ImageView implements Checkable, View.OnClickListener {
private boolean mChecked;
private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
public DaySwitcher(final Context context, final AttributeSet attrs) {
super(context, attrs);
setOnClickListener(this);
}
@Override
public int[] onCreateDrawableState(final int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked())
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
return drawableState;
}
@Override
public void toggle() {
setChecked(!mChecked);
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void setChecked(final boolean checked) {
if (mChecked == checked)
return;
mChecked = checked;
refreshDrawableState();
}
@Override
public void onClick(View v) {
toggle();
}
} | 366587e7ea13f79a715b7ca07b62d8061debf9ac | [
"Java"
] | 4 | Java | Javagic/Smart_Alarm_Clock | fb9e3bd0b5b8756831dc610eb497e94ec1b41c8c | ad570826f490945993261d6c715e19cf13506769 |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="author" content="<NAME>">
<meta name ="description" content = "Esercizio 8.5">
<title>Esercizio 8.5</title>
</head>
<body>
<?php
// $nome = $_GET['nomeProdotto'];
// $prezzo = (double) $_GET['prezzoProdotto'];
// switch ($_GET['aliquota']){
$nome = $_POST['nomeProdotto'];
$prezzo = $_POST['prezzoProdotto'];
switch ($_POST['aliquota']){
case "minima":
$iva = 0.04;
break;
case "ridotta":
$iva = 0.1;
break;
case "ordinaria":
$iva = 0.22;
break;
default:
break;
}
echo "<h1>Risultato</h1>\n<div>";
if(preg_match("/[^a-zA-Z]/",$nome)){
echo "<div>ERRORE:il prodotto deve essere una stringa</div>\n";
}else if(!$nome){
echo "<div>ERRORE: bisogna inserire un nome</div>\n";
}else{
echo "<div>Nome del prodotto: {$nome}</div>\n";
}
if(!preg_match("/^\d+(\.|,\d{1,2})?$/",$prezzo)){
echo "<div>ERRORE: il costo deve essere un numero intero oppure con massimo due cifre decimali</div>\n";
$checkPrezzo = false;
}else if(!$prezzo){
echo "<div>ERRORE: riempire campo prezzo</div>\n";
$checkPrezzo = false;
}
if(!$iva){
echo "<div>ERRORE: selezionre un tipo di aliquota</div>\n";
$checkPrezzo = false;
}
if(!isset($checkPrezzo)){
$prezzo = (float) $prezzo;
$prezzoTotale = round($prezzo+($prezzo*$iva),2);
echo "<div>Prezzo con iva a {$iva}%: $prezzoTotale Euro</div>";
}
echo "</div>";
?>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name = 'author' content = '<NAME>'>
<meta name = 'description' content= 'Esercizio 8.1'>
<title>Esercizio 8.1</title>
</head>
<body>
<?php
// $valoreInput = $_GET['inputUtente'];
$valoreInput = $_POST['inputUtente'];
echo( "<h1>Testo ricevuto</h1>\n");
echo("<p>{$valoreInput}</p>\n");
?>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="author" content="<NAME>">
<link rel="icon" type="image/png" href="https://security.polito.it/img/polito.gif">
<link rel="stylesheet" type="text/css" href="../Lab_4/foglio_stile.css">
<title>Esami studente</title>
</head>
<body>
<h1>
Libretto Voti Esami Superati
</h1>
<table class=esami_superati >
<thead>
<tr>
<th>
Nome esame
</th>
<th>
Valutazione
</th>
</tr>
</thead>
<tbody>
<tr class="voto_verde">
<td>English language first level</td>
<td class="voto">Superato</td>
</tr>
<tr class="voto_verde">
<td >Mathematical Analysis 1</td>
<td class="voto">28</td>
</tr>
<tr class="voto_verde">
<td >Computer science</td>
<td class="voto">27</td>
</tr>
<tr class="voto_rosa">
<td >Chemistry</td>
<td class="voto">20</td>
</tr>
<tr class="voto_verde">
<td >Physics 1</td>
<td class="voto">27</td>
</tr>
<tr class="voto_verde">
<td >Imprenditorialità e Innovazione</td>
<td class="voto">30 e lode</td>
</tr>
<tr class="voto_verde">
<td>Linear algebra and geometry</td>
<td class="voto">30 e lode</td>
</tr>
<tr class="voto_verde">
<td>Basi di dati</td>
<td class="voto">28</td>
</tr>
<tr class="voto_verde">
<td>Statistica</td>
<td class="voto">26</td>
</tr>
<tr class="voto_verde">
<td>Analisi Matematica 2</td>
<td class="voto">25</td>
</tr>
<tr class="voto_verde">
<td>Fisica 2</td>
<td class="voto">27</td>
</tr>
<tr class="voto_verde">
<td>Ricerca Operativa</td>
<td class="voto">30 e lode</td>
</tr>
<tr class="voto_verde">
<td>Sistemi di Produzione</td>
<td class="voto">24</td>
</tr>
<tr class="voto_verde">
<td>Sistemi Eletrici Industriali</td>
<td class="voto">30</td>
</tr>
<tr class="voto_rosa">
<td>Economia ed Orgianizzazione Aziedale</td>
<td class="voto">22</td>
</tr>
<tr class="voto_verde">
<td> Programmazione ad Oggetti</td>
<td class="voto">30 e lode</td>
</tr>
<tr class="voto_verde">
<td>Elementi di diritto privato</td>
<td class="voto">26</td>
</tr>
<tr class="voto_verde">
<td>Programmazione e Gestione della Produzione</td>
<td class="voto">24</td>
</tr>
<tr class="voto_verde">
<td>Sistemi Telematici</td>
<td class="voto">27</td>
</tr>
</tbody>
</table>
<nav>
<details>
<summary>
Link correlati
</summary>
<details>
<summary>
Informazioni personali
</summary>
<a href="Dati_studente.html" >Informazioni <NAME></a>
</details>
<details>
<summary>
Esami e valutazioni
</summary>
<a href="tabella_esami.html">Voti <NAME></a>
</details>
</details>
</nav>
<hr>
<footer>
<NAME> <EMAIL>
<p>
<img src="https://security.polito.it/img/polito.gif" alt="Logo Politecnico di Torino" usemap="#link_collegamento" class="logo">
<map name="link_collegamento">
<area shape="rect" coords="0,0,100,50" href="https://www.polito.it/" alt="Link Politecnico di Torino">
<area shape="rect" coords="0,50,100,100" href="http://www.comune.torino.it/" alt="Link Comune di Torino">
</map>
</p>
</footer>
<img src="logo_HTML5.png" alt="Logo HTML5" id="logo_HTML5">
</body>
</html><file_sep>'use strict';
window.alert('inizio caricamento');
document.writeln('<NAME>');
window.alert('fine caricamento');
//setTimeout(()=>window.alert('fine caricamento'),5000);<file_sep>function Maggiore(...input){
input.forEach(v => {Number(v)});
if(input.some(v => isNaN(v))){
return "ERRORE: inserire numeri nel formato corretto."
}
var max = input[0];
for(let i = 1; i<input.length;i++){
if(input[i]>max){
max = input[i];
}
}
return max;
}<file_sep><!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name = 'author' content="<NAME>">
<meta name = 'description' content="Esercizio 8.3">
<title>Esercizio 8.3</title>
</head>
<body>
<?php
// $numero = $_GET["menu"];
$numero = $_POST["menu"];
echo("<table>\n
<thead>\n
<tr>\n
<th>NUMERO</th>\n
<th>N^2</th>\n
<th >N^3<th>\n</tr>\n
</thead>\n<tbody>\n");
for($i=1;$i<=$numero;$i++){
$quadrato = $i*$i;
$cubo = $quadrato*$i;
echo("<tr>\n
<td>{$i}</td>\n
<td>{$quadrato}</td>\n
<td>{$cubo}</td>\n
</tr>\n");
}
echo("</tbody>\n</table>");
?>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="author" content="<NAME>">
<meta name = "description" content = "Esercizio 8.2">
<title>Esercizio 8.2</title>
</head>
<body>
<?php
// $num1 = (int) $_GET['n1'];
// $num2 = (int) $_GET['n2'];
$num1 = (int) $_POST['n1'];
$num2 = (int) $_POST['n2'];
$somma = $num1 + $num2;
echo("<h1>Risultato somma</h1>\n
<p>{$num1} + ({$num2}) = {$somma}</p>\n
<p><a href='esercizio8.2.html'>Torna alla pagina iniziale</a></p>\n");
?>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="author" content = "<NAME>">
<meta name="description" content = "Esercizio 8.4">
<title>Esercizio 8.4</title>
</head>
<body>
<?php
// $nome = $_GET['nomeProdotto'];
// $prezzo = (double) $_GET['prezzoProdotto'];
// switch ($_GET['aliquota']){
$nome = $_POST['nomeProdotto'];
$prezzo = (double) $_POST['prezzoProdotto'];
switch ($_POST['aliquota']){
case "minima":
$iva = 0.04;
break;
case "ridotta":
$iva = 0.1;
break;
case "ordinaria":
$iva = 0.22;
break;
default:
alert("ERRORE");
break;
}
$prezzoTotale = round($prezzo+($prezzo*$iva),2);
echo "<h1>Risultato</h1>\n";
echo "<p>$nome costa: $prezzoTotale Euro</p>"
?>
</body>
</html> | bad43b909df6a16ba160493fd7e801a7428fcec9 | [
"JavaScript",
"HTML",
"PHP"
] | 8 | PHP | sofialucca/LaboratoriPWR | 36b511d98faab9973d8f7ee329d35369aaafd12d | 588101c7ec7c32414c2d85e5be43a85a3330750c |
refs/heads/master | <file_sep># CodeBook
This codebook describes the variables, data and work performed to clean up the data.
The data set record human activity recognition using smartphones.
The data set was downloaded from https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip
## Background
The experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years. Each person performed six activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING) wearing a smartphone (Samsung Galaxy S II) on the waist. Using its embedded accelerometer and gyroscope, 3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz were captured. The experiments have been video-recorded to label the data manually. The obtained dataset has been randomly partitioned into two sets, where 70% of the volunteers was selected for generating the training data and 30% the test data.
The features selected for this database come from the accelerometer and gyroscope 3-axial raw signals tAcc-XYZ and tGyro-XYZ. These time domain signals (prefix 't' to denote time) were captured at a constant rate of 50 Hz. Then they were filtered using a median filter and a 3rd order low pass Butterworth filter with a corner frequency of 20 Hz to remove noise. Similarly, the acceleration signal was then separated into body and gravity acceleration signals (tBodyAcc-XYZ and tGravityAcc-XYZ) using another low pass Butterworth filter with a corner frequency of 0.3 Hz.
Subsequently, the body linear acceleration and angular velocity were derived in time to obtain Jerk signals (tBodyAccJerk-XYZ and tBodyGyroJerk-XYZ). Also the magnitude of these three-dimensional signals were calculated using the Euclidean norm (tBodyAccMag, tGravityAccMag, tBodyAccJerkMag, tBodyGyroMag, tBodyGyroJerkMag).
Finally a Fast Fourier Transform (FFT) was applied to some of these signals producing fBodyAcc-XYZ, fBodyAccJerk-XYZ, fBodyGyro-XYZ, fBodyAccJerkMag, fBodyGyroMag, fBodyGyroJerkMag. (Note the 'f' to indicate frequency domain signals).
These signals were used to estimate variables of the feature vector for each pattern:
'-XYZ' is used to denote 3-axial signals in the X, Y and Z directions.
* tBodyAcc-XYZ
* tGravityAcc-XYZ
* tBodyAccJerk-XYZ
* tBodyGyro-XYZ
* tBodyGyroJerk-XYZ
* tBodyAccMag
* tGravityAccMag
* tBodyAccJerkMag
* tBodyGyroMag
* tBodyGyroJerkMag
* fBodyAcc-XYZ
* fBodyAccJerk-XYZ
* fBodyGyro-XYZ
* fBodyAccMag
* fBodyAccJerkMag
* fBodyGyroMag
* fBodyGyroJerkMag
Features are normalized and bounded within [-1,1].
The set of variables that were estimated from these signals are:
* mean(): Mean value
* std(): Standard deviation
* mad(): Median absolute deviation
* max(): Largest value in array
* min(): Smallest value in array
* as well as other related variables.
## The Tidy Data Set
A dataframe comprises the identifier of the subject, activity label as well as the 561 feature vectors were formed by merging the training and test data sets.
A new and smaller dataframe is formed my extracting only the measurements on the mean and standard deviation for each measurement. For example tBodyAcc-mean()-X and tBodyAcc-std()-X measures the mean and the standard deviation of the variable tBodyAcc in the direction of X.
Descriptive activity names were used to name the activities in the data set.
The data set is further tidied by averaging each variable for each activity and each subject.
The heading of each variable is cleaned by removing characters such as "-","()" as well as white space. However, Capital letters are maintained for better readability.
The final data set comprises the following 81 variables:
* subject - identifier of the subject; integer values from 1 through 30.
* activity - factor variables with labels "walking", "walking_upstairs", "walking_downstairs", "sitting", "standing" and "laying".
* tBodyAccmeanX
* tBodyAccmeanY
* tBodyAccmeanZ
* tBodyAccstdX
* tBodyAccstdY
* tBodyAccstdZ
* tGravityAccmeanX
* tGravityAccmeanY
* tGravityAccmeanZ
* tGravityAccstdX
* tGravityAccstdY
* tGravityAccstdZ
* tBodyAccJerkmeanX
* tBodyAccJerkmeanY
* tBodyAccJerkmeanZ
* tBodyAccJerkstdX
* tBodyAccJerkstdY
* tBodyAccJerkstdZ
* tBodyGyromeanX
* tBodyGyromeanY
* tBodyGyromeanZ
* tBodyGyrostdX
* tBodyGyrostdY
* tBodyGyrostdZ
* tBodyGyroJerkmeanX
* tBodyGyroJerkmeanY
* tBodyGyroJerkmeanZ
* tBodyGyroJerkstdX
* tBodyGyroJerkstdY
* tBodyGyroJerkstdZ
* tBodyAccMagmean
* tBodyAccMagstd
* tGravityAccMagmean
* tGravityAccMagstd
* tBodyAccJerkMagmean
* tBodyAccJerkMagstd
* tBodyGyroMagmean
* tBodyGyroMagstd
* tBodyGyroJerkMagmean
* tBodyGyroJerkMagstd
* fBodyAccmeanX
* fBodyAccmeanY
* fBodyAccmeanZ
* fBodyAccstdX
* fBodyAccstdY
* fBodyAccstdZ
* fBodyAccmeanFreqX
* fBodyAccmeanFreqY
* fBodyAccmeanFreqZ
* fBodyAccJerkmeanX
* fBodyAccJerkmeanY
* fBodyAccJerkmeanZ
* fBodyAccJerkstdX
* fBodyAccJerkstdY
* fBodyAccJerkstdZ
* fBodyAccJerkmeanFreqX
* fBodyAccJerkmeanFreqY
* fBodyAccJerkmeanFreqZ
* fBodyGyromeanX
* fBodyGyromeanY
* fBodyGyromeanZ
* fBodyGyrostdX
* fBodyGyrostdY
* fBodyGyrostdZ
* fBodyGyromeanFreqX
* fBodyGyromeanFreqY
* fBodyGyromeanFreqZ
* fBodyAccMagmean
* fBodyAccMagstd
* fBodyAccMagmeanFreq
* fBodyBodyAccJerkMagmean
* fBodyBodyAccJerkMagstd
* fBodyBodyAccJerkMagmeanFreq
* fBodyBodyGyroMagmean
* fBodyBodyGyroMagstd
* fBodyBodyGyroMagmeanFreq
* fBodyBodyGyroJerkMagmean
* fBodyBodyGyroJerkMagstd
* fBodyBodyGyroJerkMagmeanFreq
<file_sep># A Guide to Tidy Data Set
* This document explains the process in obtaining the final data set from raw data.
## Data
* The data set was obtained from https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip.
* This data set records human activity recognition using smartphones.
* The downloaded data set was unzipped and relevant data files were saved into the working directory for easing reading into R.
## Reading Data into R and Merging
* The variable denoting the human subjects where measurements were collected were read from the files "subject_train.txt" and "subject_test.txt". These were merged into a vector named "subject" using rbind.
* The activities performed by the subjects were read from "y_train.txt" and "y_test.txt" which formed the vector "activity".
* The measurements collected from the accelerometer and gyroscope were read from the files "X_train.txt" and "X_test.txt". A dataframe named "dat" were formed by merging these data and names of each variable were added in from the "features.txt" file.
## Dataframe
* A dataframe with all measurements was constructed using cbind to bind the vectors "subject", "activity" as well as the dataframe "dat".
* This dataframe is already labelled with descriptive variable names.
## Subset the Dataframe
* To extract only the measurements on the mean and standard deviation for each measurement.
* grep is used to identify the columns with mean and std in each variable names.
* An index vector identifying the relevant columns was formed and used to subset the dataframe, resulting in the required dataframe "df".
## Naming Activities
* Data in the column activity are integers where "1" represents "walking" , "2" represents "walking_upstairs", "3" represents "walking_downstairs", "4" represents "sitting", "5" represents "standing" and "6" represents "laying".
* To replace these integers by its descriptive name, the activity data were converted into factors and labelled accordingly.
## Creating a second, independent tidy data set with the average of each variable for each activity and each subject.
* The aggregate function is used to compute the average of each variable for each activity and each subject. A new dataframe, "dfavg" is formed with the aggregate function.
* The column names of this new data set was tidied using gsub to remove "-", "()" as well as whitespace.
* Please note that Capital letters were maintained for better readability. I find astringoflowercaseletters difficult to read.
* The dataframe "dfavg" is then exported as "tidydata.txt" using write.table. <file_sep>setwd("C:/Users/leefah/Documents/Coursera/Getting and Cleaning Data/Project")
TrainSub<-read.table("subject_train.txt")
TestSub<-read.table("subject_test.txt")
subject<-rbind(TrainSub, TestSub)
colnames(subject)<-c("subject")
Ytrain<-read.table("y_train.txt")
Ytest<-read.table("y_test.txt")
activity<-rbind(Ytrain, Ytest)
colnames(activity)<-c("activity")
Xtrain<-read.table("X_train.txt")
Xtest<-read.table("X_test.txt")
dat<-rbind(Xtrain, Xtest)
feature<-read.table("features.txt")
varname<-feature$V2
colnames(dat)<-varname
dfall<-cbind(subject,activity,dat)
NameVar<-names(dfall)
labels<-c("subject","activity",NameVar[grep("mean",NameVar)],NameVar[grep("std",NameVar)])
index<-which(NameVar %in% labels)
df<-dfall[,index]
df$activity<-factor(df$activity)
levels(df$activity)<-c("walking","walking_upstairs","walking_downstairs","sitting","standing","laying")
subdf<-subset(df,select=c(names(df)[3:81]))
dfavg<-aggregate(subdf,by=list(subject=df$subject,activity=df$activity),FUN=mean, na.rm=T)
tidyname<-gsub("-|\\(|\\)|\\s","",names(dfavg))
colnames(dfavg)<-tidyname
write.table(dfavg, "C:/Users/leefah/Documents/Coursera/Getting and Cleaning Data/Project/tidydata.txt",row.names=F)
| 5ee7caa51ef9f73c1e38a21185d7ac170372fc45 | [
"Markdown",
"R"
] | 3 | Markdown | Leefah/Getting-and-Cleaning-Data-Project | bc2447cbb309111ed2d04b96d247bcfa806caebf | 6b30cbee4d41cfd6a1e12f2034df70eb37d814e9 |
refs/heads/master | <file_sep>## The code shown here is used for finding inverse of a matrix.
## The initial portion allows users to input the values of the
## required matrix. The latter half checks if the calculation
## for given matrix has been done earlier, to save time. If
## not, it performs calculation and stores result in a variable
## for future reference.
## This section of the code can obtain the value of a matrix,
## as well as display it.
makeCacheMatrix <- function(x = matrix()) {
m<-NULL
set<-function(y){
x<<-y
m<<-NULL
}
get<-function() x
setmatrix<-function(solve) m<<- solve
getmatrix<-function() m
list(set=set, get=get,
setmatrix=setmatrix,
getmatrix=getmatrix)
}
## This section of code checks if there is a stored value for
## inverse of given matrix. If not, it will perform the
## calculation and cache the value in variable 'm'.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m<-x$getmatrix()
if(!is.null(m)){
message("getting cached data")
return(m)
}
matrix<-x$get()
m<-solve(matrix, ...)
x$setmatrix(m)
m
}
| 06512638d80e6dcaedd52da0bc519265d4cd938f | [
"R"
] | 1 | R | vjkoshy/ProgrammingAssignment2 | e9c642780bcc1aa79f3d4aa33461323833e01a3f | 69a96f0d892d8b80ed1c479013e69cc0dea6de32 |
refs/heads/main | <file_sep>window.onload = function load() {
// alert("Welcome to my Porfolio Website.Work is still in progress but feel free to check it out,Thank you");
/*Code for creating a sticky header that stays on screen as user scrolls */
const faders = document.querySelectorAll(".fade-in");
const sliders = document.querySelectorAll(".slide-in");
const appearOptions = {
threshold: 0,
rootMargin: "0px 0px -250px 0px"
};
const appearOnScroll = new IntersectionObserver(function(
entries,
appearOnScroll
) {
entries.forEach(entry => {
if (!entry.isIntersecting) {
return;
} else {
entry.target.classList.add("appear");
appearOnScroll.unobserve(entry.target);
}
});
},
appearOptions);
faders.forEach(fader => {
appearOnScroll.observe(fader);
});
sliders.forEach(slider => {
appearOnScroll.observe(slider);
});
$(".about-img").hover(function(){
$(this).fadeOut(500,function(){
$(this).attr("src","image/about-me-self-image-2.jpg");
$(this).fadeIn(500);
});
}, function(){
$(this).fadeOut(1000, function(){
$(this).attr("src","image/about-me-self-image.jpg");
$(this).fadeIn(1000);
});
});
window.onscroll = function () { myFunction() };
var header = document.getElementById("header");
var sticky = header.offsetTop;
console.log(sticky);
function myFunction() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
var mobHamBtn = document.getElementById("ham-btn-cta");
var exit = document.getElementById("mob-exit");
// var nav = document.getElementById("menu");
mobHamBtn.onclick = navToggle;
function navToggle() {
var nav = document.querySelector("nav");
nav.style.display = "block";
}
exit.onclick = exitNav;
function exitNav() {
var nav = document.querySelector("nav");
nav.style.display = "none";
}
var form = document.getElementById("my-form");
async function handleSubmit(event) {
event.preventDefault();
var status = document.getElementById("my-form-status");
var data = new FormData(event.target);
let name = document.getElementById("fullname").value;
let email = document.getElementById("email").value;
let subject =document.getElementById("subject").value;
let message = document.getElementById("message").value;
if(name === "" || name === null || email === "" || email === null || subject === "" || subject === null || message === "" || message === null){
status.innerHTML = "Please Fill in all Fields";
status.style.color = "red";
return false;
name.focus();
}
else{
fetch(event.target.action, {
method: form.method,
body: data,
headers: {
'Accept': 'application/json'
}
}).then(response => {
status.style.color = "#12fcd8";
status.innerHTML = `Thank you ${name} for Contacting me. I will get in touch with you shortly!`;
form.reset()
}).catch(error => {
status.innerHTML = "Oops! There was a problem submitting your form"
});
}
}
form.addEventListener("submit", handleSubmit)
}
<file_sep><?php
//INITIALIZE THE VARIABLES
$errors = "";
$fullName = "";
$email = "";
$subject = "";
$message = "";
//FUNCTION TO VALIDATE THE FORM
function validateContactForm($fullname,$email,$subject, $message, $errors)
{
//IF FIRST NAME EMPTY, THROW AN ERROR
if (empty($fullname)) {
$errors .= "Please enter your Full Name<br/>";
} else {
$errors .= ""; }
//IF EMAIL EMPTY OR NOT A VALID FORMAT, THROW AN ERROR
if (empty($email)) {
$errors .= "Please enter your fill name";
} else{
$errors .= "";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "Please enter valid email format<br/>";
} else{
$errors .= "";
}
//IF ENQURY SELECTION ID EMPTY, THROW AN ERROR
if (empty($subject ) ) {
$errors .= "Please Enter a Subject<br/>";
}
//IF MESSAGE TEXT BOX IS EMPTY, THROW AN ERROR
if (empty($message)) {
$errors .= "Please enter a message<br/>";
}else{
$errors .= "";
}
return $errors;
} | acb8a1728feeb8be67af37d54e460f9ef666eb93 | [
"JavaScript",
"PHP"
] | 2 | JavaScript | NeilMoras/portfolio | 9cbd6c354e0b093daa1753e9f8fed3db0cff2250 | cf74bf01a0688ba30c0d64a5761bccc3e2190df5 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use App\User;
use App\Avatar;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index(){
$users= User::all();
return view ('tab_user', compact('users' ));
}
public function create(){
$users= User::all();
$avatars= Avatar::all();
return view ('ajout_user' , compact('users' , 'avatars'));
}
public function store(Request $request){
$request->validate([
'name'=> 'required|min:1',
'age'=>'required',
'email'=>'required',
'password'=>'<PASSWORD>',
'id_avatar'=>'required',
'id_role'=>'required',
]);
$users= new User();
$users->name =$request->input('name');
$users->age =$request->input('age');
$users->email =$request->input('email');
$users->password =$request->input('<PASSWORD>');
$users->id_avatar =$request->input('id_avatar');
$users->id_role =$request->input('id_role');
// ( le nom de mon input)
$users->save();
return redirect()->route('tab_user');
}
public function edit($id){
$users= User::find($id);
// $genres=Genre::all();
// $auteurs=Auteur::all();
return view('/edit_user' , compact('users'));
}
public function update(Request $request, $id){
$request->validate([
'name'=> 'required|min:1',
'age'=>'required',
'email'=>'required',
'password'=>'<PASSWORD>'
]);
$users= User::find($id);
$avatars= Avatar::all();
$users->name =$request->input('name');
$users->age =$request->input('age');
$users->email =$request->input('email');
$users->password =$request->input('<PASSWORD>');
$users->id_avatar =$request->input('id_avatar');
$users->id_role =$request->input('id_role');
$users->save();
return redirect()->route('tab_user');
}
public function show( $id){
$users=User::all()->where('id',$id);
return view ('show_user' , compact('users'));
}
public function destroy($id){
$users=User::find($id);
$users->delete();
return redirect()->back();
}
}
<file_sep>require('./bootstrap');
require('bootstrap/dist/js/bootstrap');
require('jquery');
require('popper.js');<file_sep><?php
namespace App\Http\Controllers;
use App\Image;
use Illuminate\Http\Request;
class ImageController extends Controller
{
public function index(){
$images= Image::all();
return view ('/tab_image', compact('images' ));
}
public function create(){
$images= Image::all();
return view ('ajout_image' , compact('images'));
}
public function store(Request $request){
$request->validate([
'image'=> 'required',
]);
$images= new Image();
$images->image =$request->input('image');
// ( le nom de mon input)
$images->save();
return redirect()->route('tab_image');
}
public function edit($id){
$images= Image::find($id);
// $genres=Genre::all();
// $auteurs=Auteur::all();
return view('/edit_image' , compact('images'));
}
public function update(Request $request, $id){
$request->validate([
'image'=>'required',
]);
$images= Image::find($id);
$users->image =$request->input('image');
$images->save();
return redirect()->route('tab_image');
}
public function show( $id){
$images=Image::all()->where('id',$id);
return view ('show_image' , compact('images'));
}
public function destroy($id){
$images=Image::find($id);
$images->delete();
return redirect()->back();
}
public function download($id)
{
$img = Image::find($id);
return Storage::disk('public')->download($img->image);
}
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFailedJobsTable extends Migration
{
/**
* Run the mSQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = Galerie_laravel and table_name = migrations and table_type = 'BASE TABLE')igrations.
*
* @return void
*/
public function up()
{
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('failed_jobs');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Avatar;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
class AvatarController extends Controller
{
public function index(){
$avatars= Avatar::all();
return view ('/tab_avatar', compact('avatars' ));
}
public function create(){
$avatars= Avatar::all();
return view ('ajout_avatar' , compact('avatars'));
}
public function store(Request $request){
$request->validate([
'name'=> 'required|min:1',
'avatar'=> 'required',
]);
$storages=Storage::disk('public')->put('', $request->file('avatar'));
$avatars= new Avatar();
$avatars->name =$request->input('name');
$avatars->avatar =$storages;
// ( le nom de mon input)
$avatars->save();
return redirect()->route('tab_avatar');
}
public function edit($id){
$avatars= Avatar::find($id);
// $genres=Genre::all();
// $auteurs=Auteur::all();
return view('/edit_avatar' , compact('avatars'));
}
public function update(Request $request, $id){
$request->validate([
'name'=> 'required|min:1',
'avatar'=>'required',
]);
$storages=Storage::disk('public')->put('', $request->file('avatar'));
$avatars= Avatar::find($id);
$avatars->name =$request->input('name');
$avatars->avatar =$storages;
$avatars->save();
return redirect()->route('tab_avatar');
}
public function show( $id){
$avatars=Avatar::all()->where('id',$id);
$avatars= new Avatar();
return view ('show_avatar' , compact('avatars'));
}
public function destroy($id){
$avatars=Avatar::find($id);
Storage::disk("public")->delete($avatars->avatar);
$avatars->delete();
return redirect()->back();
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/','WelcomeController@index')->name('home');
// Users
Route::get('/tab_user',"UserController@index" )->name('tab_user');
Route::get('/show_user/{id}', 'UserController@show')->name('show_user');
Route::get('/ajout_user', "UserController@create" )->name('ajout_user');
Route::post('/save_user', 'UserController@store')->name('save_user');
Route::get('/edit_user/{id}',"UserController@edit" )->name('edit_user');
Route::post('/update_user/{id}',"UserController@update" )->name('update_user');
Route::get('/delete_user/{id}', 'UserController@destroy')->name('delete_user');
// Avatar
Route::get('/tab_avatar',"AvatarController@index" )->name('tab_avatar');
Route::get('/show_avatar/{id}', 'AvatarController@show')->name('show_avatar');
Route::get('/ajout_avatar', "AvatarController@create" )->name('ajout_avatar');
Route::post('/save_avatar', 'AvatarController@store')->name('save_avatar');
Route::get('/edit_avatar/{id}',"AvatarController@edit" )->name('edit_avatar');
Route::post('/update_avatar/{id}',"AvatarController@update" )->name('update_avatar');
Route::get('/delete_avatar/{id}', 'AvatarController@destroy')->name('delete_avatar');
// Categorie
Route::get('/tab_categorie',"CategorieController@index" )->name('tab_categorie');
Route::get('/show_categorie/{id}', 'CategorieController@show')->name('show_categorie');
Route::get('/ajout_categorie', "CategorieController@create" )->name('ajout_categorie');
Route::post('/save_categorie', 'CategorieController@store')->name('save_categorie');
Route::get('/edit_categorie/{id}',"CategorieController@edit" )->name('edit_categorie');
Route::post('/update_categorie/{id}',"CategorieController@update" )->name('update_categorie');
Route::get('/delete_categorie/{id}', 'CategorieController@destroy')->name('delete_categorie');
//image
Route::get('/tab_image',"ImageController@index" )->name('tab_image');
Route::get('/show_image/{id}', 'ImageController@show')->name('show_image');
Route::get('/ajout_image', "ImageController@create" )->name('ajout_image');
Route::post('/save_image', 'ImageController@store')->name('save_image');
Route::get('/edit_image/{id}',"ImageController@edit" )->name('edit_image');
Route::post('/update_image/{id}',"ImageController@update" )->name('update_image');
Route::get('/delete_image/{id}', 'ImageController@destroy')->name('delete_image');
Route::get('/download_image/{id}', 'ImageController@download')->name('download_image');<file_sep><?php
namespace App\Http\Controllers;
use App\Categorie;
use Illuminate\Http\Request;
class CategorieController extends Controller
{
public function index(){
$categories= Categorie::all();
return view ('/tab_categorie', compact('categories' ));
}
public function create(){
$categories= Categorie::all();
return view ('ajout_categorie' , compact('categories'));
}
public function store(Request $request){
$request->validate([
'categorie'=> 'required',
]);
$categories= new Categorie();
$categories->categorie =$request->input('categorie');
// ( le nom de mon input)
$categories->save();
return redirect()->route('tab_categorie');
}
public function edit($id){
$categories= Categorie::find($id);
// $genres=Genre::all();
// $auteurs=Auteur::all();
return view('/edit_categorie' , compact('categories'));
}
public function update(Request $request, $id){
$request->validate([
'categorie'=>'required',
]);
$categories= Categorie::find($id);
$categories->categorie =$request->input('categorie');
$categories->save();
return redirect()->route('tab_categorie');
}
public function show( $id){
$categories=Categorie::all()->where('id',$id);
return view ('show_categorie' , compact('categories'));
}
public function destroy($id){
$categories=Categorie::find($id);
$categories->delete();
return redirect()->back();
}
}
| deb87a8c01fb105d0fcd5bfee859d547f3836167 | [
"JavaScript",
"PHP"
] | 7 | PHP | Oxalys/GalerieLaravel | 0d747536014f81b67af783ea0547a9fcde64b2ff | 01b09020040de6674338855fbd269f5144ded50a |
refs/heads/master | <file_sep>import React from 'react';
import {connect} from 'react-redux'
import Images from './images'
import Text from './text'
const PicturesWrapper = ({ isPicturesEmpty }) => {
return (
<div className='pictures_wrapper'>
{ isPicturesEmpty ? <Text /> : <Images /> }
</div>
)
};
export default connect(
(state) => ({
isPicturesEmpty: state.data.isPicturesEmpty
})
)(PicturesWrapper)<file_sep>import React, {Component} from 'react';
import {connect} from 'react-redux'
import { getPictures,
getImages,
getAlbum,
changeEmptyPictures
} from '../store/actions/pictures.action.js'
class Busket extends Component {
dragOver = (e) => e.preventDefault()
dragDrop = (e) => {
let tag = e.target.innerHTML;
let src = e.dataTransfer.getData('src');
let tesak = e.dataTransfer.getData('tesak');
if (tesak === tag) {
let updatedPictures = this.props.pictures.filter(pic => {
let imgSrc = 'https://farm' + pic.farm + '.staticflickr.com/' + pic.server + '/' + pic.id + '_' + pic.secret + '.jpg';
return imgSrc !== src;
});
let images = this.props.images;
images[tag].push(e.dataTransfer.getData('src'));
this.props.getImages(images)
this.props.getPictures(updatedPictures)
if (!updatedPictures.length) {
this.props.changeEmptyPictures()
}
}
}
render() {
return (
<div
className='item'
onDragOver={this.dragOver}
onDrop={this.dragDrop}
onClick={() =>
this.props.onClick(this.props.img)}
text = {this.props.text}
>
{this.props.text}
</div>
);
}
}
export default connect(
(state) => ({
pictures: state.data.pictures,
images: state.data.images
}),
{ getPictures,
getImages,
getAlbum,
changeEmptyPictures }
)(Busket)<file_sep>import React, {Component} from 'react';
import {connect} from 'react-redux'
class Images extends Component {
dragStart = (ev, obj) => {
ev.persist();
ev.dataTransfer.setData('src', obj.src);
ev.dataTransfer.setData('tesak', obj.tesak);
};
render() {
return (
<div className='image'>
{
this.props.pictures.map((pic, i) => {
let src = 'https://farm' + pic.farm + '.staticflickr.com/' + pic.server + '/' + pic.id + '_' + pic.secret + '.jpg';
return <img
key={i}
alt={pic.id}
src={src}
draggable
onDragStart={ (ev) =>
this.dragStart(ev, {src: src, tesak: pic.tesak}) }
/>
})
}
</div>
);
}
}
export default connect(
(state) => ({pictures: state.data.pictures}),
)(Images)<file_sep>import GetPhotos from '../../api'
export const GET_TAGS = 'GET_TAGS'
export const GET_PICTURES = 'GET_PICTURES'
export const GET_IMAGES = 'GET_IMAGES'
export const GET_ALBUM = 'GET_ALBUM'
export const CHANGE_EMPTYPICTURES = 'CHANGE_EMPTYPICTURES'
export const getTags = ( data ) => {
return { type: GET_TAGS, payload: data }
}
export const getPictures = ( data ) => {
return { type: GET_PICTURES, payload: data }
}
export const dispatchGetPictures = ( tags, data ) => {
return (dispatch) => {
dispatch(getTags(tags))
GetPhotos(data, tags)
.then(arr => {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
dispatch(getPictures(arr))
})
.then(res => {
let images = {}
for (let i = 0; i < tags.length; i++) {
images[tags[i]] = [];
}
dispatch(getImages(images))
})
}
}
export const getImages = (data) => {
return { type: GET_IMAGES, payload: data }
}
export const getAlbum = (data) => {
return { type: GET_ALBUM, payload: data }
}
export const changeEmptyPictures = () => {
return { type: CHANGE_EMPTYPICTURES }
}<file_sep>import {
GET_TAGS,
GET_PICTURES,
GET_IMAGES,
GET_ALBUM,
CHANGE_EMPTYPICTURES
} from '../actions/pictures.action'
const initState = {
tags: [],
searchingText: '',
pictures: [],
images: {},
albumImages: [],
isPicturesEmpty: true,
firstTime: true
}
const PicturesReducer = (state = initState, action) => {
switch (action.type) {
case GET_TAGS:
return {
...state,
tags: action.payload
}
case GET_PICTURES:
return {
...state,
pictures: action.payload,
isPicturesEmpty: false,
firstTime: false,
albumImages: []
}
case GET_IMAGES:
return {
...state,
images: action.payload
}
case GET_ALBUM:
return {
...state,
albumImages: action.payload
}
case CHANGE_EMPTYPICTURES:
return {
...state,
isPicturesEmpty: true
}
default:
return state
}
}
export default PicturesReducer<file_sep>import React from 'react';
import {connect} from 'react-redux'
import Busket from "./busket";
import { getAlbum } from '../store/actions/pictures.action.js'
const BusketsContent = ({ getAlbum, tags, images }) => {
const buskets = tags.map((tag, ind) => (
<Busket
key={ind}
text={tag}
onClick={() => getAlbum(images[tag])} />
));
return <div
className='buskets'>
{buskets}
</div>
};
export default connect(
(state) => ({
images: state.data.images,
tags: state.data.tags
}),
{ getAlbum }
)(BusketsContent)<file_sep>import React from 'react';
import {connect} from 'react-redux'
const Album = (props) => {
const albumImages = props.albumImages.map((img,i) => {
return <img
key={i}
src={img}
alt="sdfd" />
});
return <div
className='Album'>
{albumImages}
</div>
};
export default connect(
(state) => ({ albumImages: state.data.albumImages })
)(Album)<file_sep>import {createStore, applyMiddleware, combineReducers} from 'redux'
import {composeWithDevTools} from 'redux-devtools-extension'
import thunk from 'redux-thunk'
import PicturesReducer from './reducers/pictures.reducer'
const reducer = combineReducers({
data: PicturesReducer
})
export default createStore(
reducer,
composeWithDevTools(
applyMiddleware(thunk)
)
)<file_sep>import React from 'react';
import {connect} from 'react-redux'
const Text = ({ firstTime }) => {
return (
<div
className='text'>
{ firstTime ? 'Search pics to sort' : 'Search new pics to sort' }
</div>
);
}
export default connect(
(state) => ({firstTime: state.data.firstTime}),
)(Text) | 545bff06c7b607521e4853fef309c260a8d564ed | [
"JavaScript"
] | 9 | JavaScript | HYegh/dragDrop | 857b0a08b83cc56bc6a007f3c6639b67e9bfc66f | 677bee59ad329e4a52e721ae365f3c5ce77cd970 |
refs/heads/main | <file_sep>package kata.bank.model;
import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int idTransaction;
public LocalDateTime date;
public double montant;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "idAccount")
@JsonBackReference
public Account account;
public int getIdTransaction() {
return idTransaction;
}
public void setIdTransaction(int idTransaction) {
this.idTransaction = idTransaction;
}
public LocalDateTime getDate() {
return date;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
public double getMontant() {
return montant;
}
public void setMontant(double montant) {
this.montant = montant;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
<file_sep>package kata.bank.service;
import java.util.List;
import kata.bank.model.Transaction;
public interface TransactionService {
public Transaction getTransaction(int idTransaction);
public List<Transaction> getAllTransactions();
public Transaction addTransaction(Transaction transaction);
}
<file_sep>package kata.bank.controller;
import java.util.List;
import org.springframework.web.bind.annotation.RestController;
import kata.bank.model.User;
@RestController
public interface UserController {
public User getUser(int idUser) throws Exception;
public List<User> getAllUsers();
}
<file_sep>package kata.bank.controller;
import java.util.List;
import kata.bank.model.Account;
public interface AccountController {
public Account getAccount(int idAccount) throws Exception;
public List<Account> getAllAccount();
public Account updateAccount(Account account);
}
<file_sep>package kata.bank.controller.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import kata.bank.controller.UserController;
import kata.bank.model.User;
import kata.bank.service.UserService;
@RestController
@RequestMapping("/user")
public class UserControllerImpl implements UserController{
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUser(@PathVariable int id) throws Exception {
User user = userService.getUser(id);
if(user != null) {
return user;
}
else {
throw new Exception("Utilisateur introuvable");
}
}
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
}
<file_sep>package kata.bank.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import kata.bank.dao.AccountRepository;
import kata.bank.model.Account;
import kata.bank.service.AccountService;
@Service
public class AccountServiceImpl implements AccountService{
@Autowired
public AccountRepository accountRepository;
public Account getAccount(int idAccount) {
return accountRepository.findById(idAccount).orElse(null);
}
public List<Account> getAllAccounts() {
return accountRepository.findAll();
}
public Account updateAccount(Account account) {
Account accountTemp = accountRepository.findById(account.getIdAccount()).get();
accountTemp.setBalance(account.getBalance());
return accountRepository.save(accountTemp);
}
}
<file_sep>/*==============================================================*/
/*INSERT INTO USERS*/
/*==============================================================*/
INSERT INTO users(address, email, name) values ('54 <NAME>, PARIS', '<EMAIL>', '<NAME>');
INSERT INTO users(address, email, name) values ('64 rue <NAME>, TOULOUSE', '<EMAIL>', 'Gilles A');
/*==============================================================*/
/*INSERT INTO ACCOUNT*/
/*==============================================================*/
INSERT INTO account(balance, id_user) values (4826.9, 1);
INSERT INTO account(balance, id_user) values (803.42, 2);
/*==============================================================*/
/*INSERT INTO TRANSACTION*/
/*==============================================================*/
INSERT INTO transaction(date, montant, id_account) VALUES ('20210429 02:34:09 PM', -49.99, 1);
<file_sep>package kata.bank.service;
import java.util.List;
import kata.bank.model.Account;
public interface AccountService {
public Account getAccount(int idAccount);
public List<Account> getAllAccounts();
public Account updateAccount(Account account);
}
<file_sep>
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/bank
spring.datasource.username = postgres
spring.datasource.password = <PASSWORD>
spring.jpa.hibernate.ddl-auto = create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.datasource.initialization-mode=always
server.port = 8084<file_sep>package kata.bank.service;
import java.util.List;
import kata.bank.model.User;
public interface UserService {
public User getUser(int idUser);
public List<User> getAllUsers();
}
| 976ac1481b7f95a8bdae936654a136a2ea770700 | [
"Java",
"SQL",
"INI"
] | 10 | Java | sikidiabelle/kata-bank | fec9fc710e85a0086b90e19e6ac882320c65ebf7 | fc04004f7b92604742b06052b172a3a4e7ca2698 |
refs/heads/master | <repo_name>dtmkeng/IoT_farmControllers<file_sep>/room.ino
#include <DS1302.h>
#include <Keypad.h>
#include "DHT.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <EEPROM.h>
#include <SPI.h>
#include <SD.h>
//set timer
LiquidCrystal_I2C lcd(0x27, 20, 4);
File myFile;
byte termometer[8] = //icon for termometer
{
0b00100,
0b01010,
0b01010,
0b01010,
0b01110,
0b11111,
0b11111,
0b01110
};
byte humi[8] ={
0b00100,
0b00100,
0b01010,
0b01010,
0b10001,
0b10001,
0b10001,
0b01110,
};
byte degree[8]={
0b00111,
0b00101,
0b00111,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
};
uint8_t CE_PIN = 24;
uint8_t IO_PIN = 23;
uint8_t SCLK_PIN = 22;
DS1302 rtc(CE_PIN,IO_PIN,SCLK_PIN);
Time timeGet;
String str,check;
unsigned long timeCount=0;
unsigned long timeCountStart=0;
unsigned long readTime=3;
unsigned long sensorReadtime = 3;
//delay ....ms
unsigned long previousMillis = 0;
int CheckTime;
#define FanOut 30
#define FanIn 31
#define Pump 32
#define PumpWater 33
#define OFF HIGH
#define ON LOW
int key_in;
#define btnUp 1
#define btnDown 2
#define btnEnter 3
#define btnEsc 4
#define btnNon 5
#define btnSave 6
int state1=1,state2=1,state3=1;
boolean conFanOut;
boolean conFanIn;
boolean conPump;
boolean conPumpWater;
boolean onLED = true;
boolean EvenTempHigh;
boolean EvenTempLow;
boolean EvenHumiHigh;
boolean EvenHumiLow;
boolean EvenPumpWater1;
boolean EvenPumpWater2;
boolean EvenPumpWater3;
#define DHT_1_PIN 26
#define DHT_2_PIN 27
#define DHT_3_PIN 28
#define DHTTYPE DHT22
DHT dht0(DHT_1_PIN, DHTTYPE);
DHT dht1(DHT_2_PIN, DHTTYPE);
DHT dht2(DHT_3_PIN, DHTTYPE);
float currentTemp0,currentTemp1,currentTemp2;
float currentHumi0,currentHumi1,currentHumi2;
float AVGcurrentTemp,AVGcurrentHumi;
//set temp&humi
int tempHigh = 31;
int tempLow = 10;
int humiHigh = 80;
int humiLow = 10;
int state=1;
int Timedelay = 5;
int LCDtime=10;
int settime_1_pump=10;
int settime_2_pump=30;
int settime_3_pump=50;
unsigned int addtempHigh = 21;
unsigned int addtempLow = 22;
unsigned int addhumiHigh = 41;
unsigned int addhumiLow = 42;
unsigned int addstate = 51;
unsigned int addtime1=52;
unsigned int addtime2=53;
unsigned int addtime3=54;
unsigned int addtimedelay=55;
unsigned int addtimelcd=56;
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
byte rowPins[ROWS] = {9, 8, 7, 6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3, 2};
char hexaKeys[ROWS][COLS] = {
{'1','2','3','U'},
{'4','5','6','D'},
{'7','8','9','E'},
{'*','0','#','C'}
};
//sec
int showDis = 1;
boolean Display_on(boolean i){
if(i==true){
lcd.backlight();
return onLED=i;
}
if(i==false){
lcd.noBacklight();
return onLED = i;
}
}
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
char keyRead;
void Display();
void setup() {
lcd.clear();
Serial.begin(9600);
lcd.begin();
lcd.createChar(0, termometer);
lcd.createChar(1, humi);
lcd.createChar(2, degree);
pinMode(DHT_1_PIN,INPUT);
pinMode(DHT_2_PIN,INPUT);
pinMode(DHT_3_PIN,INPUT);
pinMode(FanOut,OUTPUT);
pinMode(FanIn,OUTPUT);
pinMode(Pump,OUTPUT);
pinMode(PumpWater,OUTPUT);
pinMode(8,INPUT_PULLUP);
pinMode(9,INPUT_PULLUP);
pinMode(A6,INPUT_PULLUP);
pinMode(A7,INPUT_PULLUP);
digitalWrite(FanOut,OFF);
digitalWrite(FanIn,OFF);
digitalWrite(Pump,OFF);
digitalWrite(PumpWater,OFF);
lcd.write(byte(0));
lcd.print(" Arduino! ");
lcd.write((byte) 1);
Display_on(true);
//rtc.setDOW(TUESDAY); // Set Day-of-Week to FRIDAY
//rtc.setTime(0, 1, 0); // Set the time to 12:00:00 (24hr format)
//rtc.setDate(23, 5, 2017);
tempHigh = EEPROM.read(addtempHigh);
tempLow =EEPROM.read(addtempLow);
humiHigh = EEPROM.read(addhumiHigh);
humiLow = EEPROM.read(addhumiLow);
Timedelay = EEPROM.read(addtimedelay);
LCDtime = EEPROM.read(addtimelcd);
settime_1_pump=EEPROM.read(addtime1);
settime_2_pump=EEPROM.read(addtime2);
settime_3_pump=EEPROM.read(addtime3);
if (!SD.begin(10)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
}
void loop() {
if(timeCountStart>millis()){
timeCountStart=0;
}
if(timeCount<millis()&&onLED==1){
timeCountStart++;
}
if(timeCountStart>(LCDtime*60)&&onLED!=0){
timeCountStart=0;
showDis=1;
Display_on(false);
}
timeCount=millis()/1000;
if(timeCount>readTime){
readTime = timeCount+(sensorReadtime-1);
currentTemp0 = dht0.readTemperature();
currentTemp1 = dht1.readTemperature();
currentTemp2 = dht2.readTemperature();
currentHumi0 = dht0.readHumidity();
currentHumi1 = dht1.readHumidity();
currentHumi2 = dht2.readHumidity();
AVGcurrentTemp =(currentTemp0+currentTemp1+currentTemp2)/3;
AVGcurrentHumi = (currentHumi0+currentHumi1+currentHumi2)/3;
}
timeRead();
Display();
EventStart();
//Serial.println(AVGcurrentTemp);
//Serial.println(AVGcurrentHumi);
if(AVGcurrentTemp>tempHigh)EvenTempHigh = 1;
if(AVGcurrentTemp<tempLow)EvenTempLow = 1;
if(AVGcurrentHumi>humiHigh)EvenHumiHigh =1;
if(AVGcurrentHumi<humiLow)EvenHumiLow =1;
//=====================================================Time Event====================================//
CheckTime = check.toInt();
Serial.println(settime_1_pump);
if(CheckTime==settime_1_pump||CheckTime==settime_2_pump||CheckTime==settime_3_pump)EvenPumpWater1=1;
// else if(CheckTime==settime_2_pump)EvenPumpWater2=1;
// else if(CheckTime==settime_3_pump)EvenPumpWater3=1;
if(AVGcurrentTemp>tempHigh&&EvenTempHigh == 1){
conFanIn = ON;
}else{
EvenTempHigh = 0;
conFanIn = OFF;
}
if(AVGcurrentTemp<tempLow&&EvenTempLow == 1){
conFanOut =ON;
}else{
EvenTempLow = 0;
conFanOut =OFF;
}
if(AVGcurrentHumi>humiHigh&&EvenHumiHigh ==1){
conFanOut =ON;
}else{
EvenHumiHigh =0;
conFanOut =OFF;
}
if(AVGcurrentHumi<humiLow&&EvenHumiLow ==1){
conPump =ON;
}else{
EvenHumiLow =0;
conPump =OFF;
}
if(EvenPumpWater1){
conPumpWater = ON;
switch(state){
case 1:{
if(CheckTime>settime_1_pump+Timedelay){
EvenPumpWater1=0;
}
// settime_2_pump = CheckTime;
// if(CheckTime>settime_2_pump+Timedelay){
// conPumpWater=OFF;
// }
// settime_3_pump = CheckTime;
// if(CheckTime>settime_3_pump+Timedelay){
// conPumpWater=OFF;}
break;
}
case 2:{
if(CheckTime>settime_1_pump+Timedelay){
EvenPumpWater1=0;
}
settime_2_pump = CheckTime;
if(CheckTime>settime_2_pump+Timedelay){
conPumpWater=OFF;
}
break;
}
case 3:{
if(CheckTime>settime_1_pump+Timedelay){
EvenPumpWater1=0;
}
settime_2_pump = CheckTime;
if(CheckTime>settime_2_pump+Timedelay){
conPumpWater=OFF;
}
settime_3_pump = CheckTime;
if(CheckTime>settime_3_pump+Timedelay){
conPumpWater=OFF;}
break;
}
}
}
else{
conPumpWater=OFF;
EvenPumpWater1=0;
}
// if(EvenPumpWater2){
// conPumpWater = ON;
// if(CheckTime>settime_2_pump+Timedelay){
// EvenPumpWater2=0;
// }}
EventStart();
key_in=readkey();
switch(key_in){
case btnUp:{
if(onLED==false){
Display_on(true);
timeCountStart=0;
}else{
lcd.clear();
showDis++;
if(showDis>3)showDis=1;
}
break;
}
case btnDown:{
if(onLED==false){
Display_on(true);
timeCountStart=0;
}else{
lcd.clear();
showDis--;
if(showDis<1)showDis=3;
}
break;
}
case btnEnter:{
if(onLED==false){
Display_on(true);
timeCountStart=0;
}else{
systemConfig();
}
break;
}
case btnEsc:{
showDis=1;
break;
}
case btnSave:{
myFile = SD.open("dataFarm.txt", FILE_WRITE);
if (myFile) {
Serial.print("Writing to write.....");
myFile.print(str);
myFile.print("\t");
myFile.print(AVGcurrentTemp);
myFile.print("\t");
myFile.print(AVGcurrentHumi);
myFile.close();
Serial.println("done.");
}else {
Serial.println("error opening test.txt");
}
break;
}
case btnNon:{
break;
}
}
}
<file_sep>/keyCon.ino
int readkey(){
keyRead = customKeypad.getKey();
if(keyRead=='U'){
delay(200);
return btnUp;
}
if(keyRead=='D'){
delay(200);
return btnDown;
}
if(keyRead=='E'){
delay(200);
return btnEnter;
}
if(keyRead=='C'){
delay(200);
return btnEsc;
}
if(keyRead=='1'){
delay(200);
return 1;
}
if(keyRead=='2'){
delay(200);
return 2;
}
if(keyRead=='3'){
delay(200);
return 3;
}
if(keyRead=='4'){
delay(200);
return 4;
}
if(keyRead=='5'){
delay(200);
return 5;
}
if(keyRead=='6'){
delay(200);
return 6;
}
if(keyRead=='7'){
delay(200);
return 7;
}
if(keyRead=='8'){
delay(200);
return 8;
}
if(keyRead=='9'){
delay(200);
return 9;
}
if(keyRead=='0'){
delay(200);
return 0;
}
if(keyRead=='#'){
delay(200);
return btnSave;
}
else{
return btnNon;
}
}
<file_sep>/config.ino
void systemConfig(){
unsigned int varmanu =1;
char*mymanu[]={"<1.Set Temp>>>",
"<1.1 TempLow>>",
"<<1.2 TempHigh",
"<2.Set Humi>>",
"<2.1 HumiLow>>",
"<<2.2 HumiHigh",
"<3.Set Time>>",
"<3.1 Time LCD>",
"<3.2 Time On Pump>>",
"<<3.2.1 Time On 1>>",
"<<3.2.2 Time On 2>>",
"<<3.2.3 Time On 3>>",
"<<3.3 Time Delay>"
};
int i =1;
lcd.clear();
lcd.setCursor(4,1);
lcd.print("System Config");
delay(1000);
lcd.clear();
digitalWrite(FanOut,OFF);
digitalWrite(FanIn,OFF);
digitalWrite(Pump,OFF);
digitalWrite(PumpWater,OFF);
while(i==1){
switch(varmanu){
case 1:{
lcd.setCursor(4,0);
lcd.print(mymanu[0]);
break;
}
case 11:{
lcd.setCursor(4,0);
lcd.print(mymanu[0]);
lcd.setCursor(3,1);
lcd.print(mymanu[1]);
lcd.setCursor(10,3);
if(tempLow<10)lcd.print("0");
lcd.print(tempLow);
lcd.setCursor(13, 3);
lcd.print("C");
lcd.setCursor(14, 3);
lcd.write(2);
lcd.setCursor(16, 3);
lcd.print("SET");
break;
}
case 111:{
unsigned long j = millis()/390;
lcd.setCursor(4,0);
lcd.print(mymanu[0]);
lcd.setCursor(10,3);
if((j%2)==0){
if(tempLow<10)lcd.print("0");
lcd.print(tempLow);
}
lcd.setCursor(13, 3);
lcd.print("C");
lcd.setCursor(14, 3);
lcd.write(2);
break;
}
case 12:{
lcd.setCursor(4,0);
lcd.print(mymanu[0]);
lcd.setCursor(3,1);
lcd.print(mymanu[2]);
lcd.setCursor(10,3);
if(tempLow<10)lcd.print("0");
lcd.print(tempHigh);
lcd.setCursor(14, 3);
lcd.write(2);
lcd.setCursor(13, 3);
lcd.print("C");
lcd.setCursor(16, 3);
lcd.print("SET");
break;
}
case 121:{
unsigned long j = millis()/390;
lcd.setCursor(4,0);
lcd.print(mymanu[0]);
if((j%2)==0){
if(tempHigh<10)lcd.print("0");
lcd.setCursor(10,3);
lcd.print(tempHigh);
}
lcd.setCursor(14, 3);
lcd.write(2);
break;
}
case 2:{
lcd.setCursor(4,0);
lcd.print(mymanu[3]);
break;
}
case 21:{
lcd.setCursor(4,0);
lcd.print(mymanu[3]);
lcd.setCursor(3,1);
lcd.print(mymanu[4]);
lcd.setCursor(10,3);
if(humiLow<10)lcd.print("0");
lcd.print(humiLow);
lcd.setCursor(12, 3);
lcd.print("%");
lcd.setCursor(14, 3);
lcd.print("SET");
break;
}
case 22:{
lcd.setCursor(4,0);
lcd.print(mymanu[3]);
lcd.setCursor(3,1);
lcd.print(mymanu[5]);
lcd.setCursor(10,3);
if(humiHigh<10)lcd.print("0");
lcd.print(humiHigh);
lcd.setCursor(12, 3);
lcd.print("%");
lcd.setCursor(14, 3);
lcd.print("SET");
break;
}
case 211:{
unsigned long j = millis()/390;
lcd.setCursor(4,0);
lcd.print(mymanu[4]);
if((j%2)==0){
lcd.setCursor(10,3);
if(humiLow<10)lcd.print("0");
lcd.setCursor(10,3);
lcd.print(humiLow);
}
lcd.setCursor(12, 3);
lcd.print("%");
break;
}
case 221:{
unsigned long j = millis()/390;
lcd.setCursor(4,0);
lcd.print(mymanu[5]);
if((j%2)==0){
lcd.setCursor(10,3);
if(humiHigh<10)lcd.print("0");
lcd.setCursor(10,3);
lcd.print(humiHigh);
}
lcd.setCursor(12, 3);
lcd.print("%");
break;
}
case 3:{
lcd.setCursor(4,0);
lcd.print(mymanu[6]);
break;
}
case 31:{
lcd.setCursor(4,0);
lcd.print(mymanu[6]);
lcd.setCursor(4,1);
lcd.print(mymanu[7]);
lcd.setCursor(10,3);
if(LCDtime<1)lcd.print("0");
lcd.print(LCDtime);
lcd.setCursor(13, 3);
lcd.print("Sec");
lcd.setCursor(17, 3);
lcd.print("SET");
break;
}
case 32:{
lcd.setCursor(4,0);
lcd.print(mymanu[6]);
lcd.setCursor(1,1);
lcd.print(mymanu[8]);
lcd.setCursor(10,3);
lcd.setCursor(14, 3);
lcd.print("SET");
break;
}
case 33:{
lcd.setCursor(4,0);
lcd.print(mymanu[6]);
lcd.setCursor(1,1);
lcd.print(mymanu[12]);
lcd.setCursor(10,3);
if(Timedelay<1)lcd.print("0");
lcd.print(Timedelay);
lcd.setCursor(13, 3);
lcd.print("Sec");
lcd.setCursor(17, 3);
lcd.print("SET");
break;
}
case 320:{
lcd.setCursor(6,0);
lcd.print(" Time Work");
lcd.setCursor(7,2);
lcd.print(state);
lcd.setCursor(9,2);
lcd.print("time");
break;
}
case 311:{
unsigned long j = millis()/390;
lcd.setCursor(4,0);
lcd.print(mymanu[7]);
if((j%2)==0){
lcd.setCursor(10,3);
if(LCDtime<10)lcd.print("0");
lcd.setCursor(10,3);
lcd.print(LCDtime);
}
lcd.setCursor(13, 3);
lcd.print("Sec");
break;
}
case 321:{
unsigned long j = millis()/390;
lcd.setCursor(1,0);
lcd.print(mymanu[9]);
if((j%2)==0){
lcd.setCursor(10,3);
if(settime_1_pump<1)lcd.print("0");
lcd.setCursor(10,3);
lcd.print(settime_1_pump);
}
lcd.setCursor(14, 3);
lcd.print("Sec");
break;
}
case 322:{
unsigned long j = millis()/390;
lcd.setCursor(1,0);
lcd.print(mymanu[10]);
if((j%2)==0){
lcd.setCursor(10,3);
if(settime_2_pump<1)lcd.print("0");
lcd.setCursor(10,3);
lcd.print(settime_2_pump);
}
lcd.setCursor(14, 3);
lcd.print("Sec");
break;
}
case 323:{
unsigned long j = millis()/390;
lcd.setCursor(1,0);
lcd.print(mymanu[11]);
if((j%2)==0){
lcd.setCursor(10,3);
if(settime_3_pump<1)lcd.print("0");
lcd.setCursor(10,3);
lcd.print(settime_3_pump);
}
lcd.setCursor(14, 3);
lcd.print("Sec");
break;
}
case 331:{
unsigned long j = millis()/390;
lcd.setCursor(1,0);
lcd.print(mymanu[12]);
if((j%2)==0){
lcd.setCursor(10,3);
if(Timedelay<1)lcd.print("0");
lcd.setCursor(10,3);
lcd.print(Timedelay);
}
lcd.setCursor(13, 3);
lcd.print("Sec");
break;
}
}
key_in=readkey();
switch(key_in){
///======================================================btnEnter=========================================///
case btnEnter:{
lcd.clear();
if(varmanu==1){
varmanu=varmanu*10+1;
break;
}
if(varmanu==11){
varmanu=varmanu*10+1;
break;
}
if(varmanu==12){
varmanu=varmanu*10+1;
break;
}
if(varmanu==2){
varmanu=varmanu*10+1;
break;
}
if(varmanu==21){
varmanu=varmanu*10+1;
break;
}
if(varmanu==22){
varmanu=varmanu*10+1;
break;
}
if(varmanu==31){
varmanu=varmanu*10+1;
break;
}
if(varmanu==33){
varmanu=varmanu*10+1;
break;
}
if(varmanu==32){
varmanu=varmanu*10;
break;
}
if(varmanu==320){
EEPROM.write(addstate,state);
lcd.setCursor(5,2);
lcd.print("SAVE");
delay(200);
lcd.clear();
varmanu++;
if(varmanu>323)varmanu=321;
break;
}
if(varmanu==320&&state==1){
varmanu++;
if(varmanu>321)varmanu=321;
break;
}
if(varmanu==321&&state==1){
EEPROM.write(addtime1,settime_1_pump);
lcd.setCursor(5,2);
lcd.print("SAVE");
delay(200);
lcd.clear();
varmanu=varmanu/10;
break;
}
if(varmanu==321&&state==2){
varmanu++;
if(varmanu>322)varmanu=321;
break;
}
if(varmanu==321&&state==3){
varmanu++;
if(varmanu>322)varmanu=321;
break;
}
if(varmanu==322&&state==3){
varmanu++;
if(varmanu>323)varmanu=321;
break;
}
if(varmanu==322&&state==2){
EEPROM.write(addtime2,settime_2_pump);
lcd.setCursor(5,2);
lcd.print("SAVE");
delay(200);
lcd.clear();
varmanu=varmanu/10;
break;
}
if(varmanu==323&&state==3){
EEPROM.write(addtime3,settime_3_pump);
lcd.setCursor(5,2);
lcd.print("SAVE");
delay(200);
lcd.clear();
varmanu=varmanu/10;
break;
}
if(varmanu==311){
EEPROM.write(addtimelcd,LCDtime);
lcd.setCursor(5,2);
lcd.print("SAVE");
delay(200);
lcd.clear();
varmanu=varmanu/10;
break;
}
if(varmanu==331){
EEPROM.write(addtimedelay,Timedelay);
lcd.setCursor(5,2);
lcd.print("SAVE");
delay(200);
lcd.clear();
varmanu=varmanu/10;
break;
}
if(varmanu==3){
varmanu=varmanu*10+1;
break;
}
if(varmanu==111||varmanu==121){
if(varmanu==111)EEPROM.write(addtempLow,tempLow);
if(varmanu==121)EEPROM.write(addtempHigh,tempHigh);
lcd.setCursor(5,2);
lcd.print("SAVE");
delay(200);
varmanu=varmanu/10;
lcd.clear();
break;
}
if(varmanu==211||varmanu==221){
if(varmanu==211)EEPROM.write(addhumiLow,humiLow);
if(varmanu==221)EEPROM.write(addhumiHigh,humiHigh);
lcd.setCursor(5,2);
lcd.print("SAVE");
delay(200);
varmanu=varmanu/10;
lcd.clear();
break;
}
break;
}
///======================================================btnUp=========================================///
case btnUp:{
lcd.clear();
if(varmanu==1){
varmanu++;
if(varmanu>3)varmanu=1;
break;
}
if(varmanu==2){
varmanu++;
if(varmanu>3)varmanu=1;
break;
}
if(varmanu==11){
varmanu++;
if(varmanu>12)varmanu=11;
break;
}
if(varmanu==21){
varmanu++;
if(varmanu>22)varmanu=21;
break;
}
if(varmanu==31){
varmanu++;
if(varmanu>33)varmanu=31;
break;
}
if(varmanu==32){
varmanu++;
if(varmanu>33)varmanu=31;
break;
}
if(varmanu==311){
LCDtime++;
if(LCDtime>30)LCDtime=1;
break;
}
if(varmanu==331){
Timedelay++;
if(Timedelay>30)Timedelay=1;
break;
}
if(varmanu==320||varmanu==321||varmanu==322||varmanu==323){
if(varmanu==320){
state++;
if(state>3)state=1;
break;
}
if(varmanu==321){
settime_1_pump++;
if(settime_1_pump>60)settime_1_pump=1;
break;
}
if(varmanu==322){
settime_2_pump++;
if(settime_2_pump>60)settime_2_pump=1;
break;
}
if(varmanu==323){
settime_3_pump++;
if(settime_3_pump>60)settime_3_pump=1;
break;
}
}
if(varmanu==22){
varmanu--;
if(varmanu<21)varmanu=21;
break;
}
if(varmanu==111||varmanu==121){
if(varmanu==121){
tempHigh++;
if(tempHigh>99)tempHigh=1;
}
if(varmanu==111){
tempLow++;
if(tempLow<1){
tempLow=1;
}
}
break;
}
if(varmanu==211||varmanu==221){
if(varmanu==221){
humiHigh++;
if(humiHigh>99)humiHigh=1;
}
if(varmanu==211){
humiLow++;
if(humiLow>humiHigh){
humiLow=humiHigh-2;
}
}
break;
}
if(varmanu>=11&&varmanu<=12){
varmanu--;
if(varmanu<11)varmanu=11;
break;
}
if(varmanu==1){
varmanu--;
if(varmanu<1)varmanu=1;
break;
}
break;
}
//==============================================btnDown========================================///
case btnDown:{
lcd.clear();
if(varmanu==1){
varmanu=1;
break;
}
if(varmanu==2){
varmanu--;
if(varmanu<1)varmanu=1;
break;
}
if(varmanu==3){
varmanu--;
if(varmanu<1)varmanu=1;
break;
}
if(varmanu==33){
varmanu--;
if(varmanu<31)varmanu=31;
break;
}
if(varmanu==32){
varmanu--;
if(varmanu<31)varmanu=31;
break;
}
if(varmanu==31){
varmanu=varmanu/10;
break;
}
if(varmanu==111||varmanu==121){
if(varmanu==111){
tempLow--;
if(tempLow<1){tempLow=1;
break;}
}
if(varmanu==121){
tempHigh--;
if(tempHigh<tempLow){
tempHigh=tempLow+2;
break;
}
}
break;
}
if(varmanu==211||varmanu==221){
if(varmanu==211){
humiLow--;
if(humiLow<1){
humiLow = 1;
break;
}
}
if(varmanu==221){
humiHigh--;
if(humiHigh<humiLow){
humiHigh=humiLow+10;
break;
}
}
break;
}
if(varmanu==320||varmanu==321||varmanu==322||varmanu==323){
if(varmanu==321){
settime_1_pump--;
if(settime_1_pump<1)settime_1_pump=1;
break;
}
if(varmanu==322){
settime_2_pump--;
if(settime_2_pump<1)settime_2_pump=1;
break;
}
if(varmanu==323){
settime_3_pump--;
if(settime_3_pump<1)settime_3_pump=1;
break;
}
}
if(varmanu==311){
LCDtime--;
if(LCDtime<1)LCDtime=1;
break;
}
if(varmanu==331){
Timedelay--;
if(Timedelay<1)Timedelay=1;
break;
}
}
//==============================================btnESC========================================///
case btnEsc:{
lcd.clear();
if(varmanu==111||varmanu==121){
if(varmanu==111){
tempLow = EEPROM.read(addtempLow);
varmanu =varmanu/10;
lcd.clear();
}
if(varmanu==121){
tempHigh = EEPROM.read(addtempHigh);
varmanu =varmanu/10;
lcd.clear();
}
break;
}
if(varmanu==211||varmanu==221){
if(varmanu==211){
humiLow = EEPROM.read(addhumiLow);
varmanu =varmanu/10;
lcd.clear();
}
if(varmanu==221){
humiHigh = EEPROM.read(addhumiHigh);
varmanu =varmanu/10;
lcd.clear();
}
break;
}
if(varmanu==311||varmanu==320||varmanu==321||varmanu==322||varmanu==323||varmanu==331){
if(varmanu==311){
LCDtime=EEPROM.read(addtimelcd);
varmanu =varmanu/10;
lcd.clear();
}
if(varmanu==320){
state = EEPROM.read(addstate);
varmanu =varmanu/10;
lcd.clear();
}
if(varmanu==321){
settime_1_pump=EEPROM.read(addtime1);
varmanu =varmanu/10;
lcd.clear();
}
if(varmanu==322){
settime_2_pump=EEPROM.read(addtime2);
varmanu =varmanu/10;
lcd.clear();
}
if(varmanu==323){
settime_3_pump=EEPROM.read(addtime3);
varmanu =varmanu/10;
lcd.clear();
}
if(varmanu==331){
Timedelay=EEPROM.read(addtimedelay);
varmanu =varmanu/10;
lcd.clear();
}
break;
}
if(varmanu==21||varmanu==22){
varmanu=varmanu/10;
break;
}
if(varmanu==31||varmanu==32){
varmanu=varmanu/10;
break;
}
if(varmanu==33){
varmanu=varmanu/10;
break;
}
if(varmanu==11||varmanu==12){
varmanu=varmanu/10;
break;
}
if(varmanu==1){
i=0;
lcd.clear();
break;
}
if(varmanu==2){
i=0;
lcd.clear();
break;
}
if(varmanu==3){
i=0;
lcd.clear();
break;
}
}
break;
}
//Serial.println(varmanu);
}
}
<file_sep>/Clock.ino
String timeRead(){
timeGet = rtc.getTime();
str=rtc.getTimeStr();
//check=timeGet.sec;
check=timeGet.min;
//check=timeGet.hour;
//Serial.println(timeGet.sec, DEC);
//erial.println("s");
return check;
lcd.setCursor(5, 3);
lcd.print(str);
}
<file_sep>/Event.ino
byte EventStart(){
digitalWrite(FanIn,conFanIn);
digitalWrite(FanOut,conFanOut);
digitalWrite(Pump,conPump);
digitalWrite(PumpWater,conPumpWater);
}
<file_sep>/Display.ino
void Display(){
switch(showDis){
case 1:{
showDisplay1();
break;}
case 2:{
showDisplay2();
break;}
case 3:{
showDisplay3();
break;}
}
}
void showDisplay1(){
lcd.setCursor(5, 0);
lcd.print("SMART FARM");
lcd.setCursor(0, 1);
//lcd.print("Temperature:");
lcd.write(0);
lcd.setCursor(2, 1);
lcd.print(AVGcurrentTemp);
lcd.setCursor(7, 1);
lcd.write(2);
lcd.setCursor(8, 1);
lcd.print("C");
lcd.setCursor(12, 1);
//lcd.print("Humidity:");
lcd.write(1);
lcd.setCursor(14, 1);
lcd.print(AVGcurrentHumi);
lcd.setCursor(19, 1);
lcd.print("%");
lcd.setCursor(12, 3);
lcd.print(str);
}
void showDisplay2(){
lcd.setCursor(5, 0);
lcd.print("OPPTIONS");
lcd.setCursor(0, 1);
//lcd.print("Temperature:");
lcd.write(0);
lcd.setCursor(1,1);
lcd.print("HIGH");
lcd.setCursor(6, 1);
lcd.print(tempHigh);
lcd.setCursor(8, 1);
lcd.write(2);
lcd.setCursor(9, 1);
lcd.print("C");
lcd.setCursor(11, 1);
//lcd.print("Humidity:");
lcd.write(1);
lcd.setCursor(12, 1);
lcd.print("HIGH");
lcd.setCursor(17, 1);
lcd.print(humiHigh);
lcd.setCursor(19, 1);
lcd.print("%");
lcd.setCursor(5, 0);
lcd.print("OPPTIONS");
lcd.setCursor(0, 2);
//lcd.print("Temperature:");
lcd.write(0);
lcd.setCursor(1,2);
lcd.print("LOW");
lcd.setCursor(6, 2);
lcd.print(tempLow);
lcd.setCursor(8, 2);
lcd.write(2);
lcd.setCursor(9, 2);
lcd.print("C");
lcd.setCursor(11, 2);
//lcd.print("Humidity:");
lcd.write(1);
lcd.setCursor(12, 2);
lcd.print("LOW");
lcd.setCursor(17, 2);
lcd.print(humiLow);
lcd.setCursor(19, 2);
lcd.print("%");
lcd.setCursor(12, 3);
lcd.print(str);
}
void showDisplay3(){
lcd.setCursor(4,0);
lcd.print("Times Setted");
lcd.setCursor(0,1);
lcd.print("T1");
lcd.setCursor(3,1);
lcd.print(settime_1_pump);
lcd.setCursor(6,1);
lcd.print("min");
lcd.setCursor(10,1);
lcd.print("TLCD");
lcd.setCursor(15,1);
lcd.print(LCDtime);
lcd.setCursor(17,1);
lcd.print("Sec");
lcd.setCursor(0,2);
lcd.print("T2");
lcd.setCursor(3,2);
lcd.print(settime_2_pump);
lcd.setCursor(6,2);
lcd.print("min");
lcd.setCursor(10,2);
lcd.print("TRE");
lcd.setCursor(15,2);
lcd.print(Timedelay);
lcd.setCursor(17,2);
lcd.print("min");
lcd.setCursor(0,3);
lcd.print("T3");
lcd.setCursor(3,3);
lcd.print(settime_3_pump);
lcd.setCursor(6,3);
lcd.print("min");
}
| 7c439db713128d55ed7aa8ddf222fff4c5f446f1 | [
"C++"
] | 6 | C++ | dtmkeng/IoT_farmControllers | e456a3858956781bc9e1de1d035e7d92e48635a9 | 8de5bd4a7a72609668bafb3676db67dd3513ab65 |
refs/heads/master | <repo_name>polandll/llp-graph-examples<file_sep>/food/CQL/0_drop_keyspace.cql
// START-dropKS-CQL
DROP KEYSPACE IF EXISTS food_cql;
// END-dropKS-CQL
<file_sep>/food/CQL/0_create_keyspace.cql
// START-createKS-CQL
CREATE KEYSPACE IF NOT EXISTS food_cql
WITH REPLICATION = {
'class' : 'SimpleStrategy',
'replication_factor' : 1 };
// END-createKS-CQL
<file_sep>/food/CQL/drop_table.cql
// START-dropAllTables-cql
// Drop tables using CQL:
DROP TABLE IF EXISTS food_cql.person_authored_book;
DROP TABLE IF EXISTS food_cql.book;
DROP TABLE IF EXISTS food_cql.person;
// END-dropAllTables-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_AddData_header.md
## INSERTING DATA
Insert some data into the tables.
[Top ↑](#sections)
<file_sep>/food/CQL/select_book_core.cql
// Gremlin
// START-selectBook_core-cql
// Examine book table using CQL
select * from food.book;
// END-selectBook_core-cql
<file_sep>/food/CQL/select_recipe_core.cql
// START-selectRecipe_core-cql
SELECT * FROM food.recipe_table;
// END-selectRecipe_core-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_VLs_2.md
Properties can also be added or dropped from vertex labels. The properties added here with _addProperty()_ are used to track the book discount given on a book. To drop properties, use _dropProperty()_.
<file_sep>/food/CQL/alter_keyspace_into_graph_convert.cql
// START-alterKS-convert
ALTER KEYSPACE food_cql_conversion
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}
AND graph_engine = 'Core';
// END-alterKS-convert
<file_sep>/food/CQL/drop_UDTs.cql
// START-dropUDTs-cql
DROP TYPE IF EXISTS food_cql.location_details;
DROP TYPE IF EXISTS food_cql.fullname;
DROP TYPE IF EXISTS food_cql.address;
// END-dropUDTs-cql
<file_sep>/food/CQL/alter_remove_EL.cql
// START-alterTable-edge_remove
ALTER TABLE food."personAuthoredBook" WITHOUT EDGE LABEL TO "authoredX"
// END-alterTable-edge_remove
<file_sep>/food/CQL/0_create_keyspace_convert.cql
// START-createKS-convert
CREATE KEYSPACE IF NOT EXISTS food_cql_conversion
WITH REPLICATION = {
'class' : 'SimpleStrategy',
'replication_factor' : 1 };
// END-createKS-convert
<file_sep>/food/DSBULK/food-meal.sh
#!/bin/bash
#**********************************
# food-meal.sh
# Use dsbulk to add meal data to graph
# Lorina Poland
#**********************************
dsbulkBinDir="/home/automaton/dsbulk-1.3.4/bin"
repoDataDir="/home/automaton/graph-examples/food/DATA/CSV/vertices"
ks="food"
$dsbulkBinDir/dsbulk load --schema.keyspace $ks --schema.table meal -url $repoDataDir/meal.csv -delim '|' -header true --schema.allowMissingFields true
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_VLs_2.md
The _VERTEX LABEL_ will default to the same value as the table name, but can be defined as a different value, with _VERTEX LABEL person_vl_, for instance.
In the vertex labels created above, note the use of collections (set, list, map), tuples, and lists of collections, tuples, and UDTs. These data types provide a remarkable amount of flexibility in defining meta-properties (a property on a property) and multi-properties (a property with multiple values). For instance, the _badge_ property is stored as a map of Text:Integer, such as Gold:2015, the meta-property of _year achieved_ on the _badge level_. Similarly, a set of Text values for _nickname_ store the various values for the multi-property _nickname_.
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/MISC-graphloader/ExistsIsNew/readme.txt
I need to probably break this example into two examples:
(1) Load the vertices if they are new, then load again.
(2) Load the edges without making the vertices, saying that
they exist.
(3) Wipe out the vertices, and load the edges without making
the vertices, saying that they exist (should fail)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_AddData_2.md
Note that the keyspace could be altered at the beginning of this notebook, before any work is done.
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/ALL_FOOD_SCHEMA/ALL_FOOD_SCHEMA_AddData_header.md
## Insert data ##
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_DSBulk_1.md
Copy the following data to the following files:
1. person.csv
```
person_id|name|gender|nickname|cal_goal|macro_goal
bb6d7af7-f674-4de7-8b4c-c0fdcdaa5cca|Julia CHILD|F|'Jay','Julia'|1400|25,25,50
adb8744c-d015-4d78-918a-d7f062c59e8f|Simone BECK|F|'Simca','Simone'||
888ad970-0efc-4e2c-b234-b6a71c30efb5|Fritz STREIFF|M|||
f092107c-0c5c-47e7-917c-c82c7fc2a249|Louisette BERTHOLIE|F|||
ef811281-f954-4fd6-ace0-bf67d057771a|<NAME>|F|'Pat'||
d45c76bc-6f93-4d0e-9d9f-33298dae0524|Alice WATERS|F|||
7f969e16-b81e-4fcd-87c5-1911abbed132|<NAME>|F|'Pattie'||
01e22ca6-da10-4cf7-8903-9b7e30c25805|Kelsie KERR|F|||
ad58b8bd-033f-48ee-8f3b-a84f9c24e7de|Emeril LAGASSE|M|||
4ce9caf1-25b8-468e-a983-69bad20c017a|James BEARD|M|'Jim', 'Jimmy'||
65fd73f7-0e06-49af-abd6-0725dc64737d|<NAME>|M||1750|10,30,60
3b3e89f4-5ca2-437e-b8e8-fe7c5e580068|<NAME>|M|'John'|1800|30,20,50
9b564212-9544-4f85-af36-57615e927f89|<NAME>|F|'Janie'|1500|50,15,35
ba6a6766-beae-4a35-965b-6f3878581702|<NAME>|F||1600|30,20,50
a3e7ab29-2ac9-4abf-9d4a-285bf2714a9f|<NAME>|F||1700|10,50,30
```
2. book.csv
```
book_id|name|publish_year|isbn
1001|The Art of French Cooking, Vol. 1|1961|
1002|Simca's Cuisine: 100 Classic French Recipes for Every Occasion|1972|0-394-40152-2
1003|The French Chef Cookbook|1968|0-394-40135-2
1004|The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution|2007|0-307-33679-4
```
3. person_authored_book.csv
```
person_id|person_name|book_id|book_name
bb6d7af7-f674-4de7-8b4c-c0fdcdaa5cca|<NAME>|1001|The Art of French Cooking, Vol. 1
adb8744c-d015-4d78-918a-d7f062c59e8f|Simone BECK|1001|The Art of French Cooking, Vol. 1
f092107c-0c5c-47e7-917c-c82c7fc2a249|Louisette BERTHOLIE|1001|The Art of French Cooking, Vol. 1
adb8744c-d015-4d78-918a-d7f062c59e8f|Simone BECK|1002|Simca's Cuisine: 100 Classic French Recipes for Every Occasion
ef811281-f954-4fd6-ace0-bf67d057771a|<NAME>|1002|Simca's Cuisine: 100 Classic French Recipes for Every Occasion
bb6d7af7-f674-4de7-8b4c-c0fdcdaa5cca|<NAME>|1003|The French Chef Cookbook
d45c76bc-6f93-4d0e-9d9f-33298dae0524|<NAME>|1004|The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution
7f969e16-b81e-4fcd-87c5-1911abbed132|<NAME>|1004|The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution
01e22ca6-da10-4cf7-8903-9b7e30c25805|<NAME>|1004|The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution
888ad970-0efc-4e2c-b234-b6a71c30efb5|Fritz STREIFF|1004|The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution
```
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_AllFoodFooter.md
## Full food data model schema and data ##
To create the full schema for the food data model and insert some sample data, see the Studio Notebook "All Food Schema".
[Top ↑](#sections)
<file_sep>/food/CQL/create_table_recipe.cql
// Assume we have the following existing non-vertex label table.
// Create a CQL table that can be converted into a vertex label
CREATE KEYSPACE IF NOT EXISTS food
WITH REPLICATION = {
'class' : 'SimpleStrategy',
'replication_factor' : 1 };
USE food;
// START-createTable-recipe-cql
CREATE TABLE food.recipe_table (
recipe_id int,
name text,
cuisine set<text>,
instructions text,
notes text,
PRIMARY KEY (recipe_id));
// END-createTable-recipe-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_DSBulk_header.md
### Using the DataStax Bulk Loader to insert data into CQL
Data can be loaded with DataStax Bulk Loader using CSV or JSON input files (see the next cell for CSV files that will be loaded).
The following commands should be run from a terminal on a cluster node that has `dsbulk` installed.
Load data to `person` table from a CSV file with a pipe delimiter and allow missing field values:
dsbulk load --schema.keyspace food_cql --schema.table person -url data/vertices/person.csv -delim '|' --schema.allowMissingFields true
Load data to `book` table, identifying the field -> columns with schema mapping:
dsbulk load -k food_cql -t book -url data/vertices/book.csv --schema.mapping '0=book_id, 1=name, 2=publish_year 3=isbn' -delim '|' --schema.allowMissingFields true
Load data to `person_authored_book` table from a CSV file:
dsbulk load -k food_cql -t person_authored_book -url data/edges/person_authored_book.csv -m '0=lastname, 1=person_id, 2=person_name, 3=book_id 4=book_name' -delim '|' --schema.allowMissingFields true
More information about using DataStax Bulk Loader can be found in the documentation: [https://docs.datastax.com/en/dsbulk/doc/index.html] (https://docs.datastax.com/en/dsbulk/doc/index.html)
[Top ↑](#sections)
<file_sep>/food/CQL/insert_1edge.cql
// START-insert1Edge-cql
// Insert 1 person_authored_book edge using CQL:
INSERT INTO food_cql.person_authored_book (person_id, person_name, book_id, book_name) VALUES (
bb6d7af7-f674-4de7-8b4c-c0fdcdaa5cca,
'<NAME>',
1003,
'The French Chef Cookbook'
);
// END-insert1Edge-cql
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/MISC-graphloader/runDGL.sh
#!/bin/sh
# LDR defines the graphloader path
# TYPE defines the input type. Values are: TEXT, CSV, JSON, TEXTXFORM
# DRYRUN_SETTING can be set to true (do a dryrun and show proposed schema) or false (load the data)
# INPUTFILEDIR defines the directory of the input files
# SCRIPTNAME defines the name of the mapping script
# GRAPHNAME defines the name of the graph used for loading. It does not have to exist prior
# to loading
VERSION=dse-graph-loader-5.0.5
LDR=/Users/lorinapoland/CLONES/$VERSION/graphloader
TYPE=CSV
OPTIONS=$DRYRUN $PREP $CREATE_SCHEMA $LOAD_NEW $SCHEMA_OUTPUT
DRYRUN='-dryrun true'
PREP='-preparation true'
CREATE_SCHEMA='-create_schema true'
LOAD_NEW='-load_new true'
SCHEMA_OUTPUT='-schema_output loader_output.txt'
INPUTFILEDIR=/Users/lorinapoland/CLONES/graph-examples/food/$TYPE/
SCRIPTNAME='authorBookMapping'$TYPE'.groovy'
GRAPHNAME='test'$TYPE
#$LDR $INPUTFILEDIR/$SCRIPTNAME -filename INPUTFILEDIR -graph $GRAPHNAME -address localhost -dryrun DRYRUN_SETTING
$LDR $INPUTFILEDIR/$SCRIPTNAME -graph $GRAPHNAME -address localhost $OPTIONS
<file_sep>/food/EXAMPLES/5.1-6.7_EXAMPLES/TEST/geo_dgl/NEW/readme.txt
cart-schema.groovy
Cartesian data with search index created
cart-queries.groovy
Cartesian data with search index created should be able to execute Geo.inside() queries
cartMap.groovy
Cartesian data loading map script
geo-schema.groovy
Geospatial data with search index created
geo-queries.groovy
Geospatial data with search index created should be able to execute Geo.inside() queries
geoMap.groovy
Geospatial data loading map script
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_VLs_1.md
Each vertex label must include at least one property that is used as the partition key. Composite partition keys are defined in the _PRIMARY KEY_ in the vertex label table schema. Additionally, a property or properties that will be used as a clustering key or keys can be defined in the _PRIMARY KEY_. Finally, any additional properties that are not part of the partition key or clustering keys are specified along with the property data type. Lastly, _AND VERTEX LABEL_ completes the schema statement.
<file_sep>/food/GREMLIN/README.md
# This directory has all of the code snippets used in DS Graph.
## They are used in RUN_SETS to test the code in gremlin-console and also used in Studio notebooks.
<file_sep>/food/CQL/create_book_table_convert.cql
// START-createTable-book-convert
CREATE TABLE IF NOT EXISTS food_cql_conversion.book (
book_id int,
name text,
authors list<frozen<fullname>>,
publish_year int,
isbn text,
category set<text>,
PRIMARY KEY (name, book_id)
) WITH CLUSTERING ORDER BY (book_id ASC);
// END-createTable-book-convert
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_Graphs_header.md
##GRAPHS##
[Top ↑](#sections)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_VLs_header.md
## VERTEX LABELS ##
Vertex labels define each type of object that will be connected with edges in a graph. These generally correspond to a thing or noun, like _person_ or _book_.
[Top ↑](#sections)
<file_sep>/food/EXAMPLES/5.1-6.7_EXAMPLES/TEST/searchIndex/readme.md
Run 1-ctoolStartDSEGQuickStart.sh and 2-ctoolDSEGQuickStart.sh to create a cluster and graph and schema.
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_convert_Graph/DSG_CQL_convert_graph_Keyspace_header.md
## CREATE CQL KEYSPACE
[Top ↑](#sections)
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/JDBC/mysql_schema.sql
// MySQL Database
// Connect at http://localhost:3306/
drop database if exists jdbcmysql;
create database jdbcmysql;
use `jdbcmysql`;
//drop table author;
//drop table book;
//drop table authorbook;
create table author(
name varchar(255) primary key,
gender varchar(255)
);
create table book(
name varchar(255) primary key,
year int,
ISBN varchar(255)
);
create table authorbook(
bname varchar(255),
aname varchar(255),
primary key(bname,aname)
);
<file_sep>/food/DGL/graphloader.sh
// Used in Graph QuickStart
// CLI command
graphloader mappingGRYO.groovy -graph recipe -address localhost
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_AddData_header.md
## Adding data ##
Let's start creating some instances of these vertices and edges.
[Top ↑](#sections)
<file_sep>/food/CQL/create_book_table_as_VL.cql
// START-createTable-book-asCQL
CREATE TABLE IF NOT EXISTS food_cql.book (
book_id int,
name text,
authors list<frozen<fullname>>,
publish_year int,
isbn text,
category set<text>,
PRIMARY KEY (name, book_id)
) WITH CLUSTERING ORDER BY (book_id ASC) AND VERTEX LABEL;
// END-createTable-book-asCQL
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/JDBC/mysql_insert_data.sql
// MySQL Database
// Connect at http://localhost:3306/
use `jdbcmysql`;
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','M');
insert into author values('<NAME>','M');
insert into author values('<NAME>','M');
//select * from author;
insert into book values('The Art of French Cooking, Vol. 1',1961,'0-000-00000-0');
insert into book values('Simca''s Cuisine: 100 Classic French Recipes for Every Occasion',1972,'0-394-40152-2');
insert into book values('The French Chef Cookbook',1968,'0-394-40135-2');
insert into book values('The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution',2007,'0-307-33679-4');
//select * from book;
insert into authorbook values('The Art of French Cooking, Vol. 1','<NAME>');
insert into authorbook values('The Art of French Cooking, Vol. 1','<NAME>');
insert into authorbook values('The Art of French Cooking, Vol. 1','Louisette Bertholie');
insert into authorbook values('Simca''s Cuisine: 100 Classic French Recipes for Every Occasion','<NAME>');
insert into authorbook values('Simca''s Cuisine: 100 Classic French Recipes for Every Occasion','<NAME>');
insert into authorbook values('The French Chef Cookbook','<NAME>');
insert into authorbook values('The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution','<NAME>');
insert into authorbook values('The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution','<NAME>');
insert into authorbook values('The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution','<NAME>');
insert into authorbook values('The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution','<NAME>');
//select * from authorbook;
<file_sep>/food/CQL/person_authored_book_convert.cql
// START-createTablePersonAuthoredBook_convert-cql
// Create table for conversion to edge label table using CQL:
CREATE TABLE food_cql_conversion.person_authored_book (
person_name text,
person_id UUID,
book_name text,
book_id int,
PRIMARY KEY ((person_name, person_id), book_name, book_id)
);
// END-createTablePersonAuthoredBook_convert-cql
<file_sep>/food/CQL/describe_keyspace_convert.cql
// START-descKS-convert
DESCRIBE KEYSPACE food_cql_conversion;
// END-descKS-convert
<file_sep>/food/CQL/alter_remove_VL.cql
// START-alterTable-person-remove
ALTER TABLE food.person WITHOUT VERTEX LABEL "personX"
// END-alterTable-person-remove
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/CSV/allRecipe/readme.md
## DSE QuickStart Recipe Toy Graph CSV
* [Mapping script] (recipeMapCSV.groovy)
* [schema] (recipeSchema.groovy)
* [graphloader script] (runDGL.sh)
* [vertices] (vertices)
* [edges] (edges)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_VLs_3.md
In the vertex labels created above, note the use of collections (set, list, map), tuples, and lists of collections, tuples, and UDTs. These data types provide a remarkable amount of flexibility in defining meta-properties (a property on a property) and multi-properties (a property with multiple values). For instance, the _badge_ property is stored as a map of Text:Integer, such as Gold:2015, the meta-property of _year achieved_ on the _badge level_. Similarly, a set of Text values for _nickname_ store the various values for the multi-property _nickname_.
<file_sep>/food/CQL/fullname-type.cql
// IS THIS FILE NEEDED??
// START-createUDTFull-cql
CREATE TYPE food.fullname (
lastname text,
firstname text);
// END-createUDTFull-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_Indexing_header.md
## Indexing ##
Indexes are required for many graph queries. For vertices, if a query uses any property besides the partition key, an index is required. In addition, edges are unidirectional, so if a vertex requires both _in()_ and _out()_, an index will be required. The schema step _indexFor()_ can analyze for necessary indexes, using the traversal that is desired. Both an _analyze()_ and an _apply()_ option are available, to first examine the suggested index, and also to apply it.
Currently, materialized view and search indexes will be suggested with _indexFor()_. Secondary indexes, materialized view indexes, and searches indexes can also be created manually.
[Top ↑](#sections)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_TOC.md
##DataStax Graph created using CQL as Graph##
These examples show how to create Graph schema using CQL. The types and tables are created directly in CQL.
* ####<div id="sections"></div>Table of Contents###
* ####[Graphs](http://localhost:9091/notebooks/636f7be7-3b99-4cab-9f91-bfba555612d7/cell/da9d95c0-251d-4ce3-9291-a1de079ec09f)####
* ####[User-defined types](http://localhost:9091/notebooks/636f7be7-3b99-4cab-9f91-bfba555612d7/cell/4b718d3b-7202-4821-a67d-238412d2a59d)####
* ####[Vertex Labels](http://localhost:9091/notebooks/636f7be7-3b99-4cab-9f91-bfba555612d7/cell/24993a06-b5eb-4f7f-9c9e-e7f83ddde89c)####
* ####[Edge labels](http://localhost:9091/notebooks/636f7be7-3b99-4cab-9f91-bfba555612d7/cell/6f60f93c-9323-4f40-83cf-f5e54cccf66e)####
* ####[Inserting data](http://localhost:9091/notebooks/636f7be7-3b99-4cab-9f91-bfba555612d7/cell/796a7c5e-395f-4e0d-b414-d5034faa2054)####
* ####[Using the DataStax Bulk Loader to insert data into CQL](http://localhost:9091/notebooks/636f7be7-3b99-4cab-9f91-bfba555612d7/cell/c695059c-e32e-4df7-9626-8fad57fbe2b1)####
* ####[Full food data model schema and data](http://localhost:9091/notebooks/636f7be7-3b99-4cab-9f91-bfba555612d7/cell/64cd19c5-ba88-43b3-902f-171967f0fcf9)####
<file_sep>/food/CQL/describe_keyspace.cql
// START-descKS-cql
DESCRIBE KEYSPACE food_cql;
// END-descKS-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_convert_Graph/DSG_CQL_convert_graph_visiualizeStmt.md
The visualization tools of DataStax Studio are available to examine the graph created with CQL and queried with Gremlin.
<file_sep>/food/CQL/select_book_convert.cql
// START-selectBook_convert-cql
// Examine book table using CQL
SELECT * FROM food_cql_conversion.book;
// END-selectBook_convert-cql
<file_sep>/food/EXAMPLES/5.1-6.7_EXAMPLES/TEST/NEW_COMP/traversals/readme.md

<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_convert_Graph/DSG_CQL_convert_graph_AlterTablesToGraph_header.md
## ALTER TABLES INTO GRAPH ##
The CQL tables must also be converted to graph.
<!--- KM suggested showing remove a VL or EL in CQL without losing the CQL table, add later--->
[Top ↑](#sections)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/ALL_FOOD_SCHEMA/ALL_FOOD_SCHEMA_AddVertices_header.md
## Add vertices ##
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/JDBC/mysql_load_data.mysql
load data local infile '~/graph-examples/food/JDBC/data/authors.csv'
into table fraud.author
fields terminated by '|' escaped by ''
ignore 1 lines;
<file_sep>/food/CQL/alter_VL.cql
// START-alterTable-person
ALTER TABLE food.person RENAME VERTEX LABEL TO "personX"
// END-alterTable-person
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/MISC-graphloader/dirSource/readme.md
## Simple read from multiple files in a directory example
* [Mapping script] (dirSourceMap.groovy)
* [schema] (schema.groovy)
* [graphloader script] (runDGL.sh)
* [data] (data)
* [person.csv] (data/person.csv)
* [person2.csv] (data/person2.csv)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_VLs_3.md
Properties can also be added or dropped from tables. The properties added here with _ALTER_TABLE_ are used to track the book discount given on a book.
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_Indexing_1.md
Try the next query before applying the index, and you'll see that the query fails. Come back and run it after applying the index, and it will complete without errors.
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_convert_Graph/DSG_CQL_convert_graph_ELs_header.md
## CQL TABLE FOR EDGE LABEL ##
Edge labels define each the connection between vertices in a graph. These generally correspond to a connecting word or verb, like _created_ or _authored_. The CQL table for an edge label is ????
[Top ↑](#sections)
<file_sep>/food/CQL/person_authored_book-table.cql
// START-createTablePersonAuthoredBook-cql
// Create edge label table using CQL
CREATE TABLE IF NOT EXISTS food_cql.person_authored_book (
person_id UUID,
person_name text,
book_id int,
book_name text,
PRIMARY KEY ( (person_name, person_id) , book_name, book_id)
) WITH EDGE LABEL person_authored_book
FROM person(person_name, person_id)
TO book(book_name, book_id);
// END-createTablePersonAuthoredBook-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_ELs_1.md
For edge label tables, the table is named with the pattern _startingVertexLabel_edgeLabel_endingVertexLabel_. Edge properties can be defined similarly to vertex labels. Finally, using _WITH EDGE LABEL_ ... _FROM_ ... _TO_, the definition of the primary keys to use for the edges is defined.
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_ELs_2.md
Even more narrowing of the query for edge label querying can be applied using the _from()_ and _to()_ steps.
<file_sep>/food/CQL/drop_UDTs_convert.cql
// START-dropUDTs-cql
DROP TYPE IF EXISTS food_cql_conversion.location_details;
DROP TYPE IF EXISTS food_cql_conversion.fullname;
DROP TYPE IF EXISTS food_cql_conversion.address;
// END-dropUDTs-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_convert_Graph/DSG_CQL_convert_graph_Keyspace_2.md
To discover all currently available schema information about CQL, use the Schema feature of DataStax Studio on the appropriate keyspace. _DESCRIBE KEYSPACE_ can also be used.
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_AddData_1.md
The final query in the cell above shows the results of the insertions of three people to the graph visually. The data can also be queried from the appropriate CQL table.
<file_sep>/food/CQL/drop_table_convert.cql
// START-dropAllTables_convert-cql
// Drop all conversion tables using CQL:
DROP TABLE IF EXISTS food_cql_conversion.person_authored_book;
DROP TABLE IF EXISTS food_cql_conversion.book;
DROP TABLE IF EXISTS food_cql_conversion.person;
// END-dropAllTables_convert-cql
<file_sep>/food/DSBULK/food-book-graph.sh
#!/bin/bash
#**********************************
# food-book-graph.sh
# Use dsbulk to add book data to graph
# <NAME>
#**********************************
dsbulkBinDir="/home/automaton/dsbulk-1.3.4/bin"
repoDataDir="/home/automaton/graph-examples/food/DATA/CSV/vertices"
ks="food"
$dsbulkBinDir/dsbulk load --schema.graph $ks --schema.vertex book -url $repoDataDir/book.csv -delim '|' -header true --schema.allowMissingFields true --schema.mapping '0=book_id, 1=name, 2=publish_year, 3=isbn'
<file_sep>/food/CQL/create_person_table_as_VL.cql
// START-createTable-person-asCQL
CREATE TABLE IF NOT EXISTS food_cql.person (
person_id UUID,
name text,
gender text,
nickname set<text>,
cal_goal int,
macro_goal list<int>,
badge map<text, date>,
PRIMARY KEY (name, person_id)
) WITH CLUSTERING ORDER BY (person_id ASC) AND VERTEX LABEL;
// END-createTable-person-asCQL
<file_sep>/food/EXAMPLES/5.1-6.7_EXAMPLES/TEST/geo_dgl/NEW/allScript.sh
#/bin/sh
# Cartesian - SEARCH INDEX
cat cart-schema.groovy | dse gremlin-console
~/dse-graph-loader-5.1.2-SNAPSHOT/graphloader cartMap.groovy -address localhost -graph cartSIData
cat cart-queries.groovy | dse gremlin-console >> cartSI.txt
# Geo - SEARCH INDEX
cat geo-schema.groovy | dse gremlin-console
~/dse-graph-loader-5.1.2-SNAPSHOT/graphloader geoMap.groovy -address localhost -graph geoSIData
cat geo-queries.groovy | dse gremlin-console >> geoSI.txt
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_UDTs_1.md
CQL stores schema data in several tables in the _system_schema_ keyspace: _types_, _vertices_, _edges_, _indexes_. A CQL query can be used to view the information.
<file_sep>/food/CQL/select_person_convert.cql
// START-selectPerson_convert-cql
// Examine person table using CQL:
SELECT * FROM food_cql_conversion.person;
// END-selectPerson_convert-cql
<file_sep>/README.md
# graph-examples
DSE Graph examples
<file_sep>/food/EXAMPLES/5.1-6.7_EXAMPLES/TEST/CSVTextHeader/test-csv-and-text/run-loader.sh
#!/bin/bash
START=$(date +%s)
export PATH=$PATH:/opt/dse-graph-loader-5.0.6/
graphloader loader.groovy -graph sma_graph_prod_v10 -address 192.168.69.134 -dryrun false -preparation false -abort_on_num_failures 10000 -abort_on_prep_errors false -vertex_complete false
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "It took $DIFF seconds"
<file_sep>/food/CQL/select_book.cql
// CQL as Graph
// START-selectBook-cql
// Examine book table using CQL
SELECT * FROM food_cql.book;
// END-selectBook-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_VLs_1.md
Each vertex label must include at least one property that is used as the partition key (_partitionBy_). Composite partition keys are defined by multiple _partitionBy_ steps in the vertex label schema. Additionally, a property or properties that will be used as a clustering key or keys can be defined with _clusteringBy_. Finally, any additional properties that are not part of the partition key or clustering keys are defined with a _property_ step. The property data type must also be specified. Lastly, a _create_ step completes the schema statement.
See the All Food Schema notebook for a wider variety of edge labels.
<file_sep>/food/CQL/select_system_edges.cql
// START-selectSystemEdges-cql
// Look at the created edge labels using CQL
select * from system_schema.edges;
// Look at the created edge labels using CQL
select * from system_schema.edges WHERE keyspace_name='food';
// END-selectSystemEdges-cql
<file_sep>/food/DSBULK/food-authored.sh
#!/bin/bash
#**********************************
# food-book.sh
# Use dsbulk to add book data to graph
# <NAME>
#**********************************
dsbulkBinDir="/home/automaton/dsbulk-1.3.4/bin"
repoDataDir="/home/automaton/graph-examples/food/DATA/CSV/edges"
ks="food"
$dsbulkBinDir/dsbulk load \
-k $ks \
-t person_authored_book \
-url $repoDataDir/person_authored_book.csv \
-m '0=person_id, 1=person_name, 2=book_id, 3=book_name' \
-delim '|' \
-header true \
--schema.allowMissingFields true
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/GraphSON/readme.md
## Simple GraphSON example recipe data
* [Mapping script] (recipeMappingGRAPHSON.groovy)
* [graphloader script] (runDGL.sh)
* [recipe.json] (recipe.json)
* [recipeTG.json] (recipeTG.json)
* [recipe_lossless.json] (recipe_lossless.json)
* [GraphSONExample.json] (GraphSONExample.json)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_convert_Graph/DSG_CQL_convert_graph_UDTs_header.md
##USER-DEFINED TYPES (UDTs)
User-defined types (UDTs) allow custom data types to be defined. A UDT can combine commonly coupled data within a single type, simplifying retrieval of the information in queries.
[Top ↑](#sections)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_ELs_header.md
## Edge labels ##
Edge labels define each the connection between vertices in a graph. These generally correspond to a connecting word or verb, like _created_ or _authored_.
[Top ↑](#sections)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_Intro.md
<!--- Author: <NAME> --->
##DataStax Graph##
DataStax Graph has been redesigned for more versatility in application development. Three methods of data model schema creation now exist, each equally capable. Which method you use depends on your skillset and preferences. The methods are:
- Use Gremlin exclusively to create a graph and schema and query the graph.
- Use Cassandra Query Language (CQL) to create a graph and schema that can be queried with Gremlin.
- Convert data stored in Cassandra to create a graph and schema that can be queried with Gremlin.
###This Studio notebook shows the first method, using Gremlin to create a graph and schema.###
See other Studio notebooks for the other two methods.
<file_sep>/food/CQL/select_person_authored_book_convert.cql
USE food_cql_conversion;
// START-selectPersonAuthoredBook_convert-cql
// Examine person_authored_book table using CQL:
SELECT * FROM food_cql_conversion.person_authored_book;
// END-selectPersonAuthoredBook_convert-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/ALL_FOOD_SCHEMA/ALL_FOOD_SCHEMA_header.md
--- Author: <NAME> --->
## DataStax Graph Food Data Model: Schema and Data ##
This notebook creates the schema for the food data model and inserts data.
<file_sep>/food/CQL/select_person_core.cql
// Gremlin
// START-selectPerson_core-cql
// Select all people listed in the table person
select * from food.person;
// END-selectPerson_core-cql
<file_sep>/food/CQL/alter_keyspace_into_graph.cql
// START-alterKS-graph-Core
ALTER KEYSPACE food_cql
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}
AND graph_engine = 'Core';
// END-alterKS-graph-Core
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/JDBC/H2_db_creation.sql
// H2 Database
// Connect at http://localhost:8082/
drop table author;
drop table book;
drop table authorbook;
create table author(name varchar(255) primary key, gender varchar(255));
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','F');
insert into author values('<NAME>','M');
insert into author values('<NAME>','M');
insert into author values('<NAME>','M');
select * from author;
create table book(name varchar(255) primary key, year int, ISBN varchar(255));
insert into book values('The Art of French Cooking, Vol. 1',1961,'0-000-00000-0');
insert into book values('Simca''s Cuisine: 100 Classic French Recipes for Every Occasion',1972,'0-394-40152-2');
insert into book values('The French Chef Cookbook',1968,'0-394-40135-2');
insert into book values('The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution',2007,'0-307-33679-4');
select * from book;
create table authorbook(bname varchar(255), aname varchar(255), primary key(bname,aname));
insert into authorbook values('The Art of French Cooking, Vol. 1','<NAME>');
insert into authorbook values('The Art of French Cooking, Vol. 1','<NAME>');
insert into authorbook values('The Art of French Cooking, Vol. 1','<NAME>');
insert into authorbook values('Simca''s Cuisine: 100 Classic French Recipes for Every Occasion','<NAME>');
insert into authorbook values('Simca''s Cuisine: 100 Classic French Recipes for Every Occasion','<NAME>');
insert into authorbook values('The French Chef Cookbook','<NAME>');
insert into authorbook values('The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution','<NAME>');
insert into authorbook values('The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution','<NAME>');
insert into authorbook values('The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution','<NAME>');
insert into authorbook values('The Art of Simple Food: Notes, Lessons, and Recipes from a Delicious Revolution','<NAME>');
select * from authorbook;<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_AddData_2.md
Again, the results of the insertions of three book to the graph are shown visually. The data can also be queried from the appropriate CQL table.
<file_sep>/food/DSBULK/food-authored-graph.sh
#!/bin/bash
#**********************************
# food-book.sh
# Use dsbulk to add book data to graph
# <NAME>
#**********************************
dsbulkBinDir="/home/automaton/dsbulk-1.3.4/bin"
repoDataDir="/home/automaton/graph-examples/food/DATA/CSV/edges"
ks="food"
$dsbulkBinDir/dsbulk load -k $ks -e authored -from person -to book -url $repoDataDir/person_authored_book.csv -m '0=person_id, 1=person_name, 2=book_id, 3=book_name' -delim '|' -header true --schema.allowMissingFields true
<file_sep>/food/DSBULK/food-ingredient-graph.sh
#!/bin/bash
#**********************************
# food-ingredient.sh
# Use dsbulk to add ingredient data to graph
# Lorina Poland
#**********************************
dsbulkBinDir="/home/automaton/dsbulk-1.3.4/bin"
repoDataDir="/home/automaton/graph-examples/food/DATA/CSV/vertices"
ks="food"
$dsbulkBinDir/dsbulk load --schema.graph $ks --schema.vertex ingredient -url $repoDataDir/ingredient.csv -delim '|' -header true --schema.allowMissingFields true
<file_sep>/food/CQL/select_person.cql
// CQL as Graph
// START-selectPerson-cql
// Examine person table using CQL:
SELECT * FROM food_cql.person;
// END-selectPerson-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_Graphs_1.md
In DataStax Studio, users are alerted to create a graph. If you choose to use `dse gremlin-console` to create a graph, you'll need to use the command shown in the next cell.
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/GraphML/readme.md
## Simple GraphML example recipe data
* [Mapping script] (recipeMappingGRAPHML.groovy)
* [graphloader script] (runDGL.sh)
* [recipe.gml] (recipe.gml)
* [recipe_sample.gml] (recipe_sample.gml)
* [recipeTG.xml] (recipeTG.xml)
<file_sep>/food/CQL/source.cql
// START-source-cql
source './0_create_keyspace.cql';
source './person-table.cql';
source './book-table.cql';
// END-source-cql
<file_sep>/food/EXAMPLES/DSG-LABS_EXAMPLES/QUICKSTART/quickstart.sh
#!/bin/bash
#**********************************
# quickstart.sh
# QuickStart code script for public users
# Author: <NAME>
#**********************************
repoGremlinDir="/home/automaton/graph-examples/food/DSG-LABS/GREMLIN"
cat $repoGremlinDir/0_create_graph_QS.gremlin | dse gremlin-console;
cat $repoGremlinDir/remoteQS.gremlin \
$repoGremlinDir/create_VLs.gremlin \
$repoGremlinDir/create_ELs.gremlin | dse gremlin-console;
cqlsh -f $repoGremlinDir/create_table_recipe.cql;
cat $repoGremlinDir/remoteQS.gremlin \
$repoGremlinDir/insert_3persons.gremlin \
$repoGremlinDir/insert_3books.gremlin \
$repoGremlinDir/insert_2edges.gremlin | dse gremlin-console;
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/ALL_FOOD_SCHEMA/ALL_FOOD_SCHEMA_AddEdges_header.md
## Add edges ##
<file_sep>/OLD/GoT/README.txt
This directory holds data files and Groovy scripts for Titan-Cassandra. The data set is a small Game of Thrones dataset. More data will be added over time.
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_convert_Graph/DSG_CQL_convert_graph_Keyspace_1.md
Find all the keyspaces in a cluster, and whether or not they are currently a Graph keyspace or a CQL keyspace.
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_UDTs_2.md
All the defined schema can be displayed with the broader command shown here (although only the UDTs are currently defined):
<file_sep>/food/CQL/insert_3persons_convert.cql
// START-insert3persons_convert-cql
// Insert person data using CQL:
INSERT INTO food_cql_conversion.person (person_id, name, gender) VALUES (
bb6d7af7-f674-4de7-8b4c-c0fdcdaa5cca,
'<NAME>',
'F'
);
INSERT INTO food_cql_conversion.person (person_id, name, gender, nickname) VALUES (
adb8744c-d015-4d78-918a-d7f062c59e8f,
'<NAME>',
'F',
{'Simca'}
);
INSERT INTO food_cql_conversion.person (person_id, name, gender) VALUES (
888ad970-0efc-4e2c-b234-b6a71c30efb5,
'<NAME>',
'M'
);
// END-insert3persons_convert-cql
<file_sep>/food/CQL/select_system_vertices.cql
// START-selectSystemVertices-cql
// Look at the created vertex labels using CQL
select * from system_schema.vertices;
// Look at the created vertex labels using CQL
select * from system_schema.vertices WHERE keyspace_name='food';
// END-selectSystemVertices-cql
<file_sep>/food/CQL/select_system_UDTs.cql
// START-selectUDTs-cql
// Look at the created UDTs using CQL
// There is not currently a way to look at just UDTs with Gremlin
select * from system_schema.types WHERE keyspace_name='food_cql';
// END-selectUDTs-cql
<file_sep>/food/CQL/insert_2books.cql
// START-insert2books-cql
// Insert book data using CQL:
INSERT INTO food_cql.book (name,book_id,publish_year,isbn,category) VALUES (
'The French Chef Cookbook',
1003,
1968,
'0-394-40135-2',
{'French'}
);
INSERT INTO food_cql.book (name,book_id,publish_year,isbn,category) VALUES (
$$Simca's Cuisine: 100 Classic French Recipes for Every Occasion$$,
1002,
1972,
'0-394-40152-2',
{'American','French'}
);
// END-insert2books-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_convert_Graph/DSG_CQL_convert_graph_AddData_header.md
## INSERTING DATA ##
Insert some data into the tables.
[Top ↑](#sections)
<file_sep>/food/CQL/recipe-table.cql
// START-createTableRecipe-cql
// Assume we have the following existing non-vertex label table.
// Create a CQL table that can be converted into a vertex label
CREATE TABLE food_cql.recipe_table (
recipe_id int,
name text,
cuisine set<text>,
instructions text,
notes text,
PRIMARY KEY (recipe_id));
// END-createTableRecipe-cql
<file_sep>/food/CQL/create_UDTs.cql
// START-createUDTs-cql
CREATE TYPE IF NOT EXISTS food_cql.address (
address1 text,
address2 text,
city_code text,
zip_code text);
CREATE TYPE IF NOT EXISTS food_cql.fullname (
lastname text,
firstname text);
//Using a nested UDT in another UDT:
CREATE TYPE IF NOT EXISTS food_cql.location_details (
loc_address frozen<address>,
telephone list<text>
);
// END-createUDTs-cql
<file_sep>/food/CQL/select_person_authored_book_edge_core.cql
// START-selectPersonAuthoredBook_core-cql
SELECT * FROM food.person__authored__book;
// END-selectPersonAuthoredBook_core-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_convert_Graph/DSG_CQL_convert_graph_TOC.md
##DataStax Graph created using CQL conversion##
These examples show how to create Graph schema using CQL conversion. The types and tables are created directly in CQL, originally as CQL. Then, after data exists, it converts the CQL to Graph data.
###<div id="sections"></div>Table of Contents###
* ####[Create CQL Keyspace](http://localhost:9091/notebooks/577dbd0b-dcf6-496b-8a62-48b3678e776e/cell/1f20110b-99b4-466f-a42c-1c9a8189d251)####
* ####[User-defined types](http://localhost:9091/notebooks/577dbd0b-dcf6-496b-8a62-48b3678e776e/cell/63f46bd0-ac14-4eb8-aadb-b7f49da8f1c5)####
* ####[CQL Tables for Vertex Labels](http://localhost:9091/notebooks/577dbd0b-dcf6-496b-8a62-48b3678e776e/cell/a206b8af-e6f6-4737-b256-f9f3e766a70f)####
* ####[CQL Tables for Edge labels](http://localhost:9091/notebooks/577dbd0b-dcf6-496b-8a62-48b3678e776e/cell/f1bf0908-93ef-49b1-b080-3f49bc7757d9)####
* ####[Inserting data](http://localhost:9091/notebooks/577dbd0b-dcf6-496b-8a62-48b3678e776e/cell/8a9136ce-3a83-4004-827b-f95c70e762bf)####
* ####[Alter keyspace into Graph](http://localhost:9091/notebooks/577dbd0b-dcf6-496b-8a62-48b3678e776e/cell/196c8720-c21e-49c6-b5b4-242f1cb2b203)####
* ####[Alter tables into Graph](http://localhost:9091/notebooks/577dbd0b-dcf6-496b-8a62-48b3678e776e/cell/2f902106-aba6-4cf0-b898-5693fdea9773)####
* ####[Full food data model schema and data](http://localhost:9091/notebooks/577dbd0b-dcf6-496b-8a62-48b3678e776e/cell/b5017189-4b31-4cca-b6b5-f395302bd10d)####
<file_sep>/food/CQL/alter_tables_convert.cql
// START-alterAllTables
// Alter all tables with either VERTEX LABEL or EDGE LABEL using CQL:
ALTER TABLE food_cql_conversion.person WITH VERTEX LABEL "person";
ALTER TABLE food_cql_conversion.book WITH VERTEX LABEL "book";
ALTER TABLE food_cql_conversion.person_authored_book
WITH EDGE LABEL "authored"
FROM person(person_name, person_id)
TO book(book_name, book_id);
// END-alterAllTables
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_AddData_1.md
Because the CQL tables were identified as vertex labels on creation, it is interesting that Gremlin can now also be used to examine the vertices inserted. However, the keyspace must be altered to a graph prior to the Gremlin query:
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_TOC.md
##DataStax Graph created using Gremlin##
These examples show how to create Graph schema using Gremlin. The data is also inserted using Gremlin.
###<div id="sections"></div>Table of Contents###
* ####[Graphs](http://localhost:9091/notebooks/da0b7dc3-1dd1-4027-bbef-4bf22e1506a4/cell/6f1c51fa-7660-46ca-81f8-de805159e8c1)####
* ####[User-defined types](http://localhost:9091/notebooks/da0b7dc3-1dd1-4027-bbef-4bf22e1506a4/cell/65a852b0-4d12-4328-8064-6e5e29ba978c)####
* ####[Vertex Labels](http://localhost:9091/notebooks/da0b7dc3-1dd1-4027-bbef-4bf22e1506a4/cell/bc07f7ac-9759-44e2-85d6-6d68a912dc21)####
* ####[Edge labels](http://localhost:9091/notebooks/da0b7dc3-1dd1-4027-bbef-4bf22e1506a4/cell/5c43d6f2-5d9e-4ab8-abba-afc6a506b76d)####
* ####[Adding data](http://localhost:9091/notebooks/da0b7dc3-1dd1-4027-bbef-4bf22e1506a4/cell/93772006-5df8-465e-b7a9-b93d721a2eca)####
* ####[Create vertex label by converting existing CQL table](http://localhost:9091/notebooks/da0b7dc3-1dd1-4027-bbef-4bf22e1506a4/cell/a74e2dce-7ef1-49ef-8ea3-7278c5861a08)####
* ####[Indexing](http://localhost:9091/notebooks/da0b7dc3-1dd1-4027-bbef-4bf22e1506a4/cell/888816a9-6d10-4736-9b4d-fc656c7b01d4)####
* ####[Full food data model schema and data](http://localhost:9091/notebooks/da0b7dc3-1dd1-4027-bbef-4bf22e1506a4/cell/7d736fe4-0a2e-4958-8cdc-82745f95393e)####
<file_sep>/food/DSBULK/food-book.sh
#!/bin/bash
#**********************************
# food-book.sh
# Use dsbulk to add book data to graph
# <NAME>
#**********************************
dsbulkBinDir="/home/automaton/dsbulk-1.3.4/bin"
repoDataDir="/home/automaton/graph-examples/food/DATA/CSV/vertices"
ks="food"
$dsbulkBinDir/dsbulk load --schema.keyspace $ks --schema.table book -url $repoDataDir/book.csv -delim '|' -header true --schema.allowMissingFields true --schema.mapping '0=book_id, 1=name, 2=publish_year, 3=isbn'
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/MISC-graphloader/dateTime/readme.md
## Date and Time data type test
This mapping script is currently not working. It seems to believe that the schema must be different than the schema pre-loaded before running
graphloader.
* [Mapping script] (dateTimeMap.groovy)
* [schema] (schema.groovy)
* [graphloader script] (runDGL.sh)
* [person.csv] (person.csv)
* [personEdges.csv - edges] (personEdges.csv)
* [Queries for Date and Time] (dateTime-queries.groovy)
<file_sep>/food/CQL/select_system_keyspaces.cql
// START-selectSystemKS-cql
SELECT * FROM system_schema.keyspaces;
// END-selectSystemKS-cql
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_AddData_3.md
Now insert the edges. Note that the traversal identifies each of the vertices using their partitioning keys (a UUID for _person_id_ and an Integer for _book_id_), and then adds the edge with _addE_ using the edge label and _from_/_to_ values.
<file_sep>/food/CQL/alter_VL_add_property.cql
// START-alterTable-prop
ALTER TABLE food_cql.book
ADD book_discount text;
// END-alterTable-prop
<file_sep>/food/CQL/alter_EL.cql
// START-alterTable-edge-authored
ALTER TABLE food."personAuthoredBook" RENAME EDGE LABEL TO "authoredX"
// END-alterTable-edge-authored
<file_sep>/food/CQL/README.md
This directory contains CQL code for inserting schema into CQL tables for use with DataStax Graph.
<file_sep>/food/DGL/5.1-6.7_LOADING_DATA_EXAMPLES/MISC-graphloader/filePattern/readme.md
## Simple read from multiple files in a directory example
* [Mapping script] (filePatternMap.groovy)
* [Mapping script - JSON] (filePatternJSONMap.groovy)
* [schema] (schema.groovy)
* [graphloader script] (runDGL.sh)
* [graphloader script - JSON] (runDGLJSON.sh)
* [data] (data)
* [person.csv] (data/person.csv)
* [person2.csv] (data/person2.csv)
* [badOne.csv - used for testing file pattern] (data/badOne.csv)
* [data_json] (data_json)
* [author.csv] (data/author.csv)
* [author2.csv] (data/author2.csv)
* [badOne.csv - used for testing file pattern] (data/badOne.csv)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremin_UDTs_1.md
DataStax Graph stores graph schema data in several tables in the _system_schema_ keyspace: _types_, _vertices_, _edges_, _indexes_. Either Gremlin can be used to view the existing elements in the corresponding schema, or a CQL query can be used to view the information. In addition, Gremlin can more specifically define a particular element to view, as shown for _address_.
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_Graphs_header.md
## Graphs ##
How to list graphs, make graphs, and drop graphs.
[Top ↑](#sections)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_convert_Graph/DSG_CQL_convert_graph_VLs_header.md
## CQL TABLES FOR VERTEX LABELS ##
Vertex labels define each type of object that will be connected with edges in a graph. These generally correspond to a thing or noun, like _person_ or _book_. A CQL table will need to define the same elements as the vertex label that will be created upon conversion.
[Top ↑](#sections)
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_convert_Graph/DSG_CQL_convert_graph_AlterKSToGraph_header.md
## ALTER KEYSPACE INTO GRAPH ##
Now that the tables and data exist in CQL, convert the keyspace to a graph.
[Top ↑](#sections)
<file_sep>/food/CQL/create_person_table_convert.cql
// START-createTable-person-convert
CREATE TABLE IF NOT EXISTS food_cql_conversion.person (
person_id UUID,
name text,
gender text,
nickname set<text>,
cal_goal int,
macro_goal list<int>,
badge map<text, date>,
PRIMARY KEY (name, person_id)
) WITH CLUSTERING ORDER BY (person_id ASC);
// END-createTable-person-convert
<file_sep>/food/README.md

The files found in this repo relate to DataStax Graph versions 5.1 through the newest LABS version. CQL and Gremlin code can be found here, that is used to test all Graph code from the DataStax documentation. In addition DataStax Studio notebooks are located here.
<file_sep>/food/DSBULK/food-store-graph.sh
#!/bin/bash
#**********************************
# food-store-graph.sh
# Use dsbulk to add store data to graph
# <NAME>
#**********************************
dsbulkBinDir="/home/automaton/dsbulk-1.3.4/bin"
repoDataDir="/home/automaton/graph-examples/food/DATA/CSV/vertices"
ks="food"
$dsbulkBinDir/dsbulk load --schema.graph $ks --schema.vertex store -url $repoDataDir/store.csv -delim '|' -header true --schema.allowMissingFields true
<file_sep>/food/CQL/select_system_UDTs_convert.cql
// START-selectUDTs_convert-cql
// Look at the created UDTs using CQL
select * from system_schema.types WHERE keyspace_name='food_cql_conversion';
// END-selectUDTs_convert-cql
<file_sep>/food/CQL/select_person_authored_book.cql
// START-selectPersonAuthoredBook-cql
// Examine person_authored_book table using CQL:
SELECT * FROM food_cql.person_authored_book;
// END-selectPersonAuthoredBook-cql
<file_sep>/food/CQL/0_drop_keyspace_convert.cql
// START-dropKS-convert
DROP KEYSPACE IF EXISTS food_cql_conversion;
// END-dropKS-convert
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/ALL_FOOD_SCHEMA/ALL_FOOD_SCHEMA_AddAddlData_header.md
Some some additional, complex property values and check that the values are added to the elements:
<file_sep>/food/CQL/FIX_personAuthoredBook-table.cql
// I TOOK OUT CLUSTERING ORDER - FIGURE OUT IF THAT NEEDS TO BE IN THERE
CREATE TABLE IF NOT EXISTS food_cql.person_authored_book (
person_id UUID,
lastname text,
name text,
book_id int,
PRIMARY KEY ( lastname, person_id, name, book_id)
) WITH EDGE LABEL created
FROM person(lastname, person_id)
TO book(name, book_id);
INSERT INTO food_cql.person_authored_book
(lastname,person_id, name, book_id)
VALUES ('CHILD', bb6d7af7-f674-4de7-8b4c-c0fdcdaa5cca, 'The French Chef Cookbook', 1003);
INSERT INTO food_cql.person_authored_book
(lastname,person_id, name, book_id)
VALUES ('BECK', adb8744c-d015-4d78-918a-d7f062c59e8f, $$Simca's Cuisine: 100 Classic French Recipes for Every Occasion$$, 1002);
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_CQL_as_Graph/DSG_CQL_as_Graph_Graphs_2.md
A keyspace is first created for the graph using CQL.
<file_sep>/food/STUDIO_NOTEBOOKS/NOTEBOOK_MD/DSG_GREMLIN/DSG_Gremlin_ConvertTable_header.md
## Create vertex label by converting an existing CQL table ##
Another Studio notebook covers converting an existing CQL table into a vertex label in a graph, but the next two cells show one example to whet your appetite. A CQL table, _recipe_table_ is created in CQL, and then a Gremlin command using _fromExistingTable()_ is used to convert the table into a vertex label table.
[Top ↑](#sections)
| 5567a761ae470229c8a685e0c7d77c76c60d502a | [
"Markdown",
"SQL",
"Text",
"Shell"
] | 128 | SQL | polandll/llp-graph-examples | 798d4472dff53e350af4fdf6d2a444bc73be9933 | d881b6f8c010bf76e735269a1e2e2577978708f8 |
refs/heads/master | <file_sep>from tkinter import *
from functools import partial # Importa a funcao 'partial', que reescreve uma funcao
# E importa uma lista de parametros
# Pilares do tkinter:
# Gerenciadores de Layout, Widgets e Eventos
# Um gerenciador de layout define a organização dos widgets dentro de um container
# Os 3 gerenciadores de layout: place, pack e grid
# place - usa coordenadas x e y (a origem fica no canto superior esquerdo do monitor)
# pack - empacota os widgets na horizontal ou vertical
# grid - os widgets são inseridos num sistema de células de uma tabela
def onClick(botao):
rotulo['text']= botao['text']
janela = Tk() # Instanciando a classe Tk() do pacote tk no objeto 'janela'
botao1 = Button(janela, width=20, text='Botao 1') # Instancie a classe Button no objeto botao
botao1['command'] = partial(onClick, botao1)# Ao utilizar o comando onClick sem os parenteses no final, garantimos que ele nao sera executado antes do clique
botao1.place(x=100, y=100)
botao2 = Button(janela, width=20, text='Botao 2')
botao2['command'] = partial(onClick, botao2)
botao2.place(x=100, y=130)
# Uso: Label(parent, text='string')
rotulo = Label(janela, text='Nenhuma acao realizada') # Instanciando a classe Label no objeto 'rotulo'
rotulo.place(x=100, y=160) # Estabelecendo o gerenciador de layout que deve conter o rotulo
janela.title("Janela principal") # Título da janela
# janela['background'] = 'white' # Toda janela é também um dicionário
janela.geometry('300x300+200+200') #'L' x 'H' + 'X' + 'Y'
janela.mainloop() # Interrompe a execução do script enquanto a janela principal estiver sendo exibida<file_sep># def contaDigitosPares(number):
# sum = 0
# for i in range(len(number)):
# if int(number[i])%2==0:
# sum+=1
# return sum
def contaDigitosPares(number):
sum = 0
i=0
while i<len(number):
if int(number[i])%2==0:
sum +=1
i += 1
contaDigitosPares(number[i:len(number)])
return sum
numero = input()
print(contaDigitosPares(numero))<file_sep>from random import shuffle
def sort(members):
file = open("resultado.txt", "w")
file.write("Tempo total da rodada: %d min\n" %(len(members)*10))
shuffle(members)
for i in range(1,len(members)):
file.write("\nDupla %d:\n Piloto: %s\n Co-piloto: %s\n" %(i,members[i-1],members[i]))
if (i==len(members)-1) :
file.write("\nDupla %d:\n Piloto: %s\n Co-piloto: %s\n" %(len(members),members[len(members)-1],members[0]))
file.close()<file_sep>from tkinter import *
from math import pow, sqrt, tan, atan
def ajuda():
ajuda = Tk()
ajuda.title('Ajuda')
texto = Label(ajuda,
text='Créditos:\n\n\n<NAME>\n\nSite: leonardotoledo.org\n\nE-mail: <EMAIL>\n\n\nReferências:\n\nABNT NBR 6118:2014\n\nABNT NBR 6122:2010\n\nABNT NBR 7480:2007\n\nNotas de aula de Fundações 2\nProfª. Drª <NAME>\n\n\nNão me responsabilizo pelo uso\ndeste programa por terceiros.\n')
texto.grid(row=0, column=0)
def calcBloco():
fck = float(number1.get())
P = float(number2.get())
TT = float(number3.get())
b = float(number4.get())
l = float(number5.get())
r = float(number6.get())
# fck = fck do concreto (MPa).
# P = Carga do pilar, após aplicados os coeficientes de majoracao (tf).
# TT = Valor da taxa do terreno (kgf/cm²).
# b = lado menor do pilar (cm).
# l = lado maior do pilar (cm).
# r = razao L/B
# A funcao retornara as dimensoes do bloco, em centimetros, na seguinte ordem: B, H.
P = 1000 * P # Convertendo para kgf
B = sqrt(1.05 * P / TT / r) # Calculando o valor da base do bloco.
# Arredondamento da base:
modulusB = int(B / 5)
B = 5 * (modulusB + 1)
L = r * B
if fck == 20:
fct = 0.4*1.55
elif fck == 25:
fct = 0.4*1.80
else:
fct = 0.8
Beta = 0.01
righthandside = ((TT / 10) / fct) + 1
lefthandside = tan(Beta)/Beta
i = 0
while lefthandside <= righthandside:
Beta = atan(Beta*righthandside)
lefthandside = tan(Beta) / Beta
i+=1
if i==100:
break
if (B - b) > (L - l):
H = tan(Beta) * (B - b) / 2 # Calculando a altura do bloco
z = 1.05 * P * (B - b) / 4 / H # Calculando a tracao transveral de Morsch
else:
H = tan(Beta) * (L - l) / 2 # Calculando a altura do bloco
z = 1.05 * P * (L - l) / 4 / H # Calculando a tracao transveral de Morsch
modulosH = int(H / 5)
H = 5 * (modulosH + 1)
result = Tk()
result.title('Resultado')
resultado = Label(result, text='RESULTADOS: ')
resultado.grid(row=0, column=0)
resultado_base = Label(result, text='Base: %.2f cm' % (B))
resultado_base.grid(row=1, column=0)
resultado_largura = Label(result, text='Largura: %.2f cm' % (L))
resultado_largura.grid(row=2, column=0)
resultado_altura = Label(result, text='Altura: %.2f cm' % (H))
resultado_altura.grid(row=3, column=0)
window = Tk()
rotulo1 = Label(window, text='fck do Concreto (MPa): ')
rotulo1.grid(row=0, column=0)
rotulo2 = Label(window, text='Carga do Pilar (tf): ')
rotulo2.grid(row=1, column=0)
rotulo3 = Label(window, text='Taxa do Terreno (kgf/cm²): ')
rotulo3.grid(row=2, column=0)
rotulo4 = Label(window, text='Lado do Pilar // a B (cm): ')
rotulo4.grid(row=3, column=0)
rotulo5 = Label(window, text='Lado do Pilar // a L (cm): ')
rotulo5.grid(row=4, column=0)
rotulo6 = Label(window, text='Razão L/B: ')
rotulo6.grid(row=5, column=0)
number1 = Entry(window)
number1.grid(row=0, column=1)
number2 = Entry(window)
number2.grid(row=1, column=1)
number3 = Entry(window)
number3.grid(row=2, column=1)
number4 = Entry(window)
number4.grid(row=3, column=1)
number5 = Entry(window)
number5.grid(row=4, column=1)
number6 = Entry(window)
number6.grid(row=5, column=1)
ajudaBotao = Button(window, text='Ajuda', command=ajuda).grid(row=6, column=0, sticky=W, pady=4)
contarBotao = Button(window, text='Calcular Bloco', command=calcBloco).grid(row=6, column=1, sticky=W, pady=4)
window.title('Bloco de Fundacao')
window.mainloop()
<file_sep>lista = list()
lista.append(0)
for i in range(5):
aux = int(input())
for j in range(len(lista)):
if aux <= lista[j]:
lista.insert(j,aux)
break
else:
if j==len(lista)-1:
lista.insert(j,aux)
lista.remove(lista[len(lista)-1])
print(lista)<file_sep>import sorteio
membros = [
'Biscoito',
'Leo',
'Pepe',
'Friboi',
'Victor',
'Yan'
]
sorteio(membros)<file_sep>from tkinter import *
from math import *
def ajuda():
ajuda = Tk()
ajuda.title('Ajuda')
texto = Label(ajuda, text='Créditos:\n\n\n<NAME>\n\nSite: leonardotoledo.org\n\nE-mail: <EMAIL>\n\n\nReferências:\n\nABNT NBR 6118:2014\n\nABNT NBR 6122:2010\n\nABNT NBR 7480:2007\n\nNotas de aula de Fundações 2\nProfª. Drª <NAME>\n\n\nNão me responsabilizo pelo uso\ndeste programa por terceiros.\n')
texto.grid(row=0, column=0)
def calcSapata():
c = float(number1.get())
fck = float(number2.get())
fyk = float(number3.get())
P = 1000*float(number4.get()) # Converting to kgf
TT = float(number5.get())
b = float(number6.get())
l = float(number7.get())
r = float(number8.get())
# c = cobrimento da armadura (cm).
# fck = fck do concreto (MPa).
# fyk = Resistencia ao escoamento do Aco (MPa).
# P = Carga do pilar, após aplicados os coeficientes de majoracao (kgf).
# TT = Valor da taxa do terreno (kgf/cm²).
# b = lado menor do pilar (cm).
# l = lado maior do pilar (cm).
# r = razão entre L e B (L/B).
B = sqrt(P / TT / r) # Calculando o valor do lado B da base da sapata.
modulusB = int(B / 5)
B = 5 * (modulusB + 1)
L = r * B # Calculando o valor do lado L da base da sapata.
fck = 10 * fck # Convertendo de MPa para kgf/cm²
fyk = 10 * fyk # Convertendo de MPa para kgf/cm²
# CALCULO DA ALTURA DA SAPATA
sigmac = 0.85 * fck / 1.96
h1 = (L - l) / 3
h2 = (B - b) / 3
h3 = 1.44 * sqrt(P / sigmac) + 5
comp = [h1, h2, h3]
comp.sort()
h = comp[2] # Determinacao da maior altura
# ARREDONDAMENTO DAS DIMENSOES PARA MULTIPLOS DE 5
modulosH = int(h / 5)
h = 5 * (modulosH + 1)
# CALCULO DAS ARMADURAS
dlinha = c
d = h - dlinha
Fx = P * (L - l) / (8 * d)
Fy = P * (B - b) / (8 * d)
fyd = fyk / 1.15
Asx = 1.4 * Fx / fyd
Asy = 1.4 * Fy / fyd
Barras = {'6.3': 0.312, '8.0': 0.503, '10.0': 0.785, '12.5': 1.227, '16.0': 2.011,
'20.0': 3.142} # Fonte: Pg.10 NBR 7480:2008
Areas = list(Barras.values())
Bitolas = list(Barras.keys())
# DETALHAMENTO DA ARMADURA EM X
sx = 0
i = 0 # Loop index
comprimentoX = L - 2 * c + 2 * 10
while (sx < 10 or sx > 25):
nx = int(Asx / Areas[i]) + 1 # Numero de barras
if nx>1:
sx = (B - 2 * c) / (nx - 1)
detalheX = '%d bitolas de %s c/ %.1f c. %.1f' % (nx, Bitolas[i], sx, comprimentoX)
i = i + 1
# DETALHAMENTO DA ARMADURA EM Y
sy = 0
i = 0 # Loop index
comprimentoY = B - 2 * c + 2 * 10
while (sy < 10 or sy > 25):
ny = int(Asy / Areas[i]) + 1 # Numero de barras
if ny > 1:
sy = (L - 2 * c) / (ny - 1)
detalheY = '%d bitolas de %s c/ %.1f c. %.1f' % (ny, Bitolas[i], sy, comprimentoY)
i = i + 1
result = Tk()
result.title('Resultado')
resultado = Label(result, text='RESULTADOS: ')
resultado.grid(row=0, column=0)
resultado_base = Label(result, text='Base: %.2f cm' % (B))
resultado_base.grid(row=1, column=0)
resultado_largura = Label(result, text='Largura: %.2f cm' % (L))
resultado_largura.grid(row=2, column=0)
resultado_altura = Label(result, text='Altura: %.2f cm' % (h))
resultado_altura.grid(row=3, column=0)
resultado_detalheX = Label(result, text=detalheX)
resultado_detalheX.grid(row=4, column=0)
resultado_detalheY = Label(result, text=detalheY)
resultado_detalheY.grid(row=5, column=0)
window = Tk()
rotulo1 = Label(window, text='Cobrimento da Armadura (cm): ')
rotulo1.grid(row=0, column=0)
rotulo2 = Label(window, text='fck do Concreto (MPa): ')
rotulo2.grid(row=1, column=0)
rotulo3 = Label(window, text='fyk do Aco (MPa): ')
rotulo3.grid(row=2, column=0)
rotulo4 = Label(window, text='Carga do Pilar (tf): ')
rotulo4.grid(row=3, column=0)
rotulo5 = Label(window, text='Taxa do Terreno (kgf/cm²): ')
rotulo5.grid(row=4, column=0)
rotulo6 = Label(window, text='Lado do Pilar // a B (cm): ')
rotulo6.grid(row=5, column=0)
rotulo7 = Label(window, text='Lado do Pilar // a L (cm): ')
rotulo7.grid(row=6, column=0)
rotulo8 = Label(window, text='Razão L/B: ')
rotulo8.grid(row=7, column=0)
number1 = Entry(window)
number1.grid(row=0, column=1)
number2 = Entry(window)
number2.grid(row=1, column=1)
number3 = Entry(window)
number3.grid(row=2, column=1)
number4 = Entry(window)
number4.grid(row=3, column=1)
number5 = Entry(window)
number5.grid(row=4, column=1)
number6 = Entry(window)
number6.grid(row=5, column=1)
number7 = Entry(window)
number7.grid(row=6, column=1)
number8 = Entry(window)
number8.grid(row=7, column=1)
ajudaBotao = Button(window, text='Ajuda', command=ajuda).grid(row=8, column=0, sticky=W, pady=4)
contarBotao = Button(window, text='Calcular Sapata', command=calcSapata).grid(row=8, column=1, sticky=W, pady=4)
window.title('Sapata de Fundacao')
window.mainloop()
<file_sep>from tkinter import *
from tkinter import filedialog
from random import shuffle
from datetime import datetime
def saveAs():
fileToSave = filedialog.asksaveasfilename(defaultextension=".txt", filetypes = (("Arquivo de Texto", "*.txt"),("Todos os Arquivos","*.*")), title = "Salvar como...")
with open(fileToSave, 'w') as outputFile:
outputFile.write('\n'.join(contents))
def sort():
members = [member.get() for member in membro]
resultado = Tk()
resultado.title('Resultado')
currentTime = datetime.now()
global contents
contents = list()
contents.append("%s \n\nTempo total da rodada:\n %d min\n" %(currentTime.strftime("%d/%m/%Y %H:%M:%S"), len(members)*10))
shuffle(members)
for i in range(1,len(members)):
contents.append("\nDupla %d:\n Piloto: %s\n Co-piloto: %s\n" %(i,members[i-1],members[i]))
if (i==len(members)-1) :
contents.append("\nDupla %d:\n Piloto: %s\n Co-piloto: %s\n" %(len(members),members[len(members)-1],members[0]))
rotulo = Label(resultado, text='\n'.join(contents))
rotulo.grid(row=0, column=0)
salvarBotao = Button(resultado, text='Salvar resultado', command=saveAs)
salvarBotao.grid(row=len(members)+1, column=0, sticky=W, pady=4)
def contar():
# Instancia a janela:
sorteio = Tk()
sorteio.title('Sorteio CD Py')
n = int(number.get())
# Instancia os rotulos usando a classe Label e os coloca na janela usando o gerenciador de layout 'grid'
rotulos=[]
for i in range(n):
rotulos.append(Label(sorteio, text='Membro '+str(i+1)+': ').grid(row=i, column=0))
# Usa a classe Entry para criar as caixas de texto e em seguida as coloca na janela com o gerenciador de layout 'grid'
global membro
membro = list()
for i in range(n):
membro.append(Entry(sorteio))
membro[i].grid(row=i, column=1)
sairBotao = Button(sorteio, text='Sair', command=sorteio.quit).grid(row=len(rotulos), column=0, sticky=W, pady=4)
sortearBotao = Button(sorteio, text='Fazer sorteio', command=sort).grid(row=len(rotulos), column=1, sticky=W, pady=4)
start = Tk()
rotulo = Label(start, text='Numero de integrantes: ')
rotulo.grid(row=0, column=0)
number = Entry(start)
number.grid(row=0, column=1)
sairBotao = Button(start, text='Sair', command=start.quit).grid(row=1, column=0, sticky=W, pady=4)
contarBotao = Button(start, text='Prosseguir', command = contar).grid(row=1, column=1, sticky=W, pady=4)
start.title('Sorteio CD Py')
start.mainloop()<file_sep>from tkinter import *
from random import shuffle
class InputView(Frame):
def sort(self, members):
file = open("resultado.txt", "w")
file.write("Tempo total da rodada: %d min\n" % (len(members) * 10))
shuffle(members)
for i in range(1, len(members)):
file.write("\nDupla %d:\n Piloto: %s\n Co-piloto: %s\n" % (i, members[i - 1], members[i]))
if (i == len(members) - 1):
file.write("\nDupla %d:\n Piloto: %s\n Co-piloto: %s\n" % (
len(members), members[len(members) - 1], members[0]))
file.close()
def sortear(self):
membros = []
for i in range(len(self.members)):
membros.append(self.members[i].get())
self.sort(membros)
def __init__(self, master=None):
Frame.__init__(self, master)
self.grid()
self.members = list()
for i in range(5):
self.memberLabel = Label(self, text="Membro " + str(i + 1) + ": ")
self.memberLabel.grid(row=i, column=0)
self.members.append(Entry(self))
self.members[i].grid(row=i, column=1)
self.people = [person.get() for person in self.members]
self.quitButton = Button(self, text='Sair', command=self.quit)
self.quitButton.grid(row=len(self.members)+1, column=0, sticky=W, pady=4)
self.sortButton = Button(self, text='Fazer sorteio', command=self.sortear)
self.sortButton.grid(row=len(self.members)+1, column=1, sticky=W, pady=4)
app = InputView()
app.master.title("Roleta Russa do CD Py")
app.mainloop() | 0ceb5c495b30abfca1b249b2e32323f77eca9052 | [
"Python"
] | 9 | Python | leonardotoledo/PythonSketches | 2abab5a0868699c7c28f27cc163447a370b0e82f | 8465fe711201cceb7bcc1b07e5ef7dfbefa50961 |
refs/heads/master | <repo_name>Justin-T-Wood/breakout-game<file_sep>/scripts/gameplay.js
MyGame.screens['game-play'] = (function(game, graphics, input) {
'use strict';
var particleRenders = [];
var bricks = [];
var lives = [];
var highScores = [];
var canvas = document.getElementById("canvas-main");
var ctx = canvas.getContext("2d");
var myKeyboard = input.Keyboard(),
hits = 0,
countdown = 3000,
brickWidth = 50,
paddleWidth = 150,
brickHeight = 15,
extraLives = 2,
loss = false,
lostGame = false,
paddle = null,
yellowBrick = null,
yellowBrick2 = null,
orangeBrick = null,
orangeBrick2 = null,
blueBrick = null,
blueBrick2 = null,
greenBrick = null,
greenBrick2 = null,
ball = null,
brick = null,
one = null,
two = null,
three = null,
life = null,
cancelNextRequest = false,
ps1 = null,
ps2 = null,
lastTimeStamp,
score = 0;
function newGame() {
paddle = graphics.Texture( {
image : 'images/grey.jpg',
center : { x : 400, y : 520 },
width : paddleWidth, height : brickHeight,
moveRate : 800, // pixels per second
});
ball = graphics.Texture( {
image : 'images/ball.png',
center : { x : 400, y : 505 },
width : brickHeight, height : brickHeight,
angle: - Math.PI/4 ,
moveRate : 300, // pixels per second
});
myKeyboard.registerCommand(KeyEvent.DOM_VK_LEFT, paddle.moveLeft);
myKeyboard.registerCommand(KeyEvent.DOM_VK_RIGHT, paddle.moveRight);
myKeyboard.registerCommand(KeyEvent.DOM_VK_ESCAPE, function() {
cancelNextRequest = true;
game.showScreen('main-menu');
});
score = 0;
lostGame = false;
bricks = []
lives = []
for(var i = 0; i < extraLives; i++){
life = graphics.Texture({
image : 'images/heart.png',
center : { x : 50 * i + 50 , y : 560 },
width : 20, height : 20,
})
lives.push(life);
}
for(var i = 0; i < 16; i++){
greenBrick = graphics.Texture( {
image : 'images/green.jpg',
center : { x : i * brickWidth + 25, y : 240},
width : brickWidth - 5, height : brickHeight,
points: 1,
color: "green"
})
greenBrick2 = graphics.Texture( {
image : 'images/green.jpg',
center : { x : i * brickWidth + 25, y : 220 },
width : brickWidth - 5, height : brickHeight,
points: 1,
color: "green2"
})
blueBrick = graphics.Texture( {
image : 'images/blue.jpg',
center : { x : i * brickWidth + 25, y : 200 },
width : brickWidth - 5, height : brickHeight,
points: 2,
color: "blue"
})
blueBrick2 = graphics.Texture( {
image : 'images/blue.jpg',
center : { x : i * brickWidth + 25, y : 180 },
width : brickWidth - 5, height : brickHeight,
points: 2,
color: "blue2"
})
orangeBrick = graphics.Texture( {
image : 'images/orange.jpg',
center : { x : i * brickWidth + 25, y : 160 },
width : brickWidth - 5, height : brickHeight,
points: 3,
color: "orange"
})
orangeBrick2 = graphics.Texture( {
image : 'images/orange.jpg',
center : { x : i * brickWidth + 25, y : 140 },
width : brickWidth - 5, height : brickHeight,
points: 3,
color: "orange2"
})
yellowBrick = graphics.Texture( {
image : 'images/yellow.jpg',
center : { x : i * brickWidth + 25, y : 120 },
width : brickWidth - 5, height : brickHeight,
points: 5,
color: "yellow"
})
yellowBrick2 = graphics.Texture( {
image : 'images/yellow.jpg',
center : { x : i * brickWidth + 25, y : 100 },
width : brickWidth - 5, height : brickHeight,
points: 5,
color: "yellow2"
})
bricks.push(yellowBrick)
bricks.push(yellowBrick2)
bricks.push(orangeBrick)
bricks.push(orangeBrick2)
bricks.push(blueBrick)
bricks.push(blueBrick2)
bricks.push(greenBrick)
bricks.push(greenBrick2)
}
}
function initialize() {
console.log('game initializing...');
score = 0;
paddle = graphics.Texture( {
image : 'images/grey.jpg',
center : { x : 400, y : 520 },
width : paddleWidth, height : brickHeight,
moveRate : 800, // pixels per second
});
ball = graphics.Texture( {
image : 'images/ball.png',
center : { x : 400, y : 500 },
width : brickHeight, height : brickHeight,
angle: - Math.PI/4 ,
moveRate : 300, // pixels per second
});
one = graphics.Texture({
image : 'images/one.png',
center : { x : 400, y : 300 },
width : 200, height : 200,
})
two = graphics.Texture({
image : 'images/two.png',
center : { x : 400, y : 300 },
width : 200, height : 200,
})
three = graphics.Texture({
image : 'images/three.png',
center : { x : 400, y : 300 },
width : 200, height : 200,
})
for(var i = 0; i < extraLives; i++){
life = graphics.Texture({
image : 'images/heart.png',
center : { x : 50 * i + 50 , y : 560 },
width : 20, height : 20,
})
lives.push(life);
}
for(var i = 0; i < 16; i++){
greenBrick = graphics.Texture( {
image : 'images/green.jpg',
center : { x : i * brickWidth + 25, y : 240},
width : brickWidth - 5, height : brickHeight,
points: 1
})
greenBrick2 = graphics.Texture( {
image : 'images/green.jpg',
center : { x : i * brickWidth + 25, y : 220 },
width : brickWidth - 5, height : brickHeight,
points: 1
})
blueBrick = graphics.Texture( {
image : 'images/blue.jpg',
center : { x : i * brickWidth + 25, y : 200 },
width : brickWidth - 5, height : brickHeight,
points: 2
})
blueBrick2 = graphics.Texture( {
image : 'images/blue.jpg',
center : { x : i * brickWidth + 25, y : 180 },
width : brickWidth - 5, height : brickHeight,
points: 2
})
orangeBrick = graphics.Texture( {
image : 'images/orange.jpg',
center : { x : i * brickWidth + 25, y : 160 },
width : brickWidth - 5, height : brickHeight,
points: 3
})
orangeBrick2 = graphics.Texture( {
image : 'images/orange.jpg',
center : { x : i * brickWidth + 25, y : 140 },
width : brickWidth - 5, height : brickHeight,
points: 3
})
yellowBrick = graphics.Texture( {
image : 'images/yellow.jpg',
center : { x : i * brickWidth + 25, y : 120 },
width : brickWidth - 5, height : brickHeight,
points: 5
})
yellowBrick2 = graphics.Texture( {
image : 'images/yellow.jpg',
center : { x : i * brickWidth + 25, y : 100 },
width : brickWidth - 5, height : brickHeight,
points: 5,
color: "yellow2"
})
bricks.push(yellowBrick)
bricks.push(yellowBrick2)
bricks.push(orangeBrick)
bricks.push(orangeBrick2)
bricks.push(blueBrick)
bricks.push(blueBrick2)
bricks.push(greenBrick)
bricks.push(greenBrick2)
}
//
// Create the keyboard input handler and register the keyboard commands
if(paddle.getX()-paddleWidth/2 > 0){
myKeyboard.registerCommand(KeyEvent.DOM_VK_LEFT, paddle.moveLeft);
}
myKeyboard.registerCommand(KeyEvent.DOM_VK_RIGHT, paddle.moveRight);
myKeyboard.registerCommand(KeyEvent.DOM_VK_ESCAPE, function() {
//
// Stop the game loop by canceling the request for the next animation frame
cancelNextRequest = true;
//
// Then, return to the main menu
game.showScreen('main-menu');
});
}
function collisionCheck(){
for(var i = 0; i < bricks.length; i++){
// hits left of brick
if( ball.getX() + brickHeight/2 >= bricks[i].getX() - brickWidth/2 &
ball.getX() + brickHeight/2 <= bricks[i].getX() + brickWidth/2 &
ball.getY() >= bricks[i].getY() - brickHeight/2 &
ball.getY() <= bricks[i].getY() + brickHeight/2 )
{
var index = bricks.indexOf(bricks[i]);
score += bricks[i].getScore()
if(bricks[i].getColor() == 'yellow2'){
paddle.updateWidth();
}
ps1 = ParticleSystem({
position: { x: bricks[i].getX(), y: bricks[i].getY()},
speed: { mean: 0.07, stdev: 0.025},
lifetime: { mean: 500, stdev: 50 },
size: { mean: 3, stdev: 1 },
fill: 'rgba(0, 0, 255, 0.5)',
image: 'images/fire.png',
life: 500
}, MyGame.graphics);
ps2 = ParticleSystem({
position: { x: bricks[i].getX(), y: bricks[i].getY()},
speed: { mean: 0.02, stdev: 0.0125},
lifetime: { mean: 500, stdev: 50 },
size: { mean: 3, stdev: 1 },
fill: 'rgba(255, 0, 0, 0.5)',
image: 'images/smoke.png',
life: 500
}, MyGame.graphics);
particleRenders.push(ps1);
particleRenders.push(ps2);
bricks.splice(index, 1)
ball.updateAngle(ball.getAngle() * -1 + Math.PI);
hits += 1;
}
//hits right of brick
else if( ball.getX() - brickHeight/2 <= bricks[i].getX() + brickWidth/2 &
ball.getX() - brickHeight/2 >= bricks[i].getX() - brickWidth/2 &
ball.getY() >= bricks[i].getY() - brickHeight/2 &
ball.getY() <= bricks[i].getY() + brickHeight/2 )
{
var index = bricks.indexOf(bricks[i]);
score += bricks[i].getScore()
if(bricks[i].getColor() == 'yellow2'){
paddle.updateWidth();
}
ps1 = ParticleSystem({
position: { x: bricks[i].getX(), y: bricks[i].getY()},
speed: { mean: 0.07, stdev: 0.025},
lifetime: { mean: 500, stdev: 50 },
size: { mean: 3, stdev: 1 },
fill: 'rgba(0, 0, 255, 0.5)',
image: 'images/fire.png',
life: 500
}, MyGame.graphics);
ps2 = ParticleSystem({
position: { x: bricks[i].getX(), y: bricks[i].getY()},
speed: { mean: 0.02, stdev: 0.0125},
lifetime: { mean: 500, stdev: 50 },
size: { mean: 3, stdev: 1 },
fill: 'rgba(255, 0, 0, 0.5)',
image: 'images/smoke.png',
life: 500
}, MyGame.graphics);
particleRenders.push(ps1);
particleRenders.push(ps2);
bricks.splice(index, 1)
ball.updateAngle(ball.getAngle() * -1 - Math.PI);
hits += 1;
}
//hits bottom of brick
else if( ball.getX() >= bricks[i].getX() - brickWidth/2 &
ball.getX() <= bricks[i].getX() + brickWidth/2 &
ball.getY() - brickHeight/2 >= bricks[i].getY() - brickHeight/2 &
ball.getY() - brickHeight/2 <= bricks[i].getY() + brickHeight/2 )
{
var index = bricks.indexOf(bricks[i]);
score += bricks[i].getScore()
if(bricks[i].getColor() == 'yellow2'){
paddle.updateWidth();
}
ps1 = ParticleSystem({
position: { x: bricks[i].getX(), y: bricks[i].getY()},
speed: { mean: 0.07, stdev: 0.025},
lifetime: { mean: 500, stdev: 50 },
size: { mean: 3, stdev: 1 },
fill: 'rgba(0, 0, 255, 0.5)',
image: 'images/fire.png',
life: 500
}, MyGame.graphics);
ps2 = ParticleSystem({
position: { x: bricks[i].getX(), y: bricks[i].getY()},
speed: { mean: 0.02, stdev: 0.0125},
lifetime: { mean: 500, stdev: 50 },
size: { mean: 3, stdev: 1 },
fill: 'rgba(255, 0, 0, 0.5)',
image: 'images/smoke.png',
life: 500
}, MyGame.graphics);
particleRenders.push(ps1);
particleRenders.push(ps2);
bricks.splice(index, 1)
ball.updateAngle(-1 * ball.getAngle())
hits += 1;
}
//hits top of brick
else if( ball.getX() >= bricks[i].getX() - brickWidth/2 &
ball.getX() <= bricks[i].getX() + brickWidth/2 &
ball.getY() + brickHeight/2 >= bricks[i].getY() - brickHeight/2 &
ball.getY() + brickHeight/2 <= bricks[i].getY() + brickHeight/2 )
{
var index = bricks.indexOf(bricks[i]);
score += bricks[i].getScore()
if(bricks[i].getColor() == 'yellow2'){
paddle.updateWidth();
}
ps1 = ParticleSystem({
position: { x: bricks[i].getX(), y: bricks[i].getY()},
speed: { mean: 0.07, stdev: 0.025},
lifetime: { mean: 500, stdev: 50 },
size: { mean: 3, stdev: 1 },
fill: 'rgba(0, 0, 255, 0.5)',
image: 'images/fire.png',
life: 500
}, MyGame.graphics);
ps2 = ParticleSystem({
position: { x: bricks[i].getX(), y: bricks[i].getY()},
speed: { mean: 0.02, stdev: 0.0125},
lifetime: { mean: 500, stdev: 50 },
size: { mean: 3, stdev: 1 },
fill: 'rgba(255, 0, 0, 0.5)',
image: 'images/smoke.png',
life: 500
}, MyGame.graphics);
particleRenders.push(ps1);
particleRenders.push(ps2);
bricks.splice(index, 1)
ball.updateAngle(-1 * ball.getAngle())
hits += 1;
}
}
//hits paddle
if( ball.getX() >= paddle.getX() - paddleWidth/2 &
ball.getX() <= paddle.getX() + paddleWidth/2 &
ball.getY() + brickHeight/2 >= paddle.getY() - brickHeight/2 &
ball.getY() + brickHeight/2 <= paddle.getY() + brickHeight/2 )
{
ball.updateAngle(((ball.getX()-paddle.getX()) / (paddleWidth/2)) - Math.PI/2)
}
// hits right wall
else if(ball.getX() + brickHeight/2 >= 795){
ball.updateAngle(ball.getAngle() * -1 + Math.PI);
}
// hits left wall
else if(ball.getX() - brickHeight/2 <= 5){
ball.updateAngle(ball.getAngle() * -1 - Math.PI);
}
//hits ceiling
else if(ball.getY() - brickHeight/2 <= 5){
ball.updateAngle(-1 * ball.getAngle());
}
//hits floor
else if(ball.getY() + brickHeight/2 >= 600){
loss = true;
extraLives -= 1;
if(extraLives >= 0){
lives.pop()
// paddle.center = {x: 400, y: 520};
// ball.center = { x : 400, y : 505 };
paddle = graphics.Texture( {
image : 'images/grey.jpg',
center : { x : 400, y : 520 },
width : paddleWidth, height : brickHeight,
moveRate : 800, // pixels per second
});
ball = graphics.Texture( {
image : 'images/ball.png',
center : { x : 400, y : 505 },
width : brickHeight, height : brickHeight,
angle: - Math.PI/4 ,
moveRate : 300, // pixels per second
});
hits = 0;
myKeyboard.registerCommand(KeyEvent.DOM_VK_LEFT, paddle.moveLeft);
myKeyboard.registerCommand(KeyEvent.DOM_VK_RIGHT, paddle.moveRight);
myKeyboard.registerCommand(KeyEvent.DOM_VK_ESCAPE, function() {
cancelNextRequest = true;
game.showScreen('main-menu');
});
}
else{
lostGame = true;
}
}
}
function update(elapsedTime) {
for(var i = 0; i < particleRenders.length; i++){
particleRenders[i].update(elapsedTime);
particleRenders[i].setLife(elapsedTime)
if(particleRenders[i].getLife() < 0){
var index = particleRenders.indexOf(particleRenders[i]);
particleRenders.splice(index, 1)
}
}
myKeyboard.update(elapsedTime);
if(countdown - elapsedTime > -1000){
countdown -= elapsedTime;
}
if(countdown < 0){
collisionCheck();
ball.moveAngle(elapsedTime);
if (loss == true){
countdown = 3000;
loss = false;
}
if (hits < 4 & hits >= 0){
ball.updateSpeed(400)
}
else if (hits < 12 & hits >= 4){
ball.updateSpeed(500)
}
else if (hits < 36 & hits >= 12){
ball.updateSpeed(600)
}
else if (hits >= 36){
ball.updateSpeed(700)
}
}
}
function render(elapsedTime) {
graphics.clear();
if(countdown < 4000 & countdown > 2000){
three.draw();
}
else if(countdown < 2000 & countdown > 1000){
two.draw();
}
else if(countdown < 1000 & countdown > 0){
one.draw();
}
else{
paddle.draw();
ball.draw();
for(var i = 0; i < bricks.length; i++){
bricks[i].draw()
}
for(var i = 0; i < lives.length; i++){
lives[i].draw()
}
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Score: " + score, canvas.width-100, canvas.height-50);
for(var i = 0; i < particleRenders.length; i++){
particleRenders[i].render();
}
}
}
//------------------------------------------------------------------
//
// This is the Game Loop function!
//
//------------------------------------------------------------------
function gameLoop(time) {
if(lostGame == true){
highScores.push(score)
var scores = document.getElementById("scores")
var myScore = document.createElement("li");
myScore.appendChild(document.createTextNode(score));
scores.appendChild(myScore)
game.showScreen('high-scores')
alert("You lost! Your Score was: " + score + '. Click to play again!');
game.showScreen('game-play')
newGame();
}
if(bricks.length == 0){
highScores.push(score)
var scores = document.getElementById("scores")
var myScore = document.createElement("li");
myScore.appendChild(document.createTextNode(score));
scores.appendChild(myScore)
game.showScreen('high-scores')
alert("You Won! Your Score was: " + score + '. Click to play again!');
game.showScreen('game-play')
newGame();
}
update(time - lastTimeStamp);
lastTimeStamp = time;
render(time);
if (!cancelNextRequest) {
requestAnimationFrame(gameLoop);
}
}
function run() {
lastTimeStamp = performance.now();
//
// Start the animation loop
cancelNextRequest = false;
requestAnimationFrame(gameLoop);
}
return {
initialize : initialize,
run : run
};
}(MyGame.game, MyGame.graphics, MyGame.input));
| 7b0aee7585325a35fa7ab6f2540b8ace4f544a11 | [
"JavaScript"
] | 1 | JavaScript | Justin-T-Wood/breakout-game | 928d32720180da370f100ca7cd0ac966b13ce980 | 249c52fdcfba91130236cbbd71cb403d479b8996 |
refs/heads/master | <repo_name>zaubara/ng2-completer<file_sep>/demo/app-cmp.ts
"use strict";
import { Component } from "@angular/core";
@Component({
// tslint:disable-next-line: component-selector
selector: "demo-app",
templateUrl: "./app-cmp.html"
})
export class AppComponent {
public isCollapsed = false;
}
| d5c2c45d5b9f64c56680c66bf72728343ae26335 | [
"TypeScript"
] | 1 | TypeScript | zaubara/ng2-completer | 2183fa85e8aa374420642c95ea76d5da28b3c7d7 | 45c0fab14ff890905a40e1632df7d065a055db84 |
refs/heads/master | <file_sep>/*******************************************************************************
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
package org.openscore.content.rft.entities;
import com.hp.oo.sdk.content.plugin.GlobalSessionObject;
import java.util.Map;
/**
* Date: 4/10/2015
*
* @author lesant
*/
public class RemoteSecureCopyInputs {
private String sourceHost;
private String sourcePath;
private String sourcePort;
private String sourceUsername;
private String sourcePassword;
private String sourcePrivateKeyFile;
private String destinationHost;
private String destinationPath;
private String destinatinPort;
private String destinationUsername;
private String destinationPassword;
private String destinationPrivateKeyFile;
public String getDestinationUsername() {
return destinationUsername;
}
public void setDestinationUsername(String destinationUsername) {
this.destinationUsername = destinationUsername;
}
public String getDestinationPrivateKeyFile() {
return destinationPrivateKeyFile;
}
public void setDestinationPrivateKeyFile(String destinationPrivateKeyFile) {
this.destinationPrivateKeyFile = destinationPrivateKeyFile;
}
public String getSourceHost() {
return sourceHost;
}
public void setSourceHost(String sourceHost) {
this.sourceHost = sourceHost;
}
public String getSourcePath() {
return sourcePath;
}
public void setSourcePath(String sourcePath) {
this.sourcePath = sourcePath;
}
public String getSourcePort() {
return sourcePort;
}
public void setSourcePort(String sourcePort) {
this.sourcePort = sourcePort;
}
public String getSourceUsername() {
return sourceUsername;
}
public void setSourceUsername(String sourceUsername) {
this.sourceUsername = sourceUsername;
}
public String getSourcePassword() {
return sourcePassword;
}
public void setSourcePassword(String sourcePassword) {
this.sourcePassword = sourcePassword;
}
public String getSourcePrivateKeyFile() {
return sourcePrivateKeyFile;
}
public void setSourcePrivateKeyFile(String sourcePrivateKeyFile) {
this.sourcePrivateKeyFile = sourcePrivateKeyFile;
}
public String getDestinationHost() {
return destinationHost;
}
public void setDestinationHost(String destinationHost) {
this.destinationHost = destinationHost;
}
public String getDestinationPath() {
return destinationPath;
}
public void setDestinationPath(String destinationPath) {
this.destinationPath = destinationPath;
}
public String getDestinatinPort() {
return destinatinPort;
}
public void setDestinatinPort(String destinatinPort) {
this.destinatinPort = destinatinPort;
}
public String getDestinationPassword() {
return destinationPassword;
}
public void setDestinationPassword(String destinationPassword) {
this.destinationPassword = <PASSWORD>;
}
}
<file_sep>/*******************************************************************************
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
package org.openscore.content.rft.services.impl;
import org.openscore.content.rft.services.SCPService;
/**
* Date: 4/10/2015
*
* @author lesant
*/
public class SCPServiceImpl implements SCPService {
}
| a195263c2a77badf93a92059696245ada8370836 | [
"Java"
] | 2 | Java | tudorlesan/score-actions | c80a13759d5ee4e3629289d38326f611b949f46d | d99a3f94d9817c1adc84fa71417ab3fd6330725f |
refs/heads/master | <file_sep>import LinkedList from '../Remove_Duplicates';
describe('testing remove duplicates functionality of linked list', () => {
test('removing duplicates from an empty linked list returns null', () => {
let LL = new LinkedList();
expect(LL.removeDuplicates()).toBe(null);
});
test('removing duplicates from an linked list with 1 node returns the head node', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
let newLinkedList = LL.removeDuplicates();
expect(newLinkedList.value).toBe('firstValue');
});
test('removing duplicates from an linked list with 2 nodes and no duplicates should return the original linked list', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
let newLinkedList = LL.removeDuplicates();
expect(newLinkedList.value).toBe('firstValue');
expect(newLinkedList.next.value).toBe('secondValue');
expect(newLinkedList.next.next).toBeNull();
});
test('removing duplicates from an linked list with 2 nodes and 1 duplicate should return the head node', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('firstValue');
let newLinkedList = LL.removeDuplicates();
expect(newLinkedList.value).toBe('firstValue');
expect(newLinkedList.next).toBeNull();
});
test('removing duplicates from an linked list with 5 nodes and 2 duplicate should return the 3 nodes', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.insertTail('secondValue');
LL.insertTail('thirdValue');
let newLinkedList = LL.removeDuplicates();
expect(newLinkedList.value).toBe('firstValue');
expect(newLinkedList.next.value).toBe('secondValue');
expect(newLinkedList.next.next.value).toBe('thirdValue');
expect(newLinkedList.next.next.next).toBeNull();
});
test('removing duplicates from an linked list with 5 nodes and 3 duplicate should return the 3 nodes', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.insertTail('thirdValue');
LL.insertTail('thirdValue');
LL.insertTail('thirdValue');
let newLinkedList = LL.removeDuplicates();
expect(newLinkedList.value).toBe('firstValue');
expect(newLinkedList.next.value).toBe('secondValue');
expect(newLinkedList.next.next.value).toBe('thirdValue');
expect(newLinkedList.next.next.next).toBeNull();
});
});
<file_sep>import LinkedList from '../Insert_Head';
describe('testing insert head functionality of linked list', () => {
test('initalization of linked list should result in head and tail being null', () => {
let LL = new LinkedList();
expect(LL.head && LL.tail).toBe(null);
});
test('insertHead of empty linked list', () => {
let LL = new LinkedList();
LL.insertHead('firstValue');
expect(LL.head.value).toBe('firstValue');
expect(LL.tail.value).toBe('firstValue');
expect(LL.head.next && LL.tail.next).toBe(null);
expect(LL.head.value || LL.tail.value).not.toBe(null);
});
test('insertHead of linked list with 1 node in list', () => {
let LL = new LinkedList();
LL.insertHead('firstValue');
LL.insertHead('secondValue');
expect(LL.head.value).toBe('secondValue');
expect(LL.tail.value).toBe('firstValue');
expect(LL.head.next.value).toBe('firstValue');
expect(LL.tail.next).toBe(null);
});
test('insertHead of linked list with multiple nodes in list', () => {
let LL = new LinkedList();
LL.insertHead('firstValue');
LL.insertHead('secondValue');
LL.insertHead('thirdValue');
expect(LL.head.value).toBe('thirdValue');
expect(LL.head.next.value).toBe('secondValue');
expect(LL.tail.value).toBe('firstValue');
expect(LL.tail.next).toBe(null);
});
});
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertTail(value) {
let newValue = new Node(value);
if (this.head === null) {
this.head = newValue;
this.tail = newValue;
} else {
this.tail.next = newValue;
this.tail = newValue;
}
}
reverseLinkedList() {
// If the linked list is empty
// Throw an error
if (this.head === null) {
throw new Error('linked list is empty');
}
// We need to track 2 variables: current and previous
// Current will track the current node
// Previous will track the node prior to current
let current = this.head;
let previous = null;
// Iterate over the linked list until current is equal to null
while (current !== null) {
// We need to change what the current value is pointing to
// It is currently pointing to the next node in the linked list
// We need current to point to the node before it
// We create a variable temp to store the old next node while we reassign it
let temp = current.next;
// Set the current's next node to equal the previous node
// Set previous to equal the current node
// Set current to equal the next node in the linked list (temp)
current.next = previous;
previous = current;
current = temp;
}
// Return the new head node
return previous;
}
}
export default LinkedList;
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertHead(value) {
let newValue = new Node(value);
if (this.head === null) {
this.head = newValue;
this.tail = newValue;
} else {
let temp = this.head;
this.head = newValue;
this.head.next = temp;
}
}
// Find Value takes 1 parameter, the value you are looking for
// Find value will search the linked list and return a boolean
// True if the value exists in the linked list
// False if the value does not exist in the linked list
findValue(value) {
// If the linked list is empty
// return false
if (this.head === null) {
return false;
}
// We need to iterate over the linked list
// Create a variable current and set it to the head node
// We will start checking the values here and continue until we hit the end
let current = this.head;
while (current !== null) {
// If the current value equals the value we are looking for
// Return true
if (current.value === value) {
return true;
}
// Else
// Keep iterating over the linked list
current = current.next;
}
// We did not find the value we were looking for
// Return false
return false;
}
}
export default LinkedList;
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertHead(value) {
let newNode = new Node(value);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
let temp = this.head;
this.head = newNode;
this.head.next = temp;
}
}
// Remove Kth Index From End takes 1 parameter -> Index
// This will remove the position x values away from the tail node
removeKthIndexFromEnd(index) {
// If the linked list is empty
// Throw an error
if (this.head === null) {
throw new Error('linked list is empty');
}
// We need to track 3 values: finder, current and current index
// Finder is going to seek out the value in the linked list that is x spots away from the head node
// Current index is going to keep track of how many nodes we have moved until we get to that spot
let finder = this.head;
let current = this.head;
let currentIndex = 1;
// Iterate over the linked list until we are x nodes away
while (currentIndex <= index) {
// If the value of finder is null that means the index we are looking for
// Is greater than the amount of nodes in the linked list
// Throw an error
if (finder === null) {
throw new Error('Index is out of range');
}
// If finder is not null
// Continue iterating over the linked list
// Increment the current index
// Set finder to equal the next node in the linked list
currentIndex++;
finder = finder.next;
}
// We need a specific case for when the node we are removing is the head node
// In this instance finder will equal null
// If finder is equal to null we need to set the head node to equal the node after it
// Set the head node to equal the next node in the linked list
// This will set the head node to either equal the next node or null
if (finder === null) {
this.head = this.head.next;
return;
}
// We now have everything in place but we need to find out which value to remove
// Iterate over the linked list until we get to the last node
while (finder.next !== null) {
// Set finder to equal the next node in the linked list
// Set current to equal the next node in the linked list
finder = finder.next;
current = current.next;
}
// At this point current is equal to the node before the one we need to remove
// Set the current's next value to equal 2 nodes ahead in the linked list
// This will remove the node directly after it
current.next = current.next.next;
}
}
export default LinkedList;
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
// Create function for inserting a value to the head of the linked list
// Accepts 1 parameter => value
insertHead(value) {
// Create the new node value and assign it to a variable
// To create our node we must use our Node class
// Our Node class accepts 1 value => value
// Initialize our newNode by using => new
let newNode = new Node(value);
// Determine if the linked list is empty
// If TRUE
if (this.head === null) {
// Set head to new node
this.head = newNode;
// Set tail to new node
this.tail = newNode;
// If FALSE
} else {
// Store the current head as a temp variable
let temp = this.head;
// Reassign the head node to equal => newNode
this.head = newNode;
// Set the new head's next value => old head (temp)
this.head.next = temp;
}
}
}
export default LinkedList;
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertHead(value) {
let new_node = new Node(value);
if (this.head === null) {
this.head = new_node;
this.tail = new_node;
} else {
let temp = this.head;
this.head = new_node;
this.head.next = temp;
}
}
// Function accepts 2 parameters => Value and Index
// The value represents the value we pass into the node
// The index represents the position in the linked list we will insert the node at
insertAtKthIndex(value, index) {
// Create the new node value and assign it to a variable
// To create our node we must use our Node class
// Our Node class accepts 1 value => value
// Initialize our newNode by using => new
let new_node = new Node(value);
// Determine if the linked list is empty
// If TRUE
if (this.head === null) {
// Now that we know the linked list is empty we have to handle 1 edge case
// is the index valid?
// A valid index for an empty linked list is 0
if (index !== 0) {
// The index is not 0
// This means the index is out of range
// Throw an error
throw new Error('Index out of range');
} else {
// The linked list is empty and the index is 0
// This is an insert head function
// Set the head and tail node to the new node
// Return
this.head = new_node;
this.tail = new_node;
return;
}
}
// The next case we need to handle is the ability to insert at index of 0 when the linked list is not empty
// If the head is not null and index === 0
if (this.head !== null && index === 0) {
// Store the current head as a temp variable
let temp = this.head;
// Reassign the head node to equal => newNode
this.head = new_node;
// Set the new head's next value => old head (temp)
this.head.next = temp;
return;
}
// We need to traverse the linked list until we get to the index we are looking for
// Track the current index, current node and previous node
let currentIndex = 0;
let current = this.head;
let previous = null;
// While the current index is less than the index we are looking for
while (currentIndex < index) {
// If the current node is null we are looking for an index that does not exist inside of our linked list
// Throw an error
if (current === null) {
throw new Error('Index is out of range');
} else {
// Else
// Set previous to equal the current node
// Set current to equal the next node in the linked list
// Increment the current index
previous = current;
current = current.next;
currentIndex++;
}
}
// We have found the index in our linked list
// 2 possibilities exist
// The index is somewhere in the middle of our linked list
// Or the index will be creating a new tail node
// If the current node is null (meaning we are inserting at the tail)
// Update the tail value
if (current === null) {
// Set the previous nodes next value to equal the new node
// Set the new nodes next value to equal current
// Update the new node to equal the tail
previous.next = new_node;
new_node.next = current;
this.tail = new_node;
} else {
// Set the previous nodes next value to equal the new node
// Set the new nodes next value to equal current
previous.next = new_node;
new_node.next = current;
}
}
}
export default LinkedList;
<file_sep>import LinkedList from '../Remove_Middle';
describe('testing remove head functionality of linked list', () => {
test('initialization of linked list should result in head and tail being null', () => {
let LL = new LinkedList();
expect(LL.head && LL.tail).toBe(null);
});
test('removing the middle from an empty linked list should throw an error', () => {
let LL = new LinkedList();
expect(() => LL.removeMiddle()).toThrow(Error);
});
test('removing the middle node from a linked list with 1 node sets the head and tail node to null', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.removeMiddle();
expect(LL.head && LL.tail).toBeNull();
expect(LL.head && LL.tail).toBeNull();
});
test('removing the middle node from a linked list with 2 values removes the tail node', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.removeMiddle();
expect(LL.head.value && LL.tail.value).toBe('firstValue');
expect(LL.tail.next).toBeNull();
});
test('removing middle from an odd number of values in linked list should result in the middle node being removed', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.insertTail('thirdValue');
LL.removeMiddle();
expect(LL.head.value).toBe('firstValue');
expect(LL.head.next.value).toBe('thirdValue');
expect(LL.tail.value).toBe('thirdValue');
expect(LL.tail.next).toBeNull();
});
test('remove middle node from even number of values in linked list should result in the second middle number being removed', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.insertTail('thirdValue');
LL.insertTail('fourthValue');
LL.removeMiddle();
expect(LL.head.value).toBe('firstValue');
expect(LL.head.next.value).toBe('secondValue');
expect(LL.head.next.next.value).toBe('fourthValue');
expect(LL.tail.value).toBe('fourthValue');
expect(LL.tail.next).toBeNull();
});
});
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertHead(value) {
let new_node = new Node(value);
if (this.head === null) {
this.head = new_node;
this.tail = new_node;
} else {
let temp = this.head;
this.head = new_node;
this.head.next = temp;
}
}
// Function for inserting a value into the middle of our linked list
// Takes 1 parameter => value
insertMiddle(value) {
// Create the new node value and assign it to a variable
// To create our node we must use our Node class
// Our Node class accepts 1 value => value
// Initialize our new_node by using => new
let new_node = new Node(value);
// Inserting into the middle of a linked list requires at least 2 nodes
// Assert that the length of our list is at least 2
// If LESS THAN 2
if (this.head === null || this.head.next === null) {
// Signal that we cannot insert into the middle
// return 'cannot insert middle';
throw new Error(
'Cannot insert middle with less than 2 nodes in LinkedList'
);
} else {
// We need to create 2 pointers to track where we are in the linked list
// Each tracker has a purpose
// FAST will get the value 2 nodes away
// SLOW will get the next value
let fast = this.head;
let slow = this.head;
// We want to keep moving through the linked list until fast reaches the end
// We reach the end when fast.next or fast.next.next is null
while (fast.next !== null && fast.next.next !== null) {
// Move fast forward 2 steps
fast = fast.next.next;
// Move slow forward 1 step
slow = slow.next;
}
// SLOW now represents the middle value
// We want to make the next value => new_node
// To do this we must store the current pointer of the middle node in a temp var
let temp = slow.next;
// Then we set the next node to => new_node
slow.next = new_node;
// Our new_node now has to point to the temp variable, which continues our linked list
// Forgetting this step will orphan the rest of the nodes in the list
new_node.next = temp;
}
}
}
export default LinkedList;
<file_sep>import LinkedList from '../Remove_Kth_Index_From_End';
describe('testing remove Kth index from end functionality of linked list', () => {
test('initialization of linked list should result in head and tail being null', () => {
let LL = new LinkedList();
expect(LL.head && LL.tail).toBe(null);
});
test('removing the kth index from an empty linked list should throw an error', () => {
let LL = new LinkedList();
expect(() => LL.removeKthIndexFromEnd(0)).toThrow(Error);
});
test('removing the kth index from end with only 1 node in linked list should result in a null head and tail', () => {
let LL = new LinkedList();
LL.insertHead('firstValue');
LL.removeKthIndexFromEnd(1);
expect(LL.head && LL.tail).toBeNull();
});
test('removing the 2 index from end with 3 nodes should remove the middle node', () => {
let LL = new LinkedList();
LL.insertHead('thirdValue');
LL.insertHead('secondValue');
LL.insertHead('firstValue');
LL.removeKthIndexFromEnd(2);
expect(LL.head.value).toBe('firstValue');
expect(LL.head.next.value).toBe('thirdValue');
expect(LL.tail.value).toBe('thirdValue');
expect(LL.tail.next).toBeNull();
});
test('removing the 4th index from end with 4 nodes should result in the head node being changed', () => {
let LL = new LinkedList();
LL.insertHead('fourthValue');
LL.insertHead('thirdValue');
LL.insertHead('secondValue');
LL.insertHead('firstValue');
LL.removeKthIndexFromEnd(4);
expect(LL.head.value).toBe('secondValue');
expect(LL.head.next.value).toBe('thirdValue');
expect(LL.tail.value).toBe('fourthValue');
expect(LL.tail.next).toBeNull();
});
test('removing the 100th index from end with 1 node in the linked list should throw an error', () => {
let LL = new LinkedList();
LL.insertHead('firstValue');
expect(() => LL.removeKthIndexFromEnd(100)).toThrow(Error);
});
test('removing the 1st index from end with 4 nodes should remove the node before the tail', () => {
let LL = new LinkedList();
LL.insertHead('fourthValue');
LL.insertHead('thirdValue');
LL.insertHead('secondValue');
LL.insertHead('firstValue');
LL.removeKthIndexFromEnd(2);
console.log(
'head',
LL.head.value,
'next',
LL.head.next.value,
'next',
LL.head.next.next
);
expect(LL.head.value).toBe('firstValue');
expect(LL.head.next.value).toBe('secondValue');
expect(LL.head.next.next.value).toBe('fourthValue');
expect(LL.tail.value).toBe('fourthValue');
expect(LL.tail.next).toBeNull();
});
});
<file_sep>import LinkedList from '../Detect_Cycle';
describe('testing the detect cycle functionality of linked list', () => {
test('detect cycle of an empty linked list returns false', () => {
let LL = new LinkedList();
expect(LL.detectCycle()).toBe(false);
});
test('detect cycle of a linked list with 1 node and no cycle should return false', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
expect(LL.detectCycle()).toBe(false);
});
test('detect cycle of a linked list with 1 node and a cycle should return true', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.tail.next = LL.head;
expect(LL.detectCycle()).toBe(true);
});
test('detect cycle of a linked list with 2 nodes and no cycle returns false', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
expect(LL.detectCycle()).toBe(false);
});
test('detect cycle of a linked list with 4 nodes and a cycle should return true', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.insertTail('thirdValue');
LL.insertTail('fourthValue');
LL.tail.next = LL.head;
expect(LL.detectCycle()).toBe(true);
});
test('detect cycle of a linked list with 4 nodes and a cycle in the middle should return true', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.insertTail('thirdValue');
LL.insertTail('fourthValue');
LL.tail.next = LL.head.next;
expect(LL.detectCycle()).toBe(true);
});
test('detect cycle of a linked list with 5 nodes and a cycle in the middle should return true', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.insertTail('thirdValue');
LL.insertTail('fourthValue');
LL.insertTail('fifthValue');
LL.tail.next = LL.head.next.next;
expect(LL.detectCycle()).toBe(true);
});
});
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertTail(value) {
let newValue = new Node(value);
if (this.head === null) {
this.head = newValue;
this.tail = newValue;
} else {
this.tail.next = newValue;
this.tail = newValue;
}
}
// Remove duplicates does not take any parameters
// It will remove the duplicate values of a sorted linked list
// Meaning it will keep only 1 unique value of each node in the linked list
removeDuplicates() {
// If the linked list is empty or only has 1 value then we will return the head node
// This is because if there is only 0 or 1 values there is nothing duplicate to remove
if (this.head === null || this.head.next === null) return this.head;
// Create a variable to track the nodes in the linked list
// Set the variable to equal the head node
let current = this.head;
// Iterate over the linked list until we get to the end of the linked list
while (current.next !== null) {
// If the current value does not equal the next value
// That means it is not a duplicate and we can continue iterating
if (current.value !== current.next.value) {
// Set current to equal the next node in the linked list
current = current.next;
} else {
// We need to keep moving the next node in the linked list until we meet 1 of 2 conditions
// Either the value is unique and we can change current
// Or the value is null and we exit the while loop
current.next = current.next.next;
}
}
// Return the head node, not current
return this.head;
}
}
export default LinkedList;
<file_sep>import LinkedList from '../Find_Length';
describe('testing find length functionality of linked list', () => {
test('the length of an empty linked list returns 0', () => {
let LL = new LinkedList();
expect(LL.findLength()).toBe(0);
});
test('the length of a linked list with 1 node returns 1', () => {
let LL = new LinkedList();
LL.insertTail('value');
expect(LL.findLength()).toBe(1);
});
test('the length of a linked list with 5 nodes returns 5', () => {
let LL = new LinkedList();
LL.insertTail('value');
LL.insertTail('value');
LL.insertTail('value');
LL.insertTail('value');
LL.insertTail('value');
expect(LL.findLength()).toBe(5);
});
});
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertTail(value) {
let newValue = new Node(value);
if (this.head === null) {
this.head = newValue;
this.tail = newValue;
} else {
this.tail.next = newValue;
this.tail = newValue;
}
}
findMiddle() {
// If the linked list is empty
// Throw an error
if (this.head === null) {
throw new Error('linked list is empty');
}
// If the linked list only has 1 node
// Return the head value
if (this.head.next === null) {
return this.head.value;
} else {
// Track 2 pointers: slow and fast
// Slow will increment over the linked list 1 node at a time;
// Slow will end up being the middle node
// Fast will increment over the linked list 2 nodes at a time;
let slow = this.head;
let fast = this.head;
// Iterate over the linked list until fast and fast.next equal null
while (fast !== null && fast.next !== null) {
// Set slow to equal the next node in the linked list
// Set fast to jump 2 nodes ahead in the linked list
slow = slow.next;
fast = fast.next.next;
}
return slow.value;
}
}
}
export default LinkedList;
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertTail(value) {
let newNode = new Node(value);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
// Find length takes 0 parameters
// Find length provides you with how many nodes are in the linked list
findLength() {
// Create a variable to track the length
// Set it to 0 as the default length (no nodes in linked list)
let length = 0;
// Check to see if the head node is null
// If the linked list is empty just return the length (0)
if (this.head === null) {
return length;
}
// We need to iterate over every node in the linked list
// Create a variable current to track the nodes in the linked list
let current = this.head;
// While current is not null
while (current !== null) {
// Go through each node and increment the length
// Set the current to equal the next node in the linked list
length++;
current = current.next;
}
// Return the length
return length;
}
}
export default LinkedList;
<file_sep>import LinkedList from '../Find_Middle';
describe('test find middle functionality of a linked list', () => {
test('finding the middle node of an empty linked list should throw an error', () => {
let LL = new LinkedList();
expect(() => LL.findMiddle()).toThrow(Error);
});
test('finding the middle node of a linked list with 1 value should return the head node', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
expect(LL.findMiddle()).toBe('firstValue');
});
test('finding the middle node of a linked list with 2 values should return the tail node', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
expect(LL.findMiddle()).toBe('secondValue');
});
test('finding the middle node of a linked list with 3 values should return the middle value', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.insertTail('thirdValue');
expect(LL.findMiddle()).toBe('secondValue');
});
test('finding the middle node of a linked list with 4 values should return the second middle value', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.insertTail('thirdValue');
LL.insertTail('fourthValue');
expect(LL.findMiddle()).toBe('thirdValue');
});
});
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertHead(value) {
let newValue = new Node(value);
if (this.head === null) {
this.head = newValue;
this.tail = newValue;
} else {
let temp = this.head;
this.head = newValue;
this.head.next = temp;
}
}
// Find Kth Value takes 1 parameter, the index you are looking for
// It will return the value at that index
findKthValue(index) {
// If the linked list is empty
// Throw an error
if (this.head === null) {
throw new Error('linked list is empty');
}
// We need to iterate over the linked list until we find the index we are looking for
// Or we get to the end of the linked list
// Create a variable current that tracks the current head node
// Crate a variable currentIndex that represents the current index in the linked list
let current = this.head;
let currentIndex = 0;
// Iterate over the linked list while the current index is less than the index we are looking for
while (currentIndex < index) {
// If the current's next value is null that means we are at the end of the linked list
// This means the index provided is greater than the length of our linked list
// Throw a new error
if (current.next === null) {
throw new Error('index out of range');
}
// Else
// Increment the currentIndex
// Set the current to equal current's next value
currentIndex++;
current = current.next;
}
// We have found the index we are looking for
// Return the current value
return current.value;
}
}
export default LinkedList;
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertTail(value) {
let newNode = new Node(value);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
// Remove Head function does not take any parameters
// It just removes the head node of a linked list
removeTail() {
// If the linked list is empty
// There is no tail node to remove
// Throw a error
if (this.head === null) {
throw new Error('linked list is empty');
}
// If the linked list only has one node
// Reset the head and tail node to equal null
if (this.head.next === null) {
this.head = null;
this.tail = null;
} else {
// We need to track the previous and current node
// The previous node will be used to set the new tail node
let previous = null;
let current = this.head;
// Iterate over the linked list until we hit the tail
// The current node will be the tail
// The previous node will be the node before the tail
while (current.next !== null) {
previous = current;
current = current.next;
}
// Previous node is the node before the tail
// Set the previous nodes next node to null
// Update the tail to equal the previous node
previous.next = null;
this.tail = previous;
}
}
}
export default LinkedList;
<file_sep>import LinkedList from '../Remove_Tail';
describe('testing remove head functionality of linked list', () => {
test('initialization of linked list should result in head and tail being null', () => {
let LL = new LinkedList();
expect(LL.head && LL.tail).toBe(null);
});
test('removing the tail from an empty linked list should throw an error', () => {
let LL = new LinkedList();
expect(() => LL.removeTail()).toThrow(Error);
});
test('removing the tail from a linked list with 1 node should result in an empty linked list', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.removeTail();
expect(LL.head && LL.tail).toBeNull();
});
test('removing the tail from a linked list with 2 nodes should result in the head node also becoming the tail node', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.removeTail();
expect(LL.head.value && LL.tail.value).toBe('firstValue');
expect(LL.tail.next).toBeNull();
});
test('removing the tail from a linked list with 3 nodes should result in the middle node becoming the tail node', () => {
let LL = new LinkedList();
LL.insertTail('firstValue');
LL.insertTail('secondValue');
LL.insertTail('thirdValue');
LL.removeTail();
expect(LL.head.value).toBe('firstValue');
expect(LL.head.next.value).toBe('secondValue');
expect(LL.tail.value).toBe('secondValue');
expect(LL.tail.next).toBeNull();
});
});
<file_sep># Data Structure Problem Sets with Testing
# Technology
1. JavaScript
2. Jest
# Use Case
Solving Data Structure problems and writing out the test cases for my course Illustrated JS
# Methodology
# Code Snippet
# How to run locally
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertTail(value) {
let newValue = new Node(value);
if (this.head === null) {
this.head = newValue;
this.tail = newValue;
} else {
this.tail.next = newValue;
this.tail = newValue;
}
}
// Detect Cycle does not take any parameters
// Detect a cycle will return a boolean value of true or false
detectCycle() {
// If the linked list is empty
// Return false, the linked list is not a cycle
if (this.head === null) {
return false;
}
// Create 2 pointers: slow and fast
// Both pointers will point to the head node
let slow = this.head;
let fast = this.head;
// We need to iterate over the linked list until we meet 1 of 2 conditions
// Either the fast tracker will hit null
// Or the fast and slow pointer will meet
// In the case they meet we will return true
// While fast and fast.next do not equal null - Iterate over the linked list
while (fast !== null && fast.next !== null) {
// Set slow to equal the next value in the linked list
// Set fast to equal 2 values ahead in the linked list
slow = slow.next;
fast = fast.next.next;
// If the slow and fast value are the same node
// Return true
if (slow == fast) {
return true;
}
}
// The fast tracker hit a null value (end of linked list)
// Return false
return false;
}
}
export default LinkedList;
<file_sep>class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insertTail(value) {
let newNode = new Node(value);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
// RemoveMiddle does not take any parameters
// It removes the middle node in the linked list
// If there are an even number of nodes, remove the second middle node
removeMiddle() {
// If the linked list is empty
// Throw an error
if (this.head === null) {
throw new Error('linked list is empty');
}
// If the linked list only has one value
// Reset the head and tail node to equal null;
if (this.head.next === null) {
this.head = null;
this.tail = null;
} else {
// Track 3 pointers: slow, fast and prev
// Slow will increment over the linked list 1 node at a time;
// Slow will end up being the middle node
// Fast will increment over the linked list 2 nodes at a time;
// Prev will be the old slow value
let slow = this.head;
let fast = this.head;
let prev = null;
// Iterate over the linked list until fast and fast.next equal null
while (fast !== null && fast.next !== null) {
// Set prev to equal the old slow value
// Set slow to equal the next node in the linked list
// Set fast to jump 2 nodes ahead in the linked list
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
// Edge case if the node we are trying to delete is the tail node
// If slow (a.k.a the middle node) is the tail node
// We need to also reassign the tail node!
if (slow.next === null) {
// Set prev's next value to equal null
// Set the tail to equal prev;
prev.next = null;
this.tail = prev;
} else {
// Set the prev's next value to equal null
prev.next = slow.next;
}
}
}
}
export default LinkedList;
<file_sep>import LinkedList from '../Remove_Head';
describe('testing remove head functionality of linked list', () => {
test('initialization of linked list should result in head and tail being null', () => {
let LL = new LinkedList();
expect(LL.head && LL.tail).toBe(null);
});
test('removing the head from an empty linked list should throw an error', () => {
let LL = new LinkedList();
expect(() => LL.removeHead()).toThrow(Error);
});
test('removing the head node from a linked list with 1 node should return null values', () => {
let LL = new LinkedList();
LL.insertHead('firstValue');
LL.removeHead();
expect(LL.head && LL.tail).toBeNull();
});
test('removing the head node from a linked list with 2 values should return the tail node being the head node', () => {
let LL = new LinkedList();
LL.insertHead('secondValue');
LL.insertHead('firstValue');
LL.removeHead();
expect(LL.head.value && LL.tail.value).toBe('secondValue');
expect(LL.head.next).toBeNull();
});
test('removing the head node from a linked list with 3 values should return the proper head and tail node', () => {
let LL = new LinkedList();
LL.insertHead('thirdValue');
LL.insertHead('secondValue');
LL.insertHead('firstValue');
LL.removeHead();
expect(LL.head.value).toBe('secondValue');
expect(LL.head.next.value).toBe('thirdValue');
expect(LL.tail.value).toBe('thirdValue');
expect(LL.tail.next).toBeNull();
});
});
<file_sep>import LinkedList from '../Find_Kth_Value';
describe('testing find Kth value functionality for linked list', () => {
test('finding the 2nd value of an empty linked list should throw an error', () => {
let LL = new LinkedList();
expect(() => LL.findKthValue(2)).toThrow(Error);
});
test('finding the 2nd value of a linked list with 1 node should throw an error', () => {
let LL = new LinkedList();
LL.insertHead('firstValue');
expect(() => LL.findKthValue(2)).toThrow(Error);
});
test('finding the 1st value of a linked list with 1 node should return the head node', () => {
let LL = new LinkedList();
LL.insertHead('firstValue');
expect(LL.findKthValue(0)).toBe('firstValue');
});
test('find the last value of a linked list with 3 nodes should return the tail node', () => {
let LL = new LinkedList();
LL.insertHead('thirdValue');
LL.insertHead('secondValue');
LL.insertHead('firstValue');
expect(LL.findKthValue(2)).toBe('thirdValue');
});
test('find the 2nd value of a linked list with 3 nodes should return the middle node', () => {
let LL = new LinkedList();
LL.insertHead('thirdValue');
LL.insertHead('secondValue');
LL.insertHead('firstValue');
expect(LL.findKthValue(1)).toBe('secondValue');
});
});
| 6d77b6ab20f91f2a511de5da4e8fe7d4bc46a463 | [
"JavaScript",
"Markdown"
] | 24 | JavaScript | Matt-GitHub/Data-Structures_IllustratedJS | 527afe82dbe700c9f523643c99cd17a668903827 | 46c0076c4a35104e4987b44e750995038e0a3660 |
refs/heads/main | <file_sep>// ASSESSMENT 6: JavaScript Coding Practical Questions with Jest
const { array } = require("yargs")
// Please read all questions thoroughly
// Pseudo coding is REQUIRED
// If you get stuck, please leave comments to help us understand your thought process
// Add appropriate dependencies to the repository:
// $ yarn add jest
// Use test driven development to complete the following questions
// Run the file with the following command:
// $ yarn jest
// Reminder: The test will call your function
// --------------------1) Create a function that takes in an array of objects and returns an array with a sentence about each person with their names capitalized.
// a) Create a test with an expect statement using the variable provided.
var people = [
{ name: "<NAME>", occupation: "hitchhiker" },
{ name: "<NAME>", occupation: "president of the galaxy" },
{ name: "<NAME>", occupation: "radio employee" }
]
// Expected output: ["Ford Prefect is a hitchhiker.", "<NAME> is a president of the galaxy.", "<NAME> is a radio employee."]
describe("sentence", () => {
it("returns an array with a sentence about each person with their names capitalized", () => {
expect(sentence(person)).toEqual(["Ford Prefect is a hitchhiker.", "<NAME> is a president of the galaxy.", "<NAME> is a radio employee."])
})
})
// b) Create the function that makes the test pass.
// create a function called sentence that takes in an array
const sentence = (array) => {
// create a variable with an empty array that will store each object
let allSentence = []
array.forEach(person => {
`${person.name} is a ${person.occupation}.`
allSentence.push(array)
})
return allSentence
}
console.log(sentence())
// I know the forEach method should be used but i was not able to find the right way to implement it in my code. I would run into errors such as undefined and [ [Function: sentence], [Function: sentence], [Function: sentence] ].
// --------------------2) Create a function that takes in a mixed data array and returns an array of only the REMAINDERS of the numbers when divided by 3.
// a) Create a test with an expect statement using the variables provided.
var hodgepodge1 = [23, "Heyyyy!", 45, -10, 0, "Yo", false]
// Expected output: [ 2, 0, -1, 0 ]
var hodgepodge2 = [5, "Hola", 43, -34, "greetings", true]
// Expected output: [ 2, 1, -1 ]
describe("remaining", () => {
it("returns an array of only the REMAINDERS of the numbers when divided by 3.", () => {
expect(remaining(hodgepodge1)).toEqual([ 2, 0, -1, 0 ])
expect(remaining(hodgepodge2)).toEqual([ 2, 1, -1 ])
})
})
// b) Create the function that makes the test pass.
// create an array called remaining that will take in an array
const remaining = (array) => {
// return the array with filter to return an array of only truthy arguments
return array.filter(value => {
// argument to return only numbers
return typeof value == "number"
// map through each value in the array to find the modulo of each
}).map(value => {
return value % 3
})
}
// --------------------3) Create a function that takes in an array of numbers and returns the sum of all the numbers cubed.
// a) Create a test with an expect statement using the variables provided.
var cubeAndSum1 = [2, 3, 4]
// Expected output: 99
var cubeAndSum2 = [0, 5, 10]
// Expected output: 1125
describe("cubedAndSum", () => {
it("returns the sum of all the numbers cubed.", () => {
expect(cubedAndSum(cubeAndSum1)).toEqual(99)
expect(cubedAndSum(cubeAndSum2)).toEqual(1125)
})
})
// b) Create the function that makes the test pass.
// create a function called cubedAndSum that takes in an array
const cubedAndSum = (array) => {
// create a new variable that maps through the given array
let arr = array.map(value => {
// output the value cubed
return value ** 3
})
// returning the current value of the number plus the current element in the array
return arr.reduce((accumulator, currentValue) => accumulator + currentValue)
}
<file_sep># ASSESSMENT 6: Rails Commenting Challenge
# Add comments to the Rails Blog Post Challenge
# Explain the purpose and functionality of the code directly below the 10 comment tags
# FILE: app/controller/blog_posts_controller.rb
# ---1) The controller BlogPosts is recieving information from the ApplicationController
class BlogPostsController < ApplicationController
def index
# ---2) A variable is created to return all of the blog posts that were saved as arrays.
@posts = BlogPost.all
end
def show
# ---3) This variable is allowing the user to search for a specific blog post by id.
@post = BlogPost.find(params[:id])
end
# ---4) This code is defining a new method to allow the user to create a new post.
def new
@post = Post.new
end
def create
# ---5) This code is taking in the private code block in order to only allow the creation of new blog posts with certain parameters.
@post = BlogPost.create(blog_post_params)
if @post.valid?
redirect_to blog_post_path(@post)
else
redirect_to new_blog_post_path
end
end
# ---6) The edit method allows for the user to search for a certain id and make changes to that id.
def edit
@post = BlogPost.find(params[:id])
end
def update
@post = BlogPost.find(params[:id])
# ---7) The update method takes in the private params method to only allow updates with those certain parameters.
@post.update(blog_post_params)
if @post.valid?
redirect_to blog_post_path(@post)
else
redirect_to edit_blog_post_path
end
end
def destroy
@post = BlogPost.find(params[:id])
if @post.destroy
redirect_to blog_posts_path
else
# ---8) If the blog post is not destroyed correctly, the user will be redirected to that same blog post that they were trying to delete.
redirect_to blog_post_path(@post)
end
end
# ---9) Everything below private is hidden from the user and can not be ran in the code.
private
def blog_post_params
# ---10) This makes certain parameters necessary to run certain methods. Such as a new blog post requires a title and content to be created.
params.require(:blog_post).permit(:title, :content)
end
end
<file_sep># ASSESSMENT 6: Interview Practice Questions
Answer the following questions.
First, without external resources. Challenge yourself to answer from memory.
Then, research the question to expand on your answer. Even if you feel you have answered the question completely on your own, there is always something more to learn. Write your researched answer in your OWN WORDS.
1. As a developer, I am creating an API with a model called Animal that has_many Sightings, but OOPS! I forgot to add the foreign key. How can I fix this mistake? What is the name of the foreign key? Would the foreign key be part of the Animal model or the Sightings model?
Your answer: The foreign key would be part of the Animal model and the name would be called animal_id. In order to fix this, you can go into the console and add a new migration.
Researched answer: There must be a row already existing in order to add the foreign key.
2. Which RESTful API routes must always be passed params? Why?
Your answer: show, update, destroy must always be passed params so the developer knows which item they are modifying or showing.
Researched answer:
API parameters are the variable parts of a resource. They determine the type of action you want to take on the resource. Each parameter has a name, value type ad optional description. Whenever you want to build a REST API, you have to decide which parameters should be present in the API endpoint.
3. Name three rails generator commands. What is created by each?
Your answer: rails g model, rails g resource, and rails g migration
Researched answer: rails g model creates a new model with specific keys, rails g resource creates the model, migrations routes and controllers, and rails g migration runs a migration for controllers.
4. Consider the Rails routes below. What is the name of the controller method that would be called by each route? What action would each of the controller methods perform?
method="GET" /students INDEX shows all items from a table
method="POST" /students CREATE allows for new items to be made with certain params
method="GET" /students/new NEW creates a new item in a table
method="GET" /students/2 SHOW returns a specific item that is called
method="GET" /students/edit/2 EDIT allows for a certain id to have changes made
method="PATCH" /students/2 UPDATE allows for the edit to happen
method="DELETE" /students/2 DESTROY deletes a specific item in a table
5. As a developer, you want to make an application that will help you manage your to do list. Create 10 user stories that will help you get your application started. Read more about [user stories](https://www.atlassian.com/agile/project-management/user-stories).
As a developer, I can create a person model in the database with name and address.
As a user, I can see the different people in the database.
As a user, I can add new people to the database.
As a user, I can edit people in the database.
As a user, I can delete people from the database.
As a user, I can add new people to the database.
As a user, I can add people to a list of favorites.
As a user, I can delte people from the list of favorites.
As a user, I can add a new phone number to the database.
As a user, I can delete a phone number from the database.
| e53bd183869f83958f9b28d30b0dc2eed1c70905 | [
"JavaScript",
"Ruby",
"Markdown"
] | 3 | JavaScript | learn-academy-2021-charlie/week-6-assessment-Chrisluna10 | 433e30c8d41b7ab2653a4f19f411872314057136 | be5748ce0b9f6461e749caf09e4ffa04fdb23d1e |
refs/heads/master | <file_sep>import React from 'react';
import { css } from '@emotion/react';
import styled from '@emotion/styled';
import { Link } from 'gatsby';
const EnlaceHome = styled(Link)`
color: #fff;
text-align: center;
text-decoration: none;
&:visited {
color: #fff;
}
&:hover {
cursor: pointer;
}
`;
const Footer = ({title}) => {
const year = new Date().getFullYear();
return (
<footer
css={css`
background-color: rgba(44,62,80);
padding: 1rem;
margin-top: 5rem;
`}
>
<div
css={css`
max-width: 1200px;
margin: 0 auto;
@media (min-width: 768px) {
display: flex;
align-items: center;
justify-content: space-between;
}
`}
>
<EnlaceHome to={'/'}>
<h1>{title}</h1>
</EnlaceHome>
<p css={css`color: #fff`}>Hotel Gatsby. Todos los derechos reservados</p>
<p css={css`color: #fff`}>Copyright © {year}</p>
</div>
</footer>
);
};
export default Footer; | 30e74953700764c5e52d30dc481e920d5944bf90 | [
"JavaScript"
] | 1 | JavaScript | luchoirias/hotelgatsby | a3209430dc00bcc698c62448ba7fe1cceddcaf3d | 90c8a6b8187a7ce292c9fc335290dedfb0420135 |
refs/heads/master | <file_sep>// pyramyd-formation
// https://pyramyd-formation.com/formation/tout
//
//
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const puppeteer = require('puppeteer');
const _ = require('lodash');
const pages = [
'https://pyramyd-formation.com/formation/tout?page=0',
'https://pyramyd-formation.com/formation/tout?page=1',
'https://pyramyd-formation.com/formation/tout?page=2',
'https://pyramyd-formation.com/formation/tout?page=3',
'https://pyramyd-formation.com/formation/tout?page=4',
'https://pyramyd-formation.com/formation/tout?page=5',
'https://pyramyd-formation.com/formation/tout?page=6',
'https://pyramyd-formation.com/formation/tout?page=7',
'https://pyramyd-formation.com/formation/tout?page=8',
];
const getAllItemsUrlFromPage = async (browser, url) => {
const page = await browser.newPage();
await page.goto(url);
const pageItems = await page.evaluate(() => {
return [...document.querySelectorAll('.item-list li .field-content a')].map(link => {
const regex = /\bhttps:\/\/pyramyd-formation.com\/formation\/\b(.)*/;
return (link.href.match(regex) ? link.href : null);
}).filter(val => val !== null);
});
await page.close();
return pageItems;
};
const getText = (page, selector) => {
return page.evaluate((selector) => {
return document.querySelector(selector) ? document.querySelector(selector).innerText : null;
}, selector);
};
const exists = (page, selector) => {
return page.evaluate((selector) => {
return document.querySelector(selector) ? 1 : 0;
}, selector);
};
const moment = require('moment');
const parseDate = (string, format, hours, minutes) => {
console.log(string);
const dateString = string.replace('é', 'e');
const m = moment(dateString, format, 'fr').hours(hours).minutes(minutes);
console.log('---> parsed', dateString, ' ==== ', m.format());
const res = {
date: moment(m).format('YYYY-MM-DD[T]HH:mm:ss'),
dateTz: moment(m).format(),
timestamp: moment(m).format('X'),
text: moment(m).format('dddd Do MMMM YYYY'),
};
console.log(res);
console.log('\n\n');
return res;
};
const monthsMap = {
'janv.': 01, // sure
'févr.': 02, // sure
'mars': 03, // sure
'avr.': 04, // sure
'mai': 05, // sure
'juin': 06, // sure
'juil.': 07, // sure
'août': 08, // sure
'sept.': 09, // sure
'oct.': 10, // sure
'nov.': 11, // sure
'déc.': 12 // sure
};
const browseItem = async (browser, url) => {
console.log('Item: ', url);
const page = await browser.newPage();
await page.goto(url);
const title = await getText(page, 'h1');
const description = await getText(page, 'body > main > div > div.group-content.layout-center.layout-center--mobile.clearfix > div > div.group-left > div > div > div > div.clearfix.text-formatted.field.field--name-sub-title.field--type-text-long.field--label-hidden.field__item');
const categories = await page.evaluate(() => {
const res = [...document.querySelectorAll('.breadcrumb__item')].map((item) => item.innerText);
res.shift();
return res || [];
});
const sessions = await page.evaluate(() => {
const res = [...document.querySelectorAll('#edit-comming-sessions > fieldset')].map((session) => {
return {
location: session.querySelector('span.fieldset-legend').innerText,
dates: [...session.querySelectorAll('label.option')].map(item => item.innerText),
};
});
return res;
});
// PATTERN 1
// 04 et 05 déc. 2018
// 03 et 04 déc. 2018
// 03 et 04 déc. 2000
// 19 au 21 déc. 2018
// 03 au 04 déc. 2001
// 19 au 21 déc. 2018
// 09 au 13 sept. 2019
// 14 au 16 janv. 2019
//
// // PATTERN 2
// 06 nov. 2018
// 06 nog 2019
// 08 NOv 2019
// 08 NOV. 2019
// 20 déc. 2018
// 20 juin. 2018
//
// // PATTERN 3
// 25 sept. 2019 au 15 janv. 2020
//
// // PATTERN 4
// 14 janv. au 05 juin 2019
// 14 janvd. au 05 juin 2019
// 31 janv. et 01 févr. 2019
if (sessions && sessions.length) {
sessions.forEach((session) => {
const dates = session.dates.map((date) => {
const pattern1 = /^[0-9]{2}.{0,2}\b [a-z-A-Z]{0,2} [0-9]{2}.{0,6} [0-9]{4}$/ // 04 et 05 déc. 2018 OR 03 au 08 déc. 2018
const pattern2 = /^[0-9]{2}\b .{1,5} \b[0-9]{4}$/ // 06 nov. 2018 OR 06 nov 2019 08 NOV 2019 OR 08 NOV. 2019
const pattern3 = /^[0-9]{2} .{0,6} [0-9]{1,4} [a-zA-Z]{1,3} [0-9]{2} .{0,6} [0-9]{4}$/ // 25 sept. 2019 au 15 janv. 2020
const pattern4 = /^[0-9]{2} .{1,6} [a-z]{2} [0-9]{2} .{1,9} [0-9]{4}$/ // 14 janv. au 05 juin 2019 31 janv. et 01 févr. 2019
const s = date.trim().split(' ');
let daystart = null;
let dayend = null;
let monthStart = null;
let monthEnd = null
let yearStart = null;
let yearEnd = null;
// console.log('MATCH1', date.trim().match(pattern1));
// console.log('MATCH2', date.trim().match(pattern2));
if (date.trim().match(pattern1)) {
console.log(date, '--- Matches p1');
daystart = s[0];
dayend = s[2];
monthStart = monthsMap[s[3]];
monthEnd = monthStart;
yearStart = s[4];
yearEnd = yearStart;
} else if (date.trim().match(pattern2)) {
console.log(date, '--- Matches p2');
daystart = s[0];
dayend = s[0];
monthStart = monthsMap[s[1]];
monthEnd = monthStart;
yearStart = s[2];
yearEnd = yearStart;
} else if (date.trim().match(pattern3)) {
console.log(date, '--- Matches p3');
daystart = s[0];
dayend = s[4];
monthStart = monthsMap[s[1]];
monthEnd = monthsMap[s[5]]
yearStart = s[2];
yearEnd = s[6];
} else if (date.trim().match(pattern4)) {
console.log(date, '--- Matches p4');
daystart = s[0];
dayend = s[3];
monthStart = monthsMap[s[1]];
monthEnd = monthsMap[s[4]]
yearStart = s[5];
yearEnd = s[5];
} else {
console.log(date, 'NO MATCH');
}
const dateStart = `${daystart} ${monthStart} ${yearStart}`;
const dateEnd = `${dayend} ${monthEnd} ${yearEnd}`;
console.log(date.trim(), ' <--s--> ', dateStart);
console.log(date.trim(), ' <--e--> ', dateEnd);
if (!session.formatedDates) {
session.formatedDates = [];
}
session.formatedDates.push({
begin: parseDate(dateStart, 'DD MM YYYY', 09, 00),
end: parseDate(dateEnd, 'DD MM YYYY', 17, 30),
})
});
});
}
const isCertified = await exists(page, '.field.field--name-certified.field--type-boolean.field--label-hidden.field__item > .on');
const cpf = await exists(page, '.field.field--name-cpf.field--type-boolean.field--label-hidden.field__item > .on');
const level = await getText(page, 'body > main > div > div.group-content.layout-center.layout-center--mobile.clearfix > div > div.group-left > div > div > div > div.field.field--name-level-of-difficulty.field--type-entity-reference.field--label-hidden.field__item > div');
const duration = await getText(page, 'body > main > div > div.group-content.layout-center.layout-center--mobile.clearfix > div > div.group-left > div > div > div > div.field.field--name-duration-of-training.field--type-string.field--label-hidden.field__item');
const location = await getText(page, 'body > main > div > div.group-content.layout-center.layout-center--mobile.clearfix > div > div.group-left > div > div > div > div.field.field--name-location-of-training.field--type-entity-reference.field--label-hidden.field__items > div > div');
const public = await getText(page, 'body > main > div > div.group-content.layout-center.layout-center--mobile.clearfix > div > div.group-left > div > div > div > div.clearfix.text-formatted.field.field--name-concerned-public.field--type-text-long.field--label-above > div.field__item');
const goal = await getText(page, 'div.clearfix.text-formatted.field.field--name-objectives.field--type-text-long.field--label-above > div.field__item');
let requirements = await getText(page, 'div.clearfix.text-formatted.field.field--name-prerequisite.field--type-text-long.field--label-above > div.field__item');
let competence_acquises = null;
if (requirements && requirements.split('Compétences acquises:').length > 1) {
competence_acquises = requirements.split('Compétences acquises:')[1];
}
let priceHt = await getText(page, '#edit-company-markup-b2b');
if (priceHt) {
priceHt = priceHt.split('€')[0];
}
const ref = await getText(page, 'body > main > div > div.group-content.layout-center.layout-center--mobile.clearfix > div > div.group-right > div > div.block.block-ctools.block-entity-viewnode > div > div.field.field--name-training-ref-id.field--type-string.field--label-inline > div.field__item');
const program = await getText(page, 'body > main > div > div.group-content.layout-center.layout-center--mobile.clearfix > div > div.group-left > div > div > div > div.clearfix.text-formatted.field.field--name-program.field--type-entity-reference-revisions.field--label-above > div.field__items > div > div > div > div');
const item = {
url,
isCertified,
cpf,
competence_acquises,
sessions,
title,
categories,
level,
duration,
location,
public,
goal,
requirements,
priceHt,
ref,
program,
};
await page.close();
return item;
};
const browseBatchAndGoNext = async (browser, batches, index, lastRes, db) => {
if (index === batches.length) {
console.log('DONE', lastRes);
return lastRes;
}
const res = await Promise.all(batches[index].map((itemUrl) => browseItem(browser, itemUrl)));
const result = res;
console.log(`Saving results... [${index}]:`, result.length);
// console.log(result);
await db.collection('pyramyd-formation').insertMany(result);
console.log(`SAVED batch ${index} of ${batches.length}`);
return browseBatchAndGoNext(browser, batches, index + 1, result, db);
};
(async () => {
const url = 'mongodb://mrsoyer:<EMAIL>:45620/sym';
const dbName = 'sym';
const client = new MongoClient(url);
await client.connect();
console.log("Connected correctly to server");
const db = client.db(dbName);
const browser = await puppeteer.launch({ headless: true });
// const r0 = await browseItem(browser, 'https://pyramyd-formation.com/formation/photo-prise-de-vues-avec-un-smartphone')//https://pyramyd-formation.com/formation/l-experience-utilisateur-ux-les-meilleures-pratiques');
// const r = await browseItem(browser, 'https://pyramyd-formation.com/formation/l-experience-utilisateur-ux-les-meilleures-pratiques');
// const r1 = await browseItem(browser, 'https://pyramyd-formation.com/formation/charge-de-conception-et-de-realisation-web-0');
// const p = await browseItem(browser, 'https://pyramyd-formation.com/formation/charge-de-creation-web-0'); // CAS ENVOYé PAR EMAIL
// //https://pyramyd-formation.com/formation/indesign-niveau-1-1
// // CAS AVEC START DATE === ENDDATE
// const p = await browseItem(browser, 'https://pyramyd-formation.com/formation/photo-prise-de-vues-avec-un-smartphone');
// non certifiée non pcf
// const p = await browseItem(browser, 'https://pyramyd-formation.com/formation/concevoir-une-maquette-graphique-pour-le-web');
// console.log(p);
// return;
// console.log(r0);
// console.log(r);
// console.log(r1);
const res = await Promise.all(pages.map((page) => getAllItemsUrlFromPage(browser, page)));
console.log(`Got ${res.length} pages to scrap`);
const allItems = _.flatten(res);
console.log(`Got ${allItems.length} items to browse`);
const chunks = _.chunk(allItems, 4);
console.log(`Got ${chunks.length} batches to browse`);
await browseBatchAndGoNext(browser, chunks, 0, [], db);
console.log('DONE');
})();
<file_sep>
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const moment = require('moment');
const puppeteer = require('puppeteer');
const _ = require('lodash');
const baseUrl = 'https://www.elegia.fr/formations';
const getText = (page, selector) => {
return page.evaluate((selector) => {
return document.querySelector(selector) ? document.querySelector(selector).innerText : null;
}, selector);
};
const getFormateurs = (page) => {
return page.evaluate(() => {
return [...document.querySelectorAll('#block-views-formateurs-block--2 .views-row')].map(formateur => {
const name = formateur.querySelector('.nom').innerText;
const description = formateur.querySelector('p').innerText;
return { name, description }
});
});
};
const browseItem = async (browser, url) => {
console.log('Browsing', url);
const page = await browser.newPage();
await page.goto(url);
const title = await getText(page, 'h1');
const description = await getText(page, '.panel-pane.fiche-intro.readmore');
const categories = await page.evaluate(() => {
const res = [... document.querySelectorAll('.easy-breadcrumb li:not(:first-child):not(:last-child) a')].map((el, i) => {
return {
level: i,
name: el.innerText,
url: el.href,
};
});
return res || [];
});
const sessions = await page.evaluate(() => {
const res = [...document.querySelectorAll('.dates-et-lieux')].map((session) => {
return {
location: session.querySelector('.adresse').innerText,
dates: [...session.querySelectorAll('ul > li')].map(item => item.innerText),
};
});
return res;
});
if (sessions && sessions.length) {
sessions.forEach((session) => {
// console.log('\n\n----- SESSION -----');
let dates = session.dates.map((date) => {
const splits = date.split(',');
const dates = splits.map((dateGroup) => {
let date = dateGroup.trim().split(' ');
let daysGroup = date[0];
if (dateGroup.match(/\bDu.*\b au .*/)) {
return dateGroup.split('Du')[1].trim().split(' au ').map((d) => {
return parseDate(d, 'DD MMMM');
});
}
if (daysGroup.indexOf('-') === -1) {
return parseDate(dateGroup.trim(), 'dddd DD MMMM YYYY');
}
let month = date[1];
let year = date[2];
const dates = daysGroup.split('-').map((day) => parseDate(`${day} ${month} ${year}`, 'DD MMMM YYYY'));
return dates;
});
return dates;
});
dates = _.flattenDeep(dates);
// session.allDates = dates;
session.begin = dates[0];
session.begin.dateTz = session.begin.date;
session.begin.date = moment(session.begin.date).hours(09).minutes(00).format('YYYY-MM-DD[T]HH:mm:ss');
session.end = dates[dates.length - 1];
session.end.dateTz = session.end.date;
session.end.date = moment(session.end.date).hours(17).minutes(30).format('YYYY-MM-DD[T]HH:mm:ss');
});
}
// const level = await getText(page, 'body > main > div > div.group-content.layout-center.layout-center--mobile.clearfix > div > div.group-left > div > div > div > div.field.field--name-level-of-difficulty.field--type-entity-reference.field--label-hidden.field__item > div');
const duration = await getText(page, '.duree-jour-not');
const formateurs = await getFormateurs(page);
// const location = await getText(page, 'body > main > div > div.group-content.layout-center.layout-center--mobile.clearfix > div > div.group-left > div > div > div > div.field.field--name-location-of-training.field--type-entity-reference.field--label-hidden.field__items > div > div');
const public = await getText(page, '#public-et-prerequis .field-name-field-formation-public')
const goal = await getText(page, '.formation-content-objectif > .formation-content-resume');
let prerequisite = await getText(page, '#public-et-prerequis');
if (prerequisite) {
const splits = prerequisite.split('Prérequis');
if (splits.length >= 2) {
prerequisite = splits[1];
} else {
prerequisite = null;
}
}
let priceHt = await getText(page, '.prix-inter');
if (priceHt) {
priceHt = priceHt.split(' €')[0];
}
ref = await getText(page, '.page-formations-header-type')
if (ref) {
ref = ref.split('#')[1];
}
let pointsforts = await getText(page, '#points-forts');
if (pointsforts && pointsforts.indexOf('Points forts') === 0) {
pointsforts = pointsforts.substr(12, pointsforts.length);
}
const program = await getText(page, '#programme');
const item = {
url,
sessions,
title,
description,
categories,
// level,
duration,
public,
goal,
prerequisite,
priceHt,
ref,
program,
pointsforts,
formateurs,
};
await page.close();
return item;
};
const browseBatchAndGoNext = async (browser, batches, index, lastRes, db) => {
if (index === batches.length) {
console.log('DONE', lastRes);
return lastRes;
}
const res = await Promise.all(batches[index].map((itemUrl) => browseItem(browser, itemUrl)));
const result = res;
console.log(`Saving results... [${index}]:`, result.length);
await db.collection('elegia2').insertMany(result);
console.log(`SAVED batch ${index + 1} of ${batches.length}`);
return browseBatchAndGoNext(browser, batches, index + 1, result, db);
};
const goNextPage = async (page, currentPage) => {
const isLastPage = await page.evaluate(() => {
return !document.querySelector('.pager-next');
});
if (isLastPage) {
return 'LAST_PAGE';
}
const nextPage = await page.evaluate(() => {
return document.querySelector('.pager-current+.pager-item').innerText;
});
console.log(`Current page: #${currentPage}, going to #${nextPage}`);
await page.click('.pager-next');
console.log('Is Loading');
await page.waitForFunction((nextPage) => {
return document.querySelector('.pager-current').innerText === nextPage;
}, {}, nextPage);
await page.waitFor(400);
console.log('Loaded');
};
const browseAllPages = async (page, start, lastItems) => {
const items = await getAllItemsUrlFromPage(page);
const res = await goNextPage(page, start);
if (res === 'LAST_PAGE') {
console.log('LAST_PAGE');
return [...lastItems, ...items];
}
return browseAllPages(page, start + 1, [...lastItems, ...items]);
};
const getAllItemsUrlFromPage = async (page) => {
const pageItems = await page.evaluate(() => {
return [...document.querySelectorAll('.formation-teaser .title a')].map(link => link.href);
});
return pageItems;
};
const parseDate = (dateString, format) => {
if (!format) {
format = 'dddd Do MMMM YYYY';
}
console.log('PARSE', dateString, '->', format);
const m = moment(dateString, format, 'fr');
console.log('--->', moment(m).format())
return {
date: moment(m).format(),
timestamp: moment(m).format('X'),
text: moment(m).format('dddd Do MMMM YYYY'),
};
};
(async () => {
const url = 'mongodb://mrsoyer:<EMAIL>:45620/sym';
const dbName = 'sym';
const client = new MongoClient(url);
await client.connect();
console.log("Connected correctly to server");
const db = client.db(dbName);
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.goto(baseUrl);
await page.waitForFunction(() => !!document.querySelector('#adroll_banner_close'));
await page.click('#adroll_banner_close');
await page.waitFor(2000);
const itemsToBrowse = await browseAllPages(page, 1, []);
console.log(`${itemsToBrowse.length} to browse`);
const chunks = _.chunk(itemsToBrowse, 10);
// const chunks = [
// ['https://www.elegia.fr/formations/3-minutes-convaincre_512000-0'],
// // ['https://www.elegia.fr/formations/3-minutes-convaincre_512000'],
// ];
console.log(`Got ${chunks.length} batches to browse`);
await browseBatchAndGoNext(browser, chunks, 0, [], db);
// const item = await browseItem(browser, 'https://www.elegia.fr/formations/etre-responsable-ressources-humaines-rrh_119005');
// const item2 = await browseItem(browser, 'https://www.elegia.fr/formations/arreter-cloturer-comptes-annuels_550004-0');
// const item3 = await browseItem(browser, 'https://www.elegia.fr/formations/actualite-sociale-2018-atelier-negociation-collective-integrer-nouvelles-obligations_600539#dates-et-lieux');
// console.log(item.sessions);
// console.log(item2.sessions);
// console.log(item3.sessions);
})();
<file_sep>// pyramyd-formation
// https://pyramyd-formation.com/formation/tout
//
//
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const puppeteer = require('puppeteer');
const _ = require('lodash');
const uuidv1 = require('uuid/v1');
(async () => {
const url = 'mongodb://mrsoyer:<EMAIL>:45620/sym';
const dbName = 'sym';
const client = new MongoClient(url);
await client.connect();
console.log("Connected correctly to server");
const db = client.db(dbName);
const col = db.collection('comundi');
console.log('connected to db... fetching items...');
const arr = await col.find().limit(200).toArray();
console.log('got:', arr.length, 'items');
const res = arr.map((elem) => {
const orignItem = elem;
orignItem.categories = orignItem.categories.map(e => e.name).join(',');
// Duplicate item for each session
let newItemsPerSession = [];
if (!elem.sessions || !elem.sessions.length) {
newItemsPerSession.push(orignItem);
} else {
newItemsPerSession = elem.sessions.map((session) => {
return {
sessionId: uuidv1(),
begin: _.get(session, 'begin.date', null),
end: _.get(session, 'end.date', null),
location: session.location,
...orignItem,
};
});
}
// Duplicate item for each formator
let newItemsPerFormators = [];
if (orignItem.formateurs && orignItem.formateurs.length) {
newItemsPerFormators = orignItem.formateurs.map(e => {
return {
formateurName: e.name,
formateurDesc: e.description,
...orignItem,
};
});
}
return [...newItemsPerSession, ... newItemsPerFormators];
});
const flat = _.flattenDeep(res);
console.log(flat.length);
// flat.forEach((e) => {
// console.log(`e.cats: ${e.categories}, e.begin: ${e.begin}, e.end: ${e.end}, e.url: ${e.url}\n`);
// });
/////////// HERE WE GO
///////////
///////////
///////////
var fs = require("fs")
var es = require("event-stream")
var jsoncsv = require('json-csv');
const items = flat;
const options = {
fields: [
{ label: 'URL', name: 'url' },
{ label: 'Référence', name: 'ref' },
{ label: 'Catégories', name: 'categories' },
{ label: 'ID formation unique par session', name: 'sessionId' },
{ label: 'Durée en jours', name: 'days' }, // TODO
{ label: 'Durée en heures', name: 'hours' }, // TODO
{ label: 'Date Début', name: 'begin' },
{ label: 'Date Fin', name: 'end' },
//ok
{ label: 'Nom de la formation', name: 'title' }, //ok
{ label: 'Description', name: 'description' },
{ label: 'Points forts', name: 'pointsforts' },
{ label: 'Niveau', name: 'level' },
{ label: 'Durée', name: 'duration' },
{ label: 'Lieu', name: 'location' }, //ok
{ label: 'Public', name: 'public' }, //ok
{ label: 'Objectifs', name: 'goal' }, //ok
{ label: 'Prérequis', name: 'prerequisites' }, //ok
{ label: 'Nom du formateur', name: 'formateurName' },
{ label: 'Descritpion du formateur', name: 'formateurDesc' },
{ label: 'Prix HT', name: 'priceHt' },//ok
{ label: 'Programme', name: 'program' }, //ok
// TODO: subtitle
// TODO: modalité pédagogique
// TODO: introduction...
// TODO: format: inter,intra
],
fieldSeparator : ';'
};
var out = fs.createWriteStream("comundi-output.csv", {encoding: 'utf8'})
var readable = es.readArray(items)
readable
.pipe(jsoncsv.csv(options))
.pipe(out)
})();
<file_sep>const chrono = require('chrono-node');
console.log(chrono.fr.parseDate('Du 07 au 08 février 2019'));
var Sherlock = require('sherlockjs');
var sherlocked1 = Sherlock.parse('Homework 5 due next monday at 3pm');
var sherlocked2 = Sherlock.parse('Du 07 au 08 février 2019');
console.log(sherlocked1)
console.log(sherlocked2)
| ddd8d9983fc0500a763f6c7f111d1c287725374e | [
"JavaScript"
] | 4 | JavaScript | kevinpiac/scraping-sym | 2207f46665d534680bd8970fe6805b4a5dae5c75 | 9b2875028b4684bd012267d09602b278b192b848 |
refs/heads/master | <file_sep>import requests
api_key="<KEY>"
def news():
main_url="http://newsapi.org/v2/top-headlines?country=in&category=business&apiKey="+api_key
news=requests.get(main_url).json()
#print(news)
article=news["articles"]
#print(article)
news_article=[]
for arti in article:
news_article.append(arti["title"])
print(news_article)
for i in range(5): #for 5 news
print(i+1,news_article[i]) #for numbering in news
#for i in range(len(news_article)):
# print(news_article[i])
news()
| a5c44426a1fa10b3423e4171b54b93d9ad5df19d | [
"Python"
] | 1 | Python | amrat014/Display_News_Python | d25b5bd147d5597fae7d24d680a271a02e745f6c | 0f619b22f8673f11916d0c0961f770eb104553a8 |
refs/heads/master | <file_sep>
cc.Class({
extends: cc.Component,
properties: {
totoalTime: 0,
leftTime:{
get () {
return this._time;
},
},
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
this._curScene = this.getComponent("Scene");
// cc.log("==============_curScene", this._curScene);
this._time = this.totoalTime;
},
start () {
},
update (dt) {
if (this._time <= 0 || this._curScene.status != 0) return;
this._time -= dt;
},
// End LIFE-CYCLE CALLBACKS:
timeStr(){
return cc.js.formatStr("%s:%s", this.zeroize(parseInt(this._time/60)) , this.zeroize(parseInt(this._time%60)))
},
zeroize(value, length){
if (!length) {
length = 2;
}
value = value + "";
for (var i = 0, zeros = ''; i < (length - value.length); i++) {
zeros += '0';
}
return zeros + value;
},
});
<file_sep>// Learn cc.Class:
// - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
// - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
// - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
// - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
// - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
cc.Class({
extends: cc.Component,
properties: {
id:0,
// 移动速度,敏捷
maxSpeed:0,
// 加速度
accel:0,
// 小短腿根据不同场景对象的优先级进行反应
priority:0,
// 是否有效
aviable: true,
// 0不受影响 1增益 2减益
effectByCourage:0,
//惊吓消耗体力
scaredCostPower:0,
//惊吓后退距离
scaredBackDis:10,
aliveTime:5,
scene: {
get() {
return this._scene;
},
}
},
onLoad () {
// 注冊到scene
this._scene = cc.find("scene").getComponent("Scene");
this._scene.register(this);
},
start(){
if (this.aliveTime > 0) {
var self = this;
this.scheduleOnce(function(){
self.node.destroy()
}, this.aliveTime )
}
},
onDestroy(){
this._scene.unregister(this);
}
});
<file_sep>
var SceneStatus = {
idle : 0,
success : 1,
failed :2,
pause: 3,
}
// 关卡对象,负责管理关卡中的进程以及保存关卡相关信息
cc.Class({
extends: cc.Component,
properties: {
// 场景物件
objs:{
get(){
return this._objs;
},
},
status: {
get(){
return this._status;
},
}
},
// TODO 关卡初始化工作
onLoad () {
this._objs = {};
this._status = SceneStatus.idle;
},
start () {
this.timer = this.getComponent("timer");
},
update (dt) {
if (this.timer.leftTime <= 0 && this._status == SceneStatus.idle) {
this.gameOver();
}
},
register(obj) {
this._objs[obj.id] = obj;
},
unregister(obj) {
this._objs[obj.id] = null;
delete this._objs[obj.id];
},
gameOver(){
this._status = SceneStatus.failed;
cc.log("GameOver==============")
},
});
| 45d8f6c1a05d3f47d7a1e1ed58ebdf619eefe35d | [
"JavaScript"
] | 3 | JavaScript | moohyeah/Moyer | 7ece7b8e45346bc7afd4d5f2f03cdf13369ed4e1 | 5ead14d19a25a20bcb9c706d750eae89b4cccc0a |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { SessionActions } from '../../core/actions';
import { select } from '@angular-redux/store';
import {Observable} from 'rxjs/Observable';
import { IMessage } from "../../core/store/session";
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
returnUrl: string;
@select(['session', 'isLoading']) isLoading$: Observable<boolean>;
@select(['session', 'token']) loggedIn$: Observable<string>;
@select(['session', 'hasMessage']) hasMessage$: Observable<IMessage>;
form: FormGroup;
constructor(
private route: ActivatedRoute,
private router: Router,
private actions: SessionActions) {
this.form = this._buildForm();
}
ngOnInit() {
// reset login status
// this.actions.logoutUser();
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
this.loggedIn$.subscribe(
isLoggedIn => {
if (isLoggedIn) {
this.router.navigate([this.returnUrl]);
}
},
error => {
console.log("fail to check login");
this.actions.logoutUser();
});
}
login(formCredentials) {
this.actions.loginUser(formCredentials);
}
private _buildForm() {
return new FormGroup({
usernameOrEmail: new FormControl('', Validators.required),
password: new FormControl('', Validators.required)
});
}
static isLoggedOut(s){ return !s.session.token; }
}
<file_sep>import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { ConnectionBackend, RequestOptions, Request, RequestOptionsArgs, Response, Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { select } from '@angular-redux/store';
import { SessionActions } from 'app/core';
@Injectable()
export class InterceptedHttp extends Http {
@select(['session', 'token']) Token$: Observable<boolean>;
token = null;
constructor(private backend: ConnectionBackend, private defaultOptions: RequestOptions,
private router: Router, private actions: SessionActions) {
super(backend, defaultOptions);
this.Token$.subscribe(token => {
this.token = token;
});
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, this.setRequestOptionArgs(url, options))
.catch<Response, Response>(err => this.handelErrorResponse(err, this.actions, this.router));
}
private setRequestOptionArgs(url: string | Request, options?: RequestOptionsArgs): RequestOptionsArgs {
if (options == null) {
options = new RequestOptions();
}
if (url instanceof Request) {
options.headers = url.headers;
} else if (options.headers == null) {
options.headers = new Headers();
}
options.headers.append('Content-Type', 'application/json');
if (this.token != null){
options.headers.append('Authorization', 'JWT ' + this.token);
}
return options;
}
private handelErrorResponse(error: any, actions: SessionActions, router: Router): Observable<any> {
switch (error.status) {
case 400:
router.navigate(['/bad-request']);
return Observable.of();
case 401:
actions.logoutUser();
router.navigate(['/']);
return Observable.of();
case 404:
router.navigate(['/not-found']);
return Observable.of();
}
return Observable.throw(error);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { select } from '@angular-redux/store';
import {Observable} from 'rxjs/Observable';
import {SlidesService} from '../../services/index';
import {Slides} from '../../models/index'
import {NotifBarService} from "app/core";
@Component({
selector: 'app-slides-list',
templateUrl: './slides-list.component.html',
styleUrls: ['./slides-list.component.scss']
})
export class SlidesListComponent implements OnInit {
@select(['session', 'token']) loggedIn$: Observable<string>;
private states = ['All', 'Private', 'Public'];
private selectedState = 'All';
private selectedFavorite = 'All';
private result = {
noResult: false,
noPublish: false,
noSlides: false,
noPrivate: false
};
private toSearch = {
title: '',
filter: 'All',
favorite: 'All'
};
private slides: Array<Slides> = [];
constructor(
private slidesService: SlidesService,
private notifBarService:NotifBarService
) { }
ngOnInit() {
this.slidesService.getSlidesList()
.subscribe(
slide => {
this.slides = slide;
this.result = this.calculResult(this.slides.length, this.toSearch.filter, this.toSearch.title);
},
error => {
this.notifBarService.showNotif("fail to load slides list");
});
}
search(paramsTosearch) {
//get search result
this.toSearch.title = paramsTosearch || '';
this.slidesService.getSlideToSearch(this.toSearch)
.subscribe(slides => {
this.slides = [];
this.slides = slides;
this.result = this.calculResult(this.slides.length, this.toSearch.filter, this.toSearch.title)
});
}
fState(state) {
this.toSearch.filter = state;
this.slidesService.getSlideToSearch(this.toSearch)
.subscribe(slides => {
this.slides = [];
this.slides = slides;
this.result = this.calculResult(this.slides.length, this.toSearch.filter, this.toSearch.title)
});
}
refreshList() {
this.slidesService.getSlideToSearch(this.toSearch)
.subscribe(slides => {
this.slides = [];
this.slides = slides;
this.result = this.calculResult(this.slides.length, this.toSearch.filter, this.toSearch.title);
});
}
calculResult(slidesLength, state, title) {
if (slidesLength === 0) {
if (title === "") {
if (state === "All") {
return { noResult: false, noPublish: false, noSlides: true, noPrivate: false };
} else if (state === "Public") {
return { noResult: false, noPublish: true, noSlides: false, noPrivate: false };
} else if (state === "Private") {
return { noResult: false, noPublish: false, noSlides: false, noPrivate: true };
}
} else {
return { noResult: true, noPublish: false, noSlides: false, noPrivate: false };
}
}
return { noResult: false, noPublish: false, noSlides: false, noPrivate: false };
}
fFavorite(isFavorite) {
this.toSearch.favorite = isFavorite;
this.slidesService.getSlideToSearch(this.toSearch)
.subscribe(slides => {
this.slides = [];
this.slides = slides;
this.result = this.calculResult(this.slides.length, this.toSearch.filter, this.toSearch.title)
});
}
}
<file_sep>export * from './chart.class';
export * from './bar-chart/bar-chart.component';
export * from './force-directed-graph/force-directed-graph.component';
export * from './line-chart/line-chart.component';
export * from './hierarchical-edge-bundling/hierarchical-edge-bundling.component';
export * from './ngx-charts';
export * from './pie-chart';
export * from './bubble-chart';
export * from './word-cloud';
export * from './dendogram/dendogram.component';
export * from './zoomable-treemap-chart/zoomable-treemap-chart.component';
export * from './sunburst-chart/sunburst-chart.component';
<file_sep>import * as createLogger from 'redux-logger';
import { IAppState, rootReducer, deimmutify, reimmutify } from './store';
import { ISessionRecord } from './session';
import * as adapter from 'redux-localstorage/lib/adapters/localStorage';
import persistState, {mergePersistedState} from 'redux-localstorage';
import {compose, createStore} from 'redux';
export {
IAppState,
ISessionRecord,
rootReducer,
reimmutify,
};
let storage = compose(
)(adapter(window.localStorage));
export let middleware = [];
export let enhancers = [
persistState(storage,"redux-localstorage",()=>{})
];
middleware.push(
createLogger({
level: 'info',
collapsed: true,
stateTransformer: deimmutify,
}));
<file_sep>import { Component, OnInit, Input, ViewChild, ViewChildren } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Slide } from "../../../../models";
import { PageConfig, FULL_LAYOUT } from "../../pageConfig";
import { Chart } from "../../../../../charts/chart.class";
@Component({
selector: 'app-text-slide',
templateUrl: './text-slide.component.html',
styleUrls: ['./text-slide.component.scss']
})
export class TextSlideComponent implements OnInit {
@Input() slide: Slide;
private config: PageConfig;
constructor() { }
ngOnInit() {
this.setConfig();
}
private setConfig() {
this.config = new PageConfig();
Object.assign(this.config, FULL_LAYOUT);
this.config.hasText = true;
if (this.slide.pageLayout === 'textInCenterImageBackground') {
this.config.hasImage = true;
}
}
}
<file_sep>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
// APP COMPONENTS
import { Auth } from './users';
import { HomeComponent } from "./home";
import { BadRequestPageComponent, NotFoundPageComponent } from "./core";
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'user', loadChildren: 'app/users/users.module#UsersModule' },
{ path: 'slides', loadChildren: 'app/slides/slides.module#SlidesModule' },
// otherwise redirect to home
{ path: 'bad-request', component: BadRequestPageComponent, data: { title: 'Bad-request' } },
{ path: 'not-found', component: NotFoundPageComponent, data: { title: 'Not-Found' } },
{ path: '**', redirectTo: 'not-found' }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes, { useHash: true })
],
exports: [
RouterModule
],
providers: [
Auth
]
})
export class AppRoutingModule { }
<file_sep>import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { combineEpics } from 'redux-observable';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/catch';
import { Action } from 'redux';
import { environment } from '../../../environments/environment';
import { IPayloadAction, SessionActions } from 'app/core';
@Injectable()
export class SessionEpics {
_baseUrl : string ;
constructor(private http: Http) {
this._baseUrl = `${environment.backend.protocol}://${environment.backend.host}`;
if (environment.backend.port) {
this._baseUrl += `:${environment.backend.port}`;
}
}
login = (action$: Observable<IPayloadAction>) => {
return action$
.filter<IPayloadAction>(({ type }) => type === SessionActions.LOGIN_USER)
.mergeMap<IPayloadAction, IPayloadAction>(({ payload }) => {
const backendURL = `${this._baseUrl}${environment.backend.endpoints.signin}` ;
return this.http.post(backendURL, payload)
.map<Response, IPayloadAction>(result => ({
type: SessionActions.LOGIN_USER_SUCCESS,
payload: result.json()
}))
.catch(err => Observable.of<IPayloadAction>({
type: SessionActions.LOGIN_USER_ERROR,
payload: { hasMessage: err.json().message }
})
);
});
}
editProfile = (action$: Observable<IPayloadAction>) => {
return action$
.filter<IPayloadAction>(({ type }) => type === SessionActions.PUT_USER)
.mergeMap<IPayloadAction, IPayloadAction>(({ payload }) => {
const backendURL = `${this._baseUrl}${environment.backend.endpoints.users}` ;
return this.http.put(backendURL, payload)
.map<Response, IPayloadAction>(result => ({
type: SessionActions.PUT_USER_SUCCESS,
payload: {user : result.json()}
}))
.catch(err => Observable.of<IPayloadAction>({
type: SessionActions.PUT_USER_ERROR,
payload: { hasMessage: err.json().message }
})
);
});
}
getProfile = (action$: Observable<IPayloadAction>) => {
return action$
.filter<IPayloadAction>(({ type }) => type === SessionActions.GET_USER)
.mergeMap<IPayloadAction, IPayloadAction>(({ payload }) => {
const backendURL = `${this._baseUrl}${environment.backend.endpoints.users}/me` ;
return this.http.get(backendURL)
.map<Response, IPayloadAction>(result => ({
type: SessionActions.GET_USER_SUCCESS,
payload: result.json()
}))
.catch(err => Observable.of<IPayloadAction>({
type: SessionActions.GET_USER_ERROR,
payload: {type : 'echec', message: 'An error occurred'}
}));
});
}
changePassword = (action$: Observable<IPayloadAction>) => {
return action$
.filter<IPayloadAction>(({ type }) => type === SessionActions.CHANGE_PASSWORD)
.mergeMap<IPayloadAction, IPayloadAction>(({ payload }) => {
const backendURL = `${this._baseUrl}${environment.backend.endpoints.users}/password` ;
return this.http.post(backendURL, payload)
.map<Response, IPayloadAction>(result => ({
type: SessionActions.CHANGE_PASSWORD_SUCCESS,
payload: {type : 'success', message: result.json().message}
}))
.catch(err => Observable.of<IPayloadAction>({
type: SessionActions.CHANGE_PASSWORD_ERROR,
payload: {hasMessage: err.json().message}
}));
});
}
}
<file_sep>export const titleAlign: Array<string> = [
"left", "right", "center"
]
export const graphType: Array<any> = [
{
value: "noGraph",
type: "No Graph"
},
{
value: "ngGraph",
type: "Graph builder"
},
{
value: "HierarchicalEdgeBundling",
type: "Hierarchical edge bundling"
},
{
value: "lineChart",
type: "Line Chart"
},
{
value: "advancedPieChart",
type: "Advanced Pie Chart"
},
{
value: "gaugeChart",
type: "Gauge Chart"
},
{
value: "image",
type: "Image"
}];
export const pageLayoutOption: Array<any> = [
{
value: "FullScreenGraph",
type: "Full Screen Graph",
icon: ["fa-area-chart"]
}, {
value: "textInCenter",
type: "Text in Center",
icon: ["fa-align-center"]
},
{
value: "textInCenterImageBackground",
type: "Text + Image Background",
icon: ["fa-picture-o"]
},
{
value: "LeftGraphRightText",
type: "Graph on Left + Text on Right",
icon: [ "fa-area-chart","fa-align-right"]
},
{
value: "LeftTextRightGraph",
type: "Text on Left + Graph on Right",
icon: ["fa-align-left","fa-area-chart" ]
}
];
<file_sep>import { NgModule, APP_INITIALIZER, ModuleWithProviders, Injectable } from '@angular/core';
import { MenuService } from 'app/core';
@Injectable()
export class SlidesConfig {
constructor(private menuService: MenuService) {
}
addMenu() {
this.menuService.addMenuItem('sideNav', {
state: 'slides',
title: 'slides',
icon: 'fa-desktop',
roles: ['*'],
});
}
}
export function slidesFactory(config: SlidesConfig) {
return () => config.addMenu() ;
}
@NgModule({
providers: [ SlidesConfig ]
})
export class SlidesConfigModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SlidesConfigModule,
providers: [{ provide: APP_INITIALIZER, useFactory: slidesFactory, deps: [SlidesConfig], multi: true }]
}
}
}
<file_sep>import { Injectable } from '@angular/core';
import {MenuService} from '../core/services/menu.client.service';
@Injectable()
export class UsersConfig {
constructor(private menuService : MenuService){
}
addMenu(){
this.menuService.addMenuItem('toolBar',{
state: '#/list-users',
title: 'User list',
icon: 'fa-list',
roles: ['admin'],
})
}
}
<file_sep>export * from './menu.client.service';
export * from './toggle-nav.service';
export * from './notif-bar.service';
export * from './interceptor/http.interceptor';
<file_sep>
import { NgModule, CUSTOM_ELEMENTS_SCHEMA, APP_INITIALIZER, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
// MATERIAL DESIGN MODULES
import { MaterialModule, OverlayContainer, TooltipPosition } from '@angular/material';
import { AngularFontAwesomeModule } from 'angular-font-awesome/angular-font-awesome';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import {XHRBackend, RequestOptions} from '@angular/http';
// NGX-CHARTS MODULE
import { PieChartModule, GaugeModule, NgxChartsModule } from '@swimlane/ngx-charts';
import { CodemirrorModule } from 'ng2-codemirror';
// DRAG & DROP MODULE
import { DndModule } from 'ng2-dnd';
// HANDSONTABLE MODULE
import { HotTableModule } from 'ng2-handsontable';
import {SlidesSearchComponent} from './components/slides-list/slides-search/slides-search.component';
// SLIDES COMPONENTS
import { SlidesViewComponent,
FullScreenGraphSlideComponent,
ImageComponent,
TitleSlideComponent,
LeftGraphRightTextSlideComponent,
RightGraphLeftTextSlideComponent,
TextSlideComponent,
SlidesEditorFormComponent,
SlideComponent
} from '.';
// SLIDES SERVICES
import {SlidesService, ValidService, ChartsService} from '.';
// SLIDES ROUTES MODULE
import { SlidesRoutingModule } from '.';
import { CoreModule } from 'app/core';
import { FlexLayoutModule } from '@angular/flex-layout';
import { KeySwitchDirective } from './components/slides-view/key-switch.directive';
import { DragulaModule } from 'ng2-dragula';
import { BarChartComponent } from '../charts';
import { GaugeChartComponent } from '../charts';
import { NgGraphComponent } from '../charts';
import { TreemapChartComponent } from '../charts';
import { ZoomableTreemapChartComponent } from '../charts';
import { PieGridChartComponent } from '../charts';
import { NumberCardComponent } from '../charts';
import { SunburstChartComponent } from '../charts';
import { HierarchicalEdgeBundlingComponent } from '../charts/hierarchical-edge-bundling/hierarchical-edge-bundling.component';
import { AdvancedPieChartComponent } from '../charts';
import { ForceDirectedGraphComponent } from '../charts/force-directed-graph/force-directed-graph.component';
import { LineChartComponent } from '../charts/line-chart/line-chart.component';
import { FroalaEditorModule, FroalaViewModule } from 'angular2-froala-wysiwyg';
import { DendogramComponent } from '../charts/dendogram/dendogram.component';
import { PieChartComponent } from '../charts/pie-chart/pie-chart.component';
import { BubbleChartComponent } from '../charts';
import { WordCloudComponent } from '../charts';
import { AreaChartComponent } from '../charts/ngx-charts/area-chart';
import { ImageUploadComponent } from './components/slides-editor-form/slides-editor/slide/image-upload/image-upload.component';
import { SlidesSettingComponent } from './components/slides-editor-form/slides-editor/slides-setting/slides-setting.component';
import { ChartsBuilderComponent, CodeEditorComponent, DataTableComponent } from './components/slides-editor-form/slides-editor/slide/charts-builder';
import { SlidesEditorComponent } from './components/slides-editor-form/slides-editor/slides-editor.component';
import { SlidesListComponent } from './components/slides-list/slides-list.component';
import { SlidesCardComponent } from './components/slides-list/slides-card/slides-card.component';
import { DeleteDialogComponent } from './components/slides-list/slides-card/delete-dialog/delete-dialog.component';
import { ToggleFullscreenDirective } from './components/slides-view/toggle-fullscreen.directive';
@NgModule({
imports: [
CommonModule,
MaterialModule,
FormsModule,
ReactiveFormsModule,
CoreModule,
SlidesRoutingModule,
DragulaModule,
PieChartModule,
GaugeModule,
NgxChartsModule,
CodemirrorModule,
FlexLayoutModule,
DndModule.forRoot(),
HotTableModule,
FroalaEditorModule.forRoot(),
FroalaViewModule.forRoot()
],
entryComponents: [
BarChartComponent,
LineChartComponent,
ForceDirectedGraphComponent,
HierarchicalEdgeBundlingComponent,
PieChartComponent,
PieGridChartComponent,
NumberCardComponent,
FullScreenGraphSlideComponent,
GaugeChartComponent,
AdvancedPieChartComponent,
DeleteDialogComponent,
DendogramComponent,
NgGraphComponent,
TreemapChartComponent,
ZoomableTreemapChartComponent,
BubbleChartComponent,
WordCloudComponent,
SunburstChartComponent,
AreaChartComponent,
ImageComponent],
declarations: [
KeySwitchDirective,
SlidesViewComponent,
SlidesEditorFormComponent,
SlideComponent,
ImageUploadComponent,
SlidesSearchComponent,
BarChartComponent,
ForceDirectedGraphComponent,
LineChartComponent,
SlidesSettingComponent,
CodeEditorComponent,
DataTableComponent,
ChartsBuilderComponent,
SlidesEditorComponent,
SlidesListComponent,
FullScreenGraphSlideComponent,
GaugeChartComponent,
AdvancedPieChartComponent,
TitleSlideComponent,
LeftGraphRightTextSlideComponent,
RightGraphLeftTextSlideComponent,
TextSlideComponent,
PieChartComponent,
SlidesCardComponent,
HierarchicalEdgeBundlingComponent,
AreaChartComponent,
PieGridChartComponent,
NumberCardComponent,
DeleteDialogComponent,
NgGraphComponent,
TreemapChartComponent,
ZoomableTreemapChartComponent,
DendogramComponent,
BubbleChartComponent,
WordCloudComponent,
SunburstChartComponent,
KeySwitchDirective,
ToggleFullscreenDirective,
ImageComponent
],
exports: [
SlidesCardComponent,
SlidesSearchComponent
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [OverlayContainer, SlidesService, ChartsService]
})
export class SlidesModule {
}
<file_sep>export * from './slides-config.module';
<file_sep>import { Injectable } from '@angular/core';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
@Injectable()
export class ValidService {
validAllSource = new BehaviorSubject<boolean>(false);
validAll$ = this.validAllSource.asObservable();
//validation for all page of slide
validSlideSource = new BehaviorSubject<boolean>(true);
validSlide$ = this.validAllSource.asObservable();
//validation for slides setting
validSettingSource = new BehaviorSubject<boolean>(false);
validSetting$ = this.validSettingSource.asObservable();
//record the validation for all page of slides
unvalidSlideList: Array<number> = [];
constructor() {
}
changeValidStatus() {
if (this.validSlideSource.value && this.validSettingSource.value) {
this.validAllSource.next(true);
}
else {
this.validAllSource.next(false);
}
}
changeSlideValid(status, index, option?) {
/* set the unvalid slide list*/
let find = false;
let find_index = 0;
this.unvalidSlideList.forEach((l, i) => {
if (index == l) {
find = true;
find_index = i;
}
})
/* delete slide option*/
if (option) {
if (option == "DELETE" && find){
this.unvalidSlideList.splice(find_index, 1);
this.unvalidSlideList.forEach((l,i)=>{
if(l>index) this.unvalidSlideList[i]--;
})
}
}
/* normal change*/
else {
if (status == false) {
if (!find) this.unvalidSlideList.push(index);
}
else {
if (find) this.unvalidSlideList.splice(find_index, 1);
}
}
/* check the valid for all pages*/
if (this.unvalidSlideList.length) {
this.validSlideSource.next(false);
}
else {
this.validSlideSource.next(true);
}
this.changeValidStatus();
}
changeSettingValid(status) {
this.validSettingSource.next(status);
this.changeValidStatus();
}
}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {SlideComponent} from './slide/slide.component';
import {SlidesSettingComponent} from './slides-setting/slides-setting.component'
import { SlidesEditorComponent } from './slides-editor.component';
import { DragulaModule, DragulaService } from 'ng2-dragula/ng2-dragula';
import { MaterialModule } from '@angular/material';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {ChartsBuilderComponent} from './slide/charts-builder';
import { ImageUploadComponent } from './slide/image-upload/image-upload.component';
import { DataTableComponent } from '../slides-editor/slide/charts-builder/data-table';
import { CodemirrorModule } from 'ng2-codemirror';
import { DndModule } from 'ng2-dnd';
import { HotTableModule } from 'ng2-handsontable';
import { BarChartComponent, BubbleChartComponent, DendogramComponent, ForceDirectedGraphComponent, HierarchicalEdgeBundlingComponent,
LineChartComponent, PieChartComponent, SunburstChartComponent,
WordCloudComponent, ZoomableTreemapChartComponent, AdvancedPieChartComponent, AreaChartComponent, GaugeChartComponent, NumberCardComponent,
PieGridChartComponent, TreemapChartComponent
} from '../../../../charts';
import { FroalaEditorModule, FroalaViewModule } from 'angular2-froala-wysiwyg';
import { CodeEditorComponent } from './slide/charts-builder/code-editor';
import {NgxChartsModule } from '@swimlane/ngx-charts';
import {ValidService} from '../../../services/valid.service';
import {NotifBarService} from 'app/core';
import { SlidesService } from '../../../services/slides.service';
import {HttpModule} from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
describe('SlidesEditorComponent', () => {
let component: SlidesEditorComponent;
let fixture: ComponentFixture<SlidesEditorComponent>;
let slidesServiceStub = {};
let slidesService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SlidesEditorComponent, CodeEditorComponent, BarChartComponent, BubbleChartComponent, DendogramComponent, ForceDirectedGraphComponent, HierarchicalEdgeBundlingComponent,
LineChartComponent, PieChartComponent, SunburstChartComponent,
WordCloudComponent, ZoomableTreemapChartComponent, AdvancedPieChartComponent, AreaChartComponent, GaugeChartComponent, NumberCardComponent,
PieGridChartComponent, TreemapChartComponent, DataTableComponent, SlideComponent, SlidesSettingComponent, ChartsBuilderComponent, ImageUploadComponent ],
providers: [DragulaService, ValidService, NotifBarService, {provide: SlidesService, useValue:slidesServiceStub }],
imports : [DragulaModule, BrowserAnimationsModule, HttpModule, MaterialModule, NgxChartsModule, CodemirrorModule, DndModule, HotTableModule, FormsModule, ReactiveFormsModule, FroalaEditorModule, FroalaViewModule]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SlidesEditorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
slidesService = TestBed.get(SlidesService);
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component, Input, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import {TooltipPosition} from '@angular/material';
import { Observable } from 'rxjs/Observable';
import { select } from '@angular-redux/store';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import { SessionActions } from '../../actions';
import { IUser } from '../../store/session';
import { ToggleNavService } from '../../services';
@Component({
selector: 'app-toolbar',
templateUrl: './toolbar.component.html',
styleUrls: ['./toolbar.component.scss']
})
export class ToolbarComponent implements OnInit {
title : string;
isToggled: Observable<boolean>;
@Input() titleToolbar: string;
@select(['session', 'token']) loggedIn$: Observable<string>;
@select(['session', 'user']) user$: Observable<IUser>;
constructor(private router: Router,
private activatedRoute: ActivatedRoute,
private actions: SessionActions,
private toggleNavService: ToggleNavService) {}
ngOnInit() {
this.router.events
.filter(event => event instanceof NavigationEnd)
.map(() => this.activatedRoute)
.map(route => {
while (route.firstChild) route = route.firstChild;
return route;
})
.filter(route => route.outlet === 'primary')
.mergeMap(route => route.data)
.subscribe((event) => this.title = event['title'] );
//subscribe toggle service
this.isToggled = this.toggleNavService.toggle$;
}
logout() {
this.actions.logoutUser();
this.router.navigate(['/']);
}
}
<file_sep>import {Component, OnInit, Output, Input, EventEmitter} from '@angular/core';
@Component({
selector: 'app-slides-search',
templateUrl: './slides-search.component.html',
styleUrls: ['./slides-search.component.scss']
})
export class SlidesSearchComponent implements OnInit {
@Output() textSearch: EventEmitter<string> = new EventEmitter();
@Input() kind: string;
@Output() fState = new EventEmitter();
@Input() states = new Array<string>();
@Input() selectedState = '';
@Output() fFavorite = new EventEmitter();
@Input() selectedFavorite = '';
textToSearch: string;
constructor() {
}
onChange(textToSearch) {
if (textToSearch) {
this.textSearch.emit(textToSearch);
} else {
this.textSearch.emit('');
}
}
onChangeState(state) {
this.fState.emit(state);
}
onChangeFavorite(isFavorite) {
this.fFavorite.emit(isFavorite);
}
ngOnInit() { }
}
<file_sep>import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../../environments/environment';
import { Slides } from '../models/index';
import { select } from '@angular-redux/store';
import { IUser } from '../../core/store/session';
@Injectable()
export class SlidesService {
private _baseUrl: string;
private slides: any = {};
private user: any;
private progress$;
private progressObserver;
private progress;
@select(['session', 'user']) user$: Observable<IUser>;
constructor(private http: Http) {
this.progress$ = Observable.create(observer => {
this.progressObserver = observer;
}).share();
this._baseUrl = `${environment.backend.protocol}://${environment.backend.host}`;
if (environment.backend.port) {
this._baseUrl += `:${environment.backend.port}`;
};
this.user$.subscribe(user => {
this.user = {
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
roles: user.roles,
email: user.email
};
});
}
me(): Observable<any> {
const backendURL = `${this._baseUrl}${environment.backend.endpoints.users}/me`;
return this.http.get(backendURL).map((response: Response) => response.json());
}
submitSlides(slides: Slides): Observable<any> {
slides.slidesSetting.author = this.user.username;
const backendURL = `${this._baseUrl}${environment.backend.endpoints.slides}`;
return this.http.post(backendURL, slides).map((response: Response) => response.json());
}
getSlidesList(): Observable<any> {
const params: URLSearchParams = new URLSearchParams();
if (this.user != undefined)
params.set('username', this.user.username);
const backendURL = `${this._baseUrl}${environment.backend.endpoints.search}`;
return this.http.get(backendURL, { search: params }).map((response: Response) => response.json());
}
getSlides(id): Observable<any> {
const backendURL = `${this._baseUrl}${environment.backend.endpoints.slides}/${id}`;
return this.http.get(backendURL).map((response: Response) => response.json());
}
uploadImage(img) {
return Observable.create(observer => {
const backendURL = `${this._baseUrl}${environment.backend.endpoints.images}`
let xhr: XMLHttpRequest = new XMLHttpRequest();
let formData: any = new FormData();
formData.append('file', img);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
// this.progressObserver.next(this.progress);
};
xhr.open('POST', backendURL, true);
xhr.send(formData);
})
}
getImage(id): Observable<any> {
const backendURL = `${this._baseUrl}${environment.backend.endpoints.images}/${id}`;
return this.http.get(backendURL).map((response: Response) => response.json());
}
updateSlide(slide, id): Observable<any> {
const backendURL = `${this._baseUrl}${environment.backend.endpoints.slides}/${id}`;
return this.http.put(backendURL, slide).map((response: Response) => response.json());
}
deleteSlides(id): Observable<any> {
const backendURL = `${this._baseUrl}${environment.backend.endpoints.slides}/${id}`;
return this.http.delete(backendURL).map((response: Response) => response.json());
}
getSlideToSearch(textToSearch): Observable<any> {
const params: URLSearchParams = new URLSearchParams();
params.set('title', textToSearch.title);
params.set('state', textToSearch.filter);
params.set('favorite', textToSearch.favorite);
params.set('username', this.user.username);
const backendURL = `${this._baseUrl}${environment.backend.endpoints.search}`;
return this.http.get(backendURL, { params: params }).map((response: Response) => response.json());
}
}
<file_sep>import { NgModule, CUSTOM_ELEMENTS_SCHEMA, APP_INITIALIZER } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
// MATERIAL DESIGN MODULES
import { MaterialModule, OverlayContainer } from '@angular/material';
// HOME COMPONENT
import { HomeComponent } from '.';
// HOME CONFIG
import { HomeConfig } from '.';
// SLIDES MODULE
import { SlidesModule } from 'app/slides';
import { FlexLayoutModule } from '@angular/flex-layout';
export function homeFactory(config: HomeConfig) {
return () => config.addMenu();
}
@NgModule({
imports: [
FormsModule,
MaterialModule,
CommonModule,
FlexLayoutModule,
SlidesModule
],
declarations: [
HomeComponent
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [HomeConfig, OverlayContainer,
{ provide: APP_INITIALIZER, useFactory: homeFactory, deps: [HomeConfig], multi: true }
],
})
export class HomeModule { }
<file_sep>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
// SLIDES COMPONENTS
import { SlidesViewComponent, SlidesEditorFormComponent, SlidesListComponent} from '.';
import { Auth } from 'app/users';
const slidesRoutes: Routes = [
{
path: '',
component: SlidesListComponent,
canActivate: [Auth],
data: {
roles: ['*'],
title: 'slides List'
},
pathMatch: 'full'
}, {
path: 'createSlides',
component: SlidesEditorFormComponent,
data: { title: 'Slides Creator' }
}, {
path: 'slides/:id',
component: SlidesEditorFormComponent,
data: {
roles: ['user'],
title: 'Slides Editor'
}
}, {
path: 'slidesPresentation/:id',
component: SlidesViewComponent,
data: { title: 'Presentation' }
}
];
@NgModule({
imports: [
RouterModule.forChild(slidesRoutes)
],
exports: [
RouterModule
]
})
export class SlidesRoutingModule { }
<file_sep>import { Action } from 'redux';
import { Injectable } from '@angular/core';
import { NgRedux } from '@angular-redux/store';
import { IAppState } from 'app/core';
@Injectable()
export class SessionActions {
static LOGIN_USER = 'LOGIN_USER';
static LOGIN_USER_SUCCESS = 'LOGIN_USER_SUCCESS';
static LOGIN_USER_ERROR = 'LOGIN_USER_ERROR';
static LOGOUT_USER = 'LOGOUT_USER';
static PUT_USER = 'PUT_USER';
static PUT_USER_SUCCESS = 'PUT_USER_SUCCESS';
static PUT_USER_ERROR = 'PUT_USER_ERROR';
static GET_USER = 'GET_USER';
static GET_USER_SUCCESS = 'GET_USER_SUCCESS';
static GET_USER_ERROR = 'GET_USER_ERROR';
static CHANGE_PASSWORD = '<PASSWORD>';
static CHANGE_PASSWORD_SUCCESS ='CHANGE_PASSWORD_SUCCESS';
static CHANGE_PASSWORD_ERROR = 'CHANGE_PASSWORD_ERROR';
static GET_USERS ='GET_USERS';
static GET_USERS_SUCCESS ='GET_USERS_SUCCESS';
static GET_USERS_ERROR ='GET_USERS_ERROR'
constructor(private ngRedux: NgRedux<IAppState>) { }
loginUser(credentials) {
this.ngRedux.dispatch({
type: SessionActions.LOGIN_USER,
payload: credentials,
});
};
logoutUser() {
return this.ngRedux.dispatch({ type: SessionActions.LOGOUT_USER });
};
editProfile(user) {
this.ngRedux.dispatch({
type: SessionActions.PUT_USER,
payload: user,
});
}
getProfile() {
this.ngRedux.dispatch({
type: SessionActions.GET_USER,
payload: {}
});
}
changePassword(passwords){
this.ngRedux.dispatch({
type: SessionActions.CHANGE_PASSWORD,
payload: passwords
});
}
}
export interface IPayloadAction extends Action {
payload?: any;
}
<file_sep>import { Injectable } from '@angular/core';
@Injectable()
export class MenuService {
menus= {};
menuToolBar ={};
defaultRoles = ['user', 'admin'];
constructor() {
this.addMenu('sideNav', {
roles: ['*']
}, this.menus);
this.addMenu('toolBar',{
roles : ['*']
}, this.menuToolBar);
}
ngOnInit(){
}
private shouldRender(userRoles, itemMenuRoles) {
if (itemMenuRoles.indexOf('*') !== -1) {
return true;
} else {
if (!userRoles) {
return false;
}
for (var userRoleIndex in userRoles) {
if (userRoles.hasOwnProperty(userRoleIndex)) {
for (var roleIndex in itemMenuRoles) {
if (itemMenuRoles.hasOwnProperty(roleIndex) && itemMenuRoles[roleIndex] === userRoles[userRoleIndex]) {
return true;
}
}
}
}
}
return false;
};
addMenu(menuId, options, menus){
options = options || {};
// Create the new menu
menus[menuId] = {
roles: options.roles || this.defaultRoles,
items: options.items || [],
};
// Return the menu object
return menus[menuId];
};
addMenuItem(menuId, options){
options = options || {};
this.validateMenuExistence(menuId);
if(this.validateMenuItemExistence(options.state, menuId, this.menus)){
if(this.menus[menuId]){
this.menus[menuId].items.push({
title: options.title || '',
state: options.state || '',
icon : options.icon ||'',
type: options.type || 'item',
class: options.class,
roles: ((options.roles === null || typeof options.roles === 'undefined') ? this.defaultRoles : options.roles),
position: options.position || 0,
items: [],
shouldRender: this.shouldRender
});
return this.menus[menuId];
}
}
else if(this.validateMenuItemExistence(options.state, menuId, this.menuToolBar)){
if(this.menuToolBar[menuId]){
this.menuToolBar[menuId].items.push({
title: options.title || '',
state: options.state || '',
icon : options.icon ||'',
type: options.type || 'item',
class: options.class,
roles: ((options.roles === null || typeof options.roles === 'undefined') ? this.defaultRoles : options.roles),
position: options.position || 0,
items: [],
shouldRender: this.shouldRender
});
}
return this.menuToolBar[menuId];
}
};
addSubMenuItem(){};
getMenu(menuId){
this.validateMenuExistence(menuId);
// Return the menu object
return this.menus[menuId]?this.menus[menuId]:this.menuToolBar[menuId];
};
removeMenu(){}
removeMenuItem(){};
removeSubMenuItem(){}
validateMenuExistence(menuId){
if (menuId && menuId.length) {
if (this.menus[menuId] || this.menuToolBar[menuId]) {
return true;
} else {
throw new Error('Menu does not exist');
}
} else {
throw new Error('MenuId was not provided');
}
}
validateMenuItemExistence(state, menuId, menus){
if(menus[menuId])
{
for(var item in menus[menuId].items ){
if(menus[menuId].items[item].state === state)
return false;
}
return true;
}
return false
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from "rxjs";
import { User } from '../models/index';
import { environment } from "../../../environments/environment";
const HEADER = { headers: new Headers({ 'Content-Type': 'application/json' }) };
@Injectable()
export class UsersService {
private _baseUrl : string;
constructor(private http: Http) {
// build backend base url
this._baseUrl = `${environment.backend.protocol}://${environment.backend.host}`;
if (environment.backend.port) {
this._baseUrl += `:${environment.backend.port}`;
}
}
signup(user: User): Observable<any> {
let backendURL = `${this._baseUrl}${environment.backend.endpoints.signup}` ;
return this.http.post(backendURL, user).map((response: Response) => response.json());
}
getProfile (): Observable<any> {
let backendURL = `${this._baseUrl}${environment.backend.endpoints.users}/me` ;
return this.http.get(backendURL).map((response: Response) => response.json());
}
editProfile(user):Observable<any>{
let backendURL = `${this._baseUrl}${environment.backend.endpoints.users}` ;
return this.http.put(backendURL, user).map((response: Response) => response.json());
}
getUsers():Observable<any>{
let backendURL = `${this._baseUrl}${environment.backend.endpoints.users}` ;
return this.http.get(backendURL).map((response: Response) => response.json());
}
}
<file_sep>import { NgModule,CUSTOM_ELEMENTS_SCHEMA, ModuleWithProviders, APP_INITIALIZER } from '@angular/core';
import { CommonModule } from '@angular/common';
// MATERIAL DESIGN MODULES
import { MaterialModule } from '@angular/material';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
// LOGIN COMPONENTS
import { LoginComponent, RegisterComponent, SettingsComponent, ProfileComponent,
PasswordComponent,ListComponent, EqualValidator} from './index';
// LOGIN ROUTES
import { USERS_ROUTES } from './index';
// LOGIN SERVICES
import { UsersConfig, UsersService, Auth, AuthInterceptor } from './index';
export function usersFactory(config: UsersConfig) {
return () => config.addMenu() ;
}
@NgModule({
imports: [
USERS_ROUTES,
MaterialModule,
FormsModule,
ReactiveFormsModule,
CommonModule
],
declarations: [
LoginComponent,
RegisterComponent,
SettingsComponent,
ProfileComponent,
PasswordComponent,
EqualValidator,
ListComponent
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
providers: [ UsersConfig, UsersService,
{ provide: APP_INITIALIZER, useFactory: usersFactory, deps: [UsersConfig], multi: true }
]
})
export class UsersModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: UsersModule,
providers: [Auth, AuthInterceptor]
}
}
}
<file_sep>export * from './models';
export * from './services';
export * from './login';
export * from './register';
export * from './list';
export * from './settings';
export * from './users.route';
export * from './users.config';
export * from './users.module';<file_sep>import { Component, Input, Output, EventEmitter, QueryList, OnChanges, ViewEncapsulation, ViewChildren } from '@angular/core';
import {Slides} from '../../../models/slides';
import {Slide} from '../../../models/slide';
import { DragulaService } from 'ng2-dragula';
import {ValidService} from '../../../services/valid.service';
import {NotifBarService} from 'app/core';
@Component({
selector: 'app-slides-editor',
templateUrl: './slides-editor.component.html',
styleUrls: ['./slides-editor.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class SlidesEditorComponent implements OnChanges {
slider: Slides = new Slides(); // the whole slides
curSlideIndex = 1; // the slide that will be created(the amounts of slides pages +1 )
isValidated = false;
isValidatedSlide = true;
isValidatedSetting = false;
isInShuffle = false;
shuffleOrder: Array<number> = [];
slideOpendIndex: number;
shuffleTransition = {
drag: 0,
drop: 0
};
@Input() sliderIpt: Slides;
@Output() submit = new EventEmitter();
@Output() bannerImageUpload = new EventEmitter();
constructor(private dragulaService: DragulaService, private validService: ValidService, private notifBarService: NotifBarService) {
dragulaService.drag.subscribe(value => {
this.onDrag(value.slice(1));
});
dragulaService.drop.subscribe((value: any) => {
this.onDrop(value.slice(1));
});
dragulaService.over.subscribe((value: any) => {
this.onOver(value.slice(1));
});
dragulaService.out.subscribe((value: any) => {
this.onOut(value.slice(1));
});
}
ngOnChanges() {
if (this.sliderIpt) {
this.slider = this.sliderIpt;
this.curSlideIndex = this.slider.slides.length + 1;
this.isValidated = true;
}
}
/* functions for shuffle slides drop down operation */
private hasClass(el: any, name: string): any {
return new RegExp('(?:^|\\s+)' + name + '(?:\\s+|$)').test(el.className);
}
private addClass(el: any, name: string): void {
if (!this.hasClass(el, name)) {
el.className = el.className ? [el.className, name].join(' ') : name;
}
}
private removeClass(el: any, name: string): void {
if (this.hasClass(el, name)) {
el.className = el.className.replace(new RegExp('(?:^|\\s+)' + name + '(?:\\s+|$)', 'g'), '');
}
}
private onDrag(args: any): void {
let [el] = args;
let index = [].slice.call(el.parentElement.children).indexOf(el);
this.shuffleTransition.drag = index;
this.removeClass(el, 'ex-moved');
}
private onDrop(args: any): void {
let [el] = args;
let index = [].slice.call(el.parentElement.children).indexOf(el)
this.shuffleTransition.drop = index;
// save the changed order
this.shuffleOrder.forEach((order, i) => {
if (this.shuffleTransition.drag < this.shuffleTransition.drop) {
if ((i > this.shuffleTransition.drag || i === this.shuffleTransition.drag) && i < this.shuffleTransition.drop) {
this.shuffleOrder[i]++;
}
if (i === this.shuffleTransition.drop) {
this.shuffleOrder[i] = this.shuffleTransition.drag;
}
} else if (this.shuffleTransition.drag > this.shuffleTransition.drop) {
if ((i < this.shuffleTransition.drag || i === this.shuffleTransition.drag) && i > this.shuffleTransition.drop) {
this.shuffleOrder[i]--;
}
if (i === this.shuffleTransition.drop) {
this.shuffleOrder[i] = this.shuffleTransition.drag;
}
}
});
this.addClass(el, 'ex-moved');
}
private onOver(args: any): void {
let [el] = args;
this.addClass(el, 'ex-over');
}
private onOut(args: any): void {
let [el] = args;
this.removeClass(el, 'ex-over');
}
/* update current slides index*/
openSlideIndex(index) {
this.slideOpendIndex = index;
}
/* trigger when slides setting change*/
slidesSettingChange(setting) {
this.slider.slidesSetting = setting;
}
/* validate status change*/
settingValidateChange(status) {
this.isValidatedSetting = status;
this.checkValid();
}
slideValidateChange(status) {
this.isValidatedSlide = status;
this.checkValid();
}
checkValid() {
if (this.isValidatedSetting && this.isValidatedSlide) {
this.isValidated = true;
} else {
this.isValidated = false;
}
}
/*add a new page of slide*/
addSlide() {
let s = new Slide(this.curSlideIndex++);
this.slider.slides.push(s);
this.isValidatedSlide = false;
this.checkValid();
}
/*submit a new slide*/
submitSlide(slide) {
/* modify slide*/
if (slide.index < this.curSlideIndex) {
/* slide existing */
this.slider.slides[slide.index - 1] = Object.assign({}, slide);
} else {
/* create new slide*/
this.curSlideIndex++;
let s: Slide = Object.assign({}, slide);
s.index = this.curSlideIndex;
this.slider.slides.push(s);
}
}
/* delete a page of slide*/
deleteSlide(index) {
try {
if (index < this.curSlideIndex) {
this.slider.slides.splice(index - 1, 1);
/*change slide index*/
this.slider.slides.forEach(
s => {
if (s.index > index - 1) {
s.index--;
}
}
);
/* slide deleted in local */
this.curSlideIndex--;
}
this.validService.changeSlideValid(true, index, "DELETE");
} catch (err) {
this.notifBarService.showNotif('delete fail : '+err);
}
}
/*change slide order*/
shuffleSlide() {
// save new order
if (this.isInShuffle) {
let slides = Object.assign({}, this.slider.slides);;
this.shuffleOrder.forEach((order, i) => {
this.slider.slides[i] = slides[order];
this.slider.slides[i].index = i + 1;
});
this.isInShuffle = false;
} else {
// start to shuffle
this.shuffleOrder = [];
this.slider.slides.forEach((s, i) => {
this.shuffleOrder.push(i);
});
this.isInShuffle = true;
}
}
/* clear change of shuffle*/
clearShuffle() {
this.isInShuffle = false;
}
}
<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { select } from '@angular-redux/store';
import { Observable } from 'rxjs/Observable';
import { Slides } from '../../../models/slides';
import { SlidesService } from '../../../services/slides.service';
import { MdDialog } from '@angular/material';
import { DeleteDialogComponent} from './delete-dialog/delete-dialog.component';
import {NotifBarService} from 'app/core';
@Component({
selector: 'app-slides-card',
templateUrl: './slides-card.component.html',
styleUrls: ['./slides-card.component.scss']
})
export class SlidesCardComponent implements OnInit {
@Input() slides: Slides;
@Input() editable: boolean; //whether the slides can be edited;
@Output() deletedSlides = new EventEmitter();
@Output() duplicateslidesOpt = new EventEmitter();
@select(['session', 'token']) loggedIn$: Observable<string>;
@select(['session', 'user', 'username']) username$: Observable<Object>;
constructor(private slidesService: SlidesService, private dialog: MdDialog, private notifBarService: NotifBarService) {
}
ngOnInit() {
}
open(e) {
e.stopPropagation();
}
publish(e) {
e.stopPropagation();
this.slides.slidesSetting.public = !this.slides.slidesSetting.public;
this.slidesService.updateSlide(this.slides, this.slides._id)
.subscribe(
elm => this.notifBarService.showNotif("set upload status successfully!"),
error => this.notifBarService.showNotif("fail to set upload status, error is " + error)
);
}
toggleFavorite(e) {
e.stopPropagation();
this.slides.slidesSetting.favorite = !this.slides.slidesSetting.favorite;
this.slidesService.updateSlide(this.slides, this.slides._id)
.subscribe(
elm => this.notifBarService.showNotif("set favorte status successfully!"),
error => this.notifBarService.showNotif("fail to set favorite status, error is " + error)
);
}
/*delete the whole slides*/
deleteSlides(e, id) {
e.stopPropagation();
const dialog = this.dialog.open(DeleteDialogComponent);
dialog.afterClosed().subscribe(result => {
if (result === 'YES') {
this.slidesService.deleteSlides(id)
.subscribe(res => {
this.notifBarService.showNotif("the slides has been deleted successfully!");
this.deletedSlides.emit(id);
},
error => this.notifBarService.showNotif("fail to delete the slides, error is " + error));
}
});
}
/*duplicate slides*/
duplicateSlides(e, slides) {
e.stopPropagation();
let newSlide: Slides = new Slides(slides);
this.slidesService.submitSlides(newSlide)
.subscribe(
data => {
this.duplicateslidesOpt.emit();
this.notifBarService.showNotif("slides has been copied");
},
error => {
this.notifBarService.showNotif("Opps! fail to copy the slides. error :" + error);
});
}
}
<file_sep>import { Component, ViewChild, ElementRef } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { select } from '@angular-redux/store';
import { ToggleNavService, MenuService } from '../../services';
import { IUser } from "../../store/session";
@Component({
selector: 'app-sidenav',
templateUrl: './sidenav.component.html',
styleUrls: ['./sidenav.component.scss'],
})
export class SidenavComponent {
@ViewChild('sidenav') sidenav: ElementRef;
isNormalScreen: boolean = true;
sideNavLock: boolean = false;
isToggled: Observable<boolean>;
// Menu Item
menuList: Array<Object> = [];
@select(['session', 'token']) loggedIn$: Observable<string>;
@select(['session', 'user']) user$: Observable<IUser>;
constructor(private toggleNavService: ToggleNavService, private menuService: MenuService) {
this.menuList =menuService.getMenu('sideNav').items;
//subscribe toggle service
this.isToggled = this.toggleNavService.toggle();
this.clearCookie("pin");
}
ngAfterViewInit() {
var sidenav = this.sidenav.nativeElement;
if (this.getCookie("pin") == "true") {
this.toggleNav();
this.sideNavLock = true;
}
}
/* SideNav toggle operation*/
toggleNav() {
this.toggleNavService.toggle();
}
/* Pin sideNav*/
changePinStatus() {
if (this.getCookie("pin") == "") {
this.setCookie("pin", "true", 365);
this.sideNavLock = true;
} else {
if (this.getCookie("pin") == "true") {
this.setCookie("pin", "false", 365);
this.sideNavLock = false;
this.toggleNav();
} else {
this.setCookie("pin", "true", 365);
this.sideNavLock = true;
}
}
console.log("pin", document.cookie);
}
/*Cookie operation*/
setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
clearCookie(cname) {
this.setCookie("cname", "", -1);
}
}
<file_sep>/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MaterialModule } from '@angular/material';
import { RouterTestingModule } from '@angular/router/testing';
import {SessionActions} from '../../core';
import { RegisterComponent } from './register.component';
import {UsersService} from '../services';
import { NgReduxTestingModule } from '@angular-redux/store/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {HttpModule} from '@angular/http';
describe('RegisterComponent', () => {
let component: RegisterComponent;
let fixture: ComponentFixture<RegisterComponent>;
let usersServiceStub = {};
let usersService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ RegisterComponent ],
imports : [FormsModule, ReactiveFormsModule, MaterialModule, RouterTestingModule, HttpModule, NgReduxTestingModule, BrowserAnimationsModule],
providers: [SessionActions, {provide: UsersService, useValue:usersServiceStub }]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(RegisterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
usersService = TestBed.get(UsersService);
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Injectable } from '@angular/core';
import { MdSnackBar } from '@angular/material';
@Injectable()
export class NotifBarService {
constructor(private snackBar: MdSnackBar) {
}
public showNotif(msg: string) {
this.snackBar.open(msg, null, {
duration: 4000,
});
}
}
<file_sep>/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
import { SlidesModule } from '../slides';
import { RouterTestingModule } from '@angular/router/testing';
import { NgReduxTestingModule, MockNgRedux } from '@angular-redux/store/testing';
import {SessionActions} from '../core';
import { MaterialModule } from '@angular/material';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { SlidesService } from 'app/slides';
import { Observable } from 'rxjs/Observable';
describe('HomeComponent', () => {
class SlidesServiceMock {
getSlideToSearch (): Observable<any> {
return Observable.of([]);
}
}
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HomeComponent],
imports: [
SlidesModule,
RouterTestingModule,
NgReduxTestingModule,
MaterialModule,
BrowserAnimationsModule
],
providers : [ SessionActions,
{provide: SlidesService, useClass : SlidesServiceMock}]
})
.compileComponents();
MockNgRedux.reset();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, AfterViewChecked } from '@angular/core';
import { select } from '@angular-redux/store';
import { Observable } from 'rxjs/Observable';
import { SlidesService } from 'app/slides';
import { Slides } from 'app/slides';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
@select(['session', 'token']) loggedIn$: Observable<string>;
slides: Array<Slides> = [];
showSlidesList: boolean;
noResult: boolean;
noPublish: boolean;
private states: Array<string>;
private selectedValue: string;
private toSearch;
constructor(private slidesService: SlidesService) { }
ngOnInit() {
this.showSlidesList = false;
this.noResult = false;
this.noPublish = false;
this.states = ['Public'];
this.selectedValue = 'Public';
this.toSearch = { title: '', filter: 'Public' };
}
searchSlides(searchText) {
//show slides and hide logo
this.showSlidesList = true;
//get search result
this.toSearch.title = searchText;
this.slidesService.getSlideToSearch(this.toSearch)
.subscribe(slides => {
this.slides = slides;
if (this.slides.length === 0) this.noResult = true;
else {
this.noResult = false;
}
});
}
getAllslides() {
this.showSlidesList = true;
this.toSearch.title = '';
this.slidesService.getSlideToSearch(this.toSearch)
.subscribe(slides => {
this.slides = slides;
if (this.slides.length === 0) {
this.noPublish = true;
} else {
this.noPublish = false;
}
});
}
}
<file_sep>import 'hammerjs';
import { TestBed, async } from '@angular/core/testing';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser'
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { AppComponent } from './app.component';
import { RouterTestingModule } from '@angular/router/testing';
import { NgReduxRouter } from '@angular-redux/router';
import { SessionEpics } from './core/index';
import { ToggleNavService } from './core';
import { HttpModule } from '@angular/http';
import { MaterialModule } from '@angular/material';
import { NgReduxTestingModule, MockNgRedux } from '@angular-redux/store/testing';
import { Observable } from 'rxjs/Observable';
describe('AppComponent', () => {
class SessionEpicsMock {
login = () => {
return Observable.of({
'user': {
'displayName': 'firstname lastname',
'provider': 'local',
'username': 'user01',
'updated': '2017-04-24T11:46:39.663Z',
'resetPasswordExpires': '2017-04-11T08:42:03.959Z',
'resetPasswordToken': '<PASSWORD>',
'created': '2017-03-31T08:55:11.633Z',
'roles': ['admin'],
'profileImageURL': 'modules/users/client/img/profile/default.png',
'email': '<EMAIL>',
'lastName': 'lastname',
'firstName': 'firstname'
}
});
}
}
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
imports: [
BrowserModule,
NgReduxTestingModule,
RouterTestingModule,
HttpModule,
MaterialModule,
BrowserAnimationsModule],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
providers: [
NgReduxRouter,
{ provide: SessionEpics, useClass: SessionEpicsMock },
ToggleNavService]
}).compileComponents();
MockNgRedux.reset();
});
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
}));
});
<file_sep>import { Component, OnInit, ViewChild, AfterViewChecked, ChangeDetectorRef } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ActivatedRoute, Router } from '@angular/router';
import { SlidesService } from '../../services/slides.service';
import { ValidService } from '../../services/valid.service';
import { Slides } from '../../models/slides';
import { SlidesEditorComponent} from './slides-editor/slides-editor.component';
import {NotifBarService} from 'app/core';
@Component({
selector: 'app-slides-editor-form',
templateUrl: './slides-editor-form.component.html',
styleUrls: ['./slides-editor-form.component.scss'],
providers: [SlidesService, ValidService]
})
export class SlidesEditorFormComponent implements OnInit, AfterViewChecked {
id: string = null;
isValidated: boolean;
slider: Slides = new Slides();
@ViewChild('editor') _editor: SlidesEditorComponent;
editorValid: Subscription;
mode = '';
constructor(private router: Router,
private slidesService: SlidesService,
private validService: ValidService,
private route: ActivatedRoute,
private notifBarService: NotifBarService,
private cdRef: ChangeDetectorRef) {}
ngAfterViewChecked() {
this.cdRef.detectChanges();
}
ngOnInit() {
this.route.params.subscribe(params => {
if (params['id']) {
this.id = params['id'];
}
});
if (this.id) {
this.mode = 'SAVE';
this.slidesService.getSlides(this.id)
.subscribe(
slides => {
this.slider = slides;
},
error => {
this.notifBarService.showNotif('fail to load slides list. error is ' + error);
});
} else {
this.mode = 'CREATE';
this.slider = new Slides();
}
this.editorValid = this.validService.validAll$.subscribe(
valid => {
this.isValidated = valid;
});
}
// TODO rework service, rename in presentatiion
saveSlides(id) {
if (id) {
this.slidesService.updateSlide(this.slider, this.slider._id)
.subscribe(
() => {
this.notifBarService.showNotif('your changes in slides has been saved.');
this.router.navigate(['/slides']);
},
error => this.notifBarService.showNotif('fail to save your changes. the error is ' + error));
} else {
this.slider = this._editor.slider;
this.editorValid = this.slidesService.submitSlides(this.slider)
.subscribe(
() => {
this.notifBarService.showNotif('create slides successfully!');
this.router.navigate(['/slides']);
},
error => {
this.notifBarService.showNotif('fail to create slides. the error is '+error);
});
}
}
}
<file_sep>export * from './list.component';
<file_sep>import { Component, OnInit } from '@angular/core';
import { SessionActions } from '../../core/actions';
import { NgRedux } from '@angular-redux/store';
import { IAppState } from '../../core/store';
import {UsersService} from '../services/users.service';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
users = [];
state: Object;
constructor(private usersService: UsersService) {
}
ngOnInit() {
this.usersService.getUsers().subscribe(users => {
this.users = users;
});
}
}
<file_sep>import { Component, OnInit, Input, Output, EventEmitter, ViewChild, OnChanges } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators, FormArray } from '@angular/forms';
import {ValidService} from '../../../../services/valid.service';
import { environment } from '../../../../../../environments/environment';
import * as slideOption from './slideOption';
import { Slide } from '../../../../models/slide';
@Component({
selector: 'app-slide',
templateUrl: './slide.component.html',
styleUrls: ['./slide.component.scss'],
providers: []
})
export class SlideComponent implements OnInit, OnChanges {
@Output() confirmSlideOpt: EventEmitter<Object> = new EventEmitter();
@Output() deleteSlideOpt: EventEmitter<number> = new EventEmitter();
@Input() slideIndex: number;
@Input() slideSetting: Slide;
@Input() slideOpendIndex: number;
@Output() openSlideIndex: EventEmitter<number> = new EventEmitter();
showForm= true; // indicator for showing slide setting
@Input() isInShuffle: boolean;
slide: Slide = new Slide();
form: FormGroup = this._buildForm();
graphs: Array<any>;
pageLayout: Array<any>;
titleAlign: Array<string>;
dataBuilder: any = {};
editorOptions: Object;
@ViewChild('dataInput') dataInputTab;
@ViewChild('graphSelector') graphSelector;
csvJson: any = [];
curTab = 0;
constructor(private _fb: FormBuilder, private validService: ValidService) {
}
ngOnInit() {
if (!this.slide.pageTitle.title) {
this.slide.pageTitle.title = '';
}
this.titleAlign = slideOption.titleAlign;
this.graphs = slideOption.graphType;
this.pageLayout = slideOption.pageLayoutOption;
// set server path
let baseURL = `${environment.backend.protocol}://${environment.backend.host}`;
if (environment.backend.port) {
baseURL += `:${environment.backend.port}`;
};
this.editorOptions = {
heightMin: 200,
heightMax: 400,
charCounterMax: 1000,
toolbarSticky: false,
imageUploadURL: `${baseURL}${environment.backend.endpoints.imagesServer}`,
imageManagerLoadURL: `${baseURL}${environment.backend.endpoints.imagesServer}`
};
}
ngOnChanges() {
if (this.slideSetting) {
this.slide = this.slideSetting;
}
if (this.slideIndex) {
this.slide.index = this.slideIndex;
}
this.form = this._buildForm();
this.validService.changeSlideValid(this.form.valid, this.slideIndex);
this.form.valueChanges.subscribe(data => {
this.validService.changeSlideValid(this.form.valid, this.slideIndex);
});
this.graphChanged();
this.showForm = this.slideIndex === this.slideOpendIndex;
}
private _buildForm() {
return this._fb.group({
pageTitle: new FormControl(this.slide.pageTitle.title, Validators.nullValidator),
titleAlign: new FormControl(this.slide.pageTitle.align, Validators.nullValidator),
slideText: new FormControl(this.slide.text, Validators.nullValidator),
slideGraph: new FormControl(this.slide.graph, Validators.nullValidator),
graphData: this._fb.array([
this.initData(),
])
});
}
/* toggle the slideSetting*/
toggleForm() {
this.slideOpendIndex = null;
this.showForm = !this.showForm;
if (this.showForm) {
this.openSlideIndex.emit(this.slideIndex);
}
}
validChildForm(isValid) {
this.validService.changeSlideValid(isValid, this.slideIndex);
}
confirmSlide(isValid) {
/* to decide which data to take from tab*/
if (this.slide.hasGraph) {
if (this.dataBuilder.chartOptions.chartType
&& this.dataBuilder.chartOptions.chartType.cmpName != null) {
this.slide.graph = this.dataBuilder.chartOptions.chartType.cmpName;
} else {
this.slide.graph = 'ngGraph';
}
this.slide.data = this.dataBuilder.data;
this.slide.config = this.dataBuilder.chartOptions;
} else {
this.slide.graph = 'noGraph';
}
if (!this.slide.hasText) {
this.slide.text = '';
}
if (this.slideIndex) {
this.slide.index = this.slideIndex;
}
this.slide.pageTitle.title = this.form.value.pageTitle;
this.slide.pageTitle.align = this.form.value.titleAlign;
this.csvJson = [];
}
confirmeSlideGRaphConfig(data) {
this.dataBuilder.data = data.data;
this.dataBuilder.chartOptions = data.chartOptions;
}
deleteSlide(e) {
this.deleteSlideOpt.emit(this.slideIndex);
}
initData() {
let dataForm = {
index: [''],
value: ['', Validators.pattern('^[0-9]*$')]
};
return this._fb.group(dataForm);
}
addData() {
const control = <FormArray>this.form.controls['graphData'];
control.push(this.initData());
}
/* when change graph*/
graphChanged() {
// change json sample
// if the slide data is already set
if (this.slide.data !== undefined) {
if (this.slide.data.length && this.form.value.slideGraph == this.slide.graph) {
// if has data, set tab to json
this.curTab = 0;
let data = { 'graphData': this.slide.data };
return;
}
}
}
pageLayoutChange(value) {
switch (value) {
case 'FullScreenGraph':
this.slide.hasGraph = true;
this.slide.hasText = false;
break;
case 'textInCenter': this.slide.hasGraph = false; this.slide.hasText = true; break;
case 'textInCenterImageBackground': this.slide.hasGraph = false; this.slide.hasText = true; break;
case 'LeftGraphRightText': this.slide.hasGraph = true; this.slide.hasText = true; break;
case 'LeftTextRightGraph': this.slide.hasGraph = true; this.slide.hasText = true; break;
default: break;
}
this.slide.pageLayout = value;
}
textAlignChange(value) {
this.slide.textVerAlign = value;
}
/* image background*/
setImageHtml(image) {
this.slide.slideImage = image;
}
/* sort and group series of json data*/
sortSeries(data) {
let newJson = [];
let series = [];
let isInSeries = (name) => {
let index = -1;
for (let i = 0; i < series.length; i++) {
if (name === series[i]) {
index = i;
break;
}
}
return index;
};
data.forEach(obj => {
const seriesIndex = isInSeries(obj['series']);
if (seriesIndex !== -1) {
/* add to series */
newJson[seriesIndex].push(obj);
} else {
/* create new series */
series.push(obj['series']);
const newSeries: Array<any> = [];
newSeries.push(obj);
newJson.push(newSeries);
}
});
return newJson;
}
}
<file_sep>/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { MaterialModule } from '@angular/material';
import { ToolbarComponent } from './toolbar.component';
import { ToggleNavService } from '../..';
import { AngularFontAwesomeModule } from 'angular-font-awesome/angular-font-awesome';
import {SessionActions} from '../..';
import { NgReduxTestingModule } from '@angular-redux/store/testing';
describe('ToolbarComponent', () => {
let component: ToolbarComponent;
let fixture: ComponentFixture<ToolbarComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ToolbarComponent ],
imports : [
RouterTestingModule,
MaterialModule,
AngularFontAwesomeModule,
NgReduxTestingModule],
providers: [ToggleNavService, SessionActions]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ToolbarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { RouterModule, Routes } from '@angular/router';
// APP COMPONENTS
import { SettingsComponent } from './settings/index';
import { LoginComponent, RegisterComponent, ListComponent } from './index';
import { Auth } from './services/auth.service';
const USERSROUTES: Routes = [
{ path: 'login', component: LoginComponent, data : { title : 'Login'} },
{ path: 'register', component: RegisterComponent , canActivateChild: [Auth], data : { title : 'Register'}},
{ path: 'settings/profile', component: SettingsComponent, canActivateChild: [Auth],
data : {
roles : ['user', 'admin'],
title : 'Settings / Profile'
} },
{ path:'list-users', component: ListComponent, canActivateChild: [Auth],
data : {
roles : ['admin'],
title : 'Users List'
}}];
export const USERS_ROUTES = RouterModule.forChild(USERSROUTES);
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { NgRedux, select } from '@angular-redux/store';
import { IAppState } from '../../../core/store';
import { IMessage } from "../../../core/store/session";
import {EqualValidator} from './equal-validator.directive';
import { SessionActions } from '../../../core/actions';
@Component({
selector: 'app-password',
templateUrl: './password.component.html',
styleUrls: ['./password.component.css']
})
export class PasswordComponent implements OnInit {
form: FormGroup;
state :IAppState;
@select(['session', 'isLoading']) isLoading$: Observable<boolean>;
@select(['session', 'hasMessage']) hasMessage$: Observable<IMessage>;
constructor(private actions: SessionActions, private ngRedux: NgRedux<IAppState>) {
this.ngRedux.subscribe(() =>{
this.state = this.ngRedux.getState();
})
this.form = this._buildForm();
}
ngOnInit() {
}
/**
* Function to handle component update
*
* @param record
*/
ngOnChanges(record) {
}
private _buildForm() {
return new FormGroup({
currentPassword: new FormControl('', Validators.required),
newPassword: new FormControl('', Validators.required),
verifyPassword: new FormControl('', Validators.required)
});
}
changePasword(value){
this.actions.changePassword(value);
}
}
<file_sep>import { Component, OnInit, OnChanges } from '@angular/core';
import { FormControl, Validators, FormGroup } from "@angular/forms";
import {UsersService} from '../../index';
import { Observable } from 'rxjs/Observable';
import { select } from '@angular-redux/store';
import { SessionActions } from '../../../core/actions';
import { NgRedux } from '@angular-redux/store';
import { IAppState, ISessionRecord } from '../../../core/store';
import { IUser, IMessage } from "../../../core/store/session";
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit, OnChanges {
form: FormGroup;
private model: any;
state :IAppState;
@select(['session', 'isLoading']) isLoading$: Observable<boolean>;
@select(['session', 'hasMessage']) hasMessage$: Observable<IMessage>;
constructor(private usersService : UsersService,
private actions : SessionActions, private ngRedux: NgRedux<IAppState> ) {
this.ngRedux.subscribe(() =>{
this.state=this.ngRedux.getState();
})
this.form = this._buildForm();
}
/**
* OnInit implementation
*/
ngOnInit() {
this.ngRedux.select(['session','user']).first().subscribe((user: IUser) =>{
var {firstName, lastName, email, username} = this.model = user ;
this.form.patchValue({firstName, lastName, email, username});
this.form.controls['email'].disable();
this.form.controls['username'].disable();
});
}
/**
* Function to handle component update
*
* @param record
*/
ngOnChanges(record) {
if(record.model && record.model.currentValue) {
this.model = record.model.currentValue;
this.form.patchValue(this.model);
}
}
saveProfile(user){
this.actions.editProfile(user);
}
/**
* Function to build our form
*
* @returns {FormGroup}
*
* @private
*/
private _buildForm() {
return new FormGroup({
firstName: new FormControl('', Validators.required),
lastName: new FormControl('', Validators.required),
username: new FormControl('', Validators.required),
email: new FormControl('', Validators.required)
});
}
}
<file_sep>import { Component } from '@angular/core';
import { ToggleNavService } from './core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers: [ToggleNavService]
})
export class AppComponent {
isToggled: boolean;
isNormalScreen = true;
constructor(
private ToggleNavService: ToggleNavService) {
// subscribe toggle service
this.ToggleNavService.toggle().subscribe(toggled => {
this.isToggled = toggled;
});
}
}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ChartsBuilderComponent} from './charts-builder';
import { ImageUploadComponent } from '../slide/image-upload/image-upload.component';
import { SlidesService } from '../../../../services/slides.service';
import { ValidService } from '../../../../services/valid.service';
import {NotifBarService} from 'app/core';
import { MaterialModule } from '@angular/material';
import {DragulaModule , DragulaService} from 'ng2-dragula/ng2-dragula';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { DataTableComponent } from './charts-builder/data-table';
import { CodemirrorModule } from 'ng2-codemirror';
import { DndModule } from 'ng2-dnd';
import { HotTableModule } from 'ng2-handsontable';
import { BarChartComponent, BubbleChartComponent, DendogramComponent, ForceDirectedGraphComponent, HierarchicalEdgeBundlingComponent,
LineChartComponent, PieChartComponent, SunburstChartComponent,
WordCloudComponent, ZoomableTreemapChartComponent, AdvancedPieChartComponent, AreaChartComponent, GaugeChartComponent, NumberCardComponent,
PieGridChartComponent, TreemapChartComponent
} from '../../../../../charts';
import {SlideComponent} from './slide.component';
import { FroalaEditorModule, FroalaViewModule } from 'angular2-froala-wysiwyg';
import { CodeEditorComponent } from './charts-builder/code-editor';
import {NgxChartsModule } from '@swimlane/ngx-charts';
import {HttpModule} from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
describe('SlideComponent', () => {
let component: SlideComponent;
let fixture: ComponentFixture<SlideComponent>;
let slidesServiceStub = {};
let slidesService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SlideComponent, ImageUploadComponent, DataTableComponent, CodeEditorComponent , SlideComponent,
ChartsBuilderComponent, BarChartComponent, BubbleChartComponent, DendogramComponent, ForceDirectedGraphComponent, HierarchicalEdgeBundlingComponent,
LineChartComponent, PieChartComponent, SunburstChartComponent,
WordCloudComponent, ZoomableTreemapChartComponent, AdvancedPieChartComponent, AreaChartComponent, GaugeChartComponent, NumberCardComponent,
PieGridChartComponent, TreemapChartComponent],
imports: [ MaterialModule, BrowserAnimationsModule, HttpModule, ReactiveFormsModule, FroalaEditorModule, FroalaViewModule, DragulaModule, NgxChartsModule, FormsModule, HotTableModule, DndModule, CodemirrorModule],
providers: [{provide: SlidesService, useValue:slidesServiceStub }, ValidService, NotifBarService, DragulaService]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SlideComponent);
component = fixture.componentInstance;
fixture.detectChanges();
slidesService = TestBed.get(SlidesService);
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
// FONT AWESOME
import { AngularFontAwesomeModule } from 'angular-font-awesome/angular-font-awesome';
// MATERIAL DESIGN MODULES
import { MaterialModule, OverlayContainer } from '@angular/material';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { FlexLayoutModule } from '@angular/flex-layout';
import 'hammerjs';
// NGX-CHARTS MODULE
import { NgxChartsModule } from '@swimlane/ngx-charts';
// APP ROUTING
import { AppRoutingModule } from './app-routing.module';
// APP COMPONENTS
import { AppComponent } from ".";
// CORE MODULE
import { CoreModule, StoreModule } from "app/core";
// HOME MODULE
import { HomeModule } from 'app/home';
// SLIDES CONFIG
import { SlidesConfigModule } from 'app/slides';
// USER MODULE
import { UsersModule } from "app/users";
@NgModule({
declarations: [
AppComponent
],
imports: [
ReactiveFormsModule,
FormsModule,
AngularFontAwesomeModule,
MaterialModule,
FlexLayoutModule,
BrowserAnimationsModule,
StoreModule,
CoreModule,
NgxChartsModule,
UsersModule.forRoot(),
SlidesConfigModule.forRoot(),
AppRoutingModule,
HomeModule,
BrowserModule
],
providers: [
OverlayContainer],
bootstrap: [AppComponent]
})
export class AppModule {
// Diagnostic only: inspect router configuration
constructor(router: Router) {
}
}
<file_sep>import { NgModule, CUSTOM_ELEMENTS_SCHEMA, APP_INITIALIZER, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Router } from '@angular/router';
// MATERIAL DESIGN MODULES
import { MaterialModule } from '@angular/material';
import { AngularFontAwesomeModule } from 'angular-font-awesome/angular-font-awesome';
// HTTP PROVIDER
import { HttpModule, Http, XHRBackend, RequestOptions } from "@angular/http";
// CORE COMPONENTS
import { ToolbarComponent, SidenavComponent, NotFoundPageComponent, BadRequestPageComponent } from '.';
// CORE SERVICES
import { SessionActions, MenuService, NotifBarService, ToggleNavService, InterceptedHttp } from '.';
export function httpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router, actions: SessionActions): Http {
return new InterceptedHttp(xhrBackend, requestOptions, router, actions);
}
@NgModule({
imports: [
RouterModule,
AngularFontAwesomeModule,
HttpModule,
MaterialModule,
CommonModule
],
declarations: [
ToolbarComponent,
SidenavComponent,
NotFoundPageComponent,
BadRequestPageComponent
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
providers: [
NotifBarService,
MenuService,
ToggleNavService,
{ provide: Http, useFactory: httpFactory, deps: [XHRBackend, RequestOptions, Router, SessionActions]}
],
exports: [
ToolbarComponent,
SidenavComponent,
NotFoundPageComponent,
BadRequestPageComponent
]
})
export class CoreModule {}
<file_sep>import {actionTypes} from 'redux-localstorage'
import { SessionActions, IPayloadAction } from '../../actions/session.actions';
import { ISessionRecord } from './session.types';
import {
INITIAL_STATE,
INITIAL_USER_STATE,
UserFactory,
} from './session.initial-state';
export const sessionReducer = (
state: ISessionRecord = INITIAL_STATE,
action: IPayloadAction) => {
switch (action.type) {
case SessionActions.LOGIN_USER:
return state.merge({
token: null,
user: INITIAL_USER_STATE,
hasError: false,
isLoading: true
});
case SessionActions.LOGIN_USER_SUCCESS:
return state.merge({
token: action.payload.token,
user: UserFactory(action.payload.user),
hasError: false,
isLoading: false,
hasMessage :null,
actionType : action.type
});
case SessionActions.LOGIN_USER_ERROR:
return state.merge({
token: null,
user: INITIAL_USER_STATE,
hasError: true,
isLoading: false,
hasMessage : action.payload.hasMessage,
actionType : action.type
});
case SessionActions.LOGOUT_USER:
return state.merge({
token: null,
user: INITIAL_USER_STATE,
hasError: false,
isLoading: false,
hasMessage : null,
actionType : null
});
case actionTypes.INIT:
const persistedState = action.payload;
if (persistedState) {
return state.merge({
token: persistedState.session.token,
user: UserFactory(persistedState.session.user),
hasError: persistedState.session.hasError,
isLoading: persistedState.session.isLoading,
});
}
case SessionActions.PUT_USER :
{
return state.merge({
hasMessage: null,
hasError: false,
isLoading: true
});
}
case SessionActions.PUT_USER_SUCCESS:
return state.merge({
user: UserFactory(action.payload.user),
hasMessage : action.payload.hasMessage,
hasError: false,
isLoading: false,
actionType : action.type
});
case SessionActions.PUT_USER_ERROR:
return state.merge({
hasError: true,
isLoading: false,
hasMessage: action.payload.hasMessage,
actionType : action.type
});
case SessionActions.GET_USER:
return state.merge({
hasError: false,
isLoading: false,
hasMessage:null
});
case SessionActions.GET_USER_SUCCESS:
return state.merge({
user: UserFactory(action.payload),
hasError: false,
isLoading: false,
hasMessage:null
});
case SessionActions.GET_USER_ERROR:
return state.merge({
token: null,
user: INITIAL_USER_STATE,
hasError: true,
isLoading: false,
hasMessage:null,
});
case SessionActions.CHANGE_PASSWORD:
return state.merge({
hasError: false,
isLoading: false,
hasMessage:null,
actionType : action.type
});
case SessionActions.CHANGE_PASSWORD_SUCCESS:
return state.merge({
hasMessage : action.payload.hasMessage,
hasError: false,
isLoading: false,
actionType : action.type
});
case SessionActions.CHANGE_PASSWORD_ERROR:
return state.merge({
hasMessage : action.payload.hasMessage,
hasError: true,
isLoading: false,
actionType : action.type
});
default:
return state.merge({
hasMessage: null,
hasError: false,
isLoading: false,
});
}
}
<file_sep>export * from './sidenav';
export * from './toolbar';
export * from './bad-request-page';
export * from './not-found-page';
<file_sep>import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild } from '@angular/router';
import { NgRedux } from '@angular-redux/store';
import { IAppState } from '../../core/store';
@Injectable()
export class Auth implements CanActivate, CanActivateChild{
userRoles = [];
constructor(private ngRedux: NgRedux<IAppState>){}
canActivate(route) {
this.userRoles = JSON.parse(JSON.stringify(this.ngRedux.getState())).session.user.roles;
if (route.data.roles.indexOf('*') !== -1) {
return true;
} else {
if (!this.userRoles) {
return false;
}
for (var userRoleIndex in this.userRoles) {
if (this.userRoles.hasOwnProperty(userRoleIndex)) {
for (var roleIndex in route.data.roles) {
if (route.data.roles.hasOwnProperty(roleIndex) && route.data.roles[roleIndex] === this.userRoles[userRoleIndex]) {
return true;
}
}
}
}
}
return false;
}
canActivateChild(route) {
return this.canActivate(route);
}
}
<file_sep>import { Injectable } from '@angular/core';
import {MenuService} from '../core/services/menu.client.service';
@Injectable()
export class HomeConfig {
constructor(private menuService: MenuService) {
}
addMenu() {
this.menuService.addMenuItem('sideNav', {
state: 'home',
title: 'Home',
icon: 'fa-home',
roles: ['*']
})
}
}
<file_sep># StoryTelling
[](https://travis-ci.org/weareopensource/storytelling)
## Presentation
To add presentation / screenshot ...

## Before You Begin
Before you begin we recommend you read about the basic building blocks that assemble the (backend + frontend) application:
### Front-End
* Angular CLI - The Angular 2 part of this project was generated with [angular-cli](https://github.com/angular/angular-cli) version 1.0.0.
### Back-End
* MongoDB - Go through [MongoDB Official Website](http://mongodb.org/) and proceed to their [Official Manual](http://docs.mongodb.org/manual/), which should help you understand NoSQL and MongoDB better.
* Express - The best way to understand express is through its [Official Website](http://expressjs.com/), which has a [Getting Started](http://expressjs.com/starter/installing.html) guide, as well as an [ExpressJS](http://expressjs.com/en/guide/routing.html) guide for general express topics. You can also go through this [StackOverflow Thread](http://stackoverflow.com/questions/8144214/learning-express-for-node-js) for more resources.
* Node.js - Start by going through [Node.js Official Website](http://nodejs.org/) version 7.7+ and this [StackOverflow Thread](http://stackoverflow.com/questions/2353818/how-do-i-get-started-with-node-js), which should get you going with the Node.js platform in no time.
## Prerequisites
Make sure you have installed all of the following prerequisites on your development machine:
* Git - [Download & Install Git](https://git-scm.com/downloads). OSX and Linux machines typically have this already installed.
* Node.js - [Download & Install Node.js](https://nodejs.org/en/download/) and the npm package manager. If you encounter any problems, you can also use this [GitHub Gist](https://gist.github.com/isaacs/579814) to install Node.js.
* MongoDB - [Download & Install MongoDB](http://www.mongodb.org/downloads), and make sure it's running on the default port (27017).
* Angular-cli - You're going to use the Angular cli to manage your front-end build. Make sure you've installed npm / yarn first, then install angular cli globally using npm:
```bash
$ npm install -g @angular/cli
```
or
```bash
$ yarn global add @angular/cli
```
## Quick Install
To install the dependencies, run this in the application folder from the command-line:
```bash
$ npm install
```
or
```bash
$ yarn install
```
## Running Your Application
To run teh application , you need to start the front-End as serve and the API (back-End) as another nodejs server :
* **Front End** : Run `npm run client` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
* **API** : Run `npm run gulp` for back end server . The API is up on `http://localhost:3000/`.
### Running in Production mode
To run your application with *production* environment configuration:
* **Front End** : Run `npm run prod` to build the project. The build artifacts will be stored in the `server/public/` directory. Use the `--prod` flag for a production build and `--bh` for base href in the `index.html`.
* **API** : Run `npm run gulp` for back end server . The application is up on `http://localhost:3000/`.
## Contributing
We welcome pull requests from the community!
## License
[The MIT License](LICENSE.md)
| 1eae94d4aee0a0ba31ff031a1313d3238cd78503 | [
"Markdown",
"TypeScript"
] | 51 | TypeScript | Vincentyuan/storytelling-1 | c000f248093adabb9d344e46d1a9faa814fa6776 | 6ee0a020d5ec666bc36bac7d44a5da9ea51336a3 |
refs/heads/master | <repo_name>fcogacituam/foris<file_sep>/app/Student.php
<?php
namespace App;
class Student{
public $name;
public $minutes;
public $days;
function __construct(){
}
public function createStudent($name){
$this->name = $this->cleanName($name);
$this->minutes = 0;
$this->days = [];
return $this;
}
public function cleanName($string){
return str_replace( array("\r\n","\r"," ","\n"), "", $string);
}
public function validateAndProcessData($line,$student){
$start = date_create($line[3]);
$end = date_create($line[4]);
if($minutes = $this->validPresence($start,$end)){
$student->minutes += $minutes;
if(!in_array($line[2],(array)$student->days)){ //llenar array de dias
array_push($student->days,$line[2]);
}
}
return $student;
}
private function validPresence($start,$end){
if($this->validateStartAndEndTime($start,$end)){ //validar que fecha de fin sea mayor a la de inicio
$minutes = $this->getMinutes($start,$end);
if(!$this->validatePresenceDuration($minutes)){
return false;
}
}else{
return false;
}
return $minutes;
}
public function validateStartAndEndTime($start,$end){
if($start > $end){
return false;
}
return true;
}
public function getMinutes($start,$end){
$diff= date_diff($end,$start);
$hours= $diff->format('%h');
return ($diff->format('%h')*60) + $diff->format('%i');
}
public function validatePresenceDuration($minutes){
if($minutes < 5){ // ignorar presencias de menos de 5 minutos
return false;
}
return true;
}
}
<file_sep>/tests/FileTest.php
<?php
use PHPUnit\Framework\TestCase;
use App\File;
class FileTest extends TestCase{
public function testFileExist(){
$file = new File('example.txt');
$this->assertTrue($file->fileExist());
}
public function testFileType(){
$file = new File('example.txt');
$this->assertTrue($file->fileType());
}
public function testFileSize(){
$file = new File('example.txt');
$this->assertTrue($file->fileSize());
}
public function testFileConversionToArray(){
$file = new File('example.txt');
$this->assertIsArray($file->convertToArray());
}
}<file_sep>/reporte.php
<?php
require_once 'app/Student.php';
require_once 'app/File.php';
require_once 'app/Report.php';
use App\Report;
$students=[];
if(isset($argv[1])){
$path = $argv[1];
$reporte = new Report();
$reporte->start($path);
}else{
die("Debes ingresar un archivo como parámetro. (php reporte.php <nombre.txt>) \n");
}
?><file_sep>/app/Report.php
<?php
namespace App;
class Report{
public $students;
function __construct(){
$this->students =[];
}
public function start($path){
$file = new File($path);
if($file->validate()){
$lines = $file->convertToArray();
foreach($lines as $line){
if($line && count($line)>0){
if($line[0] == "Student"){
$name = str_replace(array("\r\n","\r"),"",$line[1]);
$this->createStudentIfNotExist($name);
}
else if($line[0] == "Presence"){
$this->processPresence($line);
}
}
}
$this->sortStudents();
$this->printResult();
}
}
private function createStudentIfNotExist($name){
$key = $this->searchForName($name,$this->students);
if(!isset($key)){
$new_student = new Student;
$new_student = $new_student->createStudent($name);
array_push($this->students, (array) $new_student);
}
}
private function searchForName($name, $array) {
$found = false;
$index;
foreach ($array as $key => $val) {
if ($val['name'] === $name) {
$found= true;
$index = $key;
}
}
if($found){
return $index;
}else{
return null;
}
}
private function processPresence($line){
$indexStudent = $this->searchForName($line[1],$this->students);
if(isset($indexStudent)){ //si existe el alumno
$student = new Student();
$this->students[$indexStudent] = (array) $student->validateAndProcessData($line,(object) $this->students[$indexStudent]);
}else{ // Si no existe el alumno, lo creo y proceso los datos
$this->createStudentIfNotExist($line[1]);
$this->processPresence($line);
}
}
private function printResult(){
$out;
foreach($this->students as $student){
$out = "{$student['name']}: {$student['minutes']} minutes ";
if(count($student['days']) > 0){
$out .= "in ". count($student['days']);
if( count($student['days']) == 1){
$out .= " day";
}else if(count($student['days']) > 1){
$out .= " days";
}
}
echo $out."\n";
}
}
private function sortStudents(){
foreach($this->students as $key=> $fila){
$minutes[$key] = $fila['minutes'];
}
array_multisort($minutes,SORT_DESC,$this->students);
}
public function test(){
return "hola mundo";
}
}
<file_sep>/app/File.php
<?php
namespace App;
class File{
private $max_size;
public $path;
public $type;
public $lines;
function __construct($path){
$this->max_size= 2000; // 2 Mb
$this->path = $path;
$this->types= ["txt"];
$this->lines = [];
}
public function validate(){
if($this->fileExist() && $this->fileType() && $this->fileSize()){
return true;
}
return false;
}
public function fileExist(){
if(!file_exists($this->path) && !is_file($this->path)){
die("No existe el archivo {$this->path} \n");
}
return true;
}
public function fileType(){
$ext = pathinfo($this->path, PATHINFO_EXTENSION);
if(!in_array($ext,$this->types) ){
die("El archivo debe tener extensión .txt \n");
}
return true;
}
public function fileSize(){
$size = filesize($this->path)/1000;
if($size > $this->max_size){
die("El archivo no puede ser mayor a 2Mb \n");
}
return true;
}
public function convertToArray(){
$myfile = fopen($this->path, "r") or die("Ups! no se pudo abrir el archivo \n");
while(!feof($myfile)) {
$line = explode(" ",fgets($myfile));
array_push($this->lines, $line);
}
fclose($myfile);
return $this->lines;
}
}
<file_sep>/tests/StudentTest.php
<?php
use PHPUnit\Framework\TestCase;
use App\Student;
class StudentTest extends TestCase{
public function testCleanName(){
$student = new Student();
$this->assertEquals($student->cleanName(" Francisco \r\n"),"Francisco");
}
public function testCreateStudent(){
$student = new Student;
$new_student = $student->createStudent("Francisco");
$this->assertIsObject($new_student,"Not object");
}
public function testStartTimeLessThanEndTime(){
$student = new Student();
$start = "10:00";
$end = "10:01";
$this->assertTrue($student->validateStartAndEndTime($start,$end));
}
public function testValidatePresenceDuration(){
$student = new Student();
$minutes = 6;
$this->assertTrue($student->validatePresenceDuration($minutes));
}
public function testValidateAndProcessData(){
$line = ["Presence","Francisco", 5, "14:00" ,"15:00", "F505"];
$expected = new Student;
$expected->name = "Francisco";
$expected->minutes = 60;
$expected->days = [5];
$student = new Student;
$student->name = "Francisco";
$student->minutes = 0;
$student->days = [];
$this->assertEquals($expected, $student->validateAndProcessData($line,$student));
}
public function testValidateNoInsertPresencesLessThanFiveMin(){
$line = ["Presence","Francisco", 2, "14:00" ,"14:04", "F505"];
$expected = new Student;
$expected->name = "Francisco";
$expected->minutes = 60;
$expected->days = [];
$student = new Student;
$student->name = "Francisco";
$student->minutes = 60;
$student->days = [];
$this->assertEquals($expected, $student->validateAndProcessData($line,$student));
}
}<file_sep>/README.md
# Problema de código en Foris
## SELECCIÓN DE PARADIGMA DE PROGRAMACIÓN
En un principio pensé en utilizar paradigma de programación estructurada, ya que al ser un problema relativamente pequeño, y con un objetivo claro, se puede dividir el código en pequeñas funciones que lo hacen bastante legible y sencillo. Al ir organizando la estructura del proyecto, me di cuenta que habían ciertos componentes que podían transformarse a Clases, para hacer su interacción más intuitiva y escalable, a demás del dato del número de sala; éste me hizo pensar que el problema planteado puede ser sólo una primera entrega de un proyecto más grande, o bien, un módulo de un proyecto que también utilizará el dato de la sala para sacar reportes. Sumado al requerimiento de orientar el desarrollo al testing, se hace mucho más fácil testear una aplicación por los métodos de una clase. Por estas dos razones se decidió orientar a objetos.
## SOBRE EL CÓDIGO
### Instalación
1. Descargar bundle
2. dirigirse a la carpeta donde se desempaquetará: `cd <route/to/path>`
3. inicializar git: `git init`
4. desempaquetar bundle: `git pull <nombre_de_bundle>`
5. Instalar librerías: `composer install`
Ejecutar con `php reporte.php example.txt`, se puede seleccionar otro archivo, utilizando la ruta relativa a la ruta de `reporte.php`.
Para revisar el correcto funcionamiento de las pruebas unitarias: `vendor/bin/phpunit tests/`
El código verifica si se pasa como parámetro algun archivo, verifica que exista, y que su tamaño no exceda los 2Mb.
Si pasa esas validaciones, abre el archivo y lo convierte en un array, luego se comienza a trabajar con las posiciones de ese array.
Si el índice 0 del array de una linea, es Student, entonces el código intentará agregar el nuevo estudiante a un array de estudiantes, si es que no existe previamente. Si el indice 0 es Presence, el código intenta buscar si existe el estudiante en el array de estudiantes, si existe, continúa con el proceso. Si el estudiante no existe, lo crea y continúa con el proceso. Esta decisión se tomó para solventar el problema que se puede generar si hay un Registro Presence del estudiante Pepito, antes que haya un registro `Student Pepito`, de lo contrario, ese registro se perdería.
Siguiendo con el proceso, se toma el día de asistencia y se agrega a un array de días que asiste, este registro se agrega sólo si no existe en el array de días, para saber con exactitud la cantidad de días que asistió. Luego continúa con el cálculo de los minutos asistidos, verifica que el dato de inicio sea menor al dato final, y que la presencia haya sido mayor a 5 minutos, de lo contrario no se agrega ni el día al array de días, ni se suman los minutos al pool de minutos del estudiante.
> Se decidió no omitir las presencias de los días Domingo
Hasta aquí, Una linea `Presence David 5 14:00 15:05 F505` generaría un registro
```
[
"name" => "David",
"minutes" => 65,
"days" => [5]
]
```
Luego de iterar por todas las lineas del archivo, e ir sumando los minutos válidos de cada Estudiante, y haber añadido los días al array de días, se procede al ordenado del array. Una vez ordenados, se imprimen por consola con el formato requerido. | 358c77f954fcfa47ec0c7e3105dbb262746db7d3 | [
"Markdown",
"PHP"
] | 7 | PHP | fcogacituam/foris | baf60e00b5716ded41461ca16e9f1d3bebc13c2b | 314ee332fd66290c285e0ecd547f0e4c83b6c408 |
refs/heads/master | <file_sep>#include "loginwindow.h"
#include "ui_loginwindow.h"
#include"QMessageBox"
#include<QPixmap>
#include<login.h>
LoginWindow::LoginWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::LoginWindow)
{
ui->setupUi(this);
}
LoginWindow::~LoginWindow()
{
delete ui;
}
void LoginWindow::on_LoginButton_clicked()
{
QString username,password;
username = ui->lineEdit_username->text();
password = ui->lineEdit_password->text();
Login user(username,password);
if(user.check(username,password) == 1)
{
MemberMenu menu;
menu.setModal(true);
menu.exec();
}
else if(user.check(username,password) == 0)
{
AdminMenu menu;
menu.setModal(true);
menu.exec();
}
else
{
QMessageBox::warning(this,tr("Error"),tr("Password or useraname is wrong"));
}
}
<file_sep>#ifndef ADMINMENU_H
#define ADMINMENU_H
#include <QDialog>
#include<addmembers.h>
#include<removemembers.h>
#include<addbooks.h>
#include<vrequests.h>
#include<vrecords.h>
namespace Ui {
class AdminMenu;
}
class AdminMenu : public QDialog
{
Q_OBJECT
public:
explicit AdminMenu(QWidget *parent = nullptr);
~AdminMenu();
private slots:
void on_Logout_clicked();
void on_Add_clicked();
void on_Remove_clicked();
void on_Books_clicked();
void on_Requests_clicked();
void on_Record_clicked();
private:
Ui::AdminMenu *ui;
};
#endif // ADMINMENU_H
<file_sep>#ifndef REMOVEMEMBERS_H
#define REMOVEMEMBERS_H
#include <QDialog>
#include<admin.h>
namespace Ui {
class Removemembers;
}
class Removemembers : public QDialog
{
Q_OBJECT
public:
explicit Removemembers(QWidget *parent = nullptr);
~Removemembers();
private slots:
void on_Remove_clicked();
private:
Ui::Removemembers *ui;
};
#endif // REMOVEMEMBERS_H
<file_sep># Library-management-system-UI
A Library Management system desktop application with GUI
<file_sep>#include "vrecords.h"
#include "ui_vrecords.h"
VRecords::VRecords(QWidget *parent) :
QDialog(parent),
ui(new Ui::VRecords)
{
ui->setupUi(this);
}
VRecords::~VRecords()
{
delete ui;
}
void VRecords::on_pushButton_clicked()
{
QString line;
QFile fhandle("/home/sahejpal/LIBRARY/Records.txt");
if(fhandle.open(QIODevice::ReadOnly|QIODevice::Text))
{
QTextStream in(&fhandle);
ui->textBrowser->setText(in.readAll());
}
}
<file_sep>#include "return.h"
#include "ui_return.h"
Return::Return(QWidget *parent) :
QDialog(parent),
ui(new Ui::Return)
{
ui->setupUi(this);
}
Return::~Return()
{
delete ui;
}
void Return::on_pushButton_clicked()
{
bool flag = true;
QString username,name,author;
username = ui->lineEdit_username->text();
name = ui->lineEdit_name->text();
author = ui->lineEdit_author->text();
Member member;
try {
if(ui->lineEdit_username->text().isEmpty() || ui->lineEdit_name->text().isEmpty() || ui->lineEdit_author->text().isEmpty())
throw 1;
} catch (int a) {
QMessageBox::critical(this,tr("Critical!!"),tr(" Please enter all the fields"));
flag = false;
}
if(flag)
{
if(member.Return(username,name,author))
QMessageBox::information(this,tr("Success!"),tr("The book has been returned"));
else
QMessageBox::warning(this,tr("Error"),tr("Book does not exist in the records"));
}
}
<file_sep>#ifndef REQUETS_H
#define REQUETS_H
#include <QDialog>
#include<member.h>
#include<QFile>
#include<QTextStream>
#include"QMessageBox"
namespace Ui {
class Requets;
}
class Requets : public QDialog
{
Q_OBJECT
public:
explicit Requets(QWidget *parent = nullptr);
~Requets();
private slots:
void on_pushButton_clicked();
private:
Ui::Requets *ui;
};
#endif // REQUETS_H
<file_sep>#include "admin.h"
#include<string>
Admin::Admin()
{
;
}
Admin::Admin(QString username)
{
this->username = username;
}
bool Admin::AddMember(QString username)
{
QString Uname, Upass,line;
QStringList list;
QFile fhandle("/home/sahejpal/LIBRARY/Login.txt");
if(fhandle.open(QIODevice::ReadOnly))
{
QTextStream in(&fhandle);
while(!in.atEnd())
{
line = in.readLine();
list = line.split(' ');
Uname = list.value(0);
Upass = list.value(1);
if(Uname == username)
{
return false; }
}
}
QFile file("/home/sahejpal/LIBRARY/Login.txt");
if(file.open(QIODevice::WriteOnly|QIODevice::Append))
{
Upass = username.toUpper();
QTextStream out(&file);
out<<username<<' '<<Upass<<endl;
}
file.close();
return true;
}
bool Admin::RemoveMember(QString username)
{
bool flag = false;
QString temp,line,password;
QStringList list;
QFile fhandle("/home/sahejpal/LIBRARY/Login.txt");
if(fhandle.open(QIODevice::ReadOnly))
{
QTextStream in(&fhandle);
while(!in.atEnd())
{
QFile file("/home/sahejpal/LIBRARY/temp.txt");
line = in.readLine();
list = line.split(' ');
temp = list.value(0);
password = list.value(1);
if(temp == username)
{
flag = true;
continue;
}
else
{
if(file.open(QIODevice::WriteOnly|QIODevice::Append))
{
QTextStream out(&file);
out<<temp<<' '<<password<<endl;
}
}
file.close();
}
}
fhandle.close();
remove("/home/sahejpal/LIBRARY/Login.txt");
rename("/home/sahejpal/LIBRARY/temp.txt","/home/sahejpal/LIBRARY/Login.txt");
return flag;
}
bool Admin::AddBooks(QString name,QString author)
{
bool flag = false;
QString temp,temp2,line;
int number;
QStringList list;
name = name.toUpper();
author = author.toUpper();
QFile fhandle("/home/sahejpal/LIBRARY/Books.txt");
if(fhandle.open(QIODevice::ReadOnly))
{
QTextStream in(&fhandle);
while(!in.atEnd())
{
line = in.readLine();
list = line.split(':');
temp = list.value(0);
temp2 = list.value(1);
number = (list.value(2)).toInt();
QFile file("/home/sahejpal/LIBRARY/temp.txt");
QTextStream out(&file);
if(name == temp)
{
QFile file("/home/sahejpal/LIBRARY/temp.txt");
QTextStream out(&file);
number = number+1;
if(file.open(QIODevice::Append))
{
out<<temp<<':'<<temp2<<':'<<number<<endl;
flag = true;
}
file.close();
}
else
{
QFile file("/home/sahejpal/LIBRARY/temp.txt");
QTextStream out(&file);
if(file.open(QIODevice::Append))
out<<temp<<':'<<temp2<<':'<<number<<endl;
}
file.close();
}
}
fhandle.close();
QFile file("/home/sahejpal/LIBRARY/temp.txt");
QTextStream out(&file);
if(!flag && file.open(QIODevice::Append))
{
out<<name<<':'<<author<<':'<<'1'<<endl;
flag = false;
}
file.close();
remove("/home/sahejpal/LIBRARY/Books.txt");
rename("/home/sahejpal/LIBRARY/temp.txt","/home/sahejpal/LIBRARY/Books.txt");
return flag;
}
<file_sep>#include "issue.h"
#include "ui_issue.h"
#include"QMessageBox"
Issue::Issue(QWidget *parent) :
QDialog(parent),
ui(new Ui::Issue)
{
ui->setupUi(this);
}
Issue::~Issue()
{
delete ui;
}
void Issue::on_View_clicked()
{
QString line;
QFile fhandle("/home/sahejpal/LIBRARY/Books.txt");
if(fhandle.open(QIODevice::ReadOnly|QIODevice::Text))
{
QTextStream in(&fhandle);
ui->textBrowser->setText(in.readAll());
}
}
void Issue::on_pushButton_clicked()
{
QString name,username;
bool flag = true;
name = ui->lineEdit_name->text();
username = ui->lineEdit_username->text();
Member issue;
try {
if(ui->lineEdit_name->text().isEmpty())
throw 1;
} catch (int a) {
QMessageBox::critical(this,tr("Critical!"),tr("Enter the name"));
flag = false;
}
if(flag)
{
if(issue.Issue(username,name))
QMessageBox::information(this,tr("Sucess"),tr("The book has been issued"));
else
QMessageBox::warning(this,tr("Error"),tr("The book is not avaiable"));
}
}
<file_sep>#include "vrequests.h"
#include "ui_vrequests.h"
#include<QFile>
#include<QTextStream>
VRequests::VRequests(QWidget *parent) :
QDialog(parent),
ui(new Ui::VRequests)
{
ui->setupUi(this);
}
VRequests::~VRequests()
{
delete ui;
}
void VRequests::on_pushButton_clicked()
{
QString line,name,author;
QStringList list;
QFile fhandle("/home/sahejpal/LIBRARY/Requests.txt");
if(fhandle.open(QIODevice::ReadOnly|QIODevice::Text))
{
QTextStream in(&fhandle);
ui->textBrowser->setText(in.readAll());
}
fhandle.close();
}
<file_sep>#ifndef ADDMEMBERS_H
#define ADDMEMBERS_H
#include <QDialog>
#include"admin.h"
namespace Ui {
class AddMembers;
}
class AddMembers : public QDialog
{
Q_OBJECT
public:
explicit AddMembers(QWidget *parent = nullptr);
~AddMembers();
private slots:
void on_pushButton_clicked();
private:
Ui::AddMembers *ui;
};
#endif // ADDMEMBERS_H
<file_sep>#include "changepassword.h"
#include "ui_changepassword.h"
#include"QMessageBox"
ChangePassword::ChangePassword(QWidget *parent) :
QDialog(parent),
ui(new Ui::ChangePassword)
{
ui->setupUi(this);
}
ChangePassword::~ChangePassword()
{
delete ui;
}
void ChangePassword::on_pushButton_clicked()
{
QString username,pass,pass2;
bool flag = true;
username = ui->lineEdit_username->text();
pass = ui->lineEdit_pass->text();
pass2 = ui->lineEdit_pass2->text();
Member password;
try {
if(ui->lineEdit_username->text().isEmpty() || ui->lineEdit_pass->text().isEmpty()||ui->lineEdit_pass2->text().isEmpty())
throw 1;
} catch (int a) {
QMessageBox::critical(this,tr("Critical!!"),tr("Please enter all the fields"));
flag = false;
}
if(flag)
{
if(pass == pass2)
{
if(password.ChangePassword(username,pass))
ui->Status->setText("Password has been Changed");
else
ui->Status->setText("User doesn't exist");
}
else
QMessageBox::warning(this,tr("Warning!!"),tr("The passwords don't match"));
}
}
<file_sep>#ifndef VRECORDS_H
#define VRECORDS_H
#include <QDialog>
#include<QFile>
#include<QTextStream>
namespace Ui {
class VRecords;
}
class VRecords : public QDialog
{
Q_OBJECT
public:
explicit VRecords(QWidget *parent = nullptr);
~VRecords();
private slots:
void on_pushButton_clicked();
private:
Ui::VRecords *ui;
};
#endif // VRECORDS_H
<file_sep>#include "member.h"
Member::Member()
{
;
}
bool Member::ChangePassword(QString username, QString password)
{
QString Uname, Upass,line;
bool flag =false;
QStringList list;
QFile fhandle("/home/sahejpal/LIBRARY/Login.txt");
if(fhandle.open(QIODevice::ReadOnly))
{
QTextStream in(&fhandle);
while(!in.atEnd())
{
QFile file("/home/sahejpal/LIBRARY/temp.txt");
line = in.readLine();
list = line.split(' ');
Uname = list.value(0);
Upass = list.value(1);
if(Uname == username)
{
if(file.open(QIODevice::WriteOnly|QIODevice::Append))
{
QTextStream out(&file);
out<<username<<' '<<password<<endl;
flag = true;
}
file.close();
}
else
{
QFile file("/home/sahejpal/LIBRARY/temp.txt");
QTextStream out(&file);
if(file.open(QIODevice::Append))
out<<Uname<<' '<<Upass<<endl;
}
file.close();
}
}
fhandle.close();
remove("/home/sahejpal/LIBRARY/Login.txt");
rename("/home/sahejpal/LIBRARY/temp.txt","/home/sahejpal/LIBRARY/Login.txt");
return flag;
}
void Member::Record(QString username, QString name)
{
QFile fhandle("/home/sahejpal/LIBRARY/Records.txt");
if(fhandle.open(QIODevice::WriteOnly|QIODevice::Append))
{
QTextStream out(&fhandle);
out<<username<<'-'<<name<<endl;
}
}
bool Member::Issue(QString username,QString name)
{
bool flag = false;
QString temp,author,line;
int number;
QStringList list;
name = name.toUpper();
QFile fhandle("/home/sahejpal/LIBRARY/Books.txt");
if(fhandle.open(QIODevice::ReadOnly))
{
QTextStream in(&fhandle);
while(!in.atEnd())
{
line = in.readLine();
list = line.split(':');
temp = list.value(0);
author = list.value(1);
number = (list.value(2)).toInt();
QFile file("/home/sahejpal/LIBRARY/temp.txt");
QTextStream out(&file);
if(name == temp)
{
if(number > 0)
{
QFile file("/home/sahejpal/LIBRARY/temp.txt");
QTextStream out(&file);
number = number-1;
if(file.open(QIODevice::Append))
{
out<<temp<<':'<<author<<':'<<number<<endl;
flag = true;
Record(username,name);
}
file.close();
}
else
return false;
}
else
{
QFile file("/home/sahejpal/LIBRARY/temp.txt");
QTextStream out(&file);
if(file.open(QIODevice::Append))
out<<temp<<':'<<author<<':'<<number<<endl;
}
file.close();
}
}
fhandle.close();
remove("/home/sahejpal/LIBRARY/Books.txt");
rename("/home/sahejpal/LIBRARY/temp.txt","/home/sahejpal/LIBRARY/Books.txt");
return flag;
}
bool Member::Return(QString username, QString name,QString author)
{
name = name.toUpper();
author = author.toUpper();
bool flag = false;
QString Uname,line,Ubook;
QStringList list;
QFile fhandle("/home/sahejpal/LIBRARY/Records.txt");
if(fhandle.open(QIODevice::ReadOnly))
{
QTextStream in(&fhandle);
while(!in.atEnd())
{
QFile file("/home/sahejpal/LIBRARY/temp2.txt");
line = in.readLine();
list = line.split('-');
Uname = list.value(0);
Ubook = list.value(1);
if(Uname == username && Ubook == name)
{
Member member;
member.AddBooks(name,author);
flag = true;
}
else
{
QTextStream out(&file);
if(file.open(QIODevice::Append))
{
out<<Uname<<'-'<<Ubook<<endl;
}
}
file.close();
}
}
fhandle.close();
remove("/home/sahejpal/LIBRARY/Records.txt");
rename("/home/sahejpal/LIBRARY/temp2.txt","/home/sahejpal/LIBRARY/Records.txt");
return flag;
}
<file_sep>#ifndef LOGIN_H
#define LOGIN_H
#include<iostream>
#include<QString>
#include<QFile>
class Login
{
QString username,password;
public:
Login();
Login(QString username,QString password);
int check(QString username, QString password);
};
#endif // LOGIN_H
<file_sep>#ifndef ADDBOOKS_H
#define ADDBOOKS_H
#include <QDialog>
#include<admin.h>
namespace Ui {
class AddBooks;
}
class AddBooks : public QDialog
{
Q_OBJECT
public:
explicit AddBooks(QWidget *parent = nullptr);
~AddBooks();
private slots:
void on_Add_clicked();
private:
Ui::AddBooks *ui;
};
#endif // ADDBOOKS_H
<file_sep>#ifndef ADMIN_H
#define ADMIN_H
#include<QString>
#include<QFile>
#include"QTextStream"
class Admin
{
QString username;
public:
Admin();
Admin(QString username);
bool AddMember(QString username);
bool RemoveMember(QString username);
bool AddBooks(QString name,QString author);
};
#endif // ADMIN_H
<file_sep>#ifndef ISSUE_H
#define ISSUE_H
#include <QDialog>
#include<QFile>
#include<QTextStream>
#include<member.h>
namespace Ui {
class Issue;
}
class Issue : public QDialog
{
Q_OBJECT
public:
explicit Issue(QWidget *parent = nullptr);
~Issue();
private slots:
void on_View_clicked();
void on_pushButton_clicked();
private:
Ui::Issue *ui;
};
#endif // ISSUE_H
<file_sep>#include "adminmenu.h"
#include "ui_adminmenu.h"
AdminMenu::AdminMenu(QWidget *parent) :
QDialog(parent),
ui(new Ui::AdminMenu)
{
ui->setupUi(this);
}
AdminMenu::~AdminMenu()
{
delete ui;
}
void AdminMenu::on_Logout_clicked()
{
exit(0);
}
void AdminMenu::on_Add_clicked()
{
AddMembers member;
member.setModal(true);
member.exec();
}
void AdminMenu::on_Remove_clicked()
{
Removemembers member;
member.setModal(true);
member.exec();
}
void AdminMenu::on_Books_clicked()
{
AddBooks book;
book.setModal(true);
book.exec();
}
void AdminMenu::on_Requests_clicked()
{
VRequests request;
request.setModal(true);
request.exec();
}
void AdminMenu::on_Record_clicked()
{
VRecords record;
record.setModal(true);
record.exec();
}
<file_sep>#include "removemembers.h"
#include "ui_removemembers.h"
#include"QMessageBox"
Removemembers::Removemembers(QWidget *parent) :
QDialog(parent),
ui(new Ui::Removemembers)
{
ui->setupUi(this);
}
Removemembers::~Removemembers()
{
delete ui;
}
void Removemembers::on_Remove_clicked()
{
QString username;
bool flag = true;
username = ui->lineEdit_username->text();
Admin member(username);
if(ui->lineEdit_username->text().isEmpty())
try {
throw 1;
} catch (int a) {
QMessageBox::critical(this,tr("Critical"),tr("Please enter the username"));
flag = false;
}
if(flag)
{
if(member.RemoveMember(username))
ui->Status->setText("User has been removed!!");
else
ui->Status->setText("Username does not exists");
}
}
<file_sep>#include "requets.h"
#include "ui_requets.h"
Requets::Requets(QWidget *parent) :
QDialog(parent),
ui(new Ui::Requets)
{
ui->setupUi(this);
}
Requets::~Requets()
{
delete ui;
}
void Requets::on_pushButton_clicked()
{
bool flag = true;
QString name,author;
name = ui->lineEdit_name->text().toUpper();
author = ui->lineEdit_author->text().toUpper();
try {
if(ui->lineEdit_name->text().isEmpty() ||ui->lineEdit_author->text().isEmpty() )
throw 1;
} catch (int a) {
QMessageBox::critical(this,tr("Critical!!"),tr("Please enter all the fields"));
flag =false;
}
if(flag)
{
QFile fhandle("Requests.txt");
if(fhandle.open(QIODevice::WriteOnly|QIODevice::Append))
{
QTextStream out(&fhandle);
out<<name<<':'<<author<<endl;
QMessageBox::information(this,tr("Success"),tr("The Request has been registered"));
}
}
}
<file_sep>#include "addmembers.h"
#include "ui_addmembers.h"
#include"QMessageBox"
AddMembers::AddMembers(QWidget *parent) :
QDialog(parent),
ui(new Ui::AddMembers)
{
ui->setupUi(this);
}
AddMembers::~AddMembers()
{
delete ui;
}
void AddMembers::on_pushButton_clicked()
{
QString username;
bool flag = true;
username = ui->lineEdit_username->text();
Admin admin(username);
try {
if(ui->lineEdit_username->text().isEmpty())
throw 1;
} catch (int a)
{
QMessageBox::critical(this,tr("Critical"),tr("Please enter the value"));
flag = false;
}
if(flag)
{
if(admin.AddMember(username))
{
QString pass =<PASSWORD>();
ui->Status->setText("User has been added.\n Username:"+username+"\n Password:"+pass+"\n");
}
else
QMessageBox::warning(this,tr("Error"),tr("The username alreay exists"));
}
}
<file_sep>#ifndef MEMBER_H
#define MEMBER_H
#include<QString>
#include<QFile>
#include"QTextStream"
#include<admin.h>
class Member:public Admin
{
public:
Member();
bool ChangePassword(QString username,QString password);
bool Issue(QString username,QString name);
void Record(QString username,QString name);
bool Return(QString username,QString name,QString author);
};
#endif // MEMBER_H
<file_sep>#include "addbooks.h"
#include "ui_addbooks.h"
#include"QMessageBox"
AddBooks::AddBooks(QWidget *parent) :
QDialog(parent),
ui(new Ui::AddBooks)
{
ui->setupUi(this);
}
AddBooks::~AddBooks()
{
delete ui;
}
void AddBooks::on_Add_clicked()
{
QString name,author;
bool flag= true;
name = ui->lineEdit_name->text();
author = ui->lineEdit_author->text();
Admin book;
if(ui->lineEdit_name->text().isEmpty() || ui->lineEdit_author->text().isEmpty())
try {
throw 1;
} catch (int a) {
QMessageBox::critical(this,tr("Critical"),tr("Enter the name of the author and username"));
flag = false;
}
if(flag)
{
if(book.AddBooks(name,author))
ui->Status->setText("The Number has been updated");
else
ui->Status->setText("New Book has been added!!");
}
}
<file_sep>#include "membermenu.h"
#include "ui_membermenu.h"
MemberMenu::MemberMenu(QWidget *parent) :
QDialog(parent),
ui(new Ui::MemberMenu)
{
ui->setupUi(this);
}
MemberMenu::~MemberMenu()
{
delete ui;
}
void MemberMenu::on_Logout_clicked()
{
exit(0);
}
void MemberMenu::on_Change_clicked()
{
ChangePassword password;
password.setModal(true);
password.exec();
}
void MemberMenu::on_Issue_clicked()
{
Issue issue;
issue.setModal(true);
issue.exec();
}
void MemberMenu::on_Return_clicked()
{
Return back;
back.setModal(true);
back.exec();
}
void MemberMenu::on_Request_clicked()
{
Requets request;
request.setModal(true);
request.exec();
}
<file_sep>#ifndef MEMBERMENU_H
#define MEMBERMENU_H
#include <QDialog>
#include<changepassword.h>
#include<issue.h>
#include<return.h>
#include<requets.h>
namespace Ui {
class MemberMenu;
}
class MemberMenu : public QDialog
{
Q_OBJECT
public:
explicit MemberMenu(QWidget *parent = nullptr);
~MemberMenu();
private slots:
void on_Logout_clicked();
void on_Change_clicked();
void on_Issue_clicked();
void on_Return_clicked();
void on_Request_clicked();
private:
Ui::MemberMenu *ui;
};
#endif // MEMBERMENU_H
<file_sep>#include "login.h"
#include<QTextStream>
Login::Login()
{
;
}
Login::Login(QString username,QString password)
{
this->username = username;
this->password = <PASSWORD>;
}
int Login::check(QString username, QString password)
{
//bool flag = false;
QString line,Uname,Upass;
QStringList list;
QFile fhandle("/home/sahejpal/LIBRARY/Login.txt");
//return "pale";
if(fhandle.open(QIODevice::ReadOnly))
{
QTextStream in(&fhandle);
while(!in.atEnd())
{
line = in.readLine();
list = line.split(' ');
Uname = list.value(0);
Upass = list.value(1);
if(Uname == username && password ==<PASSWORD>)
return 1;
}
}
fhandle.close();
char *aname = new char[5];
strcpy(aname,"admin");
char *apass = new char[8];
strcpy(apass,"<PASSWORD>");
if(username == aname && password == <PASSWORD>)
return 0;
else
return -1;
delete [] aname;
delete [] apass;
}
| 8809025d87180b5f19127c5a73699988d11ec150 | [
"Markdown",
"C++"
] | 27 | C++ | Sahejpalarneja/Library-management-system-UI | 0c216ecbce38c57cd5cdd322efa4c8edc70c6fb7 | e740d0705558049df2d0bb8f2927d8a8d571cb9e |
refs/heads/master | <file_sep>class ChangeDataColumnNullToUserProfile < ActiveRecord::Migration[5.2]
def change
change_column :user_profiles, :sex, :integer, null: true
change_column :user_profiles, :work_place, :integer, null: true
change_column :user_profiles, :job, :integer, null: true
change_column :user_profiles, :specialized_field, :integer, null: true
change_column :user_profiles, :location, :integer, null: true
end
end<file_sep># frozen_string_literal: true
class Users::ConfirmationsController < Devise::ConfirmationsController
# GET /resource/confirmation/new
# def new
# super
# end
# POST /resource/confirmation
# def create
# super
# end
# GET /resource/confirmation?confirmation_token=abcdef
def show
self.resource = resource_class.confirm_by_token(params[:confirmation_token])
yield resource if block_given?
if resource.errors.empty?
set_flash_message(:notice, :confirmed) if is_flashing_format?
sign_in_count = sign_in_count_check
sign_in(resource)
mail_regi_to_payjp(resource) unless resource.pay_regi_status.to_i.zero?
respond_with_navigational(resource) { redirect_to after_confirmation_path_for(resource_name, resource, sign_in_count) }
else
respond_with_navigational(resource.errors, status: :unprocessable_entity) { render :new }
end
end
protected
def after_confirmation_path_for(resource_name, resource, sign_in_count)
new_user_registration_complete_path(sign_in_count)
end
def sign_in_count_check
sign_in_count = if user_signed_in?
current_user.sign_in_count
else
0
end
end
def mail_regi_to_payjp(resource)
Payjp.api_key = Settings.payjp[:PAYJP_SECRET_KEY]
customer_id = resource.payment.customer_id
customer = Payjp::Customer.retrieve(id: customer_id)
customer.email = resource.email
customer.save
end
end
<file_sep>class AddColumnCharges < ActiveRecord::Migration[5.2]
def change
add_column :charges, :price, :integer, null:false, after: :video_id
add_column :charges, :product_id, :string, null:false, after: :price
end
end
<file_sep>class ChangeDataBirthdayToUserProfile < ActiveRecord::Migration[5.2]
def change
change_column :user_profiles, :birthday, :date, null: true
end
end
<file_sep>document.addEventListener('turbolinks:load', function() {
$('body').on("click",".header__search-icon",function(e){
$('.search-frame').fadeToggle(100);/*ふわっと表示*/
$(this).hide();
$('.header__search-close-icon').show();
});
$('body').on("click",".search-btn",function(e){
$('.search-frame').fadeToggle(100);/*ふわっと表示*/
});
$('body').on("click",".header__search-close-icon",function(e){
$('.search-frame').fadeToggle(100);/*ふわっと表示*/
$(this).hide();
$('.header__search-icon').show();
});
$('.search-frame').on("click",".genre-tag",function(e){
if($(this).attr('class') == 'genre-tag'){
$(this).addClass('selected-genre-tag');
$(this).find('input[name="search_genre_id[]"]').prop('checked', true);
$(this).find('input[name="search_genre_name[]"]').prop('checked', true);
}else{
$(this).removeClass('selected-genre-tag');
$(this).find('input[name="search_genre_id[]"]').prop('checked', false);
$(this).find('input[name="search_genre_name[]"]').prop('checked', false);
}
});
$('.search-frame').on("click",".series-tag",function(e){
if($(this).attr('class') == 'series-tag'){
$(this).addClass('selected-series-tag');
$(this).find('input[name="search_series_id[]"]').prop('checked', true);
$(this).find('input[name="search_series_title[]"]').prop('checked', true);
}else{
$(this).removeClass('selected-series-tag');
$(this).find('input[name="search_series_id[]"]').prop('checked', false);
$(this).find('input[name="search_series_title[]"]').prop('checked', false);
}
});
$('.search-frame').on("click",".topic-tag",function(e){
if($(this).attr('class') == 'topic-tag'){
$(this).addClass('selected-topic-tag');
$(this).find('input:hidden[name="search_chef_id[]"]').prop('checked', true);
$(this).find('input:hidden[name="search_chef_name[]"]').prop('checked', true);
}else{
$(this).removeClass('selected-topic-tag');
$(this).find('input:hidden[name="search_chef_id[]"]').prop('checked', false);
$(this).find('input:hidden[name="search_chef_name[]"]').prop('checked', false);
}
});
$('.search-frame').on("click",".video-search-submit",function(e){
$('.video-search-form').submit();
});
$('.search-frame').on("click",".article-search-submit",function(e){
$('.article-search-form').submit();
});
});
<file_sep>module ApplicationHelper
require "uri"
def text_url_to_link(text)
URI.extract(text, ['http','https'] ).uniq.each do |url|
sub_text = ""
sub_text << "<a href=" << url << " target=\"_blank\">" << url << "</a>"
text.gsub!(url, sub_text)
end
return text
end
def resource_name
:user
end
def resource
@resource ||= User.new
end
def devise_mapping
@devise_mapping ||= Devise.mappings[:user]
end
def adjust_created_at(created_at)
created_at.to_s.dup.sub!(/\s.*/, "").tr!("-", "/")
end
def adjust_brank_text(text)
safe_join(text.split("\n"), tag(:br))
end
def show_order_select_list
if controller.action_name == 'index'
[["新着順", "new"], ["人気順", "like"]]
else
[["人気順", "like"], ["新着順", "new"]]
end
end
end
<file_sep>require "rails_helper"
describe "PayjpFeature" do
describe "支払い登録ができる" do
before(:each) do
User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>", confirmed_at: Time.now)
allow(Payjp::Customer).to receive(:create).and_return(PayjpMock.create_customer.extend HashExtension)
visit root_path
end
it "Payjpカード登録" do
click_on "ログイン"
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "<PASSWORD>"
click_button "ログイン"
visit '/users/my_page/pay_info'
click_on "支払い方法のみ登録する"
sleep 2
fill_in "cc-number", with: "4242 4242 4242 4242"
fill_in "cc-csc", with: "000"
fill_in "cc-exp", with: "0725"
fill_in "cc-holder", with: "TARO YAMADA"
click_on "登録"
sleep 2
expect(page).to have_css('.pay-frame__complete__title', text: '完了しました')
end
end
describe "支払い登録ができない" do
before(:each) do
User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>", confirmed_at: Time.now)
visit root_path
end
it "未入力項目があると登録できない" do
click_on "ログイン"
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "00000000"
click_button "ログイン"
visit '/users/my_page/pay_info'
click_on "支払い方法のみ登録する"
sleep 2
fill_in "cc-number", with: "4242 4242 4242 4242"
fill_in "cc-csc", with: "000"
fill_in "cc-exp", with: "0725"
# fill_in "cc-holder", with: "<NAME>"
click_on "登録"
sleep 2
expect(current_path).to eq '/payments/new_card/charge'
end
end
describe "支払い登録ができない" do
before(:each) do
@user = User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>", confirmed_at: Time.now)
allow(Payjp::Customer).to receive(:create).and_return(PayjpMock.create_customer_error.extend HashExtension)
visit root_path
end
it "無効な値(有効期限)があると登録できない。かつ登録エラーカウントが1増える" do
click_on "ログイン"
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "<PASSWORD>"
click_button "ログイン"
visit '/users/my_page/pay_info'
click_on "支払い方法のみ登録する"
sleep 2
fill_in "cc-number", with: "4242 4242 4242 4242"
fill_in "cc-csc", with: "000"
fill_in "cc-exp", with: "9999"
fill_in "cc-holder", with: "<NAME>ADA"
click_on "登録"
sleep 2
expect(page).to have_css('div.flash', text: '登録処理に失敗しました。')
expect(@user.cardRegistrationRestrict[0].error_count).to eq(1)
end
end
describe "定額課金登録ができる" do
before(:each) do
@user = User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>", confirmed_at: Time.now)
allow(Payjp::Customer).to receive(:create).and_return(PayjpMock.create_customer.extend HashExtension)
allow(Payjp::Customer).to receive(:retrieve).and_return(PayjpMock.customer_retrieve.extend HashExtension)
allow(Payjp::Subscription).to receive(:create).and_return(PayjpMock.create_subscription.extend HashExtension)
# allow_any_instance_of(UsersController).to receive(:get_card_info).and_return(PayjpMock.card_retrieve)
visit root_path
end
it "直接登録できる" do
click_on "ログイン"
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "<PASSWORD>"
click_button "ログイン"
visit '/users/my_page/pay_info'
click_on "月額1,280円のプレミアムプランを利用する"
sleep 2
fill_in "cc-number", with: "4242 4242 4242 4242"
fill_in "cc-csc", with: "000"
fill_in "cc-exp", with: "9999"
fill_in "cc-holder", with: "<NAME>"
click_on "登録"
sleep 2
expect(page).to have_css('.pay-frame__complete__title', text: 'プレミアムプランの登録手続きが 完了しました')
end
it "カード登録後に定額課金登録できる" do
click_on "ログイン"
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "<PASSWORD>"
click_button "ログイン"
visit '/users/my_page/pay_info'
click_on "支払い方法のみ登録する"
sleep 2
fill_in "cc-number", with: "4242 4242 4242 4242"
fill_in "cc-csc", with: "000"
fill_in "cc-exp", with: "9999"
fill_in "cc-holder", with: "<NAME>"
click_on "登録"
sleep 2
# click_on "戻る"
# sleep 2
visit "/payments/new_card/subscription"
# click_on "月額1,280円のプレミアムプランを利用する"
sleep 2
click_on "プレミアムプラン(¥1,280/月,税別)に登録"
sleep 2
expect(page).to have_css('.pay-frame__complete__title', text: 'プレミアムプランの登録手続きが 完了しました')
end
end
describe "有料ビデオの購入ができる" do
before(:each) do
@chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
@video_img_file_path = Rails.root.join('spec', 'fixtures/files', 'test_video_thumbnail.jpg')
chef = Chef.create!(name: "テストさん", phonetic: "てすと", introduction: "テスト経歴", biography: "テスト経歴", chef_avatar: File.open(@chef_img_file_path))
series = Series.create!(title: "テスト", introduction: "テストですよ", thumbnail: "hogehohe.jpg", chef: chef)
@video = Video.create!(title: "テスト動画", video_url: "https://player.vimeo.com/video/328143616", introduction: "これはテスト動画です。", thumbnail: File.open(@video_img_file_path), commentary: "これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。", video_order: "1", price: "100", series: series)
@user = User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>", confirmed_at: Time.now)
allow(Payjp::Customer).to receive(:create).and_return(PayjpMock.create_customer.extend HashExtension)
allow(Payjp::Customer).to receive(:retrieve).and_return(PayjpMock.customer_retrieve.extend HashExtension)
allow(Payjp::Charge).to receive(:create).and_return(PayjpMock.create_charge)
visit root_path
end
it "有料ビデオの購入ができる" do
click_on "ログイン"
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "<PASSWORD>"
click_button "ログイン"
visit '/users/my_page/pay_info'
click_on "支払い方法のみ登録する"
sleep 2
fill_in "cc-number", with: "4242 4242 4242 4242"
fill_in "cc-csc", with: "000"
fill_in "cc-exp", with: "0725"
fill_in "cc-holder", with: "TARO YAMADA"
click_on "登録"
sleep 1
visit video_path(@video.id)
sleep 1
click_on "¥100を支払う"
sleep 1
click_on "video-pay-btn"
sleep 4
expect(page).to have_css('div.flash', text: '支払が完了しました。')
end
end
private
module HashExtension
def method_missing(method, *params)
if method.to_s[-1,1] == "="
# シンボルキーに優先的に書き込む
key = method.to_s[0..-2].gsub(':', '')
key = self.has_key?(key.to_sym) ? key.to_sym :
( self.has_key?(key.to_s) ? key.to_s : key.to_sym )
self[key] = params.first
else
# シンボルキーとストリングキー両方存在する場合、
# シンボルキーを優先的に返す
key = self.has_key?(method.to_sym) ? method.to_sym : method.to_s
self[key]
end
end
end
end<file_sep>source 'https://rubygems.org'
git_source(:github) do |repo_name|
repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
"https://github.com/#{repo_name}.git"
end
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '5.2.0'
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.3.18', '< 0.6.0'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
gem 'jquery-turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
gem 'haml-rails'
gem 'erb2haml'
gem 'jquery-rails'
gem "jquery-slick-rails"
gem 'jquery-ui-rails'
gem 'font-awesome-rails'
# active admin
gem 'activeadmin'
gem 'devise'
gem 'omniauth'
gem 'omniauth-twitter'
gem 'omniauth-facebook'
# config
gem 'config'
# Pay.jp
gem 'payjp'
# for image uploader with AWS S3
gem 'carrierwave'
gem 'fog-aws'
# ckeditor(rich text)
gem 'mini_magick'
gem 'ckeditor', '4.2.4'
# flora(rich text)
# gem 'activeadmin_froala_editor'
# page nation
gem 'kaminari'
# tag
gem 'acts-as-taggable-on'
# search
gem 'ransack'
# chartkick
gem "chartkick"
# japanese
gem 'rails-i18n'
# static page
gem 'high_voltage'
# Google Analytics
gem 'google-analytics-rails'
# meta-tag seo対策
gem 'meta-tags'
# Manage crontab
gem 'whenever', require: false
# maintenance
gem 'turnout'
# Google Adsense
gem 'rack-cors'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '~> 2.13'
gem 'webdrivers'
gem 'selenium-webdriver'
gem 'pry-rails'
gem 'rails-controller-testing'
gem 'rspec-rails'
gem 'factory_girl_rails', "~> 4.4.1"
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
gem 'better_errors'
# code-review-tool
gem 'binding_of_caller'
gem 'bullet'
gem 'rubocop', require: false
end
group :deployment do
# cron management
# gem 'whenever', require: false
# Deploy
gem 'capistrano', require: false
gem 'capistrano-bundler', require: false
gem 'capistrano-rails', require: false
gem 'capistrano-rbenv', require: false
gem 'capistrano3-puma', require: false
gem 'capistrano-rails-console' # 手元の環境からデプロイ先のconsoleを使う
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
<file_sep>$(document).on('turbolinks:load', function(){
// var activeController = $('body').attr('data-controller');
// var activeAction = $('body').attr('data-action');
// var windowWidth = $(window).width();
// if (activeController == 'top' && activeAction == 'index' && windowWidth > 930) {
// $('.main__logo__img').hide();
// $('.top-slide').hide();
// $('.main__logo').css('padding-top','40%');
// var html = '<div id="top_bg_video" class="player" data-property="{videoURL:\'https://player.vimeo.com/video/316076847\',containment:\'.main__logo\',autoPlay:true, mute:true, startAt:0, opacity:1, showControls:false}"></div>';
// $('.main__logo').append(html);
// $('#top_bg_video').vimeo_player();
// }
});
<file_sep>$(document).on('turbolinks:load', function(){
function buildFirstSeriesList(suggest) {
var html = `<li class="suggest"><span><i class="fa fa-search"></i>動画シリーズ</span></li>`;
return html;
}
function buildFirstGenreList(suggest) {
var html = `<li class="suggest"><span><i class="fa fa-search"></i>動画ジャンル</span></li>`;
return html;
}
function buildFirstChefGenreList(suggest) {
var html = `<li class="suggest"><span><i class="fa fa-search"></i>専門分野</span></li>`;
return html;
}
function buildSeriesList(suggest) {
var html = `<li class="series-suggest" data-keyword="${ suggest.suggest_series }" >${ suggest.suggest_series }</li>
`;
return html;
}
function buildGenreList(suggest) {
var html = `<li class="genre-suggest" data-keyword="${ suggest.suggest_genre }" >${ suggest.suggest_genre }</li>
`;
return html;
}
function buildChefGenreList(suggest) {
var html = `<li class="chef-genre-suggest" data-keyword="${ suggest.suggest_chef_genre }" >${ suggest.suggest_chef_genre }</li>
`;
return html;
}
//インクリメンタルサーチ処理
var activeController = $('body').attr('data-controller');
var activeAction = $('body').attr('data-action');
if (activeController == 'video' && (activeAction == 'chef_search' || activeAction == 'chef_search_video')) {
$('#search-field').on('keyup compositionend', function(e){
e.preventDefault();
var inputData = $(this).val();
if(inputData.length > 1){
$.ajax({
type: "GET",
url: '/video/make_suggest?search_patarn=chef-search',
data: {
search_word: inputData
},
dataType: 'json',
})
//ajax処理が成功した場合の処理
.done(function(data_list) {
$('.suggest_chef_genre_list').empty();
$('.search-window__suggest').show();
var chef_suggest_check = 'off';
data_list.forEach(function(suggest){
if(suggest.suggest_chef_genre && chef_suggest_check == 'off'){
html = buildFirstChefGenreList(suggest);
$('.suggest_chef_genre_list').append(html);
chef_suggest_check = 'on'
}
if(suggest.suggest_chef_genre){
html = buildChefGenreList(suggest);
$('.suggest_chef_genre_list').append(html);
}
});
})
}else{
$('.suggest_chef_genre_list').empty();
}
$(document).on("click", ".chef-genre-suggest", function (e) {
var search_genre = $(this).attr('data-keyword');
$('#search-field').val(search_genre);
$('#suggest_patarn').val('chef_genre');
$('.search-form').submit();
});
});
}else{
$('#search-field, #search-field-header, #search-field-top-sp, #search-field-header-sp').on('keyup compositionend', function(e){
e.preventDefault();
var inputData = $(this).val();
if(inputData.length > 1){
$.ajax({
type: "GET",
url: '/video/make_suggest?search_patarn=keyword_search',
data: {
search_word: inputData
},
dataType: 'json',
})
//ajax処理が成功した場合の処理
.done(function(data_list) {
$('.suggest_series_list').empty();
$('.suggest_genre_list').empty();
if(activeController == 'video' && activeAction != 'show'){
$('.search-window__suggest').show();
}else if($(window).width() > 630){
$('.search-window-header__suggest').show();
}else{
$('.search-window-top-sp__suggest').show();
$('.search-window-header-sp__suggest').show();
}
var series_suggest_check = 'off';
var genre_suggest_check = 'off';
data_list.forEach(function(suggest){
if(suggest.suggest_series && series_suggest_check == 'off'){
html = buildFirstSeriesList(suggest);
$('.suggest_series_list').append(html);
series_suggest_check = 'on';
}
if(suggest.suggest_genre && genre_suggest_check == 'off'){
html = buildFirstGenreList(suggest);
$('.suggest_genre_list').append(html);
genre_suggest_check = 'on';
}
if(suggest.suggest_series){
html = buildSeriesList(suggest);
$('.suggest_series_list').append(html);
}
if(suggest.suggest_genre){
html = buildGenreList(suggest);
$('.suggest_genre_list').append(html);
}
});
})
}else{
$('.suggest_series_list').empty();
$('.suggest_genre_list').empty();
}
});
//サジェストを押された際の処理
$(document).on("click", ".series-suggest", function (e) {
var search_series = $(this).attr('data-keyword');
$('#suggest_patarn').val('series');
$('#suggest_patarn_sp').val('series');
if(activeController == 'video' && activeAction == 'show' && $(window).width() < 630){
$('#search-field-header-sp').val(search_series);
$('.header-sp-search-form').submit();
}else if(activeController == 'video' && activeAction == 'show' && $(window).width() > 630){
$('#search-field-header').val(search_series);
$('.header-search-form').submit();
}else if(activeController == 'video'){
$('#search-field').val(search_series);
$('.search-form').submit();
}else if(activeController == 'top' && $(window).width() < 630){
$('#search-field-top-sp').val(search_series);
$('.top-sp-search-form').submit();
}else if ($(window).width() > 630){
$('#search-field-header').val(search_series);
$('.header-search-form').submit();
}else{
$('#search-field-header-sp').val(search_series);
$('.header-sp-search-form').submit();
}
});
$(document).on("click", ".genre-suggest", function (e) {
var search_genre = $(this).attr('data-keyword');
$('#suggest_patarn').val('genre');
$('#suggest_patarn_sp').val('genre');
if(activeController == 'video' && activeAction == 'show' && $(window).width() < 630){
$('#search-field-header-sp').val(search_genre);
$('.header-sp-search-form').submit();
}else if(activeController == 'video' && activeAction == 'show' && $(window).width() > 630){
$('#search-field-header').val(search_genre);
$('.header-search-form').submit();
}else if(activeController == 'video'){
$('#search-field').val(search_genre);
$('.search-form').submit();
}else if(activeController == 'top' && $(window).width() < 630){
$('#search-field-top-sp').val(search_genre);
$('.top-sp-search-form').submit();
}else if ($(window).width() > 630){
$('#search-field-header').val(search_genre);
$('.header-search-form').submit();
}else{
$('#search-field-header-sp').val(search_genre);
$('.header-sp-search-form').submit();
}
});
}
});
<file_sep>require "rails_helper"
describe "VideoFeature" do
describe "お気に入り登録" do
before(:each) do
User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>", confirmed_at: Time.now)
@chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
@video_img_file_path = Rails.root.join('spec', 'fixtures/files', 'test_video_thumbnail.jpg')
chef = Chef.create!(name: "テストさん", phonetic: "てすと", introduction: "テスト経歴", biography: "テスト経歴", chef_avatar: File.open(@chef_img_file_path))
series = Series.create!(title: "テスト", introduction: "テストですよ", thumbnail: "hogehohe.jpg", chef: chef)
@video = Video.create!(title: "テスト動画", video_url: "https://player.vimeo.com/video/328143616", introduction: "これはテスト動画です。", thumbnail: File.open(@video_img_file_path), commentary: "これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。", video_order: "1", price: 0, series: series)
visit root_path
end
it "お気に入り登録ができる" do
click_on "ログイン"
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "<PASSWORD>"
click_button "ログイン"
sleep 3
visit video_path(@video.id)
sleep 3
like_btn = find(:xpath, "//a[contains(@href,'video_like')]")
like_btn.click
sleep 3
expect(page).to have_css('.text', text: '1')
end
end
end<file_sep>// $(document).on('turbolinks:load', function(){
// var ads = document.querySelectorAll('.adsbygoogle');
// if (ads.length > 0) {
// ads.forEach(function (ad) {
// if (ad.firstChild) {
// ad.removeChild(ad.firstChild);
// }
// });
// ads.forEach(function() {
// window.adsbygoogle = window.adsbygoogle || [];
// window.adsbygoogle.push({});
// });
// }
// });<file_sep>class CreateMagazineAddresses < ActiveRecord::Migration[5.2]
def change
create_table :magazine_addresses do |t|
t.references :user, index: true, foreign_key: true
t.string :address, null: false
t.integer :zipcode, null: false
t.string :pref, null: false
t.string :city_address, null: false
t.string :building
t.timestamps
end
end
end
<file_sep>class RemoveCardinfoFromPayments < ActiveRecord::Migration[5.2]
def change
remove_column :payments, :last4, :string
remove_column :payments, :brand, :string
remove_column :payments, :exp_month, :string
remove_column :payments, :exp_year, :string
end
end
<file_sep>class AddColumnArticles < ActiveRecord::Migration[5.2]
def change
add_reference :articles, :chef, foreign_key: true, after: :like_count
end
end
<file_sep># frozen_string_literal: true
class Users::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: [:create]
before_action :configure_account_update_params, only: [:update]
# GET /resource/sign_up/:account_patarn
def new
@account_patarn = account_patarn_params[:account_patarn]
super
end
# POST /resource
def create
@account_patarn = account_patarn_params[:account_patarn]
@user = User.new(configure_sign_up_params) if @account_patarn == 'mail'
@user = User.new(configure_sign_up_params_fb) if @account_patarn == 'facebook'
@user = User.new(configure_sign_up_params_tw) if @account_patarn == 'twitter'
@user.skip_confirmation! unless @account_patarn == 'mail'
if @user.save
switch_redirect_to(@account_patarn, @user)
else
render 'new'
end
end
# GET /resource/edit
def edit
@account_patarn = current_user.provider
@account_patarn = 'mail' if current_user.provider.nil?
@user = current_user
super
end
# PUT /resource
def update
@account_patarn = account_patarn_params[:account_patarn]
if @user.update_without_current_password(configure_account_update_params)
# sign_in(@user, bypass: true)
bypass_sign_in(@user)
switch_mail_aouth_redirect_to(@account_patarn, @user)
else
render 'edit'
end
end
# GET /resource/cancel
def delete
end
# DELETE /resource
def destroy
delete_payment_data(current_user) if current_user.payment.present?
MagazineAddress.delete_address(current_user) if MagazineAddress.find_by(user_id: current_user.id)
current_user.destroy
sign_out
@sign_in_count = 'delete'
render 'complete'
end
def mail_send
@sign_in_count = configure_mail_aouth_params[:sign_in_count].to_i
end
def complete
@sign_in_count = configure_mail_aouth_params[:sign_in_count].to_i
@magazine_address_check = MagazineAddress.register_check(current_user)
end
protected
def configure_sign_up_params
devise_parameter_sanitizer.sanitize(:sign_up) do |params|
params.permit(:sign_up, keys: [:name, :email, :password, :password_confirmation, :pay_regi_status, userProfile_attributes: [:sex, :work_place, :job, :specialized_field, :location, :birthday]])
end
end
def configure_sign_up_params_fb
configure_sign_up_params.merge(provider: session["devise.facebook_data"]['provider'], uid: session["devise.facebook_data"]['uid'], email: session["devise.facebook_data"]['info']['email'], password: <PASSWORD>.friendly_token[0, 20])
end
def configure_sign_up_params_tw
configure_sign_up_params.merge(provider: session["devise.twitter_data"]['provider'], uid: session["devise.twitter_data"]['uid'], email: session["devise.twitter_data"]['info']['email'], password: <PASSWORD>.friendly_token[0, 20])
end
def configure_account_update_params
devise_parameter_sanitizer.sanitize(:account_update) do |params|
params.permit(:sign_up, keys: [:name, :email, :password, :password_confirmation, :pay_regi_status, userProfile_attributes: [:sex, :work_place, :job, :specialized_field, :location, :birthday]])
end
end
def account_patarn_params
if action_name == 'new'
params.permit(:account_patarn)
else
params.require(:user).permit(:account_patarn)
end
end
def configure_mail_aouth_params
params.permit(:sign_in_count)
end
def switch_redirect_to(account_patarn, resource)
if account_patarn == 'mail'
redirect_to new_user_registration_send_path(@user.sign_in_count)
else
sign_in(resource)
redirect_to new_user_registration_complete_path(0)
end
end
def switch_mail_aouth_redirect_to(account_patarn, resource)
if resource.unconfirmed_email.nil?
@sign_in_count = 'edit'
render 'complete'
else
redirect_to new_user_registration_send_path(resource.sign_in_count)
end
end
def delete_payment_data(current_user)
#MyPayjp.delete_customer(current_user.payment.customer_id)
current_user.payment.destroy
end
end
<file_sep>class Article < ApplicationRecord
has_many :article_likes, dependent: :destroy
belongs_to :chef
mount_uploader :thumbnail, ArticleThumbnailUploader
acts_as_taggable_on :tags
with_options presence: true do
validates :title
validates :contents
validates :thumbnail
validates :chef
end
def self.tag_count(tags)
Article.tagged_with(tags, any: true).count(:all)
end
def like_user(user_id)
article_likes.find_by(user_id: user_id)
end
end
<file_sep>ActiveAdmin.register MagazineAddress do
index do
column :id
column :zipcode
column :pref
column :city_address
column :building
column '会員種類' do |ma|
ma.user.pay_regi_status
end
actions
end
end<file_sep>namespace :maintenance do
desc 'メンテナンス開始'
task :start do
on roles(:web), in: :sequence do
within current_path do
# tmp/maintenance.ymlがなければ config/ から tmp/ にコピーする
unless test(:test, "-f tmp/maintenance.yml")
execute :cp, 'config/maintenance.yml tmp/maintenance.yml'
end
end
end
end
desc 'メンテナンス終了'
task :finish do
on roles(:web), in: :sequence do
within current_path do
# tmp/maintenance.ymlがあれば削除する
if test(:test, "-f tmp/maintenance.yml")
execute :rm, 'tmp/maintenance.yml'
end
end
end
end
end<file_sep>class PaymentsController < ApplicationController
before_action :configure_payjp_token, only: [:create, :purchase_subscription, :card_change]
before_action :card_registration_restrict_check, only: [:new_card, :edit]
def new_card
if current_user.pay_regi_status_before_type_cast == 1
# クレジットカードの登録が完了済みの場合はメルマガ有料会員登録の最終確認画面を表示
@confirm_patarn = 'magazine_and_credit_finish'
render 'payments/confirm'
elsif current_user.pay_regi_status_before_type_cast == 0
@pay_patarn = params['pay_patarn']
end
end
def create
payjp_token = configure_payjp_token['payjp-token']
customer = MyPayjp.get_customer_id(payjp_token, current_user)
card_registration_restrict_status_record = CardRegistrationRestrict.find_by(user_id: current_user.id)
@lock_check = card_registration_restrict_status_record.error_count if card_registration_restrict_status_record.present?
if customer[:error].nil? && @lock_check != 5 && current_user.pay_regi_status_before_type_cast == 0
Payment.registration_card_data(customer, current_user)
User.update_pay_regi_status(current_user, 'charge')
MyPayjp.registration_customer_email(customer, current_user.email)
@registration_patarn = 'create'
card_registration_restrict_reset(card_registration_restrict_status_record, 'reset') if card_registration_restrict_status_record.present?
render 'complete'
else
card_registration_restrict_count_add(card_registration_restrict_status_record)
@pay_patarn = params['pay_patarn']
render 'new_card'
end
end
def purchase_charge
charge_check = Charge.where(user_id: current_user.id, video_id: params[:video_id])
if charge_check.empty?
customer = MyPayjp.get_customer_id('', current_user)
charge_data = MyPayjp.production_charge(params[:price], customer)
@result = charge_error_check(charge_data, params[:video_id])
else
@result = ['error']
end
respond_to do |format|
format.html
format.json
end
end
def purchase_subscription
access_type = params[:access_type]
payjp_token = configure_payjp_token['payjp-token']
customer = MyPayjp.get_customer_id(payjp_token, current_user)
card_registration_restrict_status_record = CardRegistrationRestrict.find_by(user_id: current_user.id)
@lock_check = card_registration_restrict_status_record.error_count if card_registration_restrict_status_record.present?
plan_id = "mmm_premium_10per"
subscription_data = MyPayjp.create_subscription(customer, plan_id) if customer[:error].nil?
if customer[:error].nil? && subscription_data[:error].nil? && @lock_check != 5 && current_user.pay_regi_status_before_type_cast != 2
MyPayjp.registration_customer_email(customer, current_user.email)
Payment.set_subscription_data(subscription_data, plan_id, customer, current_user)
User.update_pay_regi_status(current_user, 'subscription')
card_registration_restrict_reset(card_registration_restrict_status_record, 'reset') if card_registration_restrict_status_record.present?
@registration_patarn = 'create'
render 'complete'
else
if access_type == 'direct'
# 登録済みのカードにエラーがある場合はカード登録画面に移動し新しいカードの入力を促す
flash[:alert] = '通信エラーが発生しました。' if customer[:error].present? && subscription_data[:error].nil?
flash[:alert] = 'ご登録されているクレジットカードでの登録が出来ませんでした。' if subscription_data[:error].present?
@confirm_patarn = 'magazine_and_credit_finish'
render 'payments/confirm'
elsif access_type == 'new_card'
# card_registration_restrict_count_add(card_registration_restrict_status_record)
flash[:alert] = 'ご登録されているクレジットカードでの登録が出来ませんでした。'
@pay_patarn = params['pay_patarn']
render 'new_card'
end
end
end
def destroy
result = MyPayjp.delete_subscription_data(current_user.payment.subscription_id)
if result[:error].nil?
User.delete_user_subscription_data(current_user)
#お届け先住所を削除
MagazineAddress.delete_address(current_user)
#お気に入り登録を全て削除
VideoLike.where(user_id: current_user.id).delete_all
ArticleLike.where(user_id: current_user.id).delete_all
@registration_patarn = 'delete'
render 'complete'
else
flash.now[:alert] = 'メルマガ有料会員の解約手続きに失敗しました。お手数ですが再度ボタンを押下ください。'
render 'delete'
end
end
def card_change
payjp_token = configure_payjp_token['payjp-token']
customer = MyPayjp.get_customer_id(payjp_token, current_user)
default_card_id = customer.default_card
card_registration_restrict_status_record = CardRegistrationRestrict.find_by(user_id: current_user.id)
@lock_check = card_registration_restrict_status_record.error_count if card_registration_restrict_status_record.present?
result = MyPayjp.cards_add(customer, payjp_token)
if result[:error].nil? && @lock_check != 5
MyPayjp.cards_delete(customer, default_card_id)
card_registration_restrict_reset(card_registration_restrict_status_record, 'reset') if card_registration_restrict_status_record.present?
resume_subscription if current_user.pay_regi_status_before_type_cast == 3
@registration_patarn = 'change'
render 'complete'
else
card_registration_restrict_count_add(card_registration_restrict_status_record)
render 'edit'
end
end
private
def charge_error_check(charge_data, video_id)
@result = if charge_data[:error].present?
flash[:alert] = 'ご登録されているクレジットカードでの支払いが出来ませんでした。'
['error']
else
Charge.create(user_id: current_user.id, video_id: video_id, price: charge_data['amount'], payjp_charge_id: charge_data['id'])
flash[:notice] = '支払が完了しました。'
['ok']
end
end
def configure_payjp_token
if params['payjp-token'].nil?
'-'
else
params.permit('payjp-token')
end
end
def card_registration_restrict_check
card_registration_restrict_status_record = CardRegistrationRestrict.find_by(user_id: current_user.id)
card_registration_eternal_restrict_check(card_registration_restrict_status_record)
if card_registration_restrict_status_record.nil? || (card_registration_restrict_status_record.present? && card_registration_restrict_status_record.error_count < 5)
@card_registration_restrict_check = nil
elsif (Time.current - card_registration_restrict_status_record.locked_at).to_i > 3_600
card_registration_restrict_reset(card_registration_restrict_status_record, 'time_reset')
@card_registration_restrict_check = nil
else
@card_registration_restrict_check = 'lock'
end
end
def card_registration_eternal_restrict_check(card_registration_restrict_status_record)
@card_registration_eternal_restrict_check = 'lock' if card_registration_restrict_status_record.present? && card_registration_restrict_status_record.total_error_count > 19
end
def card_registration_restrict_reset(card_registration_restrict_status_record, reset_type)
card_registration_restrict_status_record.update(error_count: 0, locked_at: nil, total_error_count: 0) if reset_type == 'reset'
card_registration_restrict_status_record.update(error_count: 0, locked_at: nil) if reset_type == 'time_reset'
end
def card_registration_restrict_count_add(card_registration_restrict_status_record)
flash.now[:alert] = if card_registration_restrict_status_record.nil?
CardRegistrationRestrict.create(user_id: current_user.id, error_count: 1)
'クレジットカードの登録処理に失敗しました。お手数ですが再度カード情報をご登録ください。'
elsif (new_error_count = card_registration_restrict_status_record.error_count + 1) < 5
new_total_error_count = card_registration_restrict_status_record.total_error_count + 1
card_registration_restrict_status_record.update(error_count: new_error_count, total_error_count: new_total_error_count)
'クレジットカードの登録処理に失敗しました。お手数ですが再度カード情報をご登録ください。'
elsif new_error_count > 5
@card_registration_restrict_check = 'lock'
'無効な操作です!'
elsif (new_total_error_count = card_registration_restrict_status_record.total_error_count + 1) < 20
card_registration_restrict_status_record.update(error_count: new_error_count, locked_at: Time.now.to_i, total_error_count: new_total_error_count)
@card_registration_restrict_check = 'lock'
'クレジットカードの登録処理に5回連続失敗しました。お手数ですが1時間後に再度カード情報をご登録ください。'
else
card_registration_restrict_status_record.update(error_count: new_error_count, locked_at: Time.now.to_i, total_error_count: new_total_error_count)
@card_registration_restrict_check = 'lock'
@card_registration_eternal_restrict_check = 'lock'
'クレジットカードの登録処理に20回連続失敗したため、ロックがかかりました。'
end
end
def resume_subscription
User.update_pay_regi_status(current_user, 'subscription')
MyPayjp.resume_subscription(current_user.payment.subscription_id)
end
end
<file_sep>class Series < ApplicationRecord
belongs_to :chef
has_many :videos, dependent: :destroy
mount_uploader :thumbnail, SeriesThumbnailUploader
with_options presence: true do
validates :title
validates :chef
end
end
<file_sep>$(function(){
var registered_tag_list = $('#registered_tag').val().split(' ');
var autocomplete_tag_list = $('#autocomplete_tag').val().split(' ');
$('#genre-tags').tagit();
for (i = 0, len = registered_tag_list.length; i < len; i++) {
$('#genre-tags').tagit('createTag', registered_tag_list[i]);
}
$('#genre-tags').tagit({availableTags: autocomplete_tag_list });
});
<file_sep>$(function(){
$('#article-contents').bind('keydown keyup keypress change',function(){
var txt = $(this).val(),
new_txt = $.trim(txt.replace(/\n/g, "")),
couter = new_txt.length;
$('#text-count').html(couter);
});
});
<file_sep>module VideoHelper
def adjust_play_list_icon(series_video, play_video)
if series_video.id == play_video.id
fa_icon "play-circle"
else
fa_icon "film"
end
end
def new_video_check(created_at)
(Time.current - created_at).to_i < 1_296_000
end
def video_charge_check(video)
if video.price > 0
Charge.where(user_id: current_user.id, video_id: video.id).count
else
1
end
end
def article_author_check(tag)
if tag.name == '記事専門'
1
else
0
end
end
end
<file_sep>ActiveAdmin.register Video do
permit_params recipes_attributes: [:id, :food, :amount, :_destroy]
index do
column :id
column :title
column :video_order
column :price
column :like_count
column :series
actions
end
form do |f|
f.inputs do
f.input :title
f.input :video_url
f.input :introduction
f.input :commentary
f.input :series_id, as: :select, collection: Series.all.map { |s| [s.title, s.id, { "video-count" => Video.where(series_id: s.id).count }] }, :input_html => { id: "series_id" }
f.input :video_order, as: :select, collection: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17], :input_html => { id: "video_orders" }
f.input :thumbnail
f.input :price
f.input :tag_list, :input_html => { id: "genre-tags", value: nil }
f.input :registered_tag, as: :hidden, :input_html => { id: "registered_tag", value: nil } if controller.action_name == 'new'
f.input :registered_tag, as: :hidden, :input_html => { id: "registered_tag", value: Video.find(params[:id]).tag_list } if controller.action_name == 'edit'
f.input :autocmplete_tag, as: :hidden, :input_html => { id: "autocomplete_tag", value: Video.tags_on(:tags).map { |t| t.name } }
f.input :video_crud_patarn, :input_html => { id: "videoCrudPatarn", value: "edit" }, as: :hidden if controller.action_name == 'edit'
end
f.inputs do
f.has_many :recipes, heading: 'レシピ', allow_destroy: true, new_record: true do |a|
a.input :food
a.input :amount
end
end
f.actions
end
controller do
before_action -> {
video_order_duplicate_check(video_permit_params, params_crud_patarn[:video_crud_patarn])
}, only: [:create, :update]
def create
@video = Video.new(video_permit_params)
if @video.save
video_order_over_count_check(video_permit_params)
@video.tag_list = params_tag_list[:tag_list]
@video.save
redirect_to admin_videos_path
else
render :new
end
end
def update
@video = Video.find(params[:id])
if @video.update(video_permit_params)
@video.tag_list = params_tag_list[:tag_list]
@video.save
video_order_over_count_check(video_permit_params)
redirect_to admin_videos_path
else
render :edit
end
end
def destroy
video = Video.find(params[:id])
crud_patarn = 'delete'
organize_video_order_of_delete_video_series(video, crud_patarn)
video.destroy
redirect_to admin_videos_path
end
private
def video_permit_params
params.require(:video).permit(:title, :video_url, :introduction, :commentary, :video_order, :thumbnail, :price, :like_count, :series_id, recipes_attributes: [:id, :food, :amount, :_destroy])
end
def params_crud_patarn
params.require(:video).permit(:video_crud_patarn)
end
def params_tag_list
params.require(:video).permit(:tag_list)
end
def video_order_duplicate_check(video_permit_params, crud_patarn)
old_series_id = Video.find(params[:id]).series_id if crud_patarn == 'edit'
new_series_id = video_permit_params[:series_id]
new_video_order = video_permit_params[:video_order].to_i
old_video_order = Video.find(params[:id]).video_order if crud_patarn == 'edit'
duplicate_check = Video.where(video_order: new_video_order).where(series_id: new_series_id)
if old_series_id == new_series_id
Video.update_duplicate_video_order_some_series(new_seriesId, crud_patarn, old_video_order, new_video_order) if duplicate_check.present?
else
Video.update_duplicate_video_order_another_series(new_series_id, old_series_id, old_video_order, new_video_order)
end
end
def organize_video_order_of_delete_video_series(video, crud_patarn)
old_video_order = video.video_order
series_id = video.series
Video.update_duplicate_video_order_some_series(series_id, crud_patarn, old_video_order, 0)
end
def video_order_over_count_check(video_permit_params)
video_id = params[:id]
new_series_id = video_permit_params[:series_id]
new_video_order = video_permit_params[:video_order].to_i
total_video_count = Video.where(series_id: new_series_id).count
Video.find(video_id).update(video_order: total_video_count) if total_video_count < new_video_order
end
def scoped_collection
Video.includes(:recipes)
end
end
end
<file_sep>$(document).on('turbolinks:load', function(){
// $(document).on('click','#like_count_btn',function(e){
$("#like_count_btn").on("click",function(){
$('.share-frame__like-btn').off('click');
$('.share-frame__like-btn').on('click','#like_count_btn',function(e){
alert("お気に入り登録の上限数を超えています!");
return false;
});
});
});<file_sep>ActiveAdmin.register Chef do
permit_params :name, :phonetic, :introduction, :biography, :chef_avatar
index do
column :id
column :name
column :phonetic
actions
end
form do |f|
f.inputs do
f.input :name
f.input :phonetic
f.input :introduction
f.input :biography
f.input :chef_avatar
f.input :tag_list, :input_html => { id: "genre-tags", value: nil }
text_node '<div class="text-count">※記事を執筆するだけの場合は"記事専門"と入力してください。</div>'.html_safe
f.input :registered_tag, as: :hidden, :input_html => { id: "registered_tag", value: nil } if controller.action_name == 'new'
f.input :registered_tag, as: :hidden, :input_html => { id: "registered_tag", value: Chef.find(params[:id]).tag_list } if controller.action_name == 'edit'
f.input :autocmplete_tag, as: :hidden, :input_html => { id: "autocomplete_tag", value: Chef.tags_on(:tags).map(&:name) }
f.input :chef_crud_patarn, :input_html => { id: "chefCrudPatarn", value: "edit" }, as: :hidden if controller.action_name == 'edit'
end
f.actions
end
controller do
def create
@chef = Chef.new(chef_permit_params)
if @chef.save
@chef.tag_list = params_tag_list[:tag_list]
@chef.save
redirect_to admin_chefs_path
else
render :new
end
end
def update
@chef = Chef.find(params[:id])
if @chef.update(chef_permit_params)
@chef.tag_list = params_tag_list[:tag_list]
@chef.save
redirect_to admin_chefs_path
else
render :edit
end
end
def destroy
chef = Chef.find(params[:id])
chef.destroy
redirect_to admin_chefs_path
end
private
def chef_permit_params
params.require(:chef).permit(:name, :phonetic, :introduction, :biography, :chef_avatar)
end
def params_crud_patarn
params.require(:chef).permit(:chef_crud_patarn)
end
def params_tag_list
params.require(:chef).permit(:tag_list)
end
end
end
<file_sep>module UsersHelper
def adjust_expires_at(expires_at)
expires_at.to_s.dup.sub!(/\s.*/, "")
end
def menu_active(info_patarn, page_action)
'selected' if info_patarn == page_action
end
def check_pay_regi_status
current_user.pay_regi_status_before_type_cast
end
end
<file_sep>require "rails_helper"
describe "SearchFeature" do
describe "検索メニュー機能(video)" do
before do
@user = FactoryGirl.create(:testuser)
# User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>", confirmed_at: Time.now)
@chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
@video_img_file_path = Rails.root.join('spec', 'fixtures/files', 'test_video_thumbnail.jpg')
@chef = Chef.create!(name: "テストさん", phonetic: "てすと", introduction: "テスト経歴", biography: "テスト経歴", chef_avatar: File.open(@chef_img_file_path))
@series1 = Series.create!(title: "テストシリーズ1", introduction: "テストですよ", thumbnail: "hogehohe.jpg", chef: @chef)
@series2 = Series.create!(title: "テストシリーズ2", introduction: "テストですよ", thumbnail: "hogehohe.jpg", chef: @chef)
@video1 = Video.create!(title: "テスト動画1", video_url: "https://player.vimeo.com/video/328143616", introduction: "これはテスト動画1です。", thumbnail: File.open(@video_img_file_path), commentary: "これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。", tag_list: 'フランス料理', video_order: "1", price: 0, series: @series1)
@video2 = Video.create!(title: "テスト動画2", video_url: "https://player.vimeo.com/video/328143616", introduction: "これはテスト動画2です。", thumbnail: File.open(@video_img_file_path), commentary: "これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。", tag_list: '和食', video_order: "2", price: 0, series: @series2)
visit root_path
end
it "ヘッダーの検索アイコンをクリックすると検索メニューが表示される(画面サイズ1120以上)" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
#検索メニューが表示されていないことをチェック
expect(page.find('body')).to have_selector('.search-frame', count: 0)
#検索メニューを表示させる
page.find('.header__search-icon').click
sleep(1)
expect(page.find('body')).to have_selector('.search-frame', count: 1)
end
it "検索メニューのジャンル欄に登録されているジャンルが表示される(画面サイズ1120以上)" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.find('.header__search-icon').click
sleep(1)
expect(page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[0].text).to eq @video1.tag_list[0]
expect(page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[1].text).to eq @video2.tag_list[0]
end
it "検索メニューのシリーズ欄に登録されているvideoのシリーズが表示される(画面サイズ1120以上)" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.find('.header__search-icon').click
sleep(1)
expect(page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[0].text).to eq @video1.series.title
expect(page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[1].text).to eq @video2.series.title
end
it " video名で検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[0].set @video1.title
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video1.title} 〜#{@video1.series.title}シリーズ〜")
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[0].set @video2.title
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video2.title} 〜#{@video2.series.title}シリーズ〜")
end
it "videoの紹介文で検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[0].set @video1.introduction[0..15]
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video1.title} 〜#{@video1.series.title}シリーズ〜")
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[0].set @video2.introduction[0..15]
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video2.title} 〜#{@video2.series.title}シリーズ〜")
end
it "ジャンル検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[0].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video1.title} 〜#{@video1.series.title}シリーズ〜")
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video2.title} 〜#{@video2.series.title}シリーズ〜")
end
it "シリーズ検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[0].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video1.title} 〜#{@video1.series.title}シリーズ〜")
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video2.title} 〜#{@video2.series.title}シリーズ〜")
end
it "ジャンル&トピック検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[0].click
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[0].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video1.title} 〜#{@video1.series.title}シリーズ〜")
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[1].click
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video2.title} 〜#{@video2.series.title}シリーズ〜")
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[0].click
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('body')).to have_selector('.v-s-list__box', count: 0)
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[1].click
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[0].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('body')).to have_selector('.v-s-list__box', count: 0)
end
it "キーワード&ジャンル&トピック検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
visit root_path
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[0].set @video1.title
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[0].click
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[0].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video1.title} 〜#{@video1.series.title}シリーズ〜")
visit root_path
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[1].set @video2.title
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[1].click
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video2.title} 〜#{@video2.series.title}シリーズ〜")
visit root_path
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[0].set @video2.title
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[0].click
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[0].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('body')).to have_selector('.v-s-list__box', count: 0)
visit root_path
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[0].set @video1.title
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[1].click
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('body')).to have_selector('.v-s-list__box', count: 0)
# 全ジャンル選択
visit root_path
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[0].click
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('body')).to have_selector('.v-s-list__box', count: 2)
# 全シリーズタグ選択
visit root_path
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[0].click
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('body')).to have_selector('.v-s-list__box', count: 2)
# 全ジャンル&全トピックタグ選択
visit root_path
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[0].click
page.find('.search-frame').all('.search-frame__box')[1].all('.genre-tag')[1].click
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[0].click
page.find('.search-frame').all('.search-frame__box')[2].all('.series-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('body')).to have_selector('.v-s-list__box', count: 2)
end
end
describe "検索メニュー機能(TOPページの検索窓)" do
before do
@user = FactoryGirl.create(:testuser)
# User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>", confirmed_at: Time.now)
@chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
@video_img_file_path = Rails.root.join('spec', 'fixtures/files', 'test_video_thumbnail.jpg')
@chef = Chef.create!(name: "テストさん", phonetic: "てすと", introduction: "テスト経歴", biography: "テスト経歴", chef_avatar: File.open(@chef_img_file_path))
@series1 = Series.create!(title: "テストシリーズ1", introduction: "テストですよ", thumbnail: "hogehohe.jpg", chef: @chef)
@series2 = Series.create!(title: "テストシリーズ2", introduction: "テストですよ", thumbnail: "hogehohe.jpg", chef: @chef)
@video1 = Video.create!(title: "テスト動画1", video_url: "https://player.vimeo.com/video/328143616", introduction: "これはテスト動画1です。", thumbnail: File.open(@video_img_file_path), commentary: "これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。", tag_list: 'フランス料理', video_order: "1", price: 0, series: @series1)
@video2 = Video.create!(title: "テスト動画2", video_url: "https://player.vimeo.com/video/328143616", introduction: "これはテスト動画2です。", thumbnail: File.open(@video_img_file_path), commentary: "これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。", tag_list: '和食', video_order: "2", price: 0, series: @series2)
visit root_path
end
it " video名で検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
sleep(1)
page.all('.s-window-top')[0].set @video1.title
sleep(1)
page.all('.s-submit-top')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video1.title} 〜#{@video1.series.title}シリーズ〜")
visit root_path
sleep(1)
page.all('.s-window-top')[0].set @video2.title
sleep(1)
page.all('.s-submit-top')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video2.title} 〜#{@video2.series.title}シリーズ〜")
end
it "videoの紹介文で検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.all('.s-window-top')[0].set @video1.introduction[0..15]
sleep(1)
page.all('.s-submit-top')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video1.title} 〜#{@video1.series.title}シリーズ〜")
visit root_path
sleep(1)
page.all('.s-window-top')[0].set @video2.introduction[0..15]
sleep(1)
page.all('.s-submit-top')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 1)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video2.title} 〜#{@video2.series.title}シリーズ〜")
end
end
describe "検索メニュー機能(article)" do
before do
@user = FactoryGirl.create(:testuser)
@chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
@article_img_file_path = Rails.root.join('spec', 'fixtures/files', 'article_test.jpg')
@chef = Chef.create!(name: "テストさん", phonetic: "てすと", introduction: "テスト経歴", biography: "テスト経歴", chef_avatar: File.open(@chef_img_file_path))
@article1 = Article.create!(title: "テスト記事1", description: "これはテスト記事1の説明文です。これはテスト記事1です。これはテスト記事です。これはテスト記事です。これはテスト記事です。", contents: "これはテスト記事1の本文です。これはテスト記事1です。これはテスト記事です。これはテスト記事です。これはテスト記事です。", thumbnail: File.open(@article_img_file_path), chef: @chef, tag_list: 'フランス料理')
@article2 = Article.create!(title: "テスト記事2", description: "これはテスト記事2の説明文です。これはテスト記事2です。これはテスト記事です。これはテスト記事です。これはテスト記事です。", contents: "これはテスト記事2の本文です。これはテスト記事2です。これはテスト記事です。これはテスト記事です。これはテスト記事です。", thumbnail: File.open(@article_img_file_path), chef: @chef, tag_list: 'イタリア料理')
visit root_path
end
it "記事名で検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[1].set @article1.title
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 1)
expect(page.all('.a-search-result__box')[0].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article1.title)
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[1].set @article2.title
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 1)
expect(page.all('.a-search-result__box')[0].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article2.title)
end
it "記事の説明文で検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[1].set @article1.contents[0..15]
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 1)
expect(page.all('.a-search-result__box')[0].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article1.title)
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[1].set @article2.contents[0..15]
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 1)
expect(page.all('.a-search-result__box')[0].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article2.title)
end
it "記事のジャンルで検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[5].all('.genre-tag')[0].click
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 1)
expect(page.all('.a-search-result__box')[0].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article1.title)
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.find('.search-frame').all('.search-frame__box')[5].all('.genre-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 1)
expect(page.all('.a-search-result__box')[0].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article2.title)
end
it "記事タイトル&記事のジャンルで検索" do
Capybara.current_session.driver.browser.manage.window.resize_to(1130, 720)
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[1].set @article1.title
sleep(1)
page.find('.search-frame').all('.search-frame__box')[5].all('.genre-tag')[0].click
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 1)
expect(page.all('.a-search-result__box')[0].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article1.title)
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[1].set @article2.title
sleep(1)
page.find('.search-frame').all('.search-frame__box')[5].all('.genre-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 1)
expect(page.all('.a-search-result__box')[0].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article2.title)
visit root_path
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[1].set @article1.title
sleep(1)
page.find('.search-frame').all('.search-frame__box')[5].all('.genre-tag')[1].click
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 0)
visit root_path
sleep(1)
page.find('.header__search-icon').click
sleep(1)
page.all('.s-window')[1].set @article2.title
sleep(1)
page.find('.search-frame').all('.search-frame__box')[5].all('.genre-tag')[0].click
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 0)
end
end
describe "検索結果のソート機能(video)" do
before do
@user = FactoryGirl.create(:testuser)
# User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>", confirmed_at: Time.now)
@chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
@video_img_file_path = Rails.root.join('spec', 'fixtures/files', 'test_video_thumbnail.jpg')
@chef = Chef.create!(name: "テストさん", phonetic: "てすと", introduction: "テスト経歴", biography: "テスト経歴", chef_avatar: File.open(@chef_img_file_path))
@series1 = Series.create!(title: "テストシリーズ1", introduction: "テストですよ", thumbnail: "hogehohe.jpg", chef: @chef)
@series2 = Series.create!(title: "テストシリーズ2", introduction: "テストですよ", thumbnail: "hogehohe.jpg", chef: @chef)
@video1 = Video.create!(title: "テスト動画1", video_url: "https://player.vimeo.com/video/328143616", introduction: "これはテスト動画1です。", thumbnail: File.open(@video_img_file_path), commentary: "これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。", tag_list: 'フランス料理', video_order: "1", price: 0, series: @series1, created_at: Time.now, like_count: 0)
@video2 = Video.create!(title: "テスト動画2", video_url: "https://player.vimeo.com/video/328143616", introduction: "これはテスト動画2です。", thumbnail: File.open(@video_img_file_path), commentary: "これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。", tag_list: '和食', video_order: "2", price: 0, series: @series2, created_at: Time.now.yesterday, like_count: 1)
visit root_path
end
it "新着順&人気順" do
page.find('.header__search-icon').click
sleep(1)
page.all('.search-frame__submit__btn')[0].click
sleep(2)
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 2)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video1.title} 〜#{@video1.series.title}シリーズ〜")
expect(page.all('.v-s-list__box')[1].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video2.title} 〜#{@video2.series.title}シリーズ〜")
#人気順に切り替え
find("option[value='like']").select_option
expect(page.find('.v-s-list')).to have_selector('.v-s-list__box', count: 2)
expect(page.all('.v-s-list__box')[0].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video2.title} 〜#{@video2.series.title}シリーズ〜")
expect(page.all('.v-s-list__box')[1].find('.v-s-list__box__detail').find('.v-s-list__box__detail__title')).to have_css('p', text: "#{@video1.title} 〜#{@video1.series.title}シリーズ〜")
end
end
describe "検索結果のソート機能(article)" do
before do
@user = FactoryGirl.create(:testuser)
@chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
@article_img_file_path = Rails.root.join('spec', 'fixtures/files', 'article_test.jpg')
@chef = Chef.create!(name: "テストさん", phonetic: "てすと", introduction: "テスト経歴", biography: "テスト経歴", chef_avatar: File.open(@chef_img_file_path))
@article1 = Article.create!(title: "テスト記事1", description: "これはテスト記事1の説明文です。これはテスト記事1です。これはテスト記事です。これはテスト記事です。これはテスト記事です。", contents: "これはテスト記事1の本文です。これはテスト記事1です。これはテスト記事です。これはテスト記事です。これはテスト記事です。", thumbnail: File.open(@article_img_file_path), chef: @chef, tag_list: 'フランス料理', created_at: Time.now, like_count: 0)
@article2 = Article.create!(title: "テスト記事2", description: "これはテスト記事2の説明文です。これはテスト記事2です。これはテスト記事です。これはテスト記事です。これはテスト記事です。", contents: "これはテスト記事2の本文です。これはテスト記事2です。これはテスト記事です。これはテスト記事です。これはテスト記事です。", thumbnail: File.open(@article_img_file_path), chef: @chef, tag_list: 'イタリア料理', created_at: Time.now.yesterday, like_count: 1)
visit root_path
end
it "新着順&人気順" do
page.find('.header__search-icon').click
sleep(1)
page.all('.search-frame__submit__btn')[1].click
sleep(2)
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 2)
expect(page.all('.a-search-result__box')[0].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article1.title)
expect(page.all('.a-search-result__box')[1].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article2.title)
#人気順に切り替え
find("option[value='like']").select_option
expect(page.find('.article__search-result')).to have_selector('.a-search-result__box', count: 2)
expect(page.all('.a-search-result__box')[0].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article2.title)
expect(page.all('.a-search-result__box')[1].find('.a-search-result__box__detail').find('.a-search-result__box__detail__title')).to have_content(@article1.title)
end
end
end<file_sep>ActiveAdmin.register User do
actions :all, except: [:new, :create, :destroy]
index do
column :id
column :email
column :name
column '性別' do |user|
user.userProfile.sex
end
column '勤務先' do |user|
user.userProfile.work_place
end
column '職種' do |user|
user.userProfile.job
end
column '専門分野' do |user|
user.userProfile.specialized_field
end
column '勤務先の所在地' do |user|
user.userProfile.location
end
column '職種' do |user|
user.userProfile.job
end
column '生年月日' do |user|
user.userProfile.birthday
end
column :pay_regi_status
actions
end
end
<file_sep>ActiveAdmin.register Notice do
permit_params :title, :message
end
<file_sep># README
## アプリケーション概要
**3分動画でレベルアップ!プロの料理人向け技術研鑽の動画サイト**
各分野の一流の料理人が実践する各種調理工程における基礎技術を動画を通じて学習できるサイト。
飲食店/レストランで働く料理人をターゲットとしており、ユーザーは無料会員登録することで動画を視聴することができる。
また有料会員(月額負担)になることで有料会員限定の動画の視聴・全動画のレシピ閲覧・お気に入り機能(登録数に制限なし)といったサービスを利用することもできる。
<主な機能>
- お気に入り機能
各動画に対してユーザーはお気に入り登録ができ、マイページで自分のお気に入り動画を一覧で確認することができる。
- レコメンド機能
自ユーザーおよび他ユーザーのお気に入り登録履歴をもとに動画閲覧画面にてレコメンド動画を紹介する。
- タグ付け機能
管理者は各動画の投稿時にはタグ付けを行うことでタグに基づいた動画検索を行うことができる。
- 動画検索機能
料理人・ジャンル(タグ)・キーワード 軸で動画の検索を行うことができる。
- 記事検索機能
ジャンル・キーワード 軸で記事の検索を行うことができる。
- 動画管理機能/記事管理機能
動画&記事の投稿/編集/削除ができる ※動画は直接アップロードするのではなくvimeoに投稿した動画のurlを登録する。
- クレジット支払機能
Pay.jpとの連携によるクレジットカードによる定期課金。
- 管理画面(管理者専用)
gem"active-admin"を利用。この画面から動画・記事の投稿,編集を行う。
## ページ構成
[Top page](https://gyazo.com/bec5520def32bb1cc4bbf1e78f829317)
[My page](https://gyazo.com/8360a8a71e4e378bc9a7a57935bc2905)
[Video page](https://gyazo.com/ec5c48a6fb11a371ce5806509bb67dfc)
[Video search page](https://gyazo.com/831bb1c8a225beb27a0d4290f97e22bb)
[Article page](https://gyazo.com/95ca3f3172845e05d8e51bdca1033814)
[Article search page](https://gyazo.com/a8f6dcb0c5a485662f7ffb841adb7479)
[Account create page](https://gyazo.com/27ffb32797673c83b464810c90d04175)
[Premium account create page](https://gyazo.com/c7dfa65896fb4774abb91b72c020e3b2)
## アプリケーション要件
- usersテーブル(deviseにより生成)
各userは、deviseによるサインイン情報(email、password等)の他に、ユーザ名やプロフィールを設定できる。
- user_profilesテーブル
登録ユーザーのプロフィール情報を保存する。
- seriesesテーブル
テーマの情報(タイトル・解説・サムネイル画像など)を保存する。1つのシリーズに対して複数の動画が所属する(videosテーブル)。
- videosテーブル
動画を保存する。各動画はあるテーマに所属する。
※video_orderカラムにあるテーマ内での動画の再生順番を登録する。
※priceカラムの値が0以上の場合は有料動画。
- chefsテーブル
料理人情報(氏名/略歴など)を保存する。
- video_likesテーブル
各ユーザーの各動画に対するお気に入り登録情報を保存する中間テーブル。
- tagsテーブル
動画の投稿者はその動画にタグをつけることができる。そのタグに基づいてユーザーは動画の検索(ジャンル検索)を行うことができる。
tag_videosテーブルを中間テーブルとしてvideosテーブルとは多対多の関係。
- recipesテーブル
具材・文量を保存する。あるテーマに所属する。
- article_likesテーブル
各ユーザーの各記事に対するお気に入り登録情報を保存する中間テーブル。
- articlesテーブル
投稿された記事の情報(タイトル・文章・サムネイル画像など)を保存するテーブル。
※premiunカラムの値が"true"の場合は有料会員限定記事。
- article_tagsテーブル
記事の投稿者はその記事にタグをつけることができる。そのタグに基づいてユーザーは記事の検索(ジャンル検索)を行うことができる。
tag_articlesテーブルを中間テーブルとしてarticlesテーブルとは多対多の関係。
- noticesテーブル
サイト側からユーザーにお知らせする情報(メンテナンスなどでの利用不可時間の通知など)を保存するテーブル。
保存された情報はユーザーのマイページに表示させる。
- subscriptionテーブル
定期課金に対するユーザーのクレジットカード情報(クレジットカード情報登録時にPay.jpで作成されるcustomer_idなど)を保存するテーブル
- chargesテーブル
クレジットカードでの支払い済み情報を保存するテーブル(user/videoの中間テーブル)。
※支払い時の金額も保存
## DB設計
[ER図](https://gyazo.com/3efcc6ebc726707f87a49c64cf018371)
ユーザー管理
## usersテーブル
|Column|Type|Options|
|------|----|-------|
|name|string|null: false|
|email|string|null: false, unique: true|
|password|string|null: false|
|confirmation_token|string|
|confirmed_at|datetime|
|confirmation_sent_at|datetime|
|unconfirmed_email|string|
|pay_regi_status|integer|
|provider|string|
|uid|string|
|sign_in_count|integer|default: 0, null: false|
|current_sign_in_at|datetime|
|last_sign_in_at|datetime|
|current_sign_in_ip|string|
|last_sign_in_ip|string|
### Association
- has_one :subscriptions
- has_one :user_profiles
- has_many :charges
- has_many :videos, through: :video_likes
- has_many :articles, through: :article_likes
- has_many :videos, through: :charges
## user_profilesテーブル
|Column|Type|Options|
|------|----|-------|
|user_id|references|null: false, foreign_key: true|
|sex|integer|null: false|
|work_place|integer|null: false|
|job|integer|null: false|
|specialized_field|integer|null: false|
|location|integer|null: false|
|birthday|date|null: false|
### Association
- belongs_to :user
動画管理
## Seriesesテーブル
|Column|Type|Options|
|------|----|-------|
|title|string|null: false|
|introduction|string|
|thumbnail|string|
|price|integer|default: 0|
|chef_id|references|null: false, foreign_key: true|
### Association
- has_many :videos
- belongs_to :chef
## video_likesテーブル
|Column|Type|Options|
|------|----|-------|
|video_id|references|null: false, index: true, foreign_key: true|
|user_id|references|null: false, index: true, foreign_key: true|
### Association
- belongs_to :series
- belongs_to :user
## chefsテーブル
|Column|Type|Options|
|------|----|-------|
|name|string|null: false|
|phonetic|string|null: false|
|introduction|string|null: false|
|biography|text|null: false|
|chef_avatar|string|null: false|
### Association
- has_many :serieses
## tag_videosテーブル
|Column|Type|Options|
|------|----|-------|
|video_id|references|null: false, index: true, foreign_key: true|
|tag_id|references|null: false, index: true, foreign_key: true|
### Association
- belongs_to :video
- belongs_to :tag
## tagsテーブル
|Column|Type|Options|
|------|----|-------|
|title|string|null: false|
### Association
- has_many :videos, through: :tag_videos
## recipesテーブル
|Column|Type|Options|
|------|----|-------|
|food|string|null: false|
|amount|string|null: false|
|video_id|references|null: false, foreign_key: true|
### Association
- belongs_to :videos
## videosテーブル
|Column|Type|Options|
|------|----|-------|
|title|string|null: false|
|video_url|string|null: false|
|introduction|string|null: false|
|commentary|string|null: false|
|video_order|integer|null: false|
|like_count|integer|default: 0|
|price|integer|default: 0|
|series_id|references|null: false, foreign_key: true|
### Association
- belongs_to :series
- has_many :users, through: :video_likes
- has_many :recipes
- has_many :tags, through: :tag_videos
- has_many :users, through: :charges
記事管理
## article_likesテーブル
|Column|Type|Options|
|------|----|-------|
|article_id|references|null: false, index: true, foreign_key: true|
|user_id|references|null: false, index: true, foreign_key: true|
### Association
- belongs_to :article
- belongs_to :user
## articlesテーブル
|Column|Type|Options|
|------|----|-------|
|title|string|null: false|
|content|text|null: false|
|thumbnail|string|null: false|
|like_count|integer|
|premium|boolean|null: false|
### Association
- has_many :recipes
- has_many :videos
- belongs_to :chef
- has_many :article_tags, through: :tag_articles
- has_many :users, through: :article_likes
## tag_articleテーブル
|Column|Type|Options|
|------|----|-------|
|article_id|references|null: false, index: true, foreign_key: true|
|article_tag_id|references|null: false, index: true, foreign_key: true|
### Association
- belongs_to :article
- belongs_to :article_tag
## article_tagsテーブル
|Column|Type|Options|
|------|----|-------|
|title|string|null: false|
お知らせ機能
## noticesテーブル
|Column|Type|Options|
|------|----|-------|
|title|string|null: false|
|message|text|null: false|
|end_date|date|null: false|
### Association
クレジット管理機能
## Paymentsテーブル
|Column|Type|Options|
|------|----|-------|
|user_id|integer|null: false, index: true, foreign_key: true|
|customer_id|string|null: false|
|subscription_id|string|null: false|
|plan|string|
|expires_at|datetime|
|created_at|datetime|
|updated_at|datetime|
### Association
- has_one :user
## chargesテーブル
|Column|Type|Options|
|------|----|-------|
|user_id|references|null: false, index: true, foreign_key: true|
|video_id|references|null: false, index: true, foreign_key: true|
|price|integer|
|created_at|datetime|
### Association
- belongs_to :user
- belongs_to :video
<file_sep>class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :unread_check, if: :user_signed_in?
before_action :set_search_data
after_action :store_location
# seo対策 metatag の設定
include MetaTaggable
force_ssl if: :use_ssl?
private
def configure_permitted_parameters
#devise_parameter_sanitizer = 許可するパラメータを追加(railsのバージョンによって書き方が異なるので注意)
devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :pay_regi_status])
devise_parameter_sanitizer.permit(:sign_up, keys: [userProfile_attributes: [:user_id, :sex, :work_place, :job, :specialized_field, :location, :birthday]])
devise_parameter_sanitizer.permit(:account_update, keys: [:name, :pay_regi_status])
devise_parameter_sanitizer.permit(:account_update, keys: [userProfile_attributes: [:user_id, :sex, :work_place, :job, :specialized_field, :location, :birthday]])
end
def store_location
user_id = current_user.id if user_signed_in?
if request.fullpath != "/users/sign_in" &&
request.fullpath != "/users/sign_up" &&
request.fullpath != "/users" &&
request.fullpath != "/payments/new_card/charge" &&
request.fullpath != "/payments/#{user_id}/edit" &&
request.fullpath != "/payments/delete" &&
request.fullpath != "/payments/new_card/subscription" &&
request.fullpath != "/payments/card_change?id=payjp-form&method=post" &&
request.fullpath !~ Regexp.new("\\A/users/password.*\\z") &&
!request.fullpath.include?("/users/confirmation") &&
!request.fullpath.include?("make_suggest")
!request.xhr? # don't store ajax calls
session[:previous_url] = request.fullpath
end
end
def after_sign_in_path_for(resource)
if session[:previous_url] == root_path
super
else
session[:previous_url] || root_path
end
end
def unread_check
@new_notice_ids = Notice.all.order("id desc").limit(3).pluck(:id)
read_notices_ids = NoticeUser.where(user_id: current_user.id, notice_id: @new_notice_ids).pluck(:notice_id)
@unread_notices = (@new_notice_ids - read_notices_ids).length
@unread_notice_ids = (@new_notice_ids - read_notices_ids)
end
def set_search_data
@video_all_genres = Video.tags_on(:tags).order(taggings_count: 'desc')
@article_all_genres = Article.tags_on(:tags).order(taggings_count: 'desc')
@all_chefs = Chef.all
end
def use_ssl?
Rails.env.production?
end
end
<file_sep>module ArticleHelper
def all_article_count_for_index_page(total_count_execpt_newest)
total_count_execpt_newest + 1
end
end
<file_sep>$(document).on('turbolinks:load', function() {
var activeController = $('body').attr('data-controller');
var activeAction = $('body').attr('data-action');
if (activeController == 'top' && activeAction == 'index') {
$('.slider-top').slick({
// アクセシビリティ。左右ボタンで画像の切り替えをできるかどうか
// accessibility: false,
// // 自動再生。trueで自動再生される。
autoplay: true,
// // 自動再生で切り替えをする時間
// autoplaySpeed: 3000,
// // 自動再生や左右の矢印でスライドするスピード
// speed: 400,
// // 自動再生時にスライドのエリアにマウスオンで一時停止するかどうか
// pauseOnHover: false,
// // 自動再生時にドットにマウスオンで一時停止するかどうか
// pauseOnDotsHover: false,
// 切り替えのアニメーション。ease,linear,ease-in,ease-out,ease-in-out
cssEase: 'ease-in-out',
// // 画像下のドット(ページ送り)を表示
// dots: false,
// // ドットのclass名をつける
// dotsClass: 'dot-class',
// // ドラッグができるかどうか
// draggable: true,
// // 切り替え時のフェードイン設定。trueでon
fade: true,
// スライドのエリアに画像がいくつ表示されるかを指定
// slidesToShow: 1,
// 一度にスライドする数
// slidesToScroll: 1,
// タッチスワイプに対応するかどうか
swipe: true,
// 表示中の画像を中央へ
centerMode: true,
focusOnSelect:true,
// 前次ボタンを表示するか [初期値:true]
arrows: false
});
}
});
<file_sep>ActiveAdmin.register CardRegistrationRestrict do
actions :all, except: [:new, :create]
index do
column :user_id
column :user
column :error_count
column :total_error_count
column :locked_at
actions
end
end
<file_sep>module LoginMacros
def login(user)
visit new_user_session_path
fill_in 'user_email', with: user.email
fill_in 'user_password', with: <PASSWORD>
click_button 'ログイン'
expect(page).to have_css('div.flash', text: 'ログインしました。')
end
def logout
find('.header__menu-sign-in').hover
click_link 'ログアウト'
expect(page).to have_css('div.flash', text: 'ログアウトしました。')
end
end
<file_sep>if @search_patarn == 'chef-search'
json.array! @suggests_chef_genre do |g|
json.suggest_chef_genre g
end
else
json.array! @suggests_series do |t|
json.suggest_series t.title
end
json.array! @suggests_genre do |g|
json.suggest_genre g
end
end
<file_sep>class TopController < ApplicationController
before_action :make_top_slide_list
def index
@new_videos = Video.all.order("created_at desc").limit(6)
@new_articles = Article.all.order("created_at desc").limit(6)
@magazine_address_check = MagazineAddress.register_check(current_user)
@french_like_videos = Video.tagged_with("フランス料理", any: true).order("like_count desc").limit(6)
@japanese_like_videos = Video.tagged_with("日本料理", any: true).order("like_count desc").limit(6)
end
private
def make_top_slide_list
@article_top_slides = Article.where(top_slide: true).order("created_at desc").limit(3)
@video_top_slides = Video.all.order("created_at desc").limit(3)
end
end
<file_sep>class Notice < ApplicationRecord
has_many :users, through: :noticeUsers
has_many :noticeUsers, dependent: :destroy
with_options presence: true do
validates :title
validates :message
end
end
<file_sep>Rails.application.routes.draw do
mount Ckeditor::Engine => '/ckeditor'
devise_for :users, controllers: { confirmations: 'users/confirmations', registrations: 'users/registrations', omniauth_callbacks: "users/omniauth_callbacks" }
devise_scope :user do
get '/users/sign_up/:account_patarn' => 'users/registrations#new', as: :new_user_registration_customize
get '/users/edit/:account_patarn' => 'users/registrations#edit', as: :edit_user_registration_customize
get '/users/complete/:sign_in_count' => 'users/registrations#complete', as: :new_user_registration_complete
get '/users/send/:sign_in_count' => 'users/registrations#mail_send', as: :new_user_registration_send
get '/users/delete' => 'users/registrations#delete', as: :delete_user
end
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
resources :top, only: :index
resources :users, only: [:index]
get 'users/my_page/:info_patarn' => "users#my_page", as: :user_my_page
resources :video, only: :show do
collection do
# get 'genre_search'
get 'chef_search'
get 'search'
get 'make_suggest'
end
end
get 'video/chef_search_video/:chef_id' => "video#chef_search_video"
resources :article, only: [:index, :show] do
collection do
get 'genre_search'
get 'search'
end
end
resources :payments, only: [:edit, :create, :destroy] do
collection do
post 'purchase_charge'
post 'purchase_subscription'
post 'card_change'
end
end
get 'payments/new_card/:pay_patarn' => "payments#new_card", as: :new_card_registration
get 'payments/delete' => "payments#delete", as: :delete_payment
post '/video_like/:video_id' => 'video_likes#create', as: 'video_like_create'
delete '/video_like/:video_id' => 'video_likes#destroy', as: 'video_like_destroy'
post '/article_like/:article_id' => 'article_likes#create', as: 'article_like_create'
delete '/article_like/:article_id' => 'article_likes#destroy', as: 'article_like_destroy'
resources :contacts, only: [:new, :create] do
collection do
post 'confirm'
end
end
resources :magazine, only: [:new, :create, :edit, :update, :destroy] do
collection do
post 'confirm'
end
end
root 'top#index'
get '/sitemap' => 'sitemaps#index'
end
<file_sep>class ArticleLikesController < ApplicationController
def create
ArticleLike.create(user_id: current_user.id, article_id: params[:article_id])
@article = Article.find(params[:article_id])
@current_user_like_count = ArticleLike.where(user_id: current_user.id).length
end
def destroy
like = ArticleLike.find_by(user_id: current_user.id, article_id: params[:article_id])
like.destroy
@article = Article.find(params[:article_id])
@current_user_like_count = ArticleLike.where(user_id: current_user.id).length
end
end
<file_sep>class CreatePayments < ActiveRecord::Migration[5.2]
def change
create_table :payments do |t|
t.references :user,index:true, foreign_key:true
t.string :customer_id, null:false
t.string :subscription_id
t.string :plan_id
t.string :last4
t.string :brand
t.string :exp_month
t.string :exp_year
t.datetime :expires_at
t.timestamps
end
end
end
<file_sep>class ArticleLike < ApplicationRecord
belongs_to :article, counter_cache: :like_count
belongs_to :user
end
<file_sep># require 'rails_helper'
# describe User, type: :model do
# describe '#create' do
# context "can save" do
# #全項目に条件を満たす入力があれば保存できる
# it "is valid with a name, email, password, password_confirmation" do
# user = build(:user)
# expect(user).to be_valid
# end
# end
# context "can't save" do
# # メールアドレスが未入力だと保存できない
# it "is invalid without name" do
# user = build(:user, name: nil)
# user.valid?
# expect(user.errors[:name]).to include("が入力されていません。")
# end
# # メールアドレスが未入力だと保存できない
# it "is invalid without email" do
# user = build(:user, email: nil)
# user.valid?
# expect(user.errors[:email]).to include("が入力されていません。")
# end
# # 登録済みのメールアドレスだと保存できない
# it "is invalid with a duplicate email address" do
# #はじめにユーザーを登録
# user = create(:user)
# #先に登録したユーザーと同じemailの値を持つユーザーのインスタンスを作成
# another_user = build(:user)
# another_user.valid?
# expect(another_user.errors[:email]).to include("は既に使用されています。")
# end
# # パスワードが未入力だと保存できない
# it "is invalid without password" do
# user = build(:user, password: nil)
# user.valid?
# expect(user.errors[:password]).to include("が入力されていません。")
# end
# # パスワードとパスワード(確認用)が一致しないと保存できない
# it "is not match password and password_confirmation" do
# user = build(:user, password_confirmation: "gggghhhj")
# user.valid?
# expect(user.errors[:password_confirmation]).to include("が一致しません。")
# end
# # パスワードが6文字未満だと保存できない
# it "is password length less than 6" do
# user = build(:user, password: "ddf")
# user.valid?
# expect(user.errors[:password]).to include("は6文字以上に設定して下さい。")
# end
# # 生年月日が無効な日付だと保存できない
# it "is invalid without names" do
# expect { build(:user2) }.to raise_error(described_class::ArgumentError)
# end
# end
# end
# end
<file_sep>class VideoLike < ApplicationRecord
belongs_to :video, counter_cache: :like_count
belongs_to :user
end
<file_sep>require "rails_helper"
RSpec.describe "Responsive", type: :system do
describe "ナビゲーションバー" do
before do
@user = FactoryGirl.create(:testuser)
end
it "ナビゲーションバーの各リンクから指定のページにアクセスできる(未ログイン&width:640以下)" do
visit root_path
Capybara.current_session.driver.browser.manage.window.resize_to(500, 720)
sleep(1)
page.find(".navi-login-btn").click
sleep(1)
expect(current_path).to eq new_user_session_path
sleep(1)
find(".navigation-bar-sign-up-link").click # "新規登録"
sleep(1)
expect(current_path).to eq users_path
sleep(1)
click_on "ホーム"
sleep(1)
expect(current_path).to eq root_path
sleep(1)
find(".search-btn").click # "さがす"
sleep(1)
expect(page.find('body')).to have_selector('.search-frame', count: 1)
end
it "ナビゲーションバーの各リンクから指定のページにアクセスできる(ログイン済み&width:640以下)" do
login(@user)
visit root_path
Capybara.current_session.driver.browser.manage.window.resize_to(500, 720)
sleep(1)
find(".search-btn").click # "さがす"
sleep(1)
expect(page.find('body')).to have_selector('.search-frame', count: 1)
sleep(1)
click_on "マイページ"
sleep(1)
expect(current_path).to eq user_my_page_path('notice')
sleep(1)
sleep(1)
click_on "ホーム"
sleep(1)
expect(current_path).to eq root_path
sleep(1)
click_on "ログアウト"
sleep(1)
expect(page).to have_css('div.flash', text: 'ログアウトしました。')
end
end
end<file_sep>class VideoController < ApplicationController
def show
@video = Video.find(params[:id])
@chefs = [@video.series.chef]
@recommend_videos = Video.recommend(@video.id)
@series_videos = Video.where(series: @video.series).includes(:charges).order("video_order")
@current_user_like_count = VideoLike.where(user_id: current_user.id).length if user_signed_in?
end
def search
@order_patarn = params[:order_patarn]
@search_word = params[:search_word] if params[:search_word].present?
@chef_id = params[:search_chef_id] if params[:search_chef_id] != [""]
@chef_name = params[:search_chef_name].map { |c| c }.join(',') if params[:search_chef_name].present?
@genre_name = check_genre_name_type(params[:search_genre_name])
@series_title = params[:search_series_title]
@series_id = params[:search_series_id] if params[:search_series_id] != [""]
@search_patarn = 'keyword_search'
q = make_search_query(@search_word, @genre_name)
make_search_result_data(q.result(distinct: true).order("created_at desc")) if @order_patarn == 'new'
make_search_result_data(q.result(distinct: true).order("like_count desc")) if @order_patarn == 'like'
end
def chef_search
@search_word = params_permit_search[:search_word] if params_permit_search[:search_word].present?
@recommend_tags = Chef.tags_on(:tags).order(taggings_count: 'desc').limit(20)
@search_patarn = params_permit_search[:suggest_patarn]
@search_path = '/video/chef_search'
get_keyword_search_chef_results(@search_word) if @search_patarn.blank?
get_chef_genre_search_results(@search_word) if @search_patarn == 'chef_genre'
end
def chef_search_video
@chef = Chef.find(params[:chef_id])
@recommend_tags = Chef.tags_on(:tags).order(taggings_count: 'desc').limit(20)
@search_patarn = 'chef-video'
@search_path = '/video/chef_search'
get_video_of_search_chef_order_new(@chef.series) if params[:order_patarn] == 'new'
get_video_of_search_chef_order_like(@chef.series) if params[:order_patarn] == 'like' || params[:order_patarn].nil?
end
# def make_suggest
# @search_patarn = params[:search_patarn]
# keyword_suggest unless @search_patarn == 'chef-search'
# keyword_suggest_chef if @search_patarn == 'chef-search'
# end
private
def get_video_of_search_chef_order_new(series)
@videos = Video.where(series: series).order("created_at desc").page(params[:page]).per(10)
end
def get_video_of_search_chef_order_like(series)
series_id_list = series.map(&:id)
@videos = Video.where(series: series_id_list).order("like_count desc").page(params[:page]).per(10)
end
def get_keyword_search_chef_results(search_word)
if search_word.present?
query = make_chef_search_query(search_word)
q = Chef.ransack(query)
chef_ids = q.result(distinct: true).pluck(:id)
@chefs = Chef.includes(series: [:videos]).where(id: chef_ids).where.not(videos: { id: nil }).page(params[:page]).per(10) if search_word.present?
else
@chefs = Chef.all.includes(series: [:videos]).order("created_at desc").page(params[:page]).per(10)
end
end
def make_chef_search_query(search_word)
query = {}
query[:groupings] = []
search_word.split(/[ ]/).each_with_index do |word, i|
query[:groupings][i] = { name_or_introduction_or_phonetic_or_biography_or_tags_name_cont: word }
end
query
end
def make_search_query(search_word, genre_name)
query = {}
query[:groupings] = []
search_word = '' if search_word.nil?
search_word.split(/[ ]/).each_with_index do |word, i|
query[:groupings][i] = { title_or_introduction_or_commentary_or_tags_name_cont: word }
end
result = Video.ransack(query) if genre_name.nil? || genre_name.empty?
result = Video.tagged_with(genre_name, any: true).ransack(query) if genre_name.present?
result
end
def make_search_result_data(videos)
videos = videos.joins(:series).where(series_id: @series_id).where("series.chef_id" => @chef_id) if @chef_id.present? && @series_id.present?
videos = videos.joins(:series).where("series.chef_id" => @chef_id) if @chef_id.present? && @series_id.nil?
videos = videos.joins(:series).where(series_id: @series_id) if @chef_id.nil? && @series_id.present?
videos = videos.joins(:series) if @chef_id.nil? && @series_id.nil?
@videos = videos.page(params[:page]).per(10)
end
def get_chef_genre_search_results(search_word)
chef_ids = Chef.tagged_with(search_word).pluck(:id)
@chefs = Chef.includes(series: [:videos]).where(id: chef_ids).where.not(videos: { id: nil }).page(params[:page]).per(10)
end
def check_genre_name_type(genre_name)
genre_name = ["#{genre_name}"] unless genre_name.instance_of?(Array)
genre_name = nil if genre_name == [""]
genre_name
end
def params_permit_search
params.permit(:search_word, :suggest_patarn)
end
def params_permit_search_select
params.permit(:genre)
end
end
<file_sep>require 'payjp'
class MyPayjp
# Payjp::api_key = ENV['PAYJP_PRIVATE_KEY'] # Production
Payjp::api_key = Settings.payjp[:PAYJP_SECRET_KEY] # Development
def self.get_customer_id(payjp_token, current_user)
if current_user.payment.present?
Payjp::Customer.retrieve(id: current_user.payment.customer_id)
else
Payjp::Customer.create(card:payjp_token)
end
rescue => e
e.json_body
end
def self.production_charge(amount, customer)
Payjp::Charge.create(
amount: amount,
customer: customer.id,
currency: 'jpy'
)
rescue => e
e.json_body
end
def self.create_subscription(customer, plan_id)
plan = Payjp::Plan.retrieve(id: plan_id)
Payjp::Subscription.create(customer: customer.id, plan: plan.id)
rescue => e
e.json_body
end
def self.resume_subscription(subscription_id)
subscription = Payjp::Subscription.retrieve(subscription_id)
subscription.resume
end
def self.get_subscription_data(subscription_id)
Payjp::Subscription.retrieve(subscription_id)
rescue => e
e.json_body
end
def self.delete_subscription_data(subscription_id)
subscription = Payjp::Subscription.retrieve(subscription_id)
subscription.delete
rescue => e
e.json_body
end
def method_name
subscription.delete
end
def self.delete_customer(customer_id)
customer = Payjp::Customer.retrieve(customer_id)
customer.delete
rescue => e
e.json_body
end
def self.registration_customer_email(customer, email)
customer.email = email
customer.save
rescue => e
e.json_body
end
def self.cards_add(customer, payjp_token)
customer.cards.create(card: payjp_token, default: true)
rescue => e
e.json_body
end
def self.cards_delete(customer, card_id)
card = customer.cards.retrieve(card_id)
card.delete
end
def self.get_card_data(user)
get_customer_id('-', user).cards.data[0]
end
end
<file_sep>class DateValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
value = record.send("#{attribute}_before_type_cast")
begin
if value.present?
check_date = value[1].to_s + '/' + value[2].to_s + '/' + value[3].to_s
Date.parse check_date
end
rescue ArgumentError
record.errors[attribute] << I18n.t('errors.messages.invalid')
end
end
end
<file_sep>ActiveAdmin.register_page "Dashboard" do
menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") }
content title: proc{ I18n.t("active_admin.dashboard") } do
all_user_count = User.all.count
free_user_count = User.where(pay_regi_status: 0).count
charge_user_count = User.where(pay_regi_status: 1).count
premium_user_count = User.where(pay_regi_status: 2).count
now = Date.current
age = {}
(1..8).each do |num|
from = now.ago(((num + 1) * 10).years)
to = now.ago((num * 10).years)
age["#{(num * 10)}代"] = UserProfile.where(birthday: from...to).count
end
div do
h3 '会員データ'
panel "" do
table do
thead do
tr do
%w[総会員数 無料会員数 従量課金会員数 定期課金会員数].each &method(:th)
end
end
tbody do
tr do
[all_user_count, free_user_count, charge_user_count, premium_user_count].each &method(:td)
end
end
end
columns do
pie_chart({ "無料会員数": free_user_count, "従量課金会員数": charge_user_count, "定期課金会員数": premium_user_count })
end
end
h3 '会員プロフィールデータ'
columns do
column do
panel "性別" do
pie_chart UserProfile.group(:sex).count
end
end
column do
panel "職業" do
pie_chart UserProfile.group(:work_place).count
end
end
column do
panel "職種" do
pie_chart UserProfile.group(:job).count
end
end
end
columns do
column do
panel "専門ジャンル" do
pie_chart UserProfile.group(:specialized_field).count
end
end
column do
panel "都道府県" do
pie_chart UserProfile.group(:location).count
end
end
column do
panel "年齢層" do
pie_chart age
end
end
end
end
end # content
end
<file_sep>require "rails_helper"
describe "ArticleFeature" do
describe "お気に入り登録" do
before(:each) do
User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>", confirmed_at: Time.now)
@chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
@article_img_file_path = Rails.root.join('spec', 'fixtures/files', 'article_test.jpg')
chef = Chef.create!(name: "テストさん", phonetic: "てすと", introduction: "テスト経歴", biography: "テスト経歴", chef_avatar: File.open(@chef_img_file_path))
@article = Article.create!(title: "テスト記事", contents: "これはテスト記事です。これはテスト記事です。これはテスト記事です。これはテスト記事です。これはテスト記事です。", thumbnail: File.open(@article_img_file_path), chef: chef)
visit root_path
end
it "お気に入り登録ができる" do
click_on "ログイン"
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "<PASSWORD>"
click_button "ログイン"
sleep 3
visit article_path(@article.id)
sleep 3
like_btn = find(:xpath, "//a[contains(@href,'article_like')]")
like_btn.click
sleep 3
expect(page).to have_css('.text', text: '1')
end
end
end<file_sep>class MagazineAddress < ApplicationRecord
belongs_to :user
validates :zipcode, format: {with: /\A[0-9]{7}\z/}
def self.register_check(user)
MagazineAddress.find_by(user: user)
end
def self.delete_address(user)
MagazineAddress.find_by(user: user).destroy
end
end
<file_sep>class RenameProdctidColumnToCharges < ActiveRecord::Migration[5.2]
def change
rename_column :charges, :product_id, :payjp_charge_id
end
end
<file_sep>module PayjpMock
def self.prepare_valid_charge
{
"amount": 3500,
"amount_refunded": 0,
"captured": true,
"captured_at": 1433127983,
"card": {
"address_city": nil,
"address_line1": nil,
"address_line2": nil,
"address_state": nil,
"address_zip": nil,
"address_zip_check": "unchecked",
"brand": "Visa",
"country": nil,
"created": 1433127983,
"customer": nil,
"cvc_check": "unchecked",
"exp_month": 2,
"exp_year": 2020,
"fingerprint": "e<PASSWORD>",
"id": "car_d0e44730f83b0a19ba6caee04160",
"last4": "4242",
"name": nil,
"object": "card"
},
"created": 1433127983,
"currency": "jpy",
"customer": nil,
"description": nil,
"expired_at": nil,
"failure_code": nil,
"failure_message": nil,
"id": "ch_fa990a4c10672a93053a774730b0a",
"livemode": false,
"metadata": nil,
"object": "charge",
"paid": true,
"refund_reason": nil,
"refunded": false,
"subscription": nil
}
end
def self.create_customer
{
"cards": {
"count": 0,
"data": [],
"has_more": false,
"object": "list",
"url": "/v1/customers/cus_121673955bd7aa144de5a8f6c262/cards"
},
"created": 1433127983,
"default_card": nil,
"description": "test",
"email": nil,
"id": "cus_121673955bd7aa144de5a8f6c262",
"livemode": false,
"metadata": nil,
"object": "customer",
"subscriptions": {
"count": 0,
"data": [],
"has_more": false,
"object": "list",
"url": "/v1/customers/cus_121673955bd7aa144de5a8f6c262/subscriptions"
}
}
end
def self.create_charge
{'amount' => 100, 'id'=> 'ch_fa990a4c10672a93053a774730b0a'}
end
def self.create_customer_error
{
"error": {
"code": "invalid_param_key",
"message": "Invalid param key to customer.",
"param": "dummy",
"status": 400,
"type": "client_error"
}
}
end
def self.create_subscription
{
"canceled_at": nil,
"created": 1433127983,
"current_period_end": 1435732422,
"current_period_start": 1433140422,
"customer": "cus_4df4b5ed720933f4fb9e28857517",
"id": "sub_567a1e44562932ec1a7682d746e0",
"livemode": false,
"metadata": nil,
"object": "subscription",
"paused_at": nil,
"plan": {
"amount": 1000,
"billing_day": nil,
"created": 1432965397,
"currency": "jpy",
"id": "pln_9589006d14aad86aafeceac06b60",
"livemode": false,
"metadata": {},
"interval": "month",
"name": "test plan",
"object": "plan",
"trial_days": 0
},
"resumed_at": nil,
"start": 1433140422,
"status": "active",
"trial_end": nil,
"trial_start": nil,
"prorate": false
}
end
def self.customer_retrieve
{
"cards": {
"count": 0,
"data": [],
"has_more": false,
"object": "list",
"url": "/v1/customers/cus_121673955bd7aa144de5a8f6c262/cards"
},
"created": 1433127983,
"default_card": nil,
"description": "test",
"email": nil,
"id": "cus_121673955bd7aa144de5a8f6c262",
"livemode": false,
"metadata": nil,
"object": "customer",
"subscriptions": {
"count": 0,
"data": [],
"has_more": false,
"object": "list",
"url": "/v1/customers/cus_121673955bd7aa144de5a8f6c262/subscriptions"
}
}
end
def self.get_subscription_data
{
"canceled_at": nil,
"created": 1433127983,
"current_period_end": 1435732422,
"current_period_start": 1433140422,
"customer": "cus_4df4b5ed720933f4fb9e28857517",
"id": "sub_567a1e44562932ec1a7682d746e0",
"livemode": false,
"metadata": nil,
"object": "subscription",
"paused_at": nil,
"plan": {
"amount": 1000,
"billing_day": nil,
"created": 1432965397,
"currency": "jpy",
"id": "pln_9589006d14aad86aafeceac06b60",
"livemode": false,
"metadata": {},
"interval": "month",
"name": "test plan",
"object": "plan",
"trial_days": 0
},
"resumed_at": nil,
"start": 1433140422,
"status": "active",
"trial_end": nil,
"trial_start": nil,
"prorate": false
}
end
end<file_sep>ActiveAdmin.register Contact do
actions :all, except: [:new, :create, :destroy]
end
<file_sep>class Recipe < ApplicationRecord
belongs_to :video
with_options presence: true do
validates :food
validates :amount
end
end
<file_sep>class Video < ApplicationRecord
belongs_to :series
has_many :recipes, dependent: :destroy
has_many :charges, dependent: :destroy
has_many :users, through: :charges
has_many :video_likes, dependent: :destroy
accepts_nested_attributes_for :recipes, allow_destroy: true
mount_uploader :thumbnail, VideoThumbnailUploader
acts_as_taggable_on :tags
with_options presence: true do
validates :title
validates :video_url
validates :introduction
validates :commentary
validates :video_order
validates :thumbnail
validates :series_id
end
def self.update_duplicate_video_order_some_series(series_id, crud_patarn, old_video_order, new_video_order)
if crud_patarn == 'edit' && old_video_order < new_video_order
Video.where('video_order > ?', old_video_order).where('video_order <= ?', new_video_order).where(series_id: series_id).find_each { |v| v.update(video_order: v.video_order - 1) }
elsif crud_patarn == 'delete'
Video.where('video_order > ?', old_video_order).where(series_id: series_id).find_each { |v| v.update(video_order: v.video_order - 1) }
else
Video.where('video_order >= ?', new_video_order).where(series_id: series_id).find_each { |v| v.update(video_order: v.video_order + 1) }
end
end
def self.update_duplicate_video_order_another_series(new_series_id, old_series_id, old_video_order, new_video_order)
Video.where('video_order > ?', old_video_order).where(series_id: old_series_id).find_each { |v| v.update(video_order: v.video_order - 1) }
Video.where('video_order >= ?', new_video_order).where(series_id: new_series_id).find_each { |v| v.update(video_order: v.video_order + 1) }
end
def self.tag_count(tags)
Video.tagged_with(tags, any: true).count(:all)
end
def like_user(user_id)
video_likes.find_by(user_id: user_id)
end
def self.recommend(video_id) #python側へリクエスト送信
begin
uri = self.create_uri()
req = self.create_api_request(uri)
http = self.create_http(uri)
req = self.create_requet_content(req, video_id)
res = http.request(req)
id_list = res.body.split(',')
id_list = Video.all.order(id: :desc).limit(8).pluck(:id) if id_list.length == 0
Video.where(id: id_list).order(['field(id, ?)', id_list])
rescue
Video.where.not(id: video_id).order(id: :desc).limit(8)
end
end
def self.create_uri()
api_url = 'https://n8jtwk1ygc.execute-api.ap-northeast-1.amazonaws.com/dev/recommend'
uri = URI.parse(api_url)
end
def self.create_api_request(uri)
req = Net::HTTP::Post.new(uri.request_uri)
end
def self.create_http(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http
end
def self.create_requet_content(req, video_id)
req["Content-Type"] = "application/json"
req.body = { "id" => video_id }.to_json
req
end
end
<file_sep>$(function(){
var videoCrudPatarn = $('#videoCrudPatarn').val();
if (videoCrudPatarn == 'edit'){
var series_video_count = parseInt( $( 'option:selected', '#series_id').attr('video-count') );
var $options = $('option','#video_orders');
for (var i=0; i < $options.length; i++) {
$options.eq(i).show()
if( parseInt($options.eq(i).val()) > series_video_count ){
$options.eq(i).hide()
}
}
}
$(document).on('change', '#series_id', function() {
var series_video_count = parseInt($('option:selected', this).attr('video-count')) + 1;
var $options = $('option','#video_orders');
for (var i=0; i < $options.length; i++) {
$options.eq(i).show()
if( parseInt($options.eq(i).val()) > series_video_count ){
$options.eq(i).hide()
}
}
});
});
<file_sep>$(document).on('turbolinks:load', function(){
var e = $("#refreshed").val();
if(e == "no"){
$("#refreshed").val("yes");
}else{
$("#refreshed").val("no");
location.reload();
}
});
<file_sep># module Sns::Tw extend self
module PayjpCheckSubscStatus extend self
def check_status
@users = User.where(pay_regi_status: 2)
@user.each do |user|
next if user.payment.subscription_id.nil?
subscription_id = user.payment.subscription_id
begin
subscription = MyPayjp.get_subscription_data(subscription_id)
rescue # 失敗時の対応
next
end
expires_at = Time.zone.at(subscription.current_period_end)
# 定額プランの有効期日が現在より過去の場合は定額課金を停止する
unless expires_at > Time.now
user.pay_regi_status = 100
subscription.pause
end
end
end
end
<file_sep>class CreateUserProfiles < ActiveRecord::Migration[5.2]
def change
create_table :user_profiles do |t|
t.references :user,index:true, foreign_key:true
t.integer :sex,null:false
t.integer :work_place,null:false
t.integer :job,null:false
t.integer :specialized_field,null:false
t.integer :location,null:false
t.date :birthday,null:false
t.timestamps
end
end
end
<file_sep>ActiveAdmin.register Series do
permit_params :title, :introduction, :thumbnail, :price, :chef_id
index do
column :id
column :title
column :price
column :chef
actions
end
form do |f|
f.inputs do
f.input :title
f.input :introduction
f.input :thumbnail
f.input :price
f.input :chef_id, as: :select, collection: Chef.all.map { |c| [c.name, c.id] }
end
f.actions
end
end
<file_sep>class UsersController < ApplicationController
def index
end
def my_page
account_patarn_check
@info_patarn = configure_info_patarn_params[:info_patarn]
@notices = Notice.all.order("id desc").limit(3) if @info_patarn == 'notice'
old_read_notice_delete(@new_notice_ids) && unread_notice_to_read if @info_patarn == 'notice' && @unread_notice_ids.present?
@videos = current_user.videos.page(params[:page]).per(10) if @info_patarn == 'pay_video'
@videos = make_like_video_list if @info_patarn == 'like_video'
@articles = make_like_article_list if @info_patarn == 'like_article'
@magazine_address_check = MagazineAddress.register_check(current_user)
@addressee = make_addressee_text if @magazine_address_check
return unless @info_patarn == 'pay_info' && current_user.payment.present?
get_card_info(current_user)
end
private
def account_patarn_check
@account_patarn = current_user.provider
@account_patarn = 'mail' if current_user.provider.nil?
@account_aouth = 'Facebook' if @account_patarn == 'facebook'
@account_aouth = 'twitter' if @account_patarn == 'twitter'
@account_aouth = 'メールアドレス' if @account_patarn == 'mail'
end
def configure_info_patarn_params
params.permit(:info_patarn)
end
def change_card_name(brand)
if brand == 'American Express'
'AmericanExpress'
else
'DinersClub'
end
end
def get_card_info(user)
card = MyPayjp.get_card_data(user)
brand = card.brand
brand = change_card_name(brand) if ['American Express', 'Diners Club'].include?(brand)
@card_brand = brand
@last4 = card.last4
@exp_month = card.exp_month
@exp_year = card.exp_year
@expires_at = current_user.payment.expires_at
end
def make_like_video_list
like_videos = VideoLike.where(user_id: current_user.id).includes(:video)
videos = []
like_videos.each do |like_video|
videos << like_video.video
end
Kaminari.paginate_array(videos).page(params[:page]).per(10)
end
def make_like_article_list
like_articles = ArticleLike.where(user_id: current_user.id).includes(:article)
articles = []
like_articles.each do |like_article|
articles << like_article.article
end
Kaminari.paginate_array(articles).page(params[:page]).per(10)
end
def unread_notice_to_read
@unread_notice_ids.each do |notice_id|
NoticeUser.create(user_id: current_user.id, notice_id: notice_id)
end
@unread_notices = 0
end
def old_read_notice_delete(new_notices)
NoticeUser.where.not(notice_id: new_notices).where(user_id: current_user.id).destroy_all
end
def make_addressee_text
@magazine_address = MagazineAddress.find_by(user_id: current_user.id)
addressee = (@magazine_address.pref + @magazine_address.city_address[0..4]) + '******'
end
end
<file_sep>class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable, :confirmable, :lockable
has_one :userProfile, dependent: :destroy, inverse_of: :user
has_one :payment, dependent: :destroy, inverse_of: :user
has_one :magazine_address, dependent: :destroy, inverse_of: :user
has_many :charges, dependent: :destroy
has_many :cardRegistrationRestrict, dependent: :destroy
has_many :videos, through: :charges
has_many :notices, through: :noticeUsers
has_many :noticeUsers, dependent: :destroy
has_many :video_likes, dependent: :destroy
has_many :article_likes, dependent: :destroy
accepts_nested_attributes_for :userProfile
validates :name, presence: true, length: { in: 1..15 }
enum pay_regi_status: { "無料会員" => 0, "カード登録のみ" => 1, "メルマガ有料会員" => 2 }
def self.find_for_facebook_oauth(auth, signed_in_resource = nil)
User.find_by(provider: auth.provider, uid: auth.uid)
end
def self.find_for_twitter_oauth(auth, signed_in_resource = nil)
User.find_by(provider: auth.provider, uid: auth.uid)
end
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
user.email = data["email"] if user.email.blank?
user.provider = data["provider"] if user.provider.blank?
user.uid = data["uid"] if user.uid.blank?
user.password = Devise.friendly_token[0, 20] if user.password.blank?
end
if data = session["devise.twitter_data"]
user.email = data["email"] if user.email.blank?
user.provider = data["provider"] if user.provider.blank?
user.uid = data["uid"] if user.uid.blank?
user.password = Devise.friendly_token[0, 20] if user.password.blank?
end
end
end
def update_without_current_password(params, *options)
params.delete(:current_password)
if params[:password].blank? && params[:password_confirmation].blank?
params.delete(:password)
params.delete(:password_confirmation)
end
result = update(params, *options)
clean_up_passwords
result
end
def self.update_pay_regi_status(user, pay_patarn)
user.pay_regi_status = 1 if pay_patarn == 'charge' # 1 = カード登録済み(定額課金ではない),2 = 定額課金利用
user.pay_regi_status = 2 if pay_patarn == 'subscription'
user.save!
end
def self.delete_user_subscription_data(user)
user.pay_regi_status = 1
user.save!
user.payment.subscription_id = nil
user.payment.plan_id = nil
user.payment.save!
end
end
<file_sep>$(document).on('turbolinks:load', function() {
var activeController = $('body').attr('data-controller');
var activeAction = $('body').attr('data-action');
if (activeController == 'contacts' && activeAction == 'confirm') {
$(document).on('click','.contact-submit',function(e){
$(this).prop('disabled', true).css("opacity", 0.6);
$(this).parents('form').submit();
});
}
});
<file_sep>class CreateRecipes < ActiveRecord::Migration[5.2]
def change
create_table :recipes do |t|
t.string :food, null: false
t.string :amount, null: false
t.references :video, null: false, foreign_key: true
end
end
end
<file_sep>class ContactMailer < ApplicationMailer
add_template_helper(ApplicationHelper)
def contact_mail(contact)
@contact = contact
mail to: '<EMAIL>', subject: "お客様からCOOK LABにお問い合わせがありました。"
end
end
<file_sep>class CreateSeries < ActiveRecord::Migration[5.2]
def change
create_table :series do |t|
t.string :title, null: false
t.string :introduction
t.string :thumbnail
t.integer :price, default: 0
t.references :chef, null: false, foreign_key: true
t.timestamps
end
end
end
<file_sep>module MagazineHelper
def set_crud_path(crud_patarn)
if crud_patarn == 'create'
magazine_index_path
else
magazine_path(@magazine_address.id)
end
end
def set_crud_method(crud_patarn)
if crud_patarn == 'create'
'POST'
else
'PATCH'
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe MagazineController, type: :controller do
end
<file_sep>class MagazineController < ApplicationController
before_action :magazine_address_confirm_params, only: [:confirm]
before_action :magazine_address_update_confirm_params, only: [:confirm]
before_action :magazine_address_create_params, only: [:create]
def new
@magazine_address = MagazineAddress.new
@crud_patarn = 'create'
end
def confirm
@crud_patarn = params[:crud_patarn]
if @crud_patarn == 'create'
@magazine_address = MagazineAddress.new(magazine_address_confirm_params)
return if @magazine_address.valid?
render :new
elsif @crud_patarn == 'update'
@magazine_address = MagazineAddress.new(magazine_address_update_confirm_params)
return if @magazine_address.valid?
render :edit
end
end
def create
MagazineAddress.create(magazine_address_create_params.merge(user_id: current_user.id)) unless MagazineAddress.find_by(user_id: current_user.id)
if current_user.pay_regi_status_before_type_cast == 0
@pay_patarn = 'subscription'
redirect_to new_card_registration_path('subscription') # renderでなくredirectしないとpayjp tokenの発行ができない
elsif current_user.pay_regi_status_before_type_cast == 1
# クレジットカードの登録が完了済みの場合はメルマガ有料会員登録の最終確認画面を表示
@confirm_patarn = 'magazine_and_credit_finish'
render 'payments/confirm'
end
end
def edit
@magazine_address = MagazineAddress.find_by(user_id: current_user.id)
@crud_patarn = 'update'
end
def update
MagazineAddress.update(magazine_address_create_params.merge(user_id: current_user.id))
render 'complete'
end
private
def magazine_address_confirm_params
params.require(:magazine_address).permit(:address, :zipcode, :building).merge(pref: params[:pref], city_address: params[:city_address])
end
def magazine_address_update_confirm_params
params.require(:magazine_address).permit(:address, :zipcode, :building).merge(pref: params[:pref], city_address: params[:city_address], id: params[:id])
end
def magazine_address_create_params
params.require(:magazine_address).permit(:address, :zipcode, :pref, :city_address, :building)
end
end<file_sep>class AddColumnToArticle < ActiveRecord::Migration[5.2]
def change
add_column :articles, :top_slide, :boolean, after: :chef_id, default: false, null: false
end
end
<file_sep>class VideoLikesController < ApplicationController
def create
VideoLike.create(user_id: current_user.id, video_id: params[:video_id])
@video = Video.find(params[:video_id])
@current_user_like_count = VideoLike.where(user_id: current_user.id).length
end
def destroy
like = VideoLike.find_by(user_id: current_user.id, video_id: params[:video_id])
like.destroy
@video = Video.find(params[:video_id])
@current_user_like_count = VideoLike.where(user_id: current_user.id).length
end
end
<file_sep>FactoryGirl.define do
factory :testuser, class: User do
name { 'capybara' }
email { '<EMAIL>' }
password { '<PASSWORD>' }
password_confirmation { "<PASSWORD>" }
confirmed_at { Time.now }
end
end<file_sep>class Chef < ApplicationRecord
has_many :series, dependent: :destroy
has_many :articles, dependent: :destroy
acts_as_taggable_on :tags
mount_uploader :chef_avatar, ChefAvatarUploader
with_options presence: true do
validates :name
validates :phonetic
validates :introduction
validates :biography
validates :chef_avatar
end
def self.chef_search(chef_search_name)
Chef.where("name LIKE :search_name OR phonetic LIKE :search_name", search_name: "%#{chef_search_name}%")
end
def self.tag_count(tags)
Chef.tagged_with(tags, any: true).count(:all)
end
end
<file_sep>class ChangeDatatypePayregistatusOfUsers < ActiveRecord::Migration[5.2]
def change
change_column :users, :pay_regi_status, :integer, defalt: 0, null: false
end
end
<file_sep>class ArticleController < ApplicationController
before_action :make_recommend_like_article_list
before_action :make_article_genre_list
def index
@newest_article = Article.all.order(id: "desc").limit(1)[0]
@articles = Article.where.not(id: @newest_article.id).order("created_at desc").page(params[:page]).per(10) if params[:order] == 'new' || params[:order].nil?
@articles = make_all_like_article_list if params[:order] == 'like'
@search_path = '/article/search'
end
def show
@article = Article.find(params[:id])
@search_path = '/article/search'
@current_user_like_count = ArticleLike.where(user_id: current_user.id).length if user_signed_in?
end
def genre_search
@genre_search_path = '/article/genre_search'
@search_path = '/article/search'
@search_patarn = 'genre'
@genre_name = check_genre_name_type(params_permit_search_select[:search_genre_name])
get_genre_search_results_order_new(@genre_name) if params[:order_patarn] == 'new'
get_genre_search_results_order_like(@genre_name) if @genre_name.present? && (params[:order_patarn] == 'like' || params[:order_patarn].nil?)
end
def search
@search_patarn = 'keyword'
@search_word = params_permit_search[:search_word] if params_permit_search[:search_word].present?
@genre_name = check_genre_name_type(params[:search_genre_name])
get_search_results_order_new(@search_word, @genre_name) if params[:order_patarn] == 'new'
get_search_results_order_like(@search_word, @genre_name) if (params[:order_patarn] == 'like' || params[:order_patarn].nil?)
end
private
def make_recommend_like_article_list
@like_articles = Article.all.order("like_count desc").limit(5)
end
def make_search_result_like_article_list(search_hit_list)
search_hit_article_id_list = search_hit_list.map(&:id) unless search_hit_list.nil?
Article.where(id: search_hit_article_id_list).order("like_count desc").page(params[:page]).per(10)
end
def make_all_like_article_list
Article.all.order("like_count desc").page(params[:page]).per(10)
end
def get_search_results_order_new(search_word, genre_name)
q = make_article_search_query(search_word)
@articles = q.result(distinct: true).order("created_at desc").page(params[:page]).per(10) if genre_name.nil?|| genre_name == ""
@articles = q.result(distinct: true).tagged_with(genre_name).order("created_at desc").page(params[:page]).per(10) if genre_name.present?
end
def get_search_results_order_like(search_word, genre_name)
q = make_article_search_query(search_word)
articles = q.result(distinct: true).order("created_at desc") if genre_name.nil? || genre_name == ""
articles = q.result(distinct: true).tagged_with(genre_name).order("created_at desc") if genre_name.present?
@articles = make_search_result_like_article_list(articles)
end
def make_article_search_query(search_word)
query = {}
query[:groupings] = []
search_word = '' if search_word.nil?
search_word.split(/[ ]/).each_with_index do |word, i|
query[:groupings][i] = { title_or_contents_or_tags_name_cont: word }
end
Article.ransack(query)
end
def get_genre_search_results_order_new(search_word)
@articles = Article.tagged_with(search_word).order("created_at desc").page(params[:page]).per(10)
end
def get_genre_search_results_order_like(search_word)
articles = Article.tagged_with(search_word).order("created_at desc")
@articles = make_search_result_like_article_list(articles)
end
def make_article_genre_list
@genre_tags = Article.tags_on(:tags)
end
def check_genre_name_type(genre_name)
genre_name = ["#{genre_name}"] unless genre_name.instance_of?(Array)
genre_name = nil if genre_name == [""]
genre_name
end
def params_permit_search
params.permit(:search_word, :suggest_patarn)
end
def params_permit_search_select
params.permit(:search_genre_name)
end
end
<file_sep>class SitemapsController < ApplicationController
def index
@domain = "#{request.protocol}#{request.host}"
@videos = Video.all
@articles = Article.all
end
end
<file_sep>require "rails_helper"
describe "UserFeature" do
describe "メール認証でサインアップする" do
before do
visit root_path
# 新規登録ボタンをクリック
page.first(".new-btn").click
end
it "ユーザー情報の入力後に登録ボタンを押すと認証メールが送信される" do
click_on "メールアドレスで登録"
sleep 2
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "<PASSWORD>"
fill_in "user_password_confirmation", with: "<PASSWORD>"
fill_in "user_name", with: "Example User"
sleep 2
expect { click_button "新規登録" }.to change { ActionMailer::Base.deliveries.count }.by(1)
end
before do
visit root_path
# 新規登録ボタンをクリック
page.first(".new-btn").click
end
it "ユーザー情報の入力後に登録ボタンを押すとメール認証の案内ページに遷移する" do
click_on "メールアドレスで登録"
sleep 2
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "<PASSWORD>"
fill_in "user_password_confirmation", with: "<PASSWORD>"
fill_in "user_name", with: "Example User"
click_button "新規登録"
sleep 2
expect(current_path).to eq "/users/send/0"
end
end
describe "メール認証でログインする" do
before do # confirmed_atが未定義だと本登録が完了していない状態になりログインできない
User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>", confirmed_at: Time.now)
visit root_path
end
it "メール認証が完了している場合はログインできる" do
click_on "ログイン"
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "<PASSWORD>"
click_button "ログイン"
expect(page).to have_css('div.flash', text: 'ログインしました。')
end
end
describe "メール認証でログイン不可" do
before do # confirmed_atが未定義だと本登録が完了していない状態になりログインできない
User.create!(name: 'capybara', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>")
visit root_path
end
it "メール認証が完了していない場合はログインできない" do
click_on "ログイン"
fill_in "user_email", with: "<EMAIL>"
fill_in "user_password", with: "<PASSWORD>"
click_button "ログイン"
expect(page).to have_css('div.flash', text: '本登録を行ってください。')
end
end
describe "facebook認証でサインアップする" do
before do
OmniAuth.config.mock_auth[:facebook] = nil
Rails.application.env_config['omniauth.auth'] = facebook_mock
visit root_path
# 新規登録ボタンをクリック
page.first(".new-btn").click
end
it "Facebook認証が完了したらユーザー情報の登録画面に切り替わり、そこでユーザー情報を入力し新規登録ボタンを押すと登録完了画面に遷移する" do
#"Facebookで登録" ボタンをクリック
click_on "Facebookで登録"
sleep 2
fill_in "user_name", with: "Example User"
click_button "新規登録"
sleep 2
expect(current_path).to eq "/users/complete/0"
end
end
describe "facebook認証でログインする" do
before do
OmniAuth.config.mock_auth[:facebook] = nil
Rails.application.env_config['omniauth.auth'] = facebook_mock
visit root_path
# 新規登録ボタンをクリック
page.first(".new-btn").click
end
it "Facebook認証でログインできる" do
#"Facebookで登録" ボタンをクリック
click_on "Facebookで登録"
sleep 2
fill_in "user_name", with: "Example User"
click_button "新規登録"
sleep 2
click_on "ログアウト"
sleep 2
click_on "ログイン"
click_on "Facebook"
expect(page).to have_css('div.flash', text: 'Facebook から承認されました。')
expect(current_path).to eq root_path
end
end
describe "twitter認証でサインアップする" do
before do
OmniAuth.config.mock_auth[:twitter] = nil
Rails.application.env_config['omniauth.auth'] = twitter_mock
visit root_path
# 新規登録ボタンをクリック
page.first(".new-btn").click
end
it "twitter認証が完了したらユーザー情報の登録画面に切り替わり、そこでユーザー情報を入力し新規登録ボタンを押すと登録完了画面に遷移する" do
#"Facebookで登録" ボタンをクリック
click_on "Twitterで登録"
# expect(current_path).to eq "/users/sign_up/twitter"
sleep 2
fill_in "user_name", with: "Example User"
click_button "新規登録"
sleep 2
expect(current_path).to eq "/users/complete/0"
end
end
describe "twitter認証でログインする" do
before do
OmniAuth.config.mock_auth[:twitter] = nil
Rails.application.env_config['omniauth.auth'] = twitter_mock
visit root_path
# 新規登録ボタンをクリック
page.first(".new-btn").click
end
it "twitter認証でログインできる" do
#"Facebookで登録" ボタンをクリック
click_on "Twitterで登録"
# expect(current_path).to eq "/users/sign_up/twitter"
sleep 2
fill_in "user_name", with: "Example User"
click_button "新規登録"
sleep 2
click_on "ログアウト"
sleep 2
click_on "ログイン"
click_on "Twitter"
expect(page).to have_css('div.flash', text: 'Twitter から承認されました。')
expect(current_path).to eq root_path
end
end
end<file_sep>json.array! @result do |r|
json.charge_result r
end
<file_sep>require "rails_helper"
describe "AdminUserFeature" do
describe "料理人登録ができる" do
before(:each) do
@chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
AdminUser.create!(email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>")
visit admin_root_path
fill_in "admin_user_email", with: "<EMAIL>"
fill_in "admin_user_password", with: "<PASSWORD>"
click_on "ログイン"
end
it "全ての項目を入力すれば料理人が登録される" do
visit new_admin_chef_path
sleep 2
fill_in "chef_name", with: "テスト"
fill_in "chef_phonetic", with: "てすと"
fill_in "chef_introduction", with: "これはテストです。"
fill_in "chef_biography", with: "これはテストです。これはテストです。これはテストです。これはテストです。これはテストです。"
# attach_file('chef_chef_avatar', @chef_img_file_path)
click_button "料理人を作成"
sleep 2
expect(current_path).to eq admin_chefs_path
end
end
# describe "動画シリーズ登録ができる" do
# before(:each) do
# @chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
# @video_img_file_path = Rails.root.join('spec', 'fixtures/files', 'test_video_thumbnail.jpg')
# Chef.create!(name: "テストさん", phonetic: "てすと", introduction: "テスト経歴", biography: "テスト経歴", chef_avatar: File.open(@chef_img_file_path))
# AdminUser.create!(email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>")
# visit admin_root_path
# fill_in "admin_user_email", with: "<EMAIL>"
# fill_in "admin_user_password", with: "<PASSWORD>"
# click_on "ログイン"
# end
# it "全ての項目を入力すればシリーズが登録される" do
# visit new_admin_series_path
# sleep 2
# fill_in "series_title", with: "テストシリーズ"
# fill_in "series_introduction", with: "これはテストです。"
# select "テストさん", from: "series_chef_id"
# click_button "動画シリーズを作成"
# sleep 2
# expect(page).to have_css('#page_title', text: 'テストシリーズ')
# end
# end
# describe "ビデオ登録ができる" do
# before(:each) do
# @chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
# @video_img_file_path = Rails.root.join('spec', 'fixtures/files', 'test_video_thumbnail.jpg')
# chef = Chef.create!(name: "テストさん", phonetic: "てすと", introduction: "テスト経歴", biography: "テスト経歴", chef_avatar: File.open(@chef_img_file_path))
# Series.create!(title: "テスト", introduction: "テストですよ", thumbnail: "hogehohe.jpg", chef: chef)
# AdminUser.create!(email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>")
# visit admin_root_path
# fill_in "admin_user_email", with: "<EMAIL>"
# fill_in "admin_user_password", with: "<PASSWORD>"
# click_on "ログイン"
# end
# it "全ての項目を入力すればビデオが登録される" do
# visit new_admin_video_path
# sleep 2
# fill_in "video_title", with: "テスト動画"
# fill_in "video_video_url", with: "https://player.vimeo.com/video/328143616"
# fill_in "video_introduction", with: "これはテスト動画です。"
# fill_in "video_commentary", with: "これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。これはテスト動画です。"
# select "1", from: "video_orders"
# fill_in "video_price", with: "0"
# select "テスト", from: "series_id"
# attach_file('video_thumbnail', @video_img_file_path)
# click_button "ビデオを作成"
# sleep 2
# expect(current_path).to eq admin_videos_path
# end
# end
# describe "記事の登録ができる" do
# before(:each) do
# @chef_img_file_path = Rails.root.join('spec', 'fixtures/files', 'chef_test.jpg')
# @article_img_file_path = Rails.root.join('spec', 'fixtures/files', 'article_test.jpg')
# chef = Chef.create!(name: "テストさん", phonetic: "てすと", introduction: "テスト経歴", biography: "テスト経歴", chef_avatar: File.open(@chef_img_file_path))
# AdminUser.create!(email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>")
# visit admin_root_path
# fill_in "admin_user_email", with: "<EMAIL>"
# fill_in "admin_user_password", with: "<PASSWORD>"
# click_on "ログイン"
# end
# it "全ての項目を入力すれば記事が登録される" do
# visit new_admin_article_path
# sleep 2
# fill_in "article_title", with: "テスト記事"
# fill_in "article-contents", with: "これはテスト記事です。これはテスト記事です。これはテスト記事です。これはテスト記事です。これはテスト記事です。"
# select "テストさん", from: "article_chef_id"
# attach_file('article_thumbnail', @article_img_file_path)
# click_button "記事を作成"
# sleep 2
# expect(current_path).to eq admin_articles_path
# end
# end
# describe "お知らせの登録ができる" do
# before(:each) do
# AdminUser.create!(email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: "<PASSWORD>")
# visit admin_root_path
# fill_in "admin_user_email", with: "<EMAIL>"
# fill_in "admin_user_password", with: "<PASSWORD>"
# click_on "ログイン"
# end
# it "全ての項目を入力すれば記事が登録される" do
# visit new_admin_notice_path
# sleep 2
# fill_in "notice_title", with: "お知らせテスト"
# fill_in "notice_message", with: "これはテストです。これはテストです。これはテストです。これはテストです。これはテストです。"
# click_button "お知らせを作成"
# sleep 2
# expect(page).to have_css('#page_title', text: 'お知らせテスト')
# end
# end
end<file_sep>class Payment < ApplicationRecord
belongs_to :user, inverse_of: :userProfile, optional: true
def self.registration_card_data(customer, current_user)
payment = Payment.new
payment.customer_id = customer.id
payment.user_id = current_user.id
payment.save!
end
def self.set_subscription_data(subscription_data, plan_id, customer, user)
if user.payment.present?
payment = user.payment
payment.subscription_id = subscription_data.id
payment.plan_id = plan_id
payment.expires_at = Time.zone.at(subscription_data.current_period_end)
else
payment = Payment.new
payment.subscription_id = subscription_data.id
payment.plan_id = plan_id
payment.expires_at = Time.zone.at(subscription_data.current_period_end)
payment.customer_id = customer.id
payment.user_id = user.id
end
payment.save!
end
end
<file_sep>class CreateVideos < ActiveRecord::Migration[5.2]
def change
create_table :videos do |t|
t.string :title, null: false
t.string :video_url, null: false
t.text :introduction, null: false
t.text :commentary, null: false
t.integer :video_order, null: false
t.string :thumbnail, null: false
t.integer :price, default: 0
t.integer :like_count, default: 0
t.references :series, null: false, foreign_key: true
t.timestamps
end
end
end
<file_sep>ActiveAdmin.register Article do
permit_params :title, :description, :contents, :thumbnail, :chef_id, :top_slide
index do
column :id
column :title
column :like_count
column :chef
actions
end
form do |f|
f.inputs do
f.input :title
f.input :description
f.input :contents, as: :ckeditor
# f.input :contents, :input_html => { id: "article-contents", data: {options: {toolbarButtons: ['undo', 'redo', '|', 'bold', 'italic', '|', 'underline', 'strikeThrough', 'subscript', 'superscript', 'fontFamily', 'fontSize', '|', 'color', 'emoticons', 'inlineStyle', 'paragraphStyle', '|', 'paragraphFormat', 'align', 'formatOL', 'formatUL', 'outdent', 'indent', '-', 'insertLink', 'insertImage', 'insertVideo', 'insertTable', '|', 'quote', 'insertHR', 'undo', 'redo', 'clearFormatting', 'selectAll', 'html']}}}, as: :froala_editor
# text_node '<div class="text-count">入力文字数:<span id="text-count">0</span>文字(推奨2000文字)</div>'.html_safe
f.input :thumbnail
f.input :tag_list, :input_html => { id: "genre-tags", value: nil }
f.input :registered_tag, as: :hidden, :input_html => { id: "registered_tag", value: nil } if controller.action_name == 'new'
f.input :registered_tag, as: :hidden, :input_html => { id: "registered_tag", value: Article.find(params[:id]).tag_list } if controller.action_name == 'edit'
f.input :autocmplete_tag, as: :hidden, :input_html => { id: "autocomplete_tag", value: Article.tags_on(:tags).map(&:name) }
f.input :chef_id, as: :select, collection: Chef.all.map { |c| [c.name, c.id] }
f.input :top_slide, as: :select
end
f.actions
end
controller do
def create
@article = Article.new(article_permit_params)
if @article.save
@article.tag_list = params_tag_list[:tag_list]
@article.save
redirect_to admin_articles_path
else
render :new
end
end
def update
@article = Article.find(params[:id])
if @article.update(article_permit_params)
@article.tag_list = params_tag_list[:tag_list]
@article.save
redirect_to admin_articles_path
else
render :edit
end
end
def destroy
article = Article.find(params[:id])
article.destroy
redirect_to admin_articles_path
end
private
def article_permit_params
params.require(:article).permit(:title, :description, :contents, :thumbnail, :chef_id, :top_slide)
end
def params_tag_list
params.require(:article).permit(:tag_list)
end
end
end
<file_sep>set :output, 'log/crontab.log'
every 1.week , roles: %i(app) do
rake '-s sitemap:refresh'
end | 1ef58dfcdbd8d5cb810b81e118deb376976216b9 | [
"JavaScript",
"Ruby",
"Markdown"
] | 86 | Ruby | bashi-nobu/cooklab | 32fd357bcd8abc69b54caaa7975fabbf2cea04a3 | 14e133b8af8c4180ca47e2a5e709ee91ae0bc5f5 |
refs/heads/main | <file_sep>
const formulario = document.getElementById('Formulario');
const nombre = document.getElementById('nombre');
const errorNombre = document.getElementById('errorNombre');
const apellidos = document.getElementById('apellidos');
const errorApellido = document.getElementById('errorApellido');
const dni = document.getElementById('dni');
const errorDni = document.getElementById('errorDni');
const correo = document.getElementById('correo');
const errorCorreo = document.getElementById('errorCorreo');
const tlf = document.getElementById('tlf');
const errorTlf = document.getElementById('errorTel');
const user = document.getElementById('user');
const errorUser = document.getElementById('errorUser');
const fecha = document.getElementById('fecha');
const errorFecha = document.getElementById('errorFecha');
formulario.addEventListener('submit',evento=>{
let valido =true;
evento.preventDefault();
if(!dniValido(dni.value)){
errorDni.className="Errores-activado";
valido =false;
}else{
errorDni.className="error";
}
if(nombre.value == ""){
errorNombre.className="Errores-activado";
valido =false;
}else{
errorNombre.className="error";
}
if(fecha.value == ""){
errorFecha.className="Errores-activado";
valido =false;
}else{
errorFecha.className="error";
}
if(user.value == ""){
errorUser.className="Errores-activado";
valido =false;
}else{
errorUser.className="error";
}
if(apellidos.value == ""){
errorApellido.className="Errores-activado";
valido =false;
}else{
errorApellido.className="error";
}
if(!correoValido(correo.value)){
errorCorreo.className="Errores-activado";
valido =false;
}else{
errorCorreo.className="error";
}
if(tlf.value == ""){
errorTel.className="Errores-activado";
valido =false;
}else{
errorTel.className="error";
}
if(valido){
alert("Formulario enviado");
formulario.reset;
}
});
formulario.addEventListener('reset',evento=>{
alert("Se va a resetear el formulario")
formulario.reset;
errorApellido.className="error";
errorCorreo.className="error";
errorDni.className="error";
errorFecha.className="error";
errorFecha.className="error";
errorNombre.className="error";
errorTlf.className="error";
errorUser.className="error";
});
function dniValido(dni2) {
return /^[0-9]{8}[A-Z]$/.test(dni2);
}
function correoValido(correo2) {
return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(correo2);
}
function tlfValido() {
return /^(\d{9})$/.test(tlf);
}
function limpiarFormulario() {
document.getElementById("miForm").reset();
}
| b06be323fb98f47aee90c60c6925c425504c75b8 | [
"JavaScript"
] | 1 | JavaScript | dMoralesNP/Formulario | 9c98f681737f825a5753d7a8fff4fb5ea066b8e3 | 2020c28b5b1aff914967adea8072fba51ddd904a |
refs/heads/master | <repo_name>luruke/appear-animation<file_sep>/index.js
var OnAppear = require('on-appear');
var extend = function(obj, props) {
var newObj = Object.create(obj);
for(var prop in props) {
if(props.hasOwnProperty(prop)) {
newObj[prop] = props[prop];
}
}
return newObj;
};
var AppearAnimation = {
delay: 0,
offset: 0,
instances: [],
elements: [],
create: function(obj) {
return extend(this, obj);
},
init: function() {
for (var i = 0; i < this.elements.length; i++) {
var el = this.elements[i];
this.register(el);
}
},
prepare: function(el, instance) {
// To implement
},
run: function(el, instance) {
// To implement
},
register: function(el) {
var _this = this;
var instance = new OnAppear(el, {
delay: this.delay,
offset: this.offset,
callback: function() {
_this.run(el, this);
}
});
this.prepare(el, instance);
this.instances.push(instance);
},
destroy: function() {
for (var i = 0; i < this.instances.length; i++) {
this.instances[i].destroy();
}
}
};
module.exports = AppearAnimation;
<file_sep>/README.md
# appear-animation
Fade Up example
```javascript
var FadeUp = AppearAnimation.create({
offset: 100,
delay: 250,
elements: document.querySelectorAll('.card'),
prepare: function(el, instance) {
TweenLite.set(el, { opacity: 0, y: 100 });
},
run: function(el, instance) {
TweenLite.to(el, 0.5, { opacity: 1, y: 0 });
}
});
FadeUp.init();
```
Complex animation w/ Siblings calculation and Barba.js
```javascript
const AppearAnimation = require('appear-animation');
const Barba = require('barba.js');
const forEach = require('lodash/forEach');
function init(container) {
var ShowCards = AppearAnimation.create({
offset: 50,
delay: 250,
elements: container.querySelectorAll('.card'),
prepare: function(el, i) {
el = $(el);
i.title = el.find('.card__title');
i.content = el.find('.card__content');
i.code = el.find('.card__code');
i.bg = el.find('.card__bg');
i.image = el.find('.card__image img');
if (el.hasClass('card--imagefull')) {
TweenLite.set(i.image, { y: 10, opacity: 0 });
} else {
TweenLite.set(i.image, { x: 25, opacity: 0 });
}
TweenLite.set(i.content, { opacity: 0 });
TweenLite.set(i.bg, { right: '100%' });
},
run: function(el, i) {
const instances = this.getSiblings(el);
let time = 0;
forEach(instances, (instance) => {
window.setTimeout(() => {
this.runSingle(instance)
}, time);
time += 300;
});
},
runSingle: function(i) {
// i.el
const tl = new TimelineLite();
tl.add('start');
tl.to(i.bg, 0.8, { right: '0%' }, 'start');
tl.add('afterblock')
tl.to(i.image, 1, { opacity: 1 }, 'afterblock');
tl.to(i.image, 3, { x: 0, y: 0 }, 'afterblock');
tl.to(i.content, 1, { opacity: 1 }, 'afterblock+=0.5');
},
getSiblings: function(el) {
const y = el.getBoundingClientRect().top;
let sibilings = [];
forEach(this.instances, (i) => {
if (y === i.el.getBoundingClientRect().top) {
sibilings.push(i);
}
});
return sibilings;
}
});
ShowCards.init();
}
init(document.body);
Barba.Dispatcher.on('newPageReady', (a, b, container) => {
init(container);
});
```
| ea1423a0c5e4061ea09fef31d9ad4381a7d743ff | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | luruke/appear-animation | f42b86a6a29e37334581b30a1480bd6c09f7256d | 5cf8c4acc48639f615daa767719e53efefea93f0 |
refs/heads/master | <file_sep>/**
* @author xiateng
*Your goal is to create a program that prints the following figure. Your code should use loops
* (i.e. shouldn’t just be five print statements, that’s no fun).
* */
public class Exercise1a {
public static void main(String[] args) {
int index= 5;
for(int i=1;i<=index;++i){
for(int j=0;j<i;++j) {
System.out.print('*');
}
System.out.println();
}
}
}
<file_sep># ucb-cs61b-2019sp<file_sep>import java.util.Arrays;
/**
* Write a function windowPosSum(int[] a, int n) that replaces each element a[i] with the sum of a[i] through a[i + n],
* but only if a[i] is positive valued. If there are not enough values because we reach the end of the array,
* we sum only as many values as we have.
* */
public class Exercise4 {
public static void windowPosSum(int[] a, int n) {
int length= a.length;
for(int i=0;i<length;++i) {
if(a[i]>0) {
int result= 0;
for(int j=i;j<Math.min(length,i+n+1);++j) {
result+=a[j];
}
a[i]= result;
}
}
}
public static void main(String[] args) {
int[] array= new int[]{1,2,-3,4,5,4};
int n=3;
windowPosSum(array, 3);
System.out.println(Arrays.toString(array));
}
}
<file_sep>import java.util.Scanner;
/**
* Name this new method drawTriangle and give it a return type of void (this means that it doesn’t return anything at all).
* The drawTriangle method should take one parameter named N,
* and it should print out a triangle exactly like your triangle from exercise 1a, but N asterisks tall instead of 5.
* */
public class Exercise1b {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int number= sc.nextInt();
DrawTriangle(number);
}
/**
* @param N the number to be loop
* */
public static void DrawTriangle(int N) {
for(int i=0;i<N;++i) {
for(int j=0;j<i+1;++j) {
System.out.print('*');
}
System.out.println();
}
}
}
<file_sep>public class HelloNumbers{
public static void main(String[] args) {
int n= Integer.parseInt(args[0]);
int result= 0;
for(int i=0;i<n;++i) {
result+=i;
System.out.print(result+" ");
}
}
} | 9e5e2b6f59642a9ec5a8217d30c1ab2017be2bad | [
"Markdown",
"Java"
] | 5 | Java | alexalex1228/ucb-cs61b-2019sp | 4cd3da70882541f3c6a465763d5a144501f8327a | 3e9b39732c1d4d322768b8e1d03b620355d1cccd |
refs/heads/master | <file_sep>#include "../include/seriliaze.h"
char stream[100000]={'\0'};
void serialize(node* root){
strcat(stream ," ");
if(root == NULL){
strcat(stream, "null");
}
else{
char name[400] = {'\0'};
strcat(stream, root->name);
for(int i=0;i<CALL_SIZE;i++)
serialize(root->called[i]);
}
}
char* getStream(){
FILE* ptr;
ptr = fopen("file.txt","w");
if(ptr == NULL){
printf("Error happened opening file\n");
return NULL;
}
fprintf(ptr,"%d\n",CALL_SIZE);
fprintf(ptr,"%s",stream);
fclose(ptr);
return stream;
}<file_sep>
#ifndef __STACK_H
#define _STACK_H_
#include<stdlib.h>
typedef struct node node;
typedef struct stack stack;
struct stack{
node* address;
stack* prev;
stack* next;
int test;
};
extern stack* top;
void push(node*);
void pop();
#endif<file_sep>#include "../include/node.h"
node* root = NULL;
void updateStack(node* n,short i){
if(i)
push(n);
else
pop();
}
void newSpan(const char* name){
root = (node*)malloc(sizeof(node));
strcpy(root->name, name);
updateStack(root,1);
}
void childSpan(const char* name){
node* nnode = (node*)malloc(sizeof(node));
nnode->prev = NULL;
nnode->cnt=0;
nnode->prev = top->address;
strcpy(nnode->name, name);
top->address->called[top->address->cnt++] = nnode;
updateStack(nnode,1);
}
void closeSpan(){
updateStack(NULL,0);
}<file_sep>const express = require('express');
const bodyParser = require('body-parser');
const {fork} = require("child_process");
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const app = express();
// app.use(express.static("./public/uploads"));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(cors());
const storage = multer.diskStorage({
destination:'public',
filename:(req,file,cb)=>{
cb(null, new Date()+file.originalname);
}
});
const upload = multer({storage:storage}).single('file');
app.get('/',(req,res)=>{
const cp = fork('fork.js');
cp.on('message',data=>{
console.log(data);
res.send(data);
})
});
app.post('/uploadFile',(req,res)=>{
upload(req,res,(err)=>{
if(err){
console.log(err);
res.send(err);
}
else{
const cp = fork("fork.js");
cp.send(req.file.path);
cp.on("message",data=>{
res.send(data);
})
}
})
})
app.listen(3002);<file_sep>
#ifndef _SERIALIZE_
#define _SERIALIZE_
#include "node.h"
#include "string.h"
#include <stdlib.h>
#include <stdio.h>
void serialize(node*);
char* getStream();
#endif<file_sep>#include "../include/node.h"
#include "../include/seriliaze.h"
#include<stdio.h>
void funcA1(){
childSpan(__PRETTY_FUNCTION__);
pop();
}
void funcA2(){
childSpan(__PRETTY_FUNCTION__);
pop();
}
void funcA(){
childSpan(__PRETTY_FUNCTION__);
funcA1();
funcA2();
pop();
}
void funcB1(){
childSpan(__PRETTY_FUNCTION__);
pop();
}
void funcB2(){
childSpan(__PRETTY_FUNCTION__);
pop();
}
void funcB(){
childSpan(__PRETTY_FUNCTION__);
funcB1();
funcB2();
pop();
}
int main(){
newSpan(__PRETTY_FUNCTION__);
funcA();
funcB();
pop();
serialize(root);
printf("%s\n",getStream());
}<file_sep>#include "../include/stack.h"
stack* top = NULL;
void push(node* addr){
stack* n = (stack*)malloc(sizeof(stack));
n->prev = NULL;
n->next = NULL;
n->address = NULL;
n->address=addr;
if(top!=NULL){
n->prev = top;
top->next = n;
}
top=n;
}
void pop(){
if(top==NULL)
return;
stack* hld = top->prev;
free(top);
if(hld)
hld->next = NULL;
top=hld;
}<file_sep>#ifndef _NODE_H_
#define _NODE_H_
#include<stdlib.h>
#include<string.h>
#include "stack.h"
#define CALL_SIZE 5
#define NAME_SIZE 400
struct node{
char name[NAME_SIZE];
node* called[CALL_SIZE];
node* prev;
int cnt;
};
extern node* root;
void newSpan(const char *);
void childSpan(const char*);
void closeSpan();
#endif | 39c9338cbe4eeb17fb6836ac9222b36cd612f5f5 | [
"JavaScript",
"C"
] | 8 | C | suab321321/CodeTracer | 2a9fdc022a2fe1a80bc1309a41a982df139301e3 | 22cb46baa2bac2eb2bd26897521a9a7691e499a9 |
refs/heads/master | <file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package app.domain.mobile;
import app.domain.Launcher;
import app.utils.RandomGenerator;
import utils.LoggingManager;
import utils.Point3D;
import utils.PropertyManager;
/**
*
* @author Nate
*/
public class MobileLauncher extends Launcher {
private double speed;
private double maxSpeed;
private Point3D destination;
public MobileLauncher(Point3D loc, Point3D dest, double spd, String idIn, int numPredictors, int numTrackers) {
super(loc, idIn, numPredictors, numTrackers);
symbol = "ml";
speed = spd;
maxSpeed = spd;
destination = dest;
addSelf();
}
/**
* Updates the state of the launcher.
*
* @param millis the time that has passed since the last call to update
*/
public void update(double millis) {
move(millis);
}
private void move(double millis) {
double distTraveled = speed * millis / 1000;
double distToDest = location.distance(destination);
if (distToDest == 0) {
return;
}
if (distTraveled >= distToDest) {
location = (Point3D) destination.clone();
arrived();
return;
}
double delta = distTraveled / distToDest;
location.x = location.x + (destination.x - location.x) * delta;
location.y = location.y + (destination.y - location.y) * delta;
location.z = location.z + (destination.z - location.z) * delta;
}
private void arrived() {
double newx = RandomGenerator.Instance().getRandomNumber() * PropertyManager.Instance().getIntProperty("PIXELSX");
double newy = RandomGenerator.Instance().getRandomNumber() * PropertyManager.Instance().getIntProperty("PIXELSY");
destination.x = newx;
destination.y = newy;
LoggingManager.logInfo("Mobile Launcher " + id + " has reached its destination: "
+ location.toString() + "\nNew destination: ("
+ destination.toString());
}
}
<file_sep>package utils;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.HTMLLayout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.WriterAppender;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
*
* @author Nate
*/
public class LoggingManager {
private static Logger logger = null;
private static boolean initialized = false;
private static void initialize() {
if (initialized) {
return;
}
try {
logger = Logger.getLogger("SE450");
HTMLLayout layout = new HTMLLayout();
layout.setTitle("Application Log File");
FileOutputStream output = new FileOutputStream("AppLogFile.html");
// Create the first Appender - for HTML file output
WriterAppender htmlFileAppender = new WriterAppender(layout, output);
String pattern = "%d{ISO8601} %-5p %m %n";
PatternLayout layout2 = new PatternLayout(pattern);
// Create the second Appender - for Console file output
ConsoleAppender consoleAppender = new ConsoleAppender(layout2);
logger.addAppender(consoleAppender);
logger.addAppender(htmlFileAppender);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
initialized = true;
}
/**
*
*/
public static void setDebug() {
initialize();
logger.setLevel(Level.DEBUG);
}
/**
*
*/
public static void setInfo() {
initialize();
logger.setLevel(Level.INFO);
}
/**
*
*/
public static void setWarn() {
initialize();
logger.setLevel(Level.WARN);
}
/**
*
*/
public static void setError() {
initialize();
logger.setLevel(Level.ERROR);
}
/**
*
*/
public static void setFatal() {
initialize();
logger.setLevel(Level.FATAL);
}
/**
*
* @param msg
*/
public static void logDebug(String msg) {
initialize();
logger.debug(msg);
}
/**
*
* @param msg
*/
public static void logInfo(String msg) {
initialize();
logger.info(msg);
}
/**
*
* @param msg
*/
public static void logWarn(String msg) {
initialize();
logger.warn(msg);
}
/**
*
* @param msg
*/
public static void logError(String msg) {
initialize();
logger.error(msg);
}
/**
*
* @param msg
*/
public static void logFatal(String msg) {
initialize();
logger.fatal(msg);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package app.managers;
import app.domain.missiles.BallisticInbound;
import app.domain.Detector;
import app.domain.missiles.Interceptor;
import java.util.ArrayList;
import utils.Point3D;
import utils.PropertyManager;
/**
* Manages all inbound ballistic missiles
*
* @author Nate
*/
public class InboundManager {
private static InboundManager instance;
private ArrayList<BallisticInbound> entries;
/**
* @return the current static instance of the Inbound Manager
*/
public static InboundManager getInstance() {
if (instance == null) {
instance = new InboundManager();
}
return instance;
}
private InboundManager() {
entries = new ArrayList<>();
}
/**
*
* @return The number of ballistic missiles being managed
*/
public int getNumEntries() {
return entries.size();
}
/**
* Updates all of the current missiles
*
* @param millis the time that has passed since the last call to update()
*/
public void update(int millis) {
for (int i = 0; i < entries.size(); i++) {
entries.get(i).update(millis);
}
}
/**
* Adds a ballistic missile to the manager
*
* @param bi the missile to be added
*/
public void addEntry(BallisticInbound bi) {
entries.add(bi);
}
/**
* Removes a ballistic missile from the manager
*
* @param bi the missile to be removed
*/
public void removeEntry(BallisticInbound bi) {
entries.remove(bi);
}
public boolean contains(BallisticInbound bi) {
return entries.contains(bi);
}
public void lockDetected(BallisticInbound bi, Point3D location) {
bi.lockDetected(location);
}
public BallisticInbound getClosest(Point3D p) {
BallisticInbound closest = entries.get(0);
for (BallisticInbound bi : entries) {
if (bi.getLocation().distance(p) < closest.getLocation().distance(p)) {
closest = bi;
}
}
return closest;
}
public void interceptorStrike(Interceptor in) {
double interceptRange = PropertyManager.Instance().getDoubleProperty("INTERCEPTORBLASTRANGE");
for (int i = 0; i < entries.size(); i++) {
if (in.getLocation().distance(entries.get(i).getLocation()) < interceptRange) {
if (in.getLocation().distance(entries.get(i).getLocation()) < interceptRange * .75) {
entries.get(i).selfDestruct();
i--;
} else {
entries.get(i).alterCourse();
}
}
}
}
/**
* Asks the manager to detect all of the missiles in a given detectors range
*
* @param d the detector that is looking
* @return all of the missiles it can pick up
*/
public ArrayList<BallisticInbound> detect(Detector d) {
ArrayList<BallisticInbound> detected = new ArrayList<>();
double minAlt = PropertyManager.Instance().getDoubleProperty("MINALTITUDE");
for (BallisticInbound bi : entries) {
if (d.getLocation().distance(bi.getLocation()) < d.getRange() && bi.getLocation().getZ() > minAlt) {
detected.add(bi);
}
}
return detected;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="MissileDefence" default="default" basedir=".">
<description>Builds, tests, and runs the project MissileDefence.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar: JAR building
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="MissileDefence-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project><file_sep>package display.gui;
import display.interfaces.Display;
import display.interfaces.Displayable;
import display.interfaces.ViewFrameListener;
import utils.LoggingManager;
import utils.PropertyManager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* The ViewFrame class is the GUI window/interface that displays and displays
* our objects as the move around within our application. The components of the
* ViewFrame are:<br>
* The canvas display - a DisplayWindow object<br>
* A Pause Button - signals the application that a pause event has been
* requested<br>
* A Stop Button - signals the application that a stop event has been
* requested<br>
* <br>
* Additionally, the ViewFrame catches the x,y location of each mouse press and
* release and sends that data to the application
*/
public class ViewFrame extends JFrame implements ViewFrameListener, Display {
private DisplayWindow displayArea; // display canvas
private JButton pauseButton = new JButton("Pause");
private JButton stopButton = new JButton("Stop");
private static int pixelsX;
private static int pixelsY;
private ViewFrameListener viewFrameListener;
private boolean paused = false;
/**
* This constructor creates a ViewFrame object with no ViewFrameListener
* (listens for the mouse & button events).
*/
public ViewFrame() {
this(null);
}
/**
* This constructor creates a ViewFrame object with the specified
* ViewFrameListener (listens for the mouse & button events). The
* ViewFrameListener is usually an object in your application.
*
* @param vfl the associated ViewFrameListener (listens for the mouse &
* button events).
*/
public ViewFrame(ViewFrameListener vfl) {
super("View Frame");
setPixelsX(PropertyManager.Instance().getIntProperty("PIXELSX"));
setPixelsY(PropertyManager.Instance().getIntProperty("PIXELSY"));
setViewFrameListener(vfl);
setDisplayArea(new DisplayWindow(this, getPixelsX(), getPixelsY()));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
acceptClose();
}
;
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(getDisplayArea(), BorderLayout.CENTER);
getPauseButton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!isPaused()) {
getPauseButton().setText("Continue");
setPaused(true);
} else {
getPauseButton().setText("Pause");
setPaused(false);
}
acceptPause();
}
});
getStopButton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
acceptStop();
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 2));
buttonPanel.add(getPauseButton());
buttonPanel.add(getStopButton());
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
pack();
setSize(getPixelsX() + 18, getPixelsY() + 65);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* This method send the "Displayable" object passed in to the DisplayWindow
* object for addition to the list of elements that are drawn in the display
* window.
*
* @param d the "Displayable" object to be added to the list of elements
* that are drawn in the display window.
*/
public void addContent(Displayable d) {
getDisplayArea().addContent(d);
}
/**
* This method send the "Displayable" object passed in to the DisplayWindow
* object for removal from the list of elements that are drawn in the
* display window.
*
* @param d the "Displayable" object to be added to the list of elements
* that are drawn in the display window.
* @param delay
*/
public void removeContent(Displayable d, int delay) {
getDisplayArea().removeContent(d, delay);
}
/**
* This method returns the number of elements in the display
*
* @return int
*/
public int contentSize() {
return getDisplayArea().contentSize();
}
/**
* This method instructs the DisplayWindow object to re-draw the screen.
* This is usually called when you want to update the drawn elements after
* their locations have been updated or when an element has been added or
* removed from the list of elements drawn on the DisplayWindow.
*/
public void updateDisplay() {
getDisplayArea().repaint();
}
private ViewFrameListener getViewFrameListener() {
return viewFrameListener;
}
/**
* This method accepts and then sets the ViewFrame's ViewFrameListener
* object (listens for the mouse & button events). The ViewFrameListener is
* usually an object in your application.
*
* @param viewFrameListenerIn the ViewFrame's ViewFrameListener object
* (listens for the mouse & button events).
*/
public void setViewFrameListener(ViewFrameListener viewFrameListenerIn) {
viewFrameListener = viewFrameListenerIn;
}
/**
* This method receives the "pause" request from the DisplayWindow and
* forwards it to the ViewFrameListener (if any). The ViewFrameListener is
* usually an object in your application.
*/
public void acceptPause() {
LoggingManager.logInfo("Pause Pressed!");
if (getViewFrameListener() != null) {
getViewFrameListener().acceptPause();
}
}
/**
* This method receives the "stop" request from the DisplayWindow and
* forwards it to the ViewFrameListener (if any). The ViewFrameListener is
* usually an object in your application.
*/
public void acceptStop() {
LoggingManager.logInfo("Stop Pressed!");
if (getViewFrameListener() != null) {
getViewFrameListener().acceptStop();
}
}
/**
* This method receives the "close" event (i.e., the ViewFrame window was
* closed) from the DisplayWindow and forwards it to the ViewFrameListener
* (if any). The ViewFrameListener is usually an object in your application.
*/
public void acceptClose() {
if (getViewFrameListener() != null) {
getViewFrameListener().acceptClose();
}
System.exit(0);
}
/**
* This method receives the left mouse button press & release event from the
* DisplayWindow and forwards it to the ViewFrameListener (if any). The
* ViewFrameListener is usually an object in your application.
*
* @param pressX
* @param pressY
* @param releaseX
* @param releaseY
*/
public void acceptLeftButtonMouseCommand(int pressX, int pressY, int releaseX, int releaseY) {
if (getViewFrameListener() != null) {
getViewFrameListener().acceptLeftButtonMouseCommand(pressX, pressY, releaseX, releaseY);
}
}
/**
* This method receives the right mouse button press & release event from
* the DisplayWindow and forwards it to the ViewFrameListener (if any). The
* ViewFrameListener is usually an object in your application.
*
* @param pressX
* @param pressY
* @param releaseX
* @param releaseY
*/
public void acceptRightButtonMouseCommand(int pressX, int pressY, int releaseX, int releaseY) {
if (getViewFrameListener() != null) {
getViewFrameListener().acceptRightButtonMouseCommand(pressX, pressY, releaseX, releaseY);
}
}
private DisplayWindow getDisplayArea() {
return displayArea;
}
private void setDisplayArea(DisplayWindow displayAreaIn) {
displayArea = displayAreaIn;
}
private JButton getPauseButton() {
return pauseButton;
}
private JButton getStopButton() {
return stopButton;
}
private boolean isPaused() {
return paused;
}
private void setPaused(boolean pausedIn) {
paused = pausedIn;
}
/**
* This method will cause a pop-up information window to be displayed with
* the message provided in the method's parameter.
*
* @param msg the message
*/
public void popUpInfo(String msg) {
JOptionPane.showMessageDialog(null, msg, "Report", JOptionPane.INFORMATION_MESSAGE);
}
/**
* This method is a simple accessor that returns the x-size of the
* DisplayWindow in pixels
*
* @return the x-size of the DisplayWindow in pixels
*/
public static int getPixelsX() {
return pixelsX;
}
/**
* This method is a simple modifier that sets the x-size of the
* DisplayWindow in pixels
*
* @param pixelsXIn the x-size of the DisplayWindow in pixels
*/
public static void setPixelsX(int pixelsXIn) {
ViewFrame.pixelsX = pixelsXIn;
}
/**
* This method is a simple accessor that returns the y-size of the
* DisplayWindow in pixels
*
* @return the y-size of the DisplayWindow in pixels
*/
public static int getPixelsY() {
return pixelsY;
}
/**
* This method is a simple modifier that sets the x-size of the
* DisplayWindow in pixels
*
* @param pixelsYIn the y-size of the DisplayWindow in pixels
*/
public static void setPixelsY(int pixelsYIn) {
ViewFrame.pixelsY = pixelsYIn;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package app.domain;
import app.domain.missiles.BallisticInbound;
import app.domain.missiles.TrackerInterceptor;
import app.domain.missiles.PredictorInterceptor;
import app.managers.LauncherManager;
import display.interfaces.Displayable;
import display.managers.DisplayManager;
import java.util.LinkedList;
import java.util.Queue;
import utils.LoggingManager;
import utils.Point3D;
import utils.PropertyManager;
import utils.SoundUtility;
/**
*
* @author Nate
*/
public class Launcher implements Displayable {
private Detector parent;
protected Point3D location;
protected String id;
protected String symbol;
private Queue<PredictorInterceptor> predins;
private Queue<TrackerInterceptor> trackins;
public Launcher(Point3D loc, String idIn, int numPredictors, int numTrackers) {
location = loc;
id = idIn;
predins = new LinkedList<>();
trackins = new LinkedList<>();
for (int i = 0; i < numPredictors; i++) {
predins.add(new PredictorInterceptor(new Point3D(0, 0, 0), 190, 190, id + "_P_" + i, 75, this));
}
for (int i = 0; i < numTrackers; i++) {
trackins.add(new TrackerInterceptor(new Point3D(0, 0, 0), 0, 100, id + "_T_" + i, this, 100, 2500));
}
}
/**
* Updates the state of the launcher.
*
* @param millis the time that has passed since the last call to update
*/
public void update(double millis) {
}
public void setDetector(Detector d) {
parent = d;
}
public Point3D getLocation() {
return location;
}
public String getSymbol() {
return symbol;
}
public int getNumInterceptors() {
return predins.size() + trackins.size();
}
public void destroy() {
LoggingManager.logInfo("Launcher Destroyed, ID = " + id);
symbol = "#";
SoundUtility.getInstance().playSound("Argh.wav");
for (PredictorInterceptor pi : predins) {
pi.destroy();
}
for (TrackerInterceptor ti : trackins) {
ti.destroy();
}
removeSelf();
}
public void launch(BallisticInbound bi, int count) throws Exception {
for (int i = 0; i < count; i++) {
if (trackins.size() == 0 && predins.size() == 0) {
throw new Exception("Launcher Empty. Succesfully launched " + count);
} else if (trackins.size() > predins.size()) {
trackins.poll().launch(bi);
} else {
predins.poll().launch(bi);
}
}
}
/**
* Adds itself from the display and detector manager
*/
protected void addSelf() {
DisplayManager.getInstance().addContent(this);
LauncherManager.getInstance().addEntry(this);
}
/**
* Removes itself from the display and detector manager
*/
protected void removeSelf() {
LauncherManager.getInstance().removeEntry(this);
parent.removeAssociatedLauncher(this);
DisplayManager.getInstance().removeContent(this, PropertyManager.Instance().getIntProperty("REMOVALDELAY"));
}
}
<file_sep>package app.domain.fixed;
import app.domain.Launcher;
import app.domain.Detector;
import java.util.ArrayList;
import utils.Point3D;
/**
* A Fixed Detector is a detector that cannot move
*
* @author Nate
*/
public class FixedDetector extends Detector {
/**
* Creates a Fixed Detector
*
* @param locationIn the location
* @param idIn the ID string
* @param rangeIn the detection range
* @param associatedLaunchers its associated launchers
*/
public FixedDetector(Point3D locationIn, String idIn, double rangeIn, ArrayList<Launcher> associatedLaunchers) {
super(locationIn, idIn, rangeIn, associatedLaunchers);
}
}
<file_sep>package display.gui;
import display.interfaces.Displayable;
import utils.PropertyManager;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* This class is the visual canvas upon which our elements are drawn and moved
* around. The DisplayWindow itself is part of the ViewFrame object.
*/
public class DisplayWindow extends Canvas implements MouseListener {
private Image offScrImg;
private boolean unpacked = false;
private int pressRightX;
private int pressRightY;
private int releaseRightX;
private int releaseRightY;
private int pressLeftX;
private int pressLeftY;
private int releaseLeftX;
private int releaseLeftY;
private int pixelsX;
private int pixelsY;
private ViewFrame parentFrame;
private ArrayList contents = new ArrayList();
private HashMap toBeRemoved = new HashMap();
/**
* The DisplayWindow is the visual canvas upon which our elements are drawn.
* The constructor requires a ViewFrame object (the parent ViewFrame) and an
* X & Y size in pixels.
*
* @param parent the parent ViewFrame (that owns this DisplayWindow)
* @param xPixels the x-size of the DisplayWindow in pixels
* @param yPixels the y-size of the DisplayWindow in pixels
*/
public DisplayWindow(ViewFrame parent, int xPixels, int yPixels) {
setParentFrame(parent);
setPixelsX(xPixels); // For scaling use
setPixelsY(yPixels); // For scaling use
setSize(xPixels, yPixels);
addMouseListener(this);
}
/**
* This method, declared in the Canvas class, re-draws the screen using
* double-buffered graphics for smooth movement. This method does not need
* to be (and should not be) called manually, it is invoked in the process
* of a window refresh/update
*
* @param graphicsIn the java "Graphics" object passed in by the caller
*/
public void update(Graphics graphicsIn) {
if (getOffScrImg() == null || getOffScrImg().getWidth(this) != getPreferredSize().getWidth()
|| getOffScrImg().getHeight(this) != getPreferredSize().getHeight()) {
setOffScrImg(createImage((int) getPreferredSize().getWidth(), (int) getPreferredSize().getHeight()));
}
Graphics og = getOffScrImg().getGraphics();
paint(og);
graphicsIn.drawImage(getOffScrImg(), 0, 0, this);
og.dispose();
}
/**
* This method will add the "Displayable" object passed in to the list of
* elements that are drawn in the display window.
*
* @param d the "Displayable" object to be added to the list of elements
* that are drawn in the display window.
*/
public synchronized void addContent(Displayable d) {
getContents().add(d);
repaint();
}
/**
* This method returns the number of elements in the display
*
* @return int
*/
public int contentSize() {
return getContents().size();
}
/**
* This method will remove the "Displayable" object passed in from the list
* of elements that are drawn in the display window. The int delay parameter
* indicates how many screen updates much be made before the removed object
* will actually be taken off of the screen.
*
* @param d the "Displayable" object to be removed from the list of elements
* that are drawn in the display window.
* @param delay
*/
public synchronized void removeContent(Displayable d, int delay) {
getToBeRemoved().put(d, new Integer(delay));
repaint();
}
/**
* This method, declared in the Canvas class, is called by the "update"
* method to refresh the screen and redraw each of the elements on the
* display window.
*
* @param graphicsIn the java "Graphics" object passed in by the "update"
* method
*/
public void paint(Graphics graphicsIn) {
if (!isUnpacked()) {
setUnpacked(true);
}
graphicsIn.setColor(Color.black);
graphicsIn.fillRect(0, 0, (int) getPreferredSize().getWidth(), (int) getPreferredSize().getHeight()); // draw background
graphicsIn.setColor(Color.white); // set font and write applet parameters
graphicsIn.setFont(new Font("Dialog", Font.PLAIN, 10));
paintContents(graphicsIn);
}
private void clearRemoved() {
HashMap temphash = getToBeRemoved();
Set tempset = temphash.entrySet();
ArrayList a = null;
try {
a = new ArrayList(tempset);
} catch (ConcurrentModificationException e) {
a = new ArrayList();
}
for (int i = 0; i < a.size(); i++) {
int value = ((Integer) ((Map.Entry) a.get(i)).getValue()).intValue();
value--;
if (value <= 0) {
getToBeRemoved().remove(((Map.Entry) a.get(i)).getKey());
getContents().remove(((Map.Entry) a.get(i)).getKey());
} else {
getToBeRemoved().put(((Map.Entry) a.get(i)).getKey(), new Integer(value));
}
}
}
/**
* This method, declared in the Canvas class, is called by the "update"
* method to refresh the screen and redraw each of the elements on the
* display window.
*
* @param graphicsIn the java "Graphics" object passed in by the "paint"
* method
*/
private void paintContents(Graphics graphicsIn) {
clearRemoved();
ArrayList purge = new ArrayList();
int size = getContents().size();
for (int i = 0; i < size; i++) {
graphicsIn.setFont(new Font("SansSerif", Font.BOLD, 12));
graphicsIn.setColor(getColor(getContents(i).getLocation().getZ() / PropertyManager.Instance().getDoubleProperty("ZMAX")));
// LoggingManager.logInfo("Drawing(" + i + ") " + getContents(i).getSymbol() + " at: " + getContents(i).getLocation().getX() + ", " +
// getContents(i).getLocation().getY() + ", " + getContents(i).getLocation().getZ() + ": " +
// getColor(getContents(i).getLocation().getZ() / PropertyManager.Instance().getDoubleProperty("ZMAX")));
graphicsIn.drawString(getContents(i).getSymbol(),
(int) (getContents(i).getLocation().getX()),
(int) (getContents(i).getLocation().getY()));
}
if (purge.size() > 0) {
for (int i = 0; i < purge.size(); i++) {
removeContent((Displayable) purge.get(i), PropertyManager.Instance().getIntProperty("REMOVEDELAY"));
}
purge.clear();
}
}
/**
* We don't make use of this event (part of the MouseListener interface) -
* we only use the mousePressed/mouseReleased methods.
*
* @param e a MouseEvent
*/
public void mouseClicked(MouseEvent e) {
// We don't make use of this event - we only use mousePressed/mouseReleased
}
/**
* This method records the x,y location of the initial right mouse button
* click (before the release)
*
* @param e a MouseEvent
*/
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
setPressLeftX(e.getX());
setPressLeftY(e.getY());
} else if (e.getButton() == MouseEvent.BUTTON3) {
setPressRightX(e.getX());
setPressRightY(e.getY());
}
}
/**
* This method records the x,y location where the right mouse button was
* released (after it was clicked)
*
* @param e a MouseEvent
*/
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
setReleaseLeftX(e.getX());
setReleaseLeftY(e.getY());
getParentFrame().acceptLeftButtonMouseCommand(getPressLeftX(), getPressLeftY(), getReleaseLeftX(), getReleaseLeftY());
}
if (e.getButton() == MouseEvent.BUTTON3) {
setReleaseRightX(e.getX());
setReleaseRightY(e.getY());
getParentFrame().acceptRightButtonMouseCommand(getPressRightX(), getPressRightY(), getReleaseRightX(), getReleaseRightY());
}
}
/**
* We don't make use of this event (part of the MouseListener interface) -
* we only use the mousePressed/mouseReleased methods.
*
* @param e a MouseEvent
*/
public void mouseEntered(MouseEvent e) {
// We don't make use of this event - we only use mousePressed/mouseReleased
}
/**
* We don't make use of this event (part of the MouseListener interface) -
* we only use the mousePressed/mouseReleased methods.
*
* @param e a MouseEvent
*/
public void mouseExited(MouseEvent e) {
// We don't make use of this event - we only use mousePressed/mouseReleased
}
private Color getColor(double value) {
if (value > 1.0) {
value = 1.0;
}
int r, g;
if (value < 0.5) {
r = 255;
g = (int) (510 * value);
} else {
r = (int) (510 * (1.0 - value));
g = 255;
}
return new Color(r, g, 0);
}
private Image getOffScrImg() {
return offScrImg;
}
private void setOffScrImg(Image offScrImgIn) {
offScrImg = offScrImgIn;
}
private boolean isUnpacked() {
return unpacked;
}
private void setUnpacked(boolean unpackedIn) {
unpacked = unpackedIn;
}
private int getPressRightX() {
return pressRightX;
}
private void setPressRightX(int pressXIn) {
pressRightX = pressXIn;
}
private int getPressRightY() {
return pressRightY;
}
private void setPressRightY(int pressYIn) {
pressRightY = pressYIn;
}
private int getReleaseRightX() {
return releaseRightX;
}
private void setReleaseRightX(int releaseXIn) {
releaseRightX = releaseXIn;
}
private int getReleaseRightY() {
return releaseRightY;
}
private void setReleaseRightY(int releaseYIn) {
releaseRightY = releaseYIn;
}
private int getPressLeftX() {
return pressLeftX;
}
private void setPressLeftX(int pressXIn) {
pressLeftX = pressXIn;
}
private int getPressLeftY() {
return pressLeftY;
}
private void setPressLeftY(int pressYIn) {
pressLeftY = pressYIn;
}
private int getReleaseLeftX() {
return releaseLeftX;
}
private void setReleaseLeftX(int releaseXIn) {
releaseLeftX = releaseXIn;
}
private int getReleaseLeftY() {
return releaseLeftY;
}
private void setReleaseLeftY(int releaseYIn) {
releaseLeftY = releaseYIn;
}
private ViewFrame getParentFrame() {
return parentFrame;
}
private void setParentFrame(ViewFrame parentFrameIn) {
parentFrame = parentFrameIn;
}
private ArrayList getContents() {
return contents;
}
private Displayable getContents(int i) {
return (Displayable) contents.get(i);
}
/**
* This method is a simple accessor that returns the x-size of the
* DisplayWindow in pixels
*
* @return the x-size of the DisplayWindow in pixels
*/
public int getPixelsX() {
return pixelsX;
}
/**
* This method is a simple modifier that sets the x-size of the
* DisplayWindow in pixels
*
* @param pixelsXIn the x-size of the DisplayWindow in pixels
*/
public void setPixelsX(int pixelsXIn) {
pixelsX = pixelsXIn;
}
/**
* This method is a simple accessor that returns the y-size of the
* DisplayWindow in pixels
*
* @return the y-size of the DisplayWindow in pixels
*/
public int getPixelsY() {
return pixelsY;
}
/**
* This method is a simple modifier that sets the y-size of the
* DisplayWindow in pixels
*
* @param pixelsYIn the y-size of the DisplayWindow in pixels
*/
public void setPixelsY(int pixelsYIn) {
pixelsY = pixelsYIn;
}
private HashMap getToBeRemoved() {
return toBeRemoved;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package app.domain.missiles;
import app.managers.DetectorManager;
import app.managers.InboundManager;
import app.managers.LauncherManager;
import app.utils.RandomGenerator;
import display.interfaces.Displayable;
import display.managers.DisplayManager;
import utils.LoggingManager;
import utils.Point3D;
import utils.PropertyManager;
import utils.SoundUtility;
/**
* The basic inbound missile. It will move from its location to its destination
* and then detonate
*
* @author Nate
*/
public class BallisticInbound implements Displayable {
/**
* The ID for the missile
*/
protected final String id;
/**
* The current location
*/
protected Point3D location;
/**
* The missiles destination
*/
protected Point3D destination;
/**
* The speed at which it travels
*/
protected double speed;
private double maxSpeed;
private String symbol;
private boolean isDecoy;
/**
* Creates a Ballistic Inbound Missile based on the given parameters
*
* @param locationIn The start location
* @param destinationIn The missiles destination
* @param speedIn The missiles speed
* @param id The ID string for the missile
* @param isDecoy true if the missile is a decoy
*/
public BallisticInbound(Point3D locationIn, Point3D destinationIn, double speedIn, String id, boolean isDecoy) {
if (speedIn < 0) {
speed = 0;
throw new NumberFormatException("Speed less than 0");
}
this.id = id;
location = locationIn;
destination = destinationIn;
speed = speedIn;
this.isDecoy = isDecoy;
symbol = isDecoy ? "d" : "B";
maxSpeed = speed;//????
DisplayManager.getInstance().addContent(this);
InboundManager.getInstance().addEntry(this);
SoundUtility.getInstance().playSound("Inbound.wav");
LoggingManager.logInfo("BallisticInbound Created, ID = " + id);
}
/**
*
* @return The location of the missile
*/
public Point3D getLocation() {
return location;
}
public Point3D getDestination() {
return destination;
}
public String getId() {
return id;
}
public double getSpeed() {
return speed;
}
/**
*
* @return The missiles symbol
*/
public String getSymbol() {
return symbol;
}
/**
* Updates the location of the missile and detonates if it has reached its
* destination
*
* @param millis the time that has passed since the last call to update()
*/
public void update(double millis) {
if (millis < 0) {
millis = 0;
throw new NumberFormatException("Time less than 0");
}
double distTraveled = speed * millis / 1000;
double distToDest = location.distance(destination);
if (distToDest == 0) {
return;
}
if (distTraveled >= distToDest) {
location = destination;
arrived();
return;
}
double delta = distTraveled / distToDest;
location.x = location.x + (destination.x - location.x) * delta;
location.y = location.y + (destination.y - location.y) * delta;
location.z = location.z + (destination.z - location.z) * delta;
}
/**
* The missile will self destruct
*/
public void selfDestruct() {
symbol = isDecoy ? "o" : "x";
InboundManager.getInstance().removeEntry(this);
DisplayManager.getInstance().removeContent(this, PropertyManager.Instance().getIntProperty("REMOVALDELAY"));
SoundUtility.getInstance().playSound("SelfDestruct.wav");
LoggingManager.logInfo("BallisticInbound Self Destruct, ID = " + id);
}
/**
* The missile will slightly change its destination
*/
public void alterCourse() {
double alterVar = PropertyManager.Instance().getDoubleProperty("DESTALTERVARIATION");
double xmod = (1 - alterVar) + (2 * alterVar * RandomGenerator.Instance().getRandomNumber());
double ymod = (1 - alterVar) + (2 * alterVar * RandomGenerator.Instance().getRandomNumber());
LoggingManager.logInfo("Course altered\nOriginal Destination " + destination.toString());
destination.x *= xmod;
destination.y *= ymod;
LoggingManager.logInfo("New Destination " + destination.toString());
}
/**
* The missile will slightly change its speed
*/
public void alterSpeed() {
double alterVar = PropertyManager.Instance().getDoubleProperty("DESTALTERVARIATION");
double smod = (1 - alterVar) + (2 * alterVar * RandomGenerator.Instance().getRandomNumber());
speed *= smod;
}
/**
* Called when the missile detects an approaching intercepter
*
* @param point the location of the intercepter
*/
public void lockDetected(Point3D point) {
}
private void arrived() {
if (isDecoy) {
symbol = "O";
SoundUtility.getInstance().playSound("Crunch.wav");
LoggingManager.logInfo("Decoy " + id + " has reached destination: " + destination.toString());
} else {
applyGroundDamage();
symbol = "X";
SoundUtility.getInstance().playSound("Explosion.wav");
LoggingManager.logInfo("Ballistic Inbound Misssile" + id + " has reached destination: " + destination.toString());
}
InboundManager.getInstance().removeEntry(this);
DisplayManager.getInstance().removeContent(this, PropertyManager.Instance().getIntProperty("REMOVALDELAY"));
}
private void applyGroundDamage() {
DetectorManager.getInstance().applyBlastDamage(location);
LauncherManager.getInstance().applyBlastDamage(location);
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package app.domain.missiles;
import app.domain.Launcher;
import app.managers.InboundManager;
import app.managers.InterceptorManager;
import app.utils.RandomGenerator;
import utils.LoggingManager;
import utils.Point3D;
import utils.PropertyManager;
/**
*
* @author Nate
*/
public class TrackerInterceptor extends Interceptor {
double fuelTime;
double detectionRange;
public TrackerInterceptor(Point3D location, double speed, double maxSpeed, String id,
Launcher launcher, double fuelTime, double detectionRange) {
super(location, speed, maxSpeed, id, 0, launcher);
symbol = "T";
this.fuelTime = fuelTime;
this.detectionRange = detectionRange;
}
public void update(double millis) {
if (InboundManager.getInstance().contains(target) && InterceptorManager.getInstance().contains(this)) {
fuelTime -= millis / 1000;
if (fuelTime < 0) {
selfDestruct();
return;
}
speed += maxSpeed * ((millis/1000)/fuelTime);
if (verifyAcquire()) {
destination = target.getLocation();
move(millis);
}
} else {
LoggingManager.logInfo("Interceptor has no target. Acquiring new target");
if (InboundManager.getInstance().getNumEntries() > 0) {
acquire();
} else {
selfDestruct();
}
}
}
private boolean acquire() {
BallisticInbound bi = InboundManager.getInstance().getClosest(location);
if (bi.getLocation().distance(location) > detectionRange) {
selfDestruct();
return false;
}
if (bi != target) {
target = bi;
if (PropertyManager.Instance().getDoubleProperty("LOCKDETECTED") < RandomGenerator.Instance().getRandomNumber()) {
bi.lockDetected(location);
}
}
return true;
}
private boolean verifyAcquire() {
if (RandomGenerator.Instance().getRandomNumber() < PropertyManager.Instance().getDoubleProperty("REVERIFYACQUIRE")) {
return acquire();
}
return true;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package app.domain.missiles;
import app.domain.Launcher;
import app.utils.RandomGenerator;
import java.util.ArrayList;
import utils.Point3D;
import utils.PropertyManager;
/**
*
* @author Nate
*/
public class PredictorInterceptor extends Interceptor {
public PredictorInterceptor(Point3D location, double speed, double maxSpeed, String id, double minSpeed, Launcher launcher) {
super(location, speed, maxSpeed, id, minSpeed, launcher);
symbol = "P";
}
public void launch(BallisticInbound bi) throws Exception {
super.launch(bi);
plotCourse();
}
private void plotCourse() {
Point3D targetLoc = target.getLocation();
Point3D targetDest = predictDestination();
double targetSpd = obfuscate(target.getSpeed());
ArrayList<Point3D> pts = new ArrayList<>();
double delta = 1.0 / PropertyManager.Instance().getDoubleProperty("PREDICTORSEGMENTS");
for (int i = 0; i < PropertyManager.Instance().getDoubleProperty("PREDICTORSEGMENTS"); i++) {
double newx = targetLoc.getX() + (targetDest.getX() - targetLoc.getX()) * (delta * (i + 1));
double newy = targetLoc.getY() + (targetDest.getY() - targetLoc.getY()) * (delta * (i + 1));
double newz = targetLoc.getZ() + (targetDest.getZ() - targetLoc.getZ()) * (delta * (i + 1));
Point3D p = new Point3D(newx, newy, newz);
double d = targetLoc.distance(p);
double travelTime = d / targetSpd;
if (verifyDest(p, travelTime)) {
pts.add(p);
}
}
if (!pts.isEmpty()) {
Point3D closest = pts.get(0);
for (Point3D p : pts) {
if (p.distance(location) < closest.distance(location)) {
closest = p;
}
}
destination = closest;
speed = targetSpd * location.distance(destination) / targetLoc.distance(destination);
} else {
destination = location;
}
}
private Point3D predictDestination() {
double destx = obfuscate(target.getDestination().getX());
double desty = obfuscate(target.getDestination().getY());
double destz = obfuscate(target.getDestination().getZ());
return new Point3D(destx, desty, destz);
}
private boolean verifyDest(Point3D p, double travelTime) {
return (p.distance(location) / minSpeed) > travelTime
&& (p.distance(location) / maxSpeed) < travelTime
&& p.getZ() > PropertyManager.Instance().getDoubleProperty("MINALTITUDE");
}
private double obfuscate(double d) {
return d * (1 - (RandomGenerator.Instance().getRandomNumber()
* PropertyManager.Instance().getDoubleProperty("OBFUSCATIONFACTOR")));
}
}
| e7893b3ff27286ade86b5fa383acf72ab379855a | [
"Java",
"Ant Build System"
] | 11 | Java | nweiskirch/MissileDefence | bfc32a59758d5198d12b6dda9bae361fdf681d80 | 8d684c8fc755557e5635e16887fd93967b33edf4 |
refs/heads/master | <repo_name>kerlue/Snippets<file_sep>/DatabasePhase8.php
<?php
// Hope, Melissa, schillaci
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "";
switch ($_GET["option"]) {
case "Players":
$sql = searchPlayer();
break;
case "Bowl|team":
$sql = searchSuperBowlWinners();
break;
case "teams":
$sql = searchTeams();
break;
case "Position":
$sql = searchPositions();
break;
case "Alma Mater":
$sql = searchAlmaMater();
break;
case "heisman winners":
$sql = getHeisman();
break;
}
// send query to mysql database
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
// create html table to store the data base results.
if( !defined('EXECUTED') ){
echo "<table id=\"myTable\" style=\"width:100%\">";
echo" <tr>";
foreach($row as $key => $val){
echo "<th>$key</th>";
}
echo"</tr>";
define('EXECUTED', TRUE);
}
echo "<tr>";
foreach($row as $key => $val){
echo "<td>".$val."</td>";
}
echo "</tr>";
}
} else {
echo $sql . "<br><br>" . $conn->error;
}
$conn->close();
function searchPlayer()
{
//returns MySql string to search for every data relating to a player such as
//player name, age, position.
return "select player.player_name, age,player.hometown_city,
player.hometown_state,player.salary,school_name,
team_name, year_of_championship, position
from player
LEFT JOIN Attended ON player.player_name = Attended.player_name
LEFT JOIN plays_on ON player.player_name = plays_on.player_name
LEFT JOIN player_won ON player.player_name = player_won.player_name
LEFT JOIN plays ON player.player_name = plays.player_name";
}
function searchSuperBowlWinners()
{
//returns MySql string to search for teams that won the super bowl
return "select *
from team_won as won, Team team
where won.team_name = team.team_name";
}
function searchTeams()
{
// returns MySql string to search for every data relating to a team
return "select *
from Team";
}
function searchPositions()
{ // returns MySql string to search for player's position
return "select plays.player_name, position ,team_name
from plays
LEFT JOIN plays_on ON plays_on.player_name = plays.player_name";
}
function searchAlmaMater()
{
// returns MySql string to search for players' Alma Mater
return "select player_name, school_name,hometown_city, hometown_state
from Attended";
}
function getHeisman()
{
// returns MySql string to search for players who won Heisman.
return "select won.player_name, year_Heisman, team_name
from won
LEFT JOIN plays_on ON plays_on.player_name = won.player_name";
}
?>
<file_sep>/Insertion Sort.cp
//
// main.cpp
// nm
//
// Created by <NAME> on 10/28/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
#include <iostream>
#include "math.h"
using namespace std;
int func(int n);
int main(int argc, const char * argv[]) {
int list[10] = {4,2,6,0,12,9,4,3,4,90};
for (int j=0 ; j < 10; j++) {
int key = list[j] ;
int i = j-1;
while(key < list[i] && i >= 0){
list[i+1] = list[i];
i--;
}
}
return 0;
}
<file_sep>/Database Project/DatabaseWebsite/php/getTuple.php
<?php
$dbname = "nfl";
$table = $_GET["table"];
$key = $_GET["value"];
$value = $_GET["key"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$key_arr = explode(",",$key);
$value_arr = explode(",",$value);
$sql = "Select * from ".$table. " Where ".$key_arr[0]."='".$value_arr[0]."'";
for ($x = 1; $x < count($key_arr); $x++) {
$sql = $sql." And ".$key_arr[$x]." = '".$value_arr[$x]."'";
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
print_r(json_encode($row )) ;
}
}
else {
echo "0 results";
}
$conn->close();
?><file_sep>/Database Project/DatabaseWebsite/php/insertData.php
<?php
$table = $_GET["table"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$column = "";
$value = "";
foreach($_GET as $key => $val){
if($key =="table")continue;
$column = $column.",".$key;
$value = $value.","."'".$val."'";
}
$column = substr($column,"1");
$column = "(".$column.")";
$value = substr($value,"1");
$value = "(".$value.")";
$sql = "INSERT INTO ".$table." ".$column." VALUES ".$value;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?><file_sep>/Database Project/DatabaseWebsite/php/updateData.php
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="";
$value = "";
$p_key="";
$p_value="";
foreach($_GET as $key => $val){
if($key == "table")
continue;
if(substr($key, 0, 4 ) === "key_"){
$p_key = substr( $key, 4);
$p_value = $val;
continue;
}
//$column = $column.",".$key;
$value = $value.", '".$val."'";
}
$value = substr($value,"1");
$sql = "REPLACE INTO ".$table." values(". $value.")";
if ($conn->query($sql) === TRUE) {
echo "table updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?><file_sep>/Database Project/DatabaseWebsite/php/getTableStructure.php
<?php
$dbname = "nfl";
$table = $_GET["table"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_TYPE FROM information_schema.columns WHERE table_schema = 'nfl' ORDER BY TABLE_NAME, ORDINAL_POSITION";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if( !defined('EXECUTED') ){
echo "<table style=\"width:100%\">";
echo" <tr>";
foreach($row as $key => $val){
echo "<th>$key</th>";
}
echo"</tr>";
define('EXECUTED', TRUE);
}
echo "<tr>";
foreach($row as $key => $val){
//echo $key."-<br/>-".$val;
echo "<td>".$val."</td>";
}
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?><file_sep>/Database Project/DatabaseWebsite/php/getPrimarykey.php
<?php
$table = $_GET["table"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "describe ".$table;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$res="";
while($row = $result->fetch_assoc()) {
if($row["Key"] == "PRI")
$res = $res.", ".$row["Field"];
}
echo substr($res, 1);
}
else {
echo "0 results";
}
$conn->close();
?><file_sep>/Database Project/DatabaseWebsite/php/register.php
<?php
$table = $_GET["table"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Log_In (user_name, password, email,name, access)
VALUES ('".$_GET["address"]."',"."'".$_GET["password"]."',"."'".$_GET["address"]."','".$_GET["name"]."','customer')";
if ($conn->query($sql) === TRUE) {
echo "registerOkay";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?><file_sep>/Database Project/DatabaseWebsite/php/queryData.php
<?php
$sql = $_GET["sql"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if( !defined('EXECUTED') ){
echo "<table id=\"myTable\" style=\"width:100%\">";
echo" <tr>";
foreach($row as $key => $val){
echo "<th>$key</th>";
}
echo"</tr>";
define('EXECUTED', TRUE);
}
echo "<tr>";
foreach($row as $key => $val){
//echo $key."-<br/>-".$val;
echo "<td>".$val."</td>";
}
echo "</tr>";
}
} else {
echo $sql . "<br><br>" . $conn->error;
}
$conn->close();
?><file_sep>/Database Project/DatabaseWebsite/php/searchData.php
<?php
$table = $_GET["table"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//print_r($fld_value);
$sql="";
$data = explode("|", $_GET["data"]);
$operator = explode("|", $_GET["operator"]);
$count=0;
for ($x = 1; $x < count($data); $x++) {
$fld_value = explode("=", $data[$x]);
if(strlen($fld_value[1]."") < 1) continue;
if(strpos($operator[$x-1]."", 'BETWEEN') !== false
|| strpos($operator[$x-1]."", 'NOT BETWEEN') !== false
){
$temp = explode(",",$fld_value[1]);
$lowerVal = $temp[0];
$upperVal = $temp[1];
$sql = $sql.$fld_value[0]." ".$operator[$x-1]." '".$lowerVal."'". " AND '".$upperVal."' " ;
}
else if(strpos($operator[$x-1]."", 'LIKE %...%') !== false){
$sql = $sql.$fld_value[0]." LIKE '%".$fld_value[1]."%'" ;
}else{
$sql = $sql.$fld_value[0]." ".$operator[$x-1]." '".$fld_value[1]."'";
}
$sql = $sql." AND ";
$count++;
}
$sql = substr($sql, 0, (strlen($sql) - strlen(" AND ")));
if($count == 0)
$sql = "SELECT * FROM ".$table;
else
$sql = "SELECT * FROM ".$table." WHERE ".$sql;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if( !defined('EXECUTED') ){
echo "<table style=\"width:100%\">";
echo" <tr>";
foreach($row as $key => $val){
echo "<th>$key</th>";
}
echo"</tr>";
define('EXECUTED', TRUE);
}
echo "<tr>";
foreach($row as $key => $val){
//echo $key."-<br/>-".$val;
echo "<td>".$val."</td>";
}
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?><file_sep>/Database Project/DatabaseWebsite/php/deleteTuple.php
<?php
$table = $_GET["table"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$key = $_GET["key"];
$value = $_GET["value"];
$key_arr = explode(",",$key);
$value_arr = explode(",",$value);
$sql = "DELETE FROM ".$table. " Where ".$key_arr[0]."='".$value_arr[0]."'";
for ($x = 1; $x < count($key_arr); $x++) {
$sql = $sql." And ".$key_arr[$x]." = '".$value_arr[$x]."'";
}
if ($conn->query($sql) === TRUE) {
echo "table updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?> | 134a884073f66d71894eaa196ddca359cf6bb38f | [
"C++",
"PHP"
] | 11 | PHP | kerlue/Snippets | 1f56e3783a0e2771f21918f3ef650b6a5e031a2f | a136b07cc2ada8ca9be9616063609a286397d71c |
refs/heads/main | <file_sep># Similar-Movie-Recommendation
PROJECT BY : <NAME>
PROJECT NAME: "Similar Movie Recomendation using Item based Collaborative Filtering"
This is my PySpark dataframe project to perform similar movie recommendation system using item based collaborative filtering.
In Item based collaborative filtering technique, the similarity is found between items i.e; similarity between movies based on ratings provided by users. I used Cosine Similarity index as the similarity index to calculate the similarities between every pairs of movies.
Here i found every pair of movies that were watched by same person. Then i measured the similarity of the ratings of each pair of movies across all users who watched and rated the same pair of movies. Generally if we take a movie pair that a person watched together and compare it with how everyone else rated that pair of movies, we can compute how similar those two movies are to each other based on aggregated user behaviour.
DATASET USED: ml-1m dataset is used for this project, which is a Movie Lens dataset provided by movielens.com
Entire dataset is distributed into 3 files, they are: users.dat, ratings.dat, and movies.dat.
The movie id = 260 was given as input, which corresponds to => Star Wars: Episode IV - A New Hope (1977) movie.
The results of the project are saved in output.csv file, which has four columns of output in it. The 4 columns gives the information about movie id 1 , movie id 2, Cosine similarity score, and no of samples respectively for each pair of movies which qualify the thresholds set in the program. The output in this file are not sorted.
Finally the results were sorted in descending order of similarity score and top 10 similar movies were displayed as output in EMR terminal. The screenshot of this output is also uploaded in this repository with the name similar-movie-recommendation-output-screenshot.png
<file_sep>
"""
PROJECT BY : <NAME>
PROJECT NAME: "Similar Movie Recomendation using Item based Collaborative Filtering"
DATASET USED: ml-1m dataset is used for this project, which is a Movie Lens dataset provided by movielens.com
Entire dataset is distributed into 3 files, they are: users.dat, ratings.dat, and movies.dat.
The movie id = 260 was given as input, which corresponds to => Star Wars: Episode IV - A New Hope (1977) movie.
"""
from pyspark.sql import SparkSession
from pyspark.sql import functions as func
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, LongType
import sys
# defining a function used for creating a dictionary that maps movie id to movie name
def loadMovieNames():
movieNames = {}
with open("movies.dat", encoding="ISO-8859-1") as f:
for line in f:
fields = line.split("::")
movieNames[int(fields[0])] = fields[1]
return movieNames
# creating spark session
spark = SparkSession.builder.appName("MovieSimilarities-1m").getOrCreate()
# defining the schema for ratings.dat dataset
ratingSchema = StructType([StructField("userID", IntegerType(), True), \
StructField("movieID", IntegerType(), True), \
StructField("rating", IntegerType(), True), \
StructField("timeStamp", LongType(), True)])
# calling the above defined function
movieNames = loadMovieNames()
# loading the ratings.dat dataset into driver program
ratingsData = spark.read.option("sep", ":").option("charset", "ISO-8859-1").schema(ratingSchema).csv("s3n://sample/pyspark-practice/ratings.dat")
# selecting the only required columns
ratings = ratingsData.select("userID", "movieID", "rating")
# partitioned the above dataframe into 100 partitions for properly spreading the data across all the executors
ratingsPartitioned = ratings.repartition(100)
# Performing Self-join on user id column to find every combination of movie pairs that each user has watched and rated.
# Also removed duplicate rows in the resulting dataframe
ratingsJoined = ratingsPartitioned.alias("ratings1").join(ratingsPartitioned.alias("ratings2"), (func.col("ratings1.userID") == func.col("ratings2.userID")) \
& (func.col("ratings1.movieID") < func.col("ratings2.movieID")))
# Select movie pairs and rating pairs
ratingsJoinedSelected = ratingsJoined.select(func.col("ratings1.movieID").alias("movieID1"), func.col("ratings2.movieID").alias("movieID2"), \
func.col("ratings1.rating").alias("rating1"), func.col("ratings2.rating").alias("rating2"))
# adding the extra columns that are required to calculate cosine similarity and repartitioning into 100 partitions before grouping.
pairScores = ratingsJoinedSelected.withColumn("x2", func.col("rating1") * func.col("rating1")).withColumn("y2", func.col("rating2") * func.col("rating2")) \
.withColumn("xy", func.col("rating1")*func.col("rating2")).repartition(100)
# grouping of all the rows having same movie pairs and performing the necessary aggregations
pairScoreAggregate = pairScores.groupBy("movieID1", "movieID2").agg(func.sum(func.col("xy")).alias("numerator"), \
(func.sqrt(func.sum(func.col("x2"))) * func.sqrt(func.sum(func.col("y2")))).alias("denominator"), func.count(func.col("xy")).alias("noSamples"))
# calculating the cosine similarity for every unique movie pairs
cosineSimilarity = pairScoreAggregate.withColumn("cosineSimilarityScore", func.when(func.col("denominator") != 0, \
func.col("numerator") / func.col("denominator")).otherwise(0)).select("movieID1", "movieID2", "cosineSimilarityScore", "noSamples").cache()
if len(sys.argv) > 1:
# setting the threshold values
scoreThreshold = 0.97 # the minimum threshold for cosine similarity value
noSamplesThreshold = 100 #the minimum threshold for the number of samples to be considered into result.
# reading and assigning the selected movie id for which top 10 similar movies are calculated.
inputMovieID = int(sys.argv[1])
# Now filtering out only the movies that qualify the above two mentioned thresholds.
resultFiltered = cosineSimilarity.filter(((func.col("movieID1") == inputMovieID) | (func.col("movieID2") == inputMovieID)) \
& (func.col("cosineSimilarityScore") > scoreThreshold) & (func.col("noSamples") > noSamplesThreshold))
# now sorting the results by similarity score in descending order and then selecting the top 10 results
resultSorted = resultFiltered.sort(func.col("cosineSimilarityScore").desc()).cache()
# writing the results into csv file
resultSorted.repartition(1).write.format('csv').option('header',True).mode('overwrite').option('sep',',').save('s3n://sample/pyspark-practice/output')
# getting back the results into the driver program
results = resultSorted.take(10)
print("\n\n")
print("Top 10 similar movies for " + movieNames[inputMovieID])
print("\n")
# Now displaying top 10 similar movies for the given input movie id
for result in results:
similarMovieID = result.movieID1
if similarMovieID == inputMovieID :
similarMovieID = result.movieID2
# printing to top 10 similar movies
print(movieNames[similarMovieID] + "\tSimilarityScore: " + str(result.cosineSimilarityScore) + "\tSamples: " + str(result.noSamples))
print("\n\n")
spark.stop()
<file_sep>DATASET USED: ml-1m dataset is used for this project, which is a Movie Lens dataset provided by movielens.com
Entire dataset is distributed into 3 files, they are: users.dat, ratings.dat, and movies.dat
The fourth sample.dat file is added for my convenience for debugging purposes.
| 724bc08c12fc8b6e35899f62f5a6900843976e07 | [
"Markdown",
"Python",
"Text"
] | 3 | Markdown | akd95/Similar-Movie-Recommendation | f50406ae10ccdd2252ee2de10e995bdb624ca203 | 1a42c9fe4652b837ffd019bbb8071a4ed07c196d |
refs/heads/master | <repo_name>Bakkarxp/coachacademy<file_sep>/Level2/week_02_Assignments/BigInt.cpp
//
// Created by HKP28 on 05/10/2020.
//
#include "BigInt.h"
// Constructor
BigInt::BigInt(string num, bool sign):m_number(std::move(num)),m_sign(sign) {}
BigInt::BigInt():m_number("0"),m_sign(false){}
BigInt::BigInt(string num) {
if( isdigit(num[0]) )
{
setNumber(num);
m_sign = false;
}
else
{
setNumber( num.substr(1) );
m_sign = (num[0] == '-');
}
}
BigInt::BigInt(long long num) {
if(num<0){
m_sign = true;
m_number = std::to_string(std::abs(num));
}else{
m_sign = false;
m_number = std::to_string(num);
}
}
// Arithmetic operators
BigInt BigInt::operator+(const BigInt &num) {
string temp;
bool sign = false;
if(this->m_sign==num.m_sign){
temp = addBigInt(this->m_number,num.m_number);
sign = this->m_sign;
}else{
if(this->m_number>num.m_number){
temp = subtractBigInt(this->m_number,num.m_number);
sign = this->m_sign;
} else{
temp = subtractBigInt(num.m_number,this->m_number);
sign = num.m_sign;
}
}
if(temp=="0") sign = false;
return BigInt(temp,sign);
}
BigInt BigInt::operator-(BigInt num) {
num.setSign(!num.getSign()); // invert the sign of right operand and carry the addition operation
return (*this)+num;
}
BigInt BigInt::operator*(const BigInt &num) {
string temp;
bool sign = false;
temp = multiplyBigInt(this->m_number,num.m_number);
if(this->m_sign==num.m_sign){
sign = false;
} else{
sign = true;
}
if(temp=="0") sign = false;
return BigInt(temp, sign);
}
BigInt BigInt::operator/(BigInt num) {
string temp;
bool sign = false;
long long divisor = toInt(num.getNumber());
temp = divideByLl(this->m_number, divisor);
if(this->m_sign==num.m_sign){
sign = false;
} else{
sign = true;
}
if(temp=="0") sign = false;
return BigInt(temp, sign);
}
BigInt &BigInt::operator+=(const BigInt &num) {
return (*this) = (*this) + num;
}
BigInt &BigInt::operator-=(const BigInt &num) {
return (*this) = (*this) - num;
}
BigInt &BigInt::operator*=(const BigInt &num) {
return (*this) = (*this) * num;
}
BigInt &BigInt::operator/=(const BigInt &num) {
return (*this) = (*this) / num;
}
BigInt &BigInt::operator++() {
return (*this) = (*this) + 1;
}
BigInt BigInt::operator++(int) {
BigInt temp = *this;
(*this) = (*this) + 1;
return temp;
}
BigInt &BigInt::operator--() {
return (*this) = (*this) - 1;
}
BigInt BigInt::operator--(int) {
BigInt temp = *this;
(*this) = (*this) - 1;
return temp;
}
// Relational Operators
bool BigInt::operator<(const BigInt &rhs) const {
if(!this->m_sign && rhs.m_sign){
return false;
} else if(this->m_sign && !rhs.m_sign){
return true;
// signs are equal and +ve
} else if(this->m_sign == rhs.m_sign && !this->m_sign){
return this->m_number<rhs.m_number;
// signs are equal and -ve
} else if(this->m_sign == rhs.m_sign && this->m_sign){
return this->m_number>rhs.m_number;
// signs are not equal
}
}
bool BigInt::operator<=(const BigInt &rhs) const {
return !this->operator>(rhs);
}
bool BigInt::operator>(const BigInt &rhs) const {
return !this->operator<(rhs) && !this->operator==(rhs);
}
bool BigInt::operator>=(const BigInt &rhs) const {
return !this->operator<(rhs);;
}
// Equality operators
bool BigInt::operator==(const BigInt &rhs) const {
if(this->m_number==rhs.m_number && this->m_sign == rhs.m_sign) return true;
return false;
}
bool BigInt::operator!=(const BigInt &rhs) const {
return !this->operator==(rhs);
}
// Stream operators
std::ostream &operator<<(std::ostream &os, const BigInt &anInt) {
// if(anInt.getSign()) std::cout<<"-";
// std::cout<<anInt.getNumber();
std::cout << anInt.toString();
return os;
}
std::istream &operator>>(std::istream &in, BigInt &anInt) {
string sNumber;
in >> sNumber;
if( isdigit(sNumber[0]) )
{
anInt.setNumber(sNumber);
anInt.setSign(false) ;
}
else
{
anInt.setNumber( sNumber.substr(1) );
anInt.setSign(sNumber[0] == '-');
}
return in;
}
// utility functions
void BigInt::equalizeSize(string &num1, string &num2) {
unsigned int sizeDiff;
if(num1.size()>num2.size()){
sizeDiff = num1.size()-num2.size();
} else{
sizeDiff = num2.size()-num1.size();
}
// equalize vector sizes
if(num1.size()>num2.size()){
num2.insert(num2.begin(),sizeDiff,'0');
} else{
num1.insert(num1.begin(),sizeDiff,'0');
}
}
string BigInt::addBigInt(string num1, string num2) {
equalizeSize(num1,num2);
char carry{'0'};
string sum(num1.length(),'0');
for(int i = (int) num1.length()-1; i>=0;i--){
sum[i]=((carry -'0')+(num1[i] -'0')+(num2[i] -'0'))+'0';
if(i!=0){
if(sum[i]>'9'){
carry = '1';
sum[i]-=10;
} else{
carry = '0';
}
}
}
//Check the last digit in the left
if(sum[0] > '9')
{
sum[0]-= 10;
sum.insert(sum.begin(),'1');
}
return sum;
}
string BigInt::subtractBigInt(string minuend, string subtrahend) {
// minuend should be greater than subtrahend
equalizeSize(minuend, subtrahend);
string difference(minuend.length(), '0');
// subtract
for(int i = (int) minuend.length() - 1; i >= 0; i--){
if(minuend[i] < subtrahend[i]){
minuend[i]+=10;
minuend[i - 1]--;
}
difference[i]= (minuend[i] - '0') - (subtrahend[i] - '0') + '0';
}
// Remove Left zeros
while(difference[0] == '0' && difference.length() != 1){
difference.erase(difference.begin());
}
return difference;
}
string BigInt::multiplyBigInt(string num1, string num2) {
//
if(num1.length()>num2.length()){
num1.swap(num2);
}
string result{'0'};
// num1 is the smaller
for(int i = (int) num1.length()-1; i>=0;i--){
string temp(num2);
int carry = 0;
// num2 is the bigger
for(int j = (int) num2.length()-1; j>=0;j--){
temp[j] = (num2[j]-'0')*(num1[i]-'0')+carry;
if(temp[j]>9){
carry = temp[j]/10;
temp[j]-= carry*10;
}else{
carry = 0;
}
temp[j]+='0';
}
if(carry>0){
temp.insert(temp.begin(),(carry+'0'));
}
temp.insert(temp.end(),num1.length()-i-1,'0');
result = addBigInt(result,temp);
}
// Remove Left zeros
while(result[0] == '0' && result.length() != 1){
result.erase(result.begin());
}
return result;
}
string BigInt::divideByLl(string dividend, long long int divisor) {
long long rem = 0;
string result; result.resize(10000);
for(int indx=0, len = dividend.size(); indx<len; ++indx)
{
rem = (rem * 10) + (dividend[indx] - '0');
result[indx] = rem / divisor + '0';
rem %= divisor;
}
result.resize( dividend.size() );
// Remove Left zeros
while(result[0] == '0' && result.size() != 1){
result.erase(result.begin());
}
if(result.empty())
result.push_back('0');
return result;
}
void BigInt::removeLeadingZeros(string &num) {
while(m_number[0] == '0' && m_number.size() != 1){
m_number.erase(m_number.begin());
}
}
string BigInt::toString() const{
string sNumber;
if(m_sign) sNumber = "-";
sNumber.append(m_number);
return sNumber;
}
long long BigInt::toInt(const string& num) {
long long sum = 0;
for(char i : num)
sum = (sum*10) + (i - '0');
return sum;
}
<file_sep>/Level2/week_01/AutomaticAnswer.cpp
//
// Created by HKP28 on 16/09/2020.
//
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int tensColumnDigit(int n){
int result;
result = (n*567/9+7492)*235/47-498;
return (abs(result)/10)%10;
}
int main() {
int t;
cin >> t;
if(t>100 || t<1){
return -1;
}
int output[t];
int n;
for (int i = 0; i < t; i++)
{
cin>>n;
if(n<-1000 || n>1000){
return -1;
}
output[i] = tensColumnDigit(n);
}
for (int i = 0; i < t; i++)
{
cout<<output[i] <<endl;
}
return 0;
}
<file_sep>/Level2/week_01/MotherBear.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using std::cin;
using std::cout;
using std::endl;
void trim(std::string s){
std::string unWantedChars=" ";
for(char c: unWantedChars ){
s.erase(std::remove(s.begin(), s.end(), c), s.end());
}
}
std::string clean(std::string s){
std::string unWantedChars=".,?! ";
// Transform to lower
std::transform(s.begin(),s.end(),s.begin(),::tolower);
// Execlude unwanted chars
for(char c: unWantedChars ){
s.erase(std::remove(s.begin(), s.end(), c), s.end());
}
return s;
}
bool ispalindrome(std::string s){
std::string firstHalf;
std::string secondHalf;
std::string secondHalfInv;
if(s.size()%2==0){
firstHalf = s.substr(0,s.size()/2);
secondHalf = s.substr(s.size()/2,s.size());
std::reverse(secondHalf.begin(),secondHalf.end());
// cout<<s<<endl;
// cout<<firstHalf<<endl;
// cout <<secondHalf<<endl;
if(firstHalf==secondHalf){
//cout<<"true";
return true;
} else{
return false;
}
}else{
int half = (s.size()-1)/2;
firstHalf = s.substr(0,half);
secondHalf = s.substr(half+1,s.size());
std::reverse(secondHalf.begin(),secondHalf.end());
// cout<<s<<endl;
// cout<<firstHalf<<endl;
// cout <<secondHalf<<endl;
if(firstHalf==secondHalf){
//cout<<"true";
return true;
} else{
return false;
}
}
//return true;
}
int main() {
std::vector<bool> results;
std::string statement;
while(statement != "DONE"){
std::getline(std::cin, statement);
trim(statement);
if(statement == "DONE"){
break;
}
//cout << clean(statement) << endl;
std::string cleanedString;
cleanedString= clean(statement);
results.push_back(ispalindrome(cleanedString));
}
for(bool b : results){
if(b == true){
cout<<"You won't be eaten!"<<endl;
}else{
cout<<"Uh oh.."<<endl;
}
}
//char *statement;
//cin.getline(statement);
//std::cout << statement << std::endl;
return 0;
}
<file_sep>/Level2_Pretest/maxRepElement.cpp
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using std::cout;
using std::endl;
using std::cin;
char findMaxRepChar(char str[]);
int main()
{
int t;
cin>>t;
if(t<1 || t>100){
return -1;
}
char resultchars[t];
for(int i = 1; i<=t; i++){
int strlen;
cin>>strlen;
if(strlen<1 || strlen>100){
return -1;
}
char str[strlen+1];
cin>>str;
resultchars[i] = findMaxRepChar(str);
}
for(int i = 1; i<=t; i++){
cout<<resultchars[i]<<endl;
}
return 0;
}
char findMaxRepChar(char str[]){
std::map<char, int> repeatedChars;
int loopCounter{0};
// counting repeated chars in std::map
while(str[loopCounter] != '\0'){
char character = str[loopCounter];
auto iter = repeatedChars.find(character);
if(iter != repeatedChars.end())
{
iter->second++;
}else
{
auto pair = std::make_pair(character,1);
repeatedChars.insert(pair);
}
loopCounter++;
}
// copy std::map elements into std::vector
std::vector<std::pair<char, int>> repeatedCharsVec {};
for(auto pair : repeatedChars){
repeatedCharsVec.push_back(pair);
}
// sorting the vector
std::sort(repeatedCharsVec.begin(),repeatedCharsVec.end(),[=](std::pair<char, int>& a,std::pair<char, int>& b){
return b.second < a.second;
});
return repeatedCharsVec[0].first;
}<file_sep>/Level2/week_02/CompatiblePair.cpp
//
// Created by hkp28 on 23/09/2020.
//
/*
Tommy lanterns
No. = n
Brightness = a1,a2,an,.....
Banban lanterns
No. = m
Brightness = b1,b2,bm,.....
Tommy hides the largest brightness lantern
Banban the second largest of Tommy's lanterns and the largest of his own to form the pair
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main(){
int n,m;
cin >> n;
if(n<2||n>50){
return -1;
}
cin >> m;
if(m<2||m>50){
return -1;
}
vector<long long> a,b;
// Get the inputs
for(int i=1; i <= n; i++){
long long brightness;
cin>>brightness;
if(brightness<-1000'000'000||brightness>1000'000'000){
return -1;
}
a.push_back(abs(brightness));
}
for(int i=1; i <= m; i++){
long long brightness;
cin>>brightness;
if(brightness<-1000'000'000||brightness>1000'000'000){
return -1;
}
b.push_back(abs(brightness));
}
// sorting
std::sort(a.begin(), a.end(), std::greater<long long>());
std::sort(b.begin(), b.end(), std::greater<long long>());
// pop_up biggest value
cout << a[1] * b[0];
return 0;
}<file_sep>/Level2/week_01/SquareSum.cpp
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
bool isOdd(int n){
int reminder;
reminder = n%2;
if(reminder == 0)
{
return false;
} else{
return true;
}
}
int getSquaresCount(int dimention){
int squareNum ;
if(isOdd(dimention)){
squareNum= (dimention+1)/2;
}else{
squareNum= dimention/2;
}
return squareNum;
}
int main() {
int dimention{1} ;
vector<vector<int>> caseResults;
do{
// Getting Input
cin>>dimention;
if(dimention==0)
break;
int numbers[dimention][dimention];
for (int r = 0; r < dimention; r++) {
for (int c = 0; c < dimention; c++) {
cin>>numbers[r][c];
}
}
// Calculate Squares sum
int squares = getSquaresCount(dimention) ;
std::vector<int> results;
int row{0};
int col{0};
for(int i =1;i<=squares;i++){
int squareSum{0};
for(int r=row;r<dimention;r++){
for(int c=col;c<dimention;c++){
squareSum +=numbers[r][c];
}
}
results.push_back(squareSum);
row++;
col++;
dimention--;
}
std::vector<int> finalResult;
for(int i=0;i<results.size();i++) {
if(i==results.size()-1) {
finalResult.push_back(results[i]);
}else {
finalResult.push_back(results[i]-results[i+1]);
}
}
caseResults.push_back(finalResult);
if(dimention==0){
dimention=1;
}
}while (dimention!=0);
// Print output
int x= 1;
for (auto vec : caseResults){
cout<<"Case "<<x<<":";
for (auto n : vec){
cout<<" "<< n ;
}
cout<<endl;
x++;
}
return 0;
}
<file_sep>/Level2/week_02_Assignments/BigInt.h
//
// Created by HKP28 on 05/10/2020.
//
#ifndef COACHACADEMY_BIGINT_H
#define COACHACADEMY_BIGINT_H
#include <iostream>
#include <string>
using std::pair;
using std::string;
class BigInt {
private:
string m_number;
bool m_sign;
public:
// Constructors
explicit BigInt();
explicit BigInt(string num, bool sign);
explicit BigInt(string num);
BigInt(long long num);
//BigInt(const BigInt &bigInt);
// Getters & Setters
bool getSign()const{return m_sign;}
void setSign(bool sign){this->m_sign=sign;}
string getNumber()const{return m_number;}
void setNumber(string number){this->m_number=number;}
// Operators
// Arithmetic operators
BigInt operator+(const BigInt &num);
BigInt operator-(BigInt num);
BigInt operator*(const BigInt &num);
BigInt operator/(BigInt num);
BigInt& operator+=(const BigInt &num);
BigInt& operator-=(const BigInt &num);
BigInt& operator*=(const BigInt &num);
BigInt& operator/=(const BigInt &num);
BigInt& operator++();
BigInt operator++(int);
BigInt& operator--();
BigInt operator--(int );
// Relational Operators
bool operator<(const BigInt &rhs) const;
bool operator<=(const BigInt &rhs) const;
bool operator>(const BigInt &rhs) const;
bool operator>=(const BigInt &rhs) const;
// Equality operators
bool operator==(const BigInt &rhs) const;
bool operator!=(const BigInt &rhs) const;
// Stream operators
friend std::ostream & operator<<(std::ostream &os, const BigInt &anInt);
friend std::istream &operator>>(std::istream &in, BigInt &anInt);
private:
static void equalizeSize(string &num1,string &num2);
void removeLeadingZeros(string &num);
static string addBigInt(string num1,string num2);
static string subtractBigInt(string minuend, string subtrahend);
static string multiplyBigInt(string num1, string num2);
static string divideByLl(string dividend, long long divisor);
static long long toInt(const string& num);
string toString() const;
};
#endif //COACHACADEMY_BIGINT_H
<file_sep>/Level2/week_02_Assignments/Matrix.cpp
//
// Created by HKP28 on 10/10/2020.
//
#include "Matrix.h"
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.18)
project(coachacademy)
set(CMAKE_CXX_STANDARD 14)
add_executable(coachacademy ForTest.cpp
Level2/week_02_Assignments/Matrix.h
Level2/week_02_Assignments/Matrix.cpp
)<file_sep>/Level2/week_01/ThreePlusOne.cpp
//
// Created by hkp28 on 19/09/2020.
//
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
int threePlusOneRec(int n){
// static int cycle=1;
// cout<<n<<endl;
// if(n==1)
// return cycle ;
// if(n%2==0){
// //n = n/2;
// threePlusOneRec(n / 2);
// }else{
// //n=3*n+1;
// threePlusOneRec(3 * n + 1);
// }
// cycle++;
return 0;
}
int threePlusOne(int n){
int cycle{0};
while(n>1){
if(n%2==0){
n = n/2;
}else{
n=3*n+1;
}
cycle++;
}
if (n==1){
cycle++;
}
return cycle;
}
int maximumCycle(int a, int b){
int maxCycle{0};
if(a>b){
std::swap(a,b);
}
for(int i = a;i<=b;i++){
int cycleLength = threePlusOne(i);
if(cycleLength>maxCycle){
maxCycle = cycleLength;
}
}
return maxCycle;
}
int main(){
int num{0};
std::vector<int> numbers;
std::vector<int> result;
while(cin>>num){
numbers.push_back(num);
}
for(int i = 0;i<numbers.size(); i+=2){
cout<<numbers[i] <<" "<<numbers[i+1]<<" "<<maximumCycle(numbers[i],numbers[i+1])<<endl;
}
return 0;
}<file_sep>/Level2/week_01/LumberjackSequencing.cpp
//
// Created by HKP28 on 16/09/2020.
//
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int compare(int a, int b){
return a>b;
}
int lumSequencChecker(int group[]){
int result[9];
int sum{0};
for(int i=0;i<9;i++){
result[i]= compare(group[i],group[i+1]);
}
for(int i=0;i<9;i++){
sum+=result[i];
}
if(sum!=9 && sum!=0){
return 0;
} else{
return 1;
}
}
int main() {
int t;
cin >> t;
if(t>19 || t<1){
return -1;
}
int output[t];
for (int i = 0; i < t; i++)
{
int group[10];
int element;
for (int c = 0; c < 10; c++)
{
cin>>element;
if(element<0 || element>100)
{
return -1;
}
group[c]= element;
}
output[i] = lumSequencChecker(group);
}
cout<<"Lumberjacks:"<<endl;
for(int i=0;i<t;i++){
if(output[i]==0){
cout<<"Unordered"<<endl;
} else{
cout<<"Ordered"<<endl;
}
}
return 0;
}
<file_sep>/Level2_Pretest/Diamond.cpp
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
void printDiamond(int);
bool isOdd(int);
int main(){
int t;
cin>>t;
if(t<1 || t>100){
return -1;
}
int dimArray[t];
for(int i=1;i<=t;i++){
int d;
cin>>d;
if(d<1 || d>99 || isOdd(d) == false){
return -1;
}
dimArray[i] = d;
}
for(int i=1;i<=t;i++){
printDiamond(dimArray[i]);
}
return 0;
}
void printDiamond(int d){
int c = (d-1)/2;
for (int x=1;x<=c;x++){
for (int y=1;y<=x;y++){
cout<<"*";
}
for (int y=d-x*2;y>=1;y--){
cout<<" ";
}
for (int y=1;y<=x;y++){
cout<<"*";
}
cout<<endl;
}
for(int i = 1;i<=d;i++){
cout<<"*";
}
cout<<endl;
for (int x=c;x>=1;x--){
for (int y=x;y>=1;y--){
cout<<"*";
}
for (int y=1;y<=d-x*2;y++){
cout<<" ";
}
for (int y=x;y>=1;y--){
cout<<"*";
}
cout<<endl;
}
}
bool isOdd(int n){
int reminder;
reminder = n%2;
if(reminder == 0)
{
return false;
} else{
return true;
}
}<file_sep>/Level2/week_01/Median.cpp
//
// Created by HKP28 on 16/09/2020.
//
#include <iostream>
#include <math.h>
#include <vector>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
bool isOdd(int n){
int reminder;
reminder = n%2;
if(reminder == 0)
{
return false;
} else{
return true;
}
}
int median(std::vector<int> numbers, int n){
int medianIndex;
if(isOdd(n)){
medianIndex =(n-1)/2;
return numbers[medianIndex];
}else{
medianIndex = n/2;
return std::ceil((numbers[medianIndex]+numbers[medianIndex-1])/2);
}
}
int main() {
int num{0}, x{0};
std::vector<int> numbers;
while(cin>>num){
numbers.push_back(num);
std::sort(numbers.begin(), numbers.end());
cout<< median(numbers,numbers.size())<<endl;
x++;
}
return 0;
}<file_sep>/Level2_Pretest/perfectArray.cpp
#include <iostream>
#include <math.h>
using std::cout;
using std::endl;
using std::cin;
bool isPerfect(int);
int main(){
int t, arrayDim;
cin>>t;
if(t<1 || t>100 ){
return -1;
}
int output[t];
for(int i=1;i<=t; i++){
cin>>arrayDim;
if(arrayDim<1 || arrayDim>100 ){
return -1;
}
int array[arrayDim][arrayDim];
for(int r=0;r<arrayDim;r++){
for(int c=0;c<arrayDim;c++){
int element;
std::cin >> element;
if(element<1 || element>100){
return -1;
}
array[r][c] = element;
}
}
int sum{0};
for(int r=0;r<arrayDim;r++){
for(int c=0;c<arrayDim;c++){
if(isPerfect(array[r][c])){
sum += array[r][c];
}
}
}
output[i]=sum;
}
for(int i=1;i<=t; i++){
cout<<output[i]<<endl;
}
return 0;
}
bool isPerfect(int x){
return (std::sqrt(x) - std::ceil(std::sqrt(x)))==0;
}<file_sep>/Level2_Pretest/sum.cpp
#include <iostream>
int main() {
int t;
int a,b;
std::cin>>t;
if(t<1 || t>1000 ){
return -1;
}
int result[t];
for (int i=0; i<t ; i++){
std::cin>>a;
std::cin>>b;
if((a<-100000 || a>100000) || (b<-100000 || b>100000) ){
return -1;
}
result[i] = abs(a)+abs(b);
}
for(int i=0; i<t ; i++){
std::cout<< result[i] <<std::endl;
}
return 0;
}
<file_sep>/Level2_Pretest/rec.cpp
#include <iostream>
int recSum(int elements[], int n) {
if (n == 0) {
return 0;
}
return elements[0] + recSum(elements + 1, n - 1);
}
int main() {
int t;
std::cin >> t;
if(t>100){
return -1;
}
int arraySize;
int output[t];
for (int i = 0; i < t; i++) {
std::cin >> arraySize;
if(arraySize<1 || arraySize>100){
return -1;
}
int array[arraySize];
for (int x = 0; x < arraySize; x++) {
int element;
std::cin >> element;
if(element<-1000 || element>1000){
return -1;
}
array[x]= element;
}
output[i] = recSum(array, arraySize);
}
for (int i = 0; i < t; i++) {
std::cout << "Case " << i + 1 << ": " << output[i] << std::endl;
}
return 0;
}
<file_sep>/Expermenting.cpp
//
// Created by Aboubakr on 9/25/2020.
//
#include <iostream>
using namespace std;
//int invertNumber(int n){
// int reverse=0,rem;
// while(n!=0)
// {
// rem=n%10;
// reverse=reverse*10+rem;
// n/=10;
// }
// return reverse;
//}
// Linked List
template<typename T>
class LinkedList{
private:
class Node{
public:
T _data;
Node* _nxt;
Node()
{
_data = T();
_nxt = nullptr;
}
};
Node* _head;
Node* _tail;
int _size;
public:
LinkedList(){
_head=_tail= nullptr;
_size = 0;
}
void push_front(const T& val){
Node* temp = new Node();
temp->_data = val;
temp->_nxt = _head;
if(_head== nullptr) _tail= temp;
_head = temp;
_size++;
}
void push_back(const T& val){
Node* temp = new Node();
temp->data = val;
temp->_nxt = nullptr;
if(_tail!= nullptr) _tail->_nxt = temp;
_tail = temp;
if(_head== nullptr) _head= temp;
_size++;
}
bool empty(){
return _head == nullptr;
}
T front(){
return _head->_data;
}
T back(){
return _tail->_data;
}
void pop_front(const T& val){
Node* temp = new Node();
_head = _head->_nxt;
if(_head== nullptr) _tail= nullptr;
delete temp;
_size--;
}
void insert(int idx, const T& val){
if(idx == 0)push_front(val);
else if (idx >= _size)push_back(val);
else{
Node* temp = new Node();
temp->_data=val;
Node* j = _head;
for(int i = 0; i < idx-1 ; ++i) j = j->_nxt;
temp->_nxt = j->_nxt;
j->_nxt = temp;
}
_size++;
}
void clear(){
while (_head != nullptr){
Node* temp = _head;
_head = _head->_nxt;
delete temp;
}
_size = 0;
}
virtual ~LinkedList() {
clear();
}
};
int main()
{
LinkedList<int> ll;
ll.push_front(10);
ll.push_front(9);
ll.push_front(8);
ll.push_front(7);
ll.push_front(6);
ll.push_front(5);
cout<<ll.front()<<endl;
cout<<ll.back()<<endl;
// int n, reverse=0, rem;
// cout<<"Enter a number: ";
// cin>>n;
// while(n!=0)
// {
// rem=n%10;
// reverse=reverse*10+rem;
// n/=10;
// }
// cout<<"Reversed Number: "<<invertNumber(n)<<endl;
return 0;
}
<file_sep>/ForTest.cpp
//
// Created by hkp28 on 21/09/2020.
//
#include <iostream>
#include "Level2/week_02_Assignments/Matrix.h"
#include <vector>
using std::pair;
using std::cout;
using std::endl;
using std::string;
void equalizeSize(string &num1,string &num2){
unsigned int sizeDiff;
if(num1.length()>num2.length()){
sizeDiff = num1.length()-num2.length();
} else{
sizeDiff = num2.length()-num1.length();
}
// equalize vector sizes
if(num1.length()>num2.length()){
num2.insert(num2.begin(),sizeDiff,'0');
} else{
num1.insert(num1.begin(),sizeDiff,'0');
}
}
string addBigInt(string num1,string num2){
equalizeSize(num1,num2);
char carry{'0'};
string sum(num1.length(),'0');
for(int i = (int) num1.length()-1; i>=0;i--){
sum[i]=((carry -'0')+(num1[i] -'0')+(num2[i] -'0'))+'0';
if(i!=0){
if(sum[i]>'9'){
carry = '1';
sum[i]-=10;
} else{
carry = '0';
}
}
}
//Check the last digit in the left
if(sum[0] > '9')
{
sum[0]-= 10;
sum.insert(sum.begin(),'1');
}
return sum;
}
string subtractBigInt(string minuend, string subtrahend){
// minuend should be greater than subtrahend
equalizeSize(minuend, subtrahend);
string difference(minuend.length(), '0');
// subtract
for(int i = (int) minuend.length() - 1; i >= 0; i--){
if(minuend[i] < subtrahend[i]){
minuend[i]+=10;
minuend[i - 1]--;
}
difference[i]= (minuend[i] - '0') - (subtrahend[i] - '0') + '0';
}
// Remove Left zeros
while(difference[0] == '0' && difference.length() != 1){
difference.erase(difference.begin());
}
return difference;
}
string multiplyBigInt(string num1, string num2){
//
if(num1.length()>num2.length()){
num1.swap(num2);
}
string result{'0'};
// num1 is the smaller
for(int i = (int) num1.length()-1; i>=0;i--){
string temp(num2);
int carry = 0;
// num2 is the bigger
for(int j = (int) num2.length()-1; j>=0;j--){
temp[j] = (num2[j]-'0')*(num1[i]-'0')+carry;
if(temp[j]>9){
carry = temp[j]/10;
temp[j]-= carry*10;
}else{
carry = 0;
}
temp[j]+='0';
}
if(carry>0){
temp.insert(temp.begin(),(carry+'0'));
}
temp.insert(temp.end(),num1.length()-i-1,'0');
result = addBigInt(result,temp);
}
// Remove Left zeros
while(result[0] == '0' && result.length() != 1){
result.erase(result.begin());
}
return result;
}
string divideBigInt(string dividend, string divisor){
string reminder;
return string ("0");
}
pair<string, long long> divideByLl(string dividend, long long divisor){
long long rem = 0;
string result; result.resize(10000);
for(int indx=0, len = dividend.size(); indx<len; ++indx)
{
rem = (rem * 10) + (dividend[indx] - '0');
result[indx] = rem / divisor + '0';
rem %= divisor;
}
result.resize( dividend.size() );
// Remove Left zeros
while(result[0] == '0' && result.size() != 1){
result.erase(result.begin());
}
if(result.size() == 0)
result.push_back('0');
return make_pair(result, rem);
}
int main()
{
Matrix<int> matrix;
// BigInt bigInt1;
// BigInt bigInt2("25");
//
// std::cin>>bigInt1;
// cout<< bigInt1.getSign()<<endl;
// cout<< bigInt1.getNumber()<<endl;
// cout<< endl << bigInt1<< endl;
// cout<<"bigInt1 + bigInt2 = "<<bigInt1 + bigInt2<<endl;
// cout<<"bigInt1 - bigInt2 = "<<bigInt1 - bigInt2<<endl;
// cout<<"bigInt1 * bigInt2 = "<<bigInt1 * bigInt2<<endl;
// cout<<"bigInt1 / bigInt2 = "<<bigInt1 / bigInt2<<endl;
//
// cout<<"bigInt1++ = "<<bigInt1++<<endl;
// cout<<"bigInt1 = "<<bigInt1 <<endl;
// string num1="645842";
// string num2="25";
// vector<char>sum = addBigInt(num1,num2);
// vector<char>sum = multiplyBigInt(num1,num2);
// auto result = subtractBigInt(num1,num2);
// cout<<bigInt1<<endl;
return 0;
}<file_sep>/Level2/week_02_Assignments/Matrix.h
//
// Created by HKP28 on 10/10/2020.
//
#ifndef COACHACADEMY_MATRIX_H
#define COACHACADEMY_MATRIX_H
#include <vector>
using std::vector;
template<typename T>
class Matrix {
private:
vector<vector<T>> matrix;
int rows, cols;
public:
Matrix();
Matrix operator+(const Matrix& matrix);
private:
vector<vector<T>> AddMatrix(vector<vector<T>>matrix1,vector<vector<T>> matrix2);
vector<vector<T>> subtractMatrix(vector<vector<T>>matrix1,vector<vector<T>> matrix2);
vector<vector<T>> MultiplyMatrix(vector<vector<T>>matrix1,vector<vector<T>> matrix2);
vector<vector<T>> TransposeMatrix(vector<vector<T>> matrix);
};
template<typename T>
Matrix<T>::Matrix() {
}
template<typename T>
vector<vector<T>> Matrix<T>::AddMatrix(vector<vector<T>> matrix1, vector<vector<T>> matrix2) {
vector<vector<T>> result;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols ; ++j) {
result[i][j] = matrix1[i][j] + matrix1[i][j];
}
}
return result;
}
template<typename T>
vector<vector<T>> Matrix<T>::subtractMatrix(vector<vector<T>> matrix1, vector<vector<T>> matrix2) {
return vector<vector<T>>();
}
template<typename T>
vector<vector<T>> Matrix<T>::MultiplyMatrix(vector<vector<T>> matrix1, vector<vector<T>> matrix2) {
return vector<vector<T>>();
}
template<typename T>
vector<vector<T>> Matrix<T>::TransposeMatrix(vector<vector<T>> matrix) {
return vector<vector<T>>();
}
#endif //COACHACADEMY_MATRIX_H
<file_sep>/Level2/week_01/RationalOperator.cpp
//
// Created by Aboubakr on 9/15/2020.
//
#include <iostream>
int main() {
int t;
std::cin>>t;
if(t>=15)
return -1;
char result[t];
int a,b;
for (int i = 0; i<t; i++){
std::cin>>a;
std::cin>>b;
if(a>b)
{
result[i]='>';
}
else if(a<b)
{
result[i]='<';
}
else
{
result[i]='=';
}
}
for (int i = 0; i<t; i++){
std::cout<<result[i]<<std::endl;
}
return 0;
}<file_sep>/Level2_Pretest/maxOf3.cpp
#include <iostream>
#include <algorithm>
// compiler should support c++17 for std::max_element to work
int main() {
int t;
std::cin>>t;
if(t<1 || t>100 ){
return -1;
}
int result[t];
for (int i=0; i<t ; i++){
int numbers[3];
for (int x=0; x<3 ;x++){
int number;
std::cin>>number;
if(number<1 || number>5 ){
return -1;
}
numbers[x]= number;
}
result[i] = *std::max_element(numbers,numbers+3);
}
for(int i=0; i<t ; i++){
std::cout<< result[i] <<std::endl;
}
return 0;
}
<file_sep>/Level2/week_02/BooksQueries.cpp
//
// Created by hkp28 on 25/09/2020.
//
#include <iostream>
#include <deque>
#include <vector>
#include <algorithm>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::deque;
using std::vector;
int booksToPopup(deque<int> shelf, int id){
int pos{0};
int books{0};
for(int i=0 ;i<shelf.size();i++){
if(shelf[i]==id){
pos = i+1;
break;
}
}
if(pos<=shelf.size()/2){
books = pos-1;
}else{
books = shelf.size()-pos;
}
return books;
}
int main(){
int queries;
cin>>queries;
deque<int> shelf;
vector<int> queryresults;
for(int i=1 ;i<=queries;i++){
char queryType;
int id;
cin>>queryType;
cin >> id;
if(queryType=='L'){
// Insert left
shelf.push_front(id);
} else if (queryType=='R'){
// Insert right
shelf.push_back(id);
} else if (queryType=='?'){
// Search id
int books = booksToPopup(shelf,id);
// insert query result
queryresults.push_back(books);
}
}
for (int r:queryresults){
cout<<r<<endl;
}
// for(int i=0 ;i<shelf.size();i++){
// cout<<shelf[i]<<endl;
// }
// cout<<"Popped books: "<< booksToPopup(shelf,115);
return 0;
}
| 74360ae7fb48d4f59b6e2d8c3b022cf8283a3fc9 | [
"CMake",
"C++"
] | 22 | C++ | Bakkarxp/coachacademy | 539de72b2e83164d455fe1631a94f3153c41adf7 | 8c1315e3bdc123526f57323b0298f8051352f758 |
refs/heads/master | <repo_name>HugoF92/SisVenLog-WEB<file_sep>/SisVenLog-ejb/src/java/entidad/Clientes.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Hugo
*/
@Entity
@Table(name = "clientes")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Clientes.findAll", query = "SELECT c FROM Clientes c")
, @NamedQuery(name = "Clientes.findByCodCliente", query = "SELECT c FROM Clientes c WHERE c.codCliente = :codCliente")
, @NamedQuery(name = "Clientes.findByXnombre", query = "SELECT c FROM Clientes c WHERE c.xnombre = :xnombre")
, @NamedQuery(name = "Clientes.findByCodEmpr", query = "SELECT c FROM Clientes c WHERE c.codEmpr = :codEmpr")
, @NamedQuery(name = "Clientes.findByCodRuta", query = "SELECT c FROM Clientes c WHERE c.codRuta = :codRuta")
, @NamedQuery(name = "Clientes.findByCodCiudad", query = "SELECT c FROM Clientes c WHERE c.codCiudad = :codCiudad")
, @NamedQuery(name = "Clientes.findByCtipoCliente", query = "SELECT c FROM Clientes c WHERE c.ctipoCliente = :ctipoCliente")
, @NamedQuery(name = "Clientes.findByXcedula", query = "SELECT c FROM Clientes c WHERE c.xcedula = :xcedula")
, @NamedQuery(name = "Clientes.findByXruc", query = "SELECT c FROM Clientes c WHERE c.xruc = :xruc")
, @NamedQuery(name = "Clientes.findByXtelef", query = "SELECT c FROM Clientes c WHERE c.xtelef = :xtelef")
, @NamedQuery(name = "Clientes.findByXfax", query = "SELECT c FROM Clientes c WHERE c.xfax = :xfax")
, @NamedQuery(name = "Clientes.findByXdirec", query = "SELECT c FROM Clientes c WHERE c.xdirec = :xdirec")
, @NamedQuery(name = "Clientes.findByNordenRuta", query = "SELECT c FROM Clientes c WHERE c.nordenRuta = :nordenRuta")
, @NamedQuery(name = "Clientes.findByXpropietario", query = "SELECT c FROM Clientes c WHERE c.xpropietario = :xpropietario")
, @NamedQuery(name = "Clientes.findByNplazoCredito", query = "SELECT c FROM Clientes c WHERE c.nplazoCredito = :nplazoCredito")
, @NamedQuery(name = "Clientes.findByIlimiteCompra", query = "SELECT c FROM Clientes c WHERE c.ilimiteCompra = :ilimiteCompra")
, @NamedQuery(name = "Clientes.findByMformaPago", query = "SELECT c FROM Clientes c WHERE c.mformaPago = :mformaPago")
, @NamedQuery(name = "Clientes.findByNriesgo", query = "SELECT c FROM Clientes c WHERE c.nriesgo = :nriesgo")
, @NamedQuery(name = "Clientes.findByCodGrupo", query = "SELECT c FROM Clientes c WHERE c.codGrupo = :codGrupo")
, @NamedQuery(name = "Clientes.findByCodEstado", query = "SELECT c FROM Clientes c WHERE c.codEstado = :codEstado")
, @NamedQuery(name = "Clientes.findByXrazonEstado", query = "SELECT c FROM Clientes c WHERE c.xrazonEstado = :xrazonEstado")
, @NamedQuery(name = "Clientes.findByFprimFact", query = "SELECT c FROM Clientes c WHERE c.fprimFact = :fprimFact")
, @NamedQuery(name = "Clientes.findByXcontacto", query = "SELECT c FROM Clientes c WHERE c.xcontacto = :xcontacto")
, @NamedQuery(name = "Clientes.findByIsaldo", query = "SELECT c FROM Clientes c WHERE c.isaldo = :isaldo")
, @NamedQuery(name = "Clientes.findByFalta", query = "SELECT c FROM Clientes c WHERE c.falta = :falta")
, @NamedQuery(name = "Clientes.findByCusuario", query = "SELECT c FROM Clientes c WHERE c.cusuario = :cusuario")
, @NamedQuery(name = "Clientes.findByFultimModif", query = "SELECT c FROM Clientes c WHERE c.fultimModif = :fultimModif")
, @NamedQuery(name = "Clientes.findByCusuarioModif", query = "SELECT c FROM Clientes c WHERE c.cusuarioModif = :cusuarioModif")
, @NamedQuery(name = "Clientes.findByCodAnterior", query = "SELECT c FROM Clientes c WHERE c.codAnterior = :codAnterior")
, @NamedQuery(name = "Clientes.findByXobs", query = "SELECT c FROM Clientes c WHERE c.xobs = :xobs")
, @NamedQuery(name = "Clientes.findByXemail", query = "SELECT c FROM Clientes c WHERE c.xemail = :xemail")
, @NamedQuery(name = "Clientes.findByXctacte", query = "SELECT c FROM Clientes c WHERE c.xctacte = :xctacte")
, @NamedQuery(name = "Clientes.findByCodBanco", query = "SELECT c FROM Clientes c WHERE c.codBanco = :codBanco")
, @NamedQuery(name = "Clientes.findByNfrec", query = "SELECT c FROM Clientes c WHERE c.nfrec = :nfrec")
, @NamedQuery(name = "Clientes.findByXdiasVisita", query = "SELECT c FROM Clientes c WHERE c.xdiasVisita = :xdiasVisita")
, @NamedQuery(name = "Clientes.findByCcategCliente", query = "SELECT c FROM Clientes c WHERE c.ccategCliente = :ccategCliente")
, @NamedQuery(name = "Clientes.findByCodCanal", query = "SELECT c FROM Clientes c WHERE c.codCanal = :codCanal")
, @NamedQuery(name = "Clientes.findByNplazoImpresion", query = "SELECT c FROM Clientes c WHERE c.nplazoImpresion = :nplazoImpresion")})
public class Clientes implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
//@NotNull
@Column(name = "cod_cliente")
private Integer codCliente;
//@Size(max = 50)
@Column(name = "xnombre")
private String xnombre;
@Basic(optional = false)
//@NotNull
@Column(name = "cod_empr")
private short codEmpr;
@Column(name = "cod_ruta")
private Short codRuta;
@Column(name = "cod_ciudad")
private Short codCiudad;
@Column(name = "ctipo_cliente")
private Character ctipoCliente;
@Column(name = "xcedula")
private Long xcedula;
//@Size(max = 15)
@Column(name = "xruc")
private String xruc;
//@Size(max = 16)
@Column(name = "xtelef")
private String xtelef;
//@Size(max = 16)
@Column(name = "xfax")
private String xfax;
//@Size(max = 50)
@Column(name = "xdirec")
private String xdirec;
@Column(name = "norden_ruta")
private Short nordenRuta;
//@Size(max = 50)
@Column(name = "xpropietario")
private String xpropietario;
@Column(name = "nplazo_credito")
private Short nplazoCredito;
@Basic(optional = false)
//@NotNull
@Column(name = "ilimite_compra")
private long ilimiteCompra;
@Basic(optional = false)
//@NotNull
@Column(name = "mforma_pago")
private Character mformaPago;
@Column(name = "nriesgo")
private Short nriesgo;
@Column(name = "cod_grupo")
private Short codGrupo;
//@Size(max = 2)
@Column(name = "cod_estado")
private String codEstado;
//@Size(max = 150)
@Column(name = "xrazon_estado")
private String xrazonEstado;
@Column(name = "fprim_fact")
@Temporal(TemporalType.TIMESTAMP)
private Date fprimFact;
//@Size(max = 50)
@Column(name = "xcontacto")
private String xcontacto;
@Basic(optional = false)
//@NotNull
@Column(name = "isaldo")
private long isaldo;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
//@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
//@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
//@Size(max = 6)
@Column(name = "cod_anterior")
private String codAnterior;
//@Size(max = 300)
@Column(name = "xobs")
private String xobs;
//@Size(max = 50)
@Column(name = "xemail")
private String xemail;
//@Size(max = 15)
@Column(name = "xctacte")
private String xctacte;
@Column(name = "cod_banco")
private Short codBanco;
@Column(name = "nfrec")
private Short nfrec;
//@Size(max = 7)
@Column(name = "xdias_visita")
private String xdiasVisita;
//@Size(max = 2)
@Column(name = "ccateg_cliente")
private String ccategCliente;
//@Size(max = 2)
@Column(name = "cod_canal")
private String codCanal;
@Column(name = "nplazo_impresion")
private Short nplazoImpresion;
@OneToMany(mappedBy = "codCliente")
private Collection<CuentasCorrientes> cuentasCorrientesCollection;
@OneToMany(mappedBy = "codCliente")
private Collection<Cheques> chequesCollection;
public Clientes() {
}
public Clientes(Integer codCliente) {
this.codCliente = codCliente;
}
public Clientes(Integer codCliente, short codEmpr, long ilimiteCompra, Character mformaPago, long isaldo) {
this.codCliente = codCliente;
this.codEmpr = codEmpr;
this.ilimiteCompra = ilimiteCompra;
this.mformaPago = mformaPago;
this.isaldo = isaldo;
}
public Integer getCodCliente() {
return codCliente;
}
public void setCodCliente(Integer codCliente) {
this.codCliente = codCliente;
}
public String getXnombre() {
return xnombre;
}
public void setXnombre(String xnombre) {
this.xnombre = xnombre;
}
public short getCodEmpr() {
return codEmpr;
}
public void setCodEmpr(short codEmpr) {
this.codEmpr = codEmpr;
}
public Short getCodRuta() {
return codRuta;
}
public void setCodRuta(Short codRuta) {
this.codRuta = codRuta;
}
public Short getCodCiudad() {
return codCiudad;
}
public void setCodCiudad(Short codCiudad) {
this.codCiudad = codCiudad;
}
public Character getCtipoCliente() {
return ctipoCliente;
}
public void setCtipoCliente(Character ctipoCliente) {
this.ctipoCliente = ctipoCliente;
}
public Long getXcedula() {
return xcedula;
}
public void setXcedula(Long xcedula) {
this.xcedula = xcedula;
}
public String getXruc() {
return xruc;
}
public void setXruc(String xruc) {
this.xruc = xruc;
}
public String getXtelef() {
return xtelef;
}
public void setXtelef(String xtelef) {
this.xtelef = xtelef;
}
public String getXfax() {
return xfax;
}
public void setXfax(String xfax) {
this.xfax = xfax;
}
public String getXdirec() {
return xdirec;
}
public void setXdirec(String xdirec) {
this.xdirec = xdirec;
}
public Short getNordenRuta() {
return nordenRuta;
}
public void setNordenRuta(Short nordenRuta) {
this.nordenRuta = nordenRuta;
}
public String getXpropietario() {
return xpropietario;
}
public void setXpropietario(String xpropietario) {
this.xpropietario = xpropietario;
}
public Short getNplazoCredito() {
return nplazoCredito;
}
public void setNplazoCredito(Short nplazoCredito) {
this.nplazoCredito = nplazoCredito;
}
public long getIlimiteCompra() {
return ilimiteCompra;
}
public void setIlimiteCompra(long ilimiteCompra) {
this.ilimiteCompra = ilimiteCompra;
}
public Character getMformaPago() {
return mformaPago;
}
public void setMformaPago(Character mformaPago) {
this.mformaPago = mformaPago;
}
public Short getNriesgo() {
return nriesgo;
}
public void setNriesgo(Short nriesgo) {
this.nriesgo = nriesgo;
}
public Short getCodGrupo() {
return codGrupo;
}
public void setCodGrupo(Short codGrupo) {
this.codGrupo = codGrupo;
}
public String getCodEstado() {
return codEstado;
}
public void setCodEstado(String codEstado) {
this.codEstado = codEstado;
}
public String getXrazonEstado() {
return xrazonEstado;
}
public void setXrazonEstado(String xrazonEstado) {
this.xrazonEstado = xrazonEstado;
}
public Date getFprimFact() {
return fprimFact;
}
public void setFprimFact(Date fprimFact) {
this.fprimFact = fprimFact;
}
public String getXcontacto() {
return xcontacto;
}
public void setXcontacto(String xcontacto) {
this.xcontacto = xcontacto;
}
public long getIsaldo() {
return isaldo;
}
public void setIsaldo(long isaldo) {
this.isaldo = isaldo;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
public String getCodAnterior() {
return codAnterior;
}
public void setCodAnterior(String codAnterior) {
this.codAnterior = codAnterior;
}
public String getXobs() {
return xobs;
}
public void setXobs(String xobs) {
this.xobs = xobs;
}
public String getXemail() {
return xemail;
}
public void setXemail(String xemail) {
this.xemail = xemail;
}
public String getXctacte() {
return xctacte;
}
public void setXctacte(String xctacte) {
this.xctacte = xctacte;
}
public Short getCodBanco() {
return codBanco;
}
public void setCodBanco(Short codBanco) {
this.codBanco = codBanco;
}
public Short getNfrec() {
return nfrec;
}
public void setNfrec(Short nfrec) {
this.nfrec = nfrec;
}
public String getXdiasVisita() {
return xdiasVisita;
}
public void setXdiasVisita(String xdiasVisita) {
this.xdiasVisita = xdiasVisita;
}
public String getCcategCliente() {
return ccategCliente;
}
public void setCcategCliente(String ccategCliente) {
this.ccategCliente = ccategCliente;
}
public String getCodCanal() {
return codCanal;
}
public void setCodCanal(String codCanal) {
this.codCanal = codCanal;
}
public Short getNplazoImpresion() {
return nplazoImpresion;
}
public void setNplazoImpresion(Short nplazoImpresion) {
this.nplazoImpresion = nplazoImpresion;
}
@Override
public int hashCode() {
int hash = 0;
hash += (codCliente != null ? codCliente.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Clientes)) {
return false;
}
Clientes other = (Clientes) object;
if ((this.codCliente == null && other.codCliente != null) || (this.codCliente != null && !this.codCliente.equals(other.codCliente))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Clientes[ codCliente=" + codCliente + " ]";
}
@XmlTransient
public Collection<CuentasCorrientes> getCuentasCorrientesCollection() {
return cuentasCorrientesCollection;
}
public void setCuentasCorrientesCollection(Collection<CuentasCorrientes> cuentasCorrientesCollection) {
this.cuentasCorrientesCollection = cuentasCorrientesCollection;
}
@XmlTransient
public Collection<Cheques> getChequesCollection() {
return chequesCollection;
}
public void setChequesCollection(Collection<Cheques> chequesCollection) {
this.chequesCollection = chequesCollection;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/DivisionesFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Divisiones;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
/**
*
* @author admin
*/
@Stateless
public class DivisionesFacade extends AbstractFacade<Divisiones> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public DivisionesFacade() {
super(Divisiones.class);
}
public List<Divisiones> listarSubdiviciones() {
Query q = getEntityManager().createNativeQuery("SELECT DISTINCT d.cod_division, d.xdesc \n"
+ "FROM divisiones d, categorias g, lineas l, sublineas s, mercaderias m \n"
+ " WHERE d.cod_division = g.cod_division AND g.cod_categoria = l.cod_categoria \n"
+ " AND l.cod_linea = s.cod_linea \n"
+ " AND s.cod_sublinea = m.cod_sublinea \n"
+ " AND m.mestado = 'A' \n"
+ "ORDER BY d.xdesc", Divisiones.class);
//System.out.println(q.toString());
List<Divisiones> respuesta = new ArrayList<Divisiones>();
respuesta = q.getResultList();
return respuesta;
}
public void insertarDivisiones(Divisiones divisiones) {
StoredProcedureQuery q = getEntityManager().createStoredProcedureQuery("InsertarDivisiones");
q.registerStoredProcedureParameter("xdesc", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("falta", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cusuario", String.class, ParameterMode.IN);
q.setParameter("xdesc", divisiones.getXdesc());
q.setParameter("falta", divisiones.getFalta());
q.setParameter("cusuario", divisiones.getCusuario());
q.execute();
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Proveedores.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author admin
*/
@Entity
@Table(name = "proveedores")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Proveedores.findAll", query = "SELECT p FROM Proveedores p")
, @NamedQuery(name = "Proveedores.findByCodProveed", query = "SELECT p FROM Proveedores p WHERE p.codProveed = :codProveed")
, @NamedQuery(name = "Proveedores.findByCodCanal", query = "SELECT p FROM Proveedores p WHERE p.codCanal = :codCanal")
, @NamedQuery(name = "Proveedores.findByXnombre", query = "SELECT p FROM Proveedores p WHERE p.xnombre = :xnombre")
, @NamedQuery(name = "Proveedores.findByXtelef", query = "SELECT p FROM Proveedores p WHERE p.xtelef = :xtelef")
, @NamedQuery(name = "Proveedores.findByXruc", query = "SELECT p FROM Proveedores p WHERE p.xruc = :xruc")
, @NamedQuery(name = "Proveedores.findByXdirec", query = "SELECT p FROM Proveedores p WHERE p.xdirec = :xdirec")
, @NamedQuery(name = "Proveedores.findByIlimiteCredito", query = "SELECT p FROM Proveedores p WHERE p.ilimiteCredito = :ilimiteCredito")
, @NamedQuery(name = "Proveedores.findByXcontacto", query = "SELECT p FROM Proveedores p WHERE p.xcontacto = :xcontacto")
, @NamedQuery(name = "Proveedores.findByCusuario", query = "SELECT p FROM Proveedores p WHERE p.cusuario = :cusuario")
, @NamedQuery(name = "Proveedores.findByFalta", query = "SELECT p FROM Proveedores p WHERE p.falta = :falta")
, @NamedQuery(name = "Proveedores.findByCusuarioModif", query = "SELECT p FROM Proveedores p WHERE p.cusuarioModif = :cusuarioModif")
, @NamedQuery(name = "Proveedores.findByFultimModif", query = "SELECT p FROM Proveedores p WHERE p.fultimModif = :fultimModif")
, @NamedQuery(name = "Proveedores.findByCodContasys", query = "SELECT p FROM Proveedores p WHERE p.codContasys = :codContasys")})
public class Proveedores implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "cod_proveed")
private Short codProveed;
@Column(name = "ilimite_credito")
private Long ilimiteCredito;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@Column(name = "cod_contasys")
private Short codContasys;
@Size(max = 2)
@Column(name = "cod_canal")
private String codCanal;
@Size(max = 50)
@Column(name = "xnombre")
private String xnombre;
@Size(max = 15)
@Column(name = "xtelef")
private String xtelef;
@Size(max = 15)
@Column(name = "xruc")
private String xruc;
@Size(max = 50)
@Column(name = "xdirec")
private String xdirec;
@Size(max = 50)
@Column(name = "xcontacto")
private String xcontacto;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
@Column(name = "mestado")
private Character mestado;
@OneToMany(mappedBy = "codProveed")
private Collection<Mercaderias> mercaderiasCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "codProveed")
private Collection<ChequesEmitidos> chequesEmitidosCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "codProveed")
private Collection<CuentasProveedores> cuentasProveedoresCollection;
public Proveedores() {
}
public Proveedores(Short codProveed) {
this.codProveed = codProveed;
}
public Short getCodProveed() {
return codProveed;
}
public void setCodProveed(Short codProveed) {
this.codProveed = codProveed;
}
public String getCodCanal() {
return codCanal;
}
public void setCodCanal(String codCanal) {
this.codCanal = codCanal;
}
public Long getIlimiteCredito() {
return ilimiteCredito;
}
public void setIlimiteCredito(Long ilimiteCredito) {
this.ilimiteCredito = ilimiteCredito;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public Short getCodContasys() {
return codContasys;
}
public void setCodContasys(Short codContasys) {
this.codContasys = codContasys;
}
@Override
public int hashCode() {
int hash = 0;
hash += (codProveed != null ? codProveed.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Proveedores)) {
return false;
}
Proveedores other = (Proveedores) object;
if ((this.codProveed == null && other.codProveed != null) || (this.codProveed != null && !this.codProveed.equals(other.codProveed))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Proveedores[ codProveed=" + codProveed + " ]";
}
public String getXnombre() {
return xnombre;
}
public void setXnombre(String xnombre) {
this.xnombre = xnombre;
}
public String getXtelef() {
return xtelef;
}
public void setXtelef(String xtelef) {
this.xtelef = xtelef;
}
public String getXruc() {
return xruc;
}
public void setXruc(String xruc) {
this.xruc = xruc;
}
public String getXdirec() {
return xdirec;
}
public void setXdirec(String xdirec) {
this.xdirec = xdirec;
}
public String getXcontacto() {
return xcontacto;
}
public void setXcontacto(String xcontacto) {
this.xcontacto = xcontacto;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Character getMestado() {
return mestado;
}
public void setMestado(Character mestado) {
this.mestado = mestado;
}
@XmlTransient
public Collection<Mercaderias> getMercaderiasCollection() {
return mercaderiasCollection;
}
public void setMercaderiasCollection(Collection<Mercaderias> mercaderiasCollection) {
this.mercaderiasCollection = mercaderiasCollection;
}
@XmlTransient
public Collection<ChequesEmitidos> getChequesEmitidosCollection() {
return chequesEmitidosCollection;
}
public void setChequesEmitidosCollection(Collection<ChequesEmitidos> chequesEmitidosCollection) {
this.chequesEmitidosCollection = chequesEmitidosCollection;
}
@XmlTransient
public Collection<CuentasProveedores> getCuentasProveedoresCollection() {
return cuentasProveedoresCollection;
}
public void setCuentasProveedoresCollection(Collection<CuentasProveedores> cuentasProveedoresCollection) {
this.cuentasProveedoresCollection = cuentasProveedoresCollection;
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/CompraDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import entidad.Compras;
/**
*
* @author dadob
*/
public class CompraDto {
private Compras compra;
private String descripcionDeposito;
private String nombreProveedor;
public Compras getCompra() {
return compra;
}
public void setCompra(Compras compra) {
this.compra = compra;
}
public String getDescripcionDeposito() {
return descripcionDeposito;
}
public void setDescripcionDeposito(String descripcionDeposito) {
this.descripcionDeposito = descripcionDeposito;
}
public String getNombreProveedor() {
return nombreProveedor;
}
public void setNombreProveedor(String nombreProveedor) {
this.nombreProveedor = nombreProveedor;
}
}
<file_sep>/SisVenLog-war/src/java/bean/ParametrosBean.java
package bean;
import dao.ParametrosFacade;
import entidad.Parametros;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class ParametrosBean implements Serializable {
@EJB
private ParametrosFacade parametrosFacade;
private String filtro = "";
private Parametros parametros = new Parametros();
private List<Parametros> listaParametros = new ArrayList<Parametros>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public ParametrosBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public Parametros getParametros() {
return parametros;
}
public void setParametros(Parametros parametros) {
this.parametros = parametros;
}
public List<Parametros> getListaParametros() {
return listaParametros;
}
public void setListaParametros(List<Parametros> listaParametros) {
this.listaParametros = listaParametros;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaParametros = new ArrayList<Parametros>();
this.parametros = new Parametros();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
this.filtro = "";
listar();
RequestContext.getCurrentInstance().update("formParametros");
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public void nuevo() {
this.parametros = new Parametros();
}
public List<Parametros> listar() {
listaParametros = parametrosFacade.findAll();
return listaParametros;
}
public void insertar() {
try {
parametros.setXdesc(parametros.getXdesc().toUpperCase());
parametros.setFalta(new Date());
parametros.setCusuario("admin");
parametrosFacade.create(parametros);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevParametros').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editar() {
try {
if ("".equals(this.parametros.getXdesc())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
parametros.setXdesc(parametros.getXdesc().toUpperCase());
parametrosFacade.edit(parametros);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditParametros').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void borrar() {
try {
parametrosFacade.remove(parametros);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacParametros').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
if ("" != this.parametros.getXdesc()) {
this.setHabBtnEdit(false);
} else {
this.setHabBtnEdit(true);
}
}
public void verificarCargaDatos() {
boolean cargado = false;
if (parametros != null) {
if (parametros.getXdesc() != null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarParametros').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevParametros').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarParametros').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevParametros').hide();");
}
public String tipoDato(String tipo) {
String retorno = "";
String aux = tipo;
if (aux.equals("N")) {
retorno = "NUMERICO";
}
if (aux.equals("A")) {
retorno = "ALFANUMERICO";
}
return retorno;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Conductores.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Hugo
*/
@Entity
@Table(name = "conductores")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Conductores.findAll", query = "SELECT c FROM Conductores c")
, @NamedQuery(name = "Conductores.findByCodConductor", query = "SELECT c FROM Conductores c WHERE c.codConductor = :codConductor")
, @NamedQuery(name = "Conductores.findByXconductor", query = "SELECT c FROM Conductores c WHERE c.xconductor = :xconductor")
, @NamedQuery(name = "Conductores.findByXdocum", query = "SELECT c FROM Conductores c WHERE c.xdocum = :xdocum")
, @NamedQuery(name = "Conductores.findByXdomicilio", query = "SELECT c FROM Conductores c WHERE c.xdomicilio = :xdomicilio")
, @NamedQuery(name = "Conductores.findByCusuario", query = "SELECT c FROM Conductores c WHERE c.cusuario = :cusuario")
, @NamedQuery(name = "Conductores.findByFalta", query = "SELECT c FROM Conductores c WHERE c.falta = :falta")
, @NamedQuery(name = "Conductores.findByCusuarioModif", query = "SELECT c FROM Conductores c WHERE c.cusuarioModif = :cusuarioModif")
, @NamedQuery(name = "Conductores.findByFultimModif", query = "SELECT c FROM Conductores c WHERE c.fultimModif = :fultimModif")})
public class Conductores implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
//@NotNull
@Column(name = "cod_conductor")
private Short codConductor;
//@Size(max = 50)
@Column(name = "xconductor")
private String xconductor;
//@Size(max = 30)
@Column(name = "xdocum")
private String xdocum;
//@Size(max = 50)
@Column(name = "xdomicilio")
private String xdomicilio;
//@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
//@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@OneToMany(mappedBy = "codConductor")
private Collection<Depositos> depositosCollection;
public Conductores() {
}
public Conductores(Short codConductor) {
this.codConductor = codConductor;
}
public Short getCodConductor() {
return codConductor;
}
public void setCodConductor(Short codConductor) {
this.codConductor = codConductor;
}
public String getXconductor() {
return xconductor;
}
public void setXconductor(String xconductor) {
this.xconductor = xconductor;
}
public String getXdocum() {
return xdocum;
}
public void setXdocum(String xdocum) {
this.xdocum = xdocum;
}
public String getXdomicilio() {
return xdomicilio;
}
public void setXdomicilio(String xdomicilio) {
this.xdomicilio = xdomicilio;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
@XmlTransient
public Collection<Depositos> getDepositosCollection() {
return depositosCollection;
}
public void setDepositosCollection(Collection<Depositos> depositosCollection) {
this.depositosCollection = depositosCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (codConductor != null ? codConductor.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Conductores)) {
return false;
}
Conductores other = (Conductores) object;
if ((this.codConductor == null && other.codConductor != null) || (this.codConductor != null && !this.codConductor.equals(other.codConductor))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Conductores[ codConductor=" + codConductor + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/RutasFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Rutas;
import java.util.Date;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.StoredProcedureQuery;
/**
*
* @author admin
*/
@Stateless
public class RutasFacade extends AbstractFacade<Rutas> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public RutasFacade() {
super(Rutas.class);
}
public void insertarRutas(Rutas rutas) {
StoredProcedureQuery q = getEntityManager().createStoredProcedureQuery("InsertarRutas");
q.registerStoredProcedureParameter("cod_zona", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xdesc", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("falta", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cusuario", String.class, ParameterMode.IN);
q.setParameter("cod_zona", rutas.getZonas().getZonasPK().getCodZona());
q.setParameter("xdesc", rutas.getXdesc());
q.setParameter("falta", rutas.getFalta());
q.setParameter("cusuario", rutas.getCusuario());
q.execute();
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/CuentaProveedorDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import java.util.Date;
/**
*
* @author dadob
*/
public class CuentaProveedorDto {
private Date fechaMovimiento;
private long exentas;
private long gravadas;
private long impuestos;
private String concepto;
private Date fechaVencimiento;
private long importePagado;
private String tipoDocumento;
private String tipoDocumentoDescripcion;
private String numeroDocumentoCheque;
private String otroTipoDocumento;
private Long otroNumeroDocumento;
public Date getFechaMovimiento() {
return fechaMovimiento;
}
public void setFechaMovimiento(Date fechaMovimiento) {
this.fechaMovimiento = fechaMovimiento;
}
public long getExentas() {
return exentas;
}
public void setExentas(long exentas) {
this.exentas = exentas;
}
public long getGravadas() {
return gravadas;
}
public void setGravadas(long gravadas) {
this.gravadas = gravadas;
}
public long getImpuestos() {
return impuestos;
}
public void setImpuestos(long impuestos) {
this.impuestos = impuestos;
}
public String getConcepto() {
return concepto;
}
public void setConcepto(String concepto) {
this.concepto = concepto;
}
public Date getFechaVencimiento() {
return fechaVencimiento;
}
public void setFechaVencimiento(Date fechaVencimiento) {
this.fechaVencimiento = fechaVencimiento;
}
public long getImportePagado() {
return importePagado;
}
public void setImportePagado(long importePagado) {
this.importePagado = importePagado;
}
public String getTipoDocumento() {
return tipoDocumento;
}
public void setTipoDocumento(String tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
public String getNumeroDocumentoCheque() {
return numeroDocumentoCheque;
}
public void setNumeroDocumentoCheque(String numeroDocumentoCheque) {
this.numeroDocumentoCheque = numeroDocumentoCheque;
}
public String getOtroTipoDocumento() {
return otroTipoDocumento;
}
public void setOtroTipoDocumento(String otroTipoDocumento) {
this.otroTipoDocumento = otroTipoDocumento;
}
public Long getOtroNumeroDocumento() {
return otroNumeroDocumento;
}
public void setOtroNumeroDocumento(Long otroNumeroDocumento) {
this.otroNumeroDocumento = otroNumeroDocumento;
}
public String getTipoDocumentoDescripcion() {
return tipoDocumentoDescripcion;
}
public void setTipoDocumentoDescripcion(String tipoDocumentoDescripcion) {
this.tipoDocumentoDescripcion = tipoDocumentoDescripcion;
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/NotasComprasDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import entidad.NotasCompras;
/**
*
* @author dadob
*/
public class NotasComprasDto {
private NotasCompras notaCompra;
private String nombreProveedor;
public NotasCompras getNotaCompra() {
return notaCompra;
}
public void setNotaCompra(NotasCompras notaCompra) {
this.notaCompra = notaCompra;
}
public String getNombreProveedor() {
return nombreProveedor;
}
public void setNombreProveedor(String nombreProveedor) {
this.nombreProveedor = nombreProveedor;
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/RecibosComprasDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Date;
/**
*
* @author Asus
*/
public class RecibosComprasDto implements Serializable {
private String ctipoDocum;
private long ncuota;
private Date frecibo;
private long nrecibo;
private Long nrofact;
private String ctipo;
private Date ffactur;
private long iefectivo;
private String nroCheque;
private long ipagado;
private long moneda;
private long cotizacion;
private short codProveed;
private long itotal;
private BigInteger ntimbrado;
private BigInteger factTimbrado;
private String notaTimbrado;
public RecibosComprasDto(String ctipoDocum, long ncuota, Date frecibo, long nrecibo, Long nrofact, String ctipo, Date ffactur, long iefectivo, String nroCheque, long ipagado, long moneda, long cotizacion, short codProveed, long itotal, BigInteger ntimbrado, BigInteger factTimbrado, String notaTimbrado) {
this.ctipoDocum = ctipoDocum;
this.ncuota = ncuota;
this.frecibo = frecibo;
this.nrecibo = nrecibo;
this.nrofact = nrofact;
this.ctipo = ctipo;
this.ffactur = ffactur;
this.iefectivo = iefectivo;
this.nroCheque = nroCheque;
this.ipagado = ipagado;
this.moneda = moneda;
this.cotizacion = cotizacion;
this.codProveed = codProveed;
this.itotal = itotal;
this.ntimbrado = ntimbrado;
this.factTimbrado = factTimbrado;
this.notaTimbrado = notaTimbrado;
}
public RecibosComprasDto() {
}
public String getCtipoDocum() {
return ctipoDocum;
}
public long getNcuota() {
return ncuota;
}
public Date getFrecibo() {
return frecibo;
}
public long getNrecibo() {
return nrecibo;
}
public Long getNrofact() {
return nrofact;
}
public String getCtipo() {
return ctipo;
}
public Date getFfactur() {
return ffactur;
}
public long getIefectivo() {
return iefectivo;
}
public String getNroCheque() {
return nroCheque;
}
public long getIpagado() {
return ipagado;
}
public long getMoneda() {
return moneda;
}
public long getCotizacion() {
return cotizacion;
}
public short getCodProveed() {
return codProveed;
}
public long getItotal() {
return itotal;
}
public BigInteger getNtimbrado() {
return ntimbrado;
}
public BigInteger getFactTimbrado() {
return factTimbrado;
}
public String getNotaTimbrado() {
return notaTimbrado;
}
public void setCtipoDocum(String ctipoDocum) {
this.ctipoDocum = ctipoDocum;
}
public void setNcuota(long ncuota) {
this.ncuota = ncuota;
}
public void setFrecibo(Date frecibo) {
this.frecibo = frecibo;
}
public void setNrecibo(long nrecibo) {
this.nrecibo = nrecibo;
}
public void setNrofact(Long nrofact) {
this.nrofact = nrofact;
}
public void setCtipo(String ctipo) {
this.ctipo = ctipo;
}
public void setFfactur(Date ffactur) {
this.ffactur = ffactur;
}
public void setIefectivo(long iefectivo) {
this.iefectivo = iefectivo;
}
public void setNroCheque(String nroCheque) {
this.nroCheque = nroCheque;
}
public void setIpagado(long ipagado) {
this.ipagado = ipagado;
}
public void setMoneda(long moneda) {
this.moneda = moneda;
}
public void setCotizacion(long cotizacion) {
this.cotizacion = cotizacion;
}
public void setCodProveed(short codProveed) {
this.codProveed = codProveed;
}
public void setItotal(long itotal) {
this.itotal = itotal;
}
public void setNtimbrado(BigInteger ntimbrado) {
this.ntimbrado = ntimbrado;
}
public void setFactTimbrado(BigInteger factTimbrado) {
this.factTimbrado = factTimbrado;
}
public void setNotaTimbrado(String notaTimbrado) {
this.notaTimbrado = notaTimbrado;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/DocumVariosFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.DocumVarios;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author admin
*/
@Stateless
public class DocumVariosFacade extends AbstractFacade<DocumVarios> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public DocumVariosFacade() {
super(DocumVarios.class);
}
public List<DocumVarios> listarDocumValidos(String sql) {
Query q = getEntityManager().createNativeQuery(sql, DocumVarios.class);
System.out.println(q.toString());
List<DocumVarios> respuesta = new ArrayList<DocumVarios>();
respuesta = q.getResultList();
return respuesta;
}
public Integer actualizarVigenciaPromocion(int nro_documento,String usuarioAutorize) {
try {
Query q = getEntityManager().createNativeQuery(""
+ " UPDATE docum_varios SET mestado = 'A', cusuario_autoriz = '"+usuarioAutorize+"'"
+ " WHERE ndocum ="+nro_documento
+ " AND cod_empr = 2 AND mestado = 'P' "
+ " AND ctipo_docum = 'SG' ");
System.out.println(q.toString());
Integer respuesta = q.executeUpdate();
return respuesta;
} catch (Exception e) {
System.out.println("MESAJE DE ERROR:");
return -1;
}
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Cheques.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Edu
*/
@Entity
@Table(name = "cheques")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Cheques.findAll", query = "SELECT c FROM Cheques c")
, @NamedQuery(name = "Cheques.findByCodEmpr", query = "SELECT c FROM Cheques c WHERE c.chequesPK.codEmpr = :codEmpr")
, @NamedQuery(name = "Cheques.findByCodBanco", query = "SELECT c FROM Cheques c WHERE c.chequesPK.codBanco = :codBanco")
, @NamedQuery(name = "Cheques.findByNroCheque", query = "SELECT c FROM Cheques c WHERE c.chequesPK.nroCheque = :nroCheque")
, @NamedQuery(name = "Cheques.findByXcuentaBco", query = "SELECT c FROM Cheques c WHERE c.chequesPK.xcuentaBco = :xcuentaBco")
, @NamedQuery(name = "Cheques.findByFcheque", query = "SELECT c FROM Cheques c WHERE c.fcheque = :fcheque")
, @NamedQuery(name = "Cheques.findByIcheque", query = "SELECT c FROM Cheques c WHERE c.icheque = :icheque")
, @NamedQuery(name = "Cheques.findByFrechazo", query = "SELECT c FROM Cheques c WHERE c.frechazo = :frechazo")
, @NamedQuery(name = "Cheques.findByFcobro", query = "SELECT c FROM Cheques c WHERE c.fcobro = :fcobro")
, @NamedQuery(name = "Cheques.findByFemision", query = "SELECT c FROM Cheques c WHERE c.femision = :femision")
, @NamedQuery(name = "Cheques.findByXtitular", query = "SELECT c FROM Cheques c WHERE c.xtitular = :xtitular")
, @NamedQuery(name = "Cheques.findByFalta", query = "SELECT c FROM Cheques c WHERE c.falta = :falta")
, @NamedQuery(name = "Cheques.findByCusuario", query = "SELECT c FROM Cheques c WHERE c.cusuario = :cusuario")
, @NamedQuery(name = "Cheques.findByMtipo", query = "SELECT c FROM Cheques c WHERE c.mtipo = :mtipo")
, @NamedQuery(name = "Cheques.findByCodEntregador", query = "SELECT c FROM Cheques c WHERE c.codEntregador = :codEntregador")
, @NamedQuery(name = "Cheques.findByCodZona", query = "SELECT c FROM Cheques c WHERE c.codZona = :codZona")})
public class Cheques implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected ChequesPK chequesPK;
@Column(name = "fcheque")
@Temporal(TemporalType.TIMESTAMP)
private Date fcheque;
@Column(name = "icheque")
private Long icheque;
@Column(name = "frechazo")
@Temporal(TemporalType.TIMESTAMP)
private Date frechazo;
@Column(name = "fcobro")
@Temporal(TemporalType.TIMESTAMP)
private Date fcobro;
@Column(name = "femision")
@Temporal(TemporalType.TIMESTAMP)
private Date femision;
@Size(max = 50)
@Column(name = "xtitular")
private String xtitular;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Basic(optional = false)
@NotNull
@Column(name = "mtipo")
private Character mtipo;
@Column(name = "cod_entregador")
private Short codEntregador;
@Size(max = 2)
@Column(name = "cod_zona")
private String codZona;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "cheques")
private Collection<ChequesDet> chequesDetCollection;
@JoinColumn(name = "cod_banco", referencedColumnName = "cod_banco", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Bancos bancos;
@JoinColumn(name = "cod_cliente", referencedColumnName = "cod_cliente")
@ManyToOne
private Clientes codCliente;
public Cheques() {
}
public Cheques(ChequesPK chequesPK) {
this.chequesPK = chequesPK;
}
public Cheques(ChequesPK chequesPK, Character mtipo) {
this.chequesPK = chequesPK;
this.mtipo = mtipo;
}
public Cheques(short codEmpr, short codBanco, String nroCheque, String xcuentaBco) {
this.chequesPK = new ChequesPK(codEmpr, codBanco, nroCheque, xcuentaBco);
}
public ChequesPK getChequesPK() {
return chequesPK;
}
public void setChequesPK(ChequesPK chequesPK) {
this.chequesPK = chequesPK;
}
public Date getFcheque() {
return fcheque;
}
public void setFcheque(Date fcheque) {
this.fcheque = fcheque;
}
public Long getIcheque() {
return icheque;
}
public void setIcheque(Long icheque) {
this.icheque = icheque;
}
public Date getFrechazo() {
return frechazo;
}
public void setFrechazo(Date frechazo) {
this.frechazo = frechazo;
}
public Date getFcobro() {
return fcobro;
}
public void setFcobro(Date fcobro) {
this.fcobro = fcobro;
}
public Date getFemision() {
return femision;
}
public void setFemision(Date femision) {
this.femision = femision;
}
public String getXtitular() {
return xtitular;
}
public void setXtitular(String xtitular) {
this.xtitular = xtitular;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Character getMtipo() {
return mtipo;
}
public void setMtipo(Character mtipo) {
this.mtipo = mtipo;
}
public Short getCodEntregador() {
return codEntregador;
}
public void setCodEntregador(Short codEntregador) {
this.codEntregador = codEntregador;
}
public String getCodZona() {
return codZona;
}
public void setCodZona(String codZona) {
this.codZona = codZona;
}
@XmlTransient
public Collection<ChequesDet> getChequesDetCollection() {
return chequesDetCollection;
}
public void setChequesDetCollection(Collection<ChequesDet> chequesDetCollection) {
this.chequesDetCollection = chequesDetCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (chequesPK != null ? chequesPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Cheques)) {
return false;
}
Cheques other = (Cheques) object;
if ((this.chequesPK == null && other.chequesPK != null) || (this.chequesPK != null && !this.chequesPK.equals(other.chequesPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Cheques[ chequesPK=" + chequesPK + " ]";
}
public Bancos getBancos() {
return bancos;
}
public void setBancos(Bancos bancos) {
this.bancos = bancos;
}
public Clientes getCodCliente() {
return codCliente;
}
public void setCodCliente(Clientes codCliente) {
this.codCliente = codCliente;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/MetasVendedores.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "metas_vendedores")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "MetasVendedores.findAll", query = "SELECT m FROM MetasVendedores m")
, @NamedQuery(name = "MetasVendedores.findByCodEmpleado", query = "SELECT m FROM MetasVendedores m WHERE m.metasVendedoresPK.codEmpleado = :codEmpleado")
, @NamedQuery(name = "MetasVendedores.findByCodEmpr", query = "SELECT m FROM MetasVendedores m WHERE m.metasVendedoresPK.codEmpr = :codEmpr")
, @NamedQuery(name = "MetasVendedores.findByCodZona", query = "SELECT m FROM MetasVendedores m WHERE m.metasVendedoresPK.codZona = :codZona")
, @NamedQuery(name = "MetasVendedores.findByCodSublinea", query = "SELECT m FROM MetasVendedores m WHERE m.metasVendedoresPK.codSublinea = :codSublinea")
, @NamedQuery(name = "MetasVendedores.findByNcajas", query = "SELECT m FROM MetasVendedores m WHERE m.ncajas = :ncajas")
, @NamedQuery(name = "MetasVendedores.findByNunidad", query = "SELECT m FROM MetasVendedores m WHERE m.nunidad = :nunidad")
, @NamedQuery(name = "MetasVendedores.findByNtotPeso", query = "SELECT m FROM MetasVendedores m WHERE m.ntotPeso = :ntotPeso")
, @NamedQuery(name = "MetasVendedores.findByItotalVta", query = "SELECT m FROM MetasVendedores m WHERE m.itotalVta = :itotalVta")
, @NamedQuery(name = "MetasVendedores.findByFrigeDesde", query = "SELECT m FROM MetasVendedores m WHERE m.frigeDesde = :frigeDesde")
, @NamedQuery(name = "MetasVendedores.findByFrigeHasta", query = "SELECT m FROM MetasVendedores m WHERE m.frigeHasta = :frigeHasta")
, @NamedQuery(name = "MetasVendedores.findByNmes", query = "SELECT m FROM MetasVendedores m WHERE m.metasVendedoresPK.nmes = :nmes")
, @NamedQuery(name = "MetasVendedores.findByNanno", query = "SELECT m FROM MetasVendedores m WHERE m.metasVendedoresPK.nanno = :nanno")
, @NamedQuery(name = "MetasVendedores.findByMestado", query = "SELECT m FROM MetasVendedores m WHERE m.mestado = :mestado")
, @NamedQuery(name = "MetasVendedores.findByPesototlinea", query = "SELECT m FROM MetasVendedores m WHERE m.pesototlinea = :pesototlinea")
, @NamedQuery(name = "MetasVendedores.findByGstotlinea", query = "SELECT m FROM MetasVendedores m WHERE m.gstotlinea = :gstotlinea")
, @NamedQuery(name = "MetasVendedores.findByPesototsub", query = "SELECT m FROM MetasVendedores m WHERE m.pesototsub = :pesototsub")
, @NamedQuery(name = "MetasVendedores.findByGstotsub", query = "SELECT m FROM MetasVendedores m WHERE m.gstotsub = :gstotsub")
, @NamedQuery(name = "MetasVendedores.findByPpartisub", query = "SELECT m FROM MetasVendedores m WHERE m.ppartisub = :ppartisub")
, @NamedQuery(name = "MetasVendedores.findByPpartisubGs", query = "SELECT m FROM MetasVendedores m WHERE m.ppartisubGs = :ppartisubGs")
, @NamedQuery(name = "MetasVendedores.findByPesosubMeta", query = "SELECT m FROM MetasVendedores m WHERE m.pesosubMeta = :pesosubMeta")
, @NamedQuery(name = "MetasVendedores.findByGssubMeta", query = "SELECT m FROM MetasVendedores m WHERE m.gssubMeta = :gssubMeta")
, @NamedQuery(name = "MetasVendedores.findByPpartidet", query = "SELECT m FROM MetasVendedores m WHERE m.ppartidet = :ppartidet")
, @NamedQuery(name = "MetasVendedores.findByPpartidetGs", query = "SELECT m FROM MetasVendedores m WHERE m.ppartidetGs = :ppartidetGs")
, @NamedQuery(name = "MetasVendedores.findByPesoMeta", query = "SELECT m FROM MetasVendedores m WHERE m.pesoMeta = :pesoMeta")
, @NamedQuery(name = "MetasVendedores.findByCajasMeta", query = "SELECT m FROM MetasVendedores m WHERE m.cajasMeta = :cajasMeta")
, @NamedQuery(name = "MetasVendedores.findByGsMeta", query = "SELECT m FROM MetasVendedores m WHERE m.gsMeta = :gsMeta")
, @NamedQuery(name = "MetasVendedores.findByPesoMetaMod", query = "SELECT m FROM MetasVendedores m WHERE m.pesoMetaMod = :pesoMetaMod")
, @NamedQuery(name = "MetasVendedores.findByCajasMetaMod", query = "SELECT m FROM MetasVendedores m WHERE m.cajasMetaMod = :cajasMetaMod")
, @NamedQuery(name = "MetasVendedores.findByGsMetaMod", query = "SELECT m FROM MetasVendedores m WHERE m.gsMetaMod = :gsMetaMod")
, @NamedQuery(name = "MetasVendedores.findByFalta", query = "SELECT m FROM MetasVendedores m WHERE m.falta = :falta")
, @NamedQuery(name = "MetasVendedores.findByCusuario", query = "SELECT m FROM MetasVendedores m WHERE m.cusuario = :cusuario")
, @NamedQuery(name = "MetasVendedores.findByFultimModif", query = "SELECT m FROM MetasVendedores m WHERE m.fultimModif = :fultimModif")
, @NamedQuery(name = "MetasVendedores.findByCusuarioModif", query = "SELECT m FROM MetasVendedores m WHERE m.cusuarioModif = :cusuarioModif")})
public class MetasVendedores implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected MetasVendedoresPK metasVendedoresPK;
@Column(name = "ncajas")
private Integer ncajas;
@Column(name = "nunidad")
private Integer nunidad;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "ntot_peso")
private BigDecimal ntotPeso;
@Column(name = "itotal_vta")
private Long itotalVta;
@Basic(optional = false)
@NotNull
@Column(name = "frige_desde")
@Temporal(TemporalType.TIMESTAMP)
private Date frigeDesde;
@Column(name = "frige_hasta")
@Temporal(TemporalType.TIMESTAMP)
private Date frigeHasta;
@Basic(optional = false)
@NotNull
@Column(name = "mestado")
private Character mestado;
@Column(name = "pesototlinea")
private BigDecimal pesototlinea;
@Column(name = "gstotlinea")
private Long gstotlinea;
@Column(name = "pesototsub")
private BigDecimal pesototsub;
@Column(name = "gstotsub")
private Long gstotsub;
@Column(name = "ppartisub")
private BigDecimal ppartisub;
@Column(name = "ppartisub_gs")
private BigDecimal ppartisubGs;
@Column(name = "pesosub_meta")
private BigDecimal pesosubMeta;
@Column(name = "gssub_meta")
private Long gssubMeta;
@Column(name = "ppartidet")
private BigDecimal ppartidet;
@Column(name = "ppartidet_gs")
private BigDecimal ppartidetGs;
@Column(name = "peso_meta")
private BigDecimal pesoMeta;
@Column(name = "cajas_meta")
private Integer cajasMeta;
@Column(name = "gs_meta")
private BigDecimal gsMeta;
@Column(name = "peso_meta_mod")
private Long pesoMetaMod;
@Column(name = "cajas_meta_mod")
private Integer cajasMetaMod;
@Column(name = "gs_meta_mod")
private Long gsMetaMod;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "cod_empleado", referencedColumnName = "cod_empleado", insertable = false, updatable = false)})
@ManyToOne(optional = false)
private Empleados empleados;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "cod_zona", referencedColumnName = "cod_zona", insertable = false, updatable = false)
, @JoinColumn(name = "cod_empleado", referencedColumnName = "cod_empleado", insertable = false, updatable = false)})
@ManyToOne(optional = false)
private EmpleadosZonas empleadosZonas;
@JoinColumn(name = "cod_linea", referencedColumnName = "cod_linea")
@ManyToOne
private Lineas codLinea;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "cod_zona", referencedColumnName = "cod_zona", insertable = false, updatable = false)})
@ManyToOne(optional = false)
private Zonas zonas;
public MetasVendedores() {
}
public MetasVendedores(MetasVendedoresPK metasVendedoresPK) {
this.metasVendedoresPK = metasVendedoresPK;
}
public MetasVendedores(MetasVendedoresPK metasVendedoresPK, Date frigeDesde, Character mestado) {
this.metasVendedoresPK = metasVendedoresPK;
this.frigeDesde = frigeDesde;
this.mestado = mestado;
}
public MetasVendedores(short codEmpleado, short codEmpr, String codZona, short codSublinea, short nmes, short nanno) {
this.metasVendedoresPK = new MetasVendedoresPK(codEmpleado, codEmpr, codZona, codSublinea, nmes, nanno);
}
public MetasVendedoresPK getMetasVendedoresPK() {
return metasVendedoresPK;
}
public void setMetasVendedoresPK(MetasVendedoresPK metasVendedoresPK) {
this.metasVendedoresPK = metasVendedoresPK;
}
public Integer getNcajas() {
return ncajas;
}
public void setNcajas(Integer ncajas) {
this.ncajas = ncajas;
}
public Integer getNunidad() {
return nunidad;
}
public void setNunidad(Integer nunidad) {
this.nunidad = nunidad;
}
public BigDecimal getNtotPeso() {
return ntotPeso;
}
public void setNtotPeso(BigDecimal ntotPeso) {
this.ntotPeso = ntotPeso;
}
public Long getItotalVta() {
return itotalVta;
}
public void setItotalVta(Long itotalVta) {
this.itotalVta = itotalVta;
}
public Date getFrigeDesde() {
return frigeDesde;
}
public void setFrigeDesde(Date frigeDesde) {
this.frigeDesde = frigeDesde;
}
public Date getFrigeHasta() {
return frigeHasta;
}
public void setFrigeHasta(Date frigeHasta) {
this.frigeHasta = frigeHasta;
}
public Character getMestado() {
return mestado;
}
public void setMestado(Character mestado) {
this.mestado = mestado;
}
public BigDecimal getPesototlinea() {
return pesototlinea;
}
public void setPesototlinea(BigDecimal pesototlinea) {
this.pesototlinea = pesototlinea;
}
public Long getGstotlinea() {
return gstotlinea;
}
public void setGstotlinea(Long gstotlinea) {
this.gstotlinea = gstotlinea;
}
public BigDecimal getPesototsub() {
return pesototsub;
}
public void setPesototsub(BigDecimal pesototsub) {
this.pesototsub = pesototsub;
}
public Long getGstotsub() {
return gstotsub;
}
public void setGstotsub(Long gstotsub) {
this.gstotsub = gstotsub;
}
public BigDecimal getPpartisub() {
return ppartisub;
}
public void setPpartisub(BigDecimal ppartisub) {
this.ppartisub = ppartisub;
}
public BigDecimal getPpartisubGs() {
return ppartisubGs;
}
public void setPpartisubGs(BigDecimal ppartisubGs) {
this.ppartisubGs = ppartisubGs;
}
public BigDecimal getPesosubMeta() {
return pesosubMeta;
}
public void setPesosubMeta(BigDecimal pesosubMeta) {
this.pesosubMeta = pesosubMeta;
}
public Long getGssubMeta() {
return gssubMeta;
}
public void setGssubMeta(Long gssubMeta) {
this.gssubMeta = gssubMeta;
}
public BigDecimal getPpartidet() {
return ppartidet;
}
public void setPpartidet(BigDecimal ppartidet) {
this.ppartidet = ppartidet;
}
public BigDecimal getPpartidetGs() {
return ppartidetGs;
}
public void setPpartidetGs(BigDecimal ppartidetGs) {
this.ppartidetGs = ppartidetGs;
}
public BigDecimal getPesoMeta() {
return pesoMeta;
}
public void setPesoMeta(BigDecimal pesoMeta) {
this.pesoMeta = pesoMeta;
}
public Integer getCajasMeta() {
return cajasMeta;
}
public void setCajasMeta(Integer cajasMeta) {
this.cajasMeta = cajasMeta;
}
public BigDecimal getGsMeta() {
return gsMeta;
}
public void setGsMeta(BigDecimal gsMeta) {
this.gsMeta = gsMeta;
}
public Long getPesoMetaMod() {
return pesoMetaMod;
}
public void setPesoMetaMod(Long pesoMetaMod) {
this.pesoMetaMod = pesoMetaMod;
}
public Integer getCajasMetaMod() {
return cajasMetaMod;
}
public void setCajasMetaMod(Integer cajasMetaMod) {
this.cajasMetaMod = cajasMetaMod;
}
public Long getGsMetaMod() {
return gsMetaMod;
}
public void setGsMetaMod(Long gsMetaMod) {
this.gsMetaMod = gsMetaMod;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
public Empleados getEmpleados() {
return empleados;
}
public void setEmpleados(Empleados empleados) {
this.empleados = empleados;
}
public EmpleadosZonas getEmpleadosZonas() {
return empleadosZonas;
}
public void setEmpleadosZonas(EmpleadosZonas empleadosZonas) {
this.empleadosZonas = empleadosZonas;
}
public Lineas getCodLinea() {
return codLinea;
}
public void setCodLinea(Lineas codLinea) {
this.codLinea = codLinea;
}
public Zonas getZonas() {
return zonas;
}
public void setZonas(Zonas zonas) {
this.zonas = zonas;
}
@Override
public int hashCode() {
int hash = 0;
hash += (metasVendedoresPK != null ? metasVendedoresPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof MetasVendedores)) {
return false;
}
MetasVendedores other = (MetasVendedores) object;
if ((this.metasVendedoresPK == null && other.metasVendedoresPK != null) || (this.metasVendedoresPK != null && !this.metasVendedoresPK.equals(other.metasVendedoresPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.MetasVendedores[ metasVendedoresPK=" + metasVendedoresPK + " ]";
}
}
<file_sep>/SisVenLog-war/src/java/bean/ImpresionFacturasServiciosBean.java
package bean;
import dao.PersonalizedFacade;
import dao.TiposDocumentosFacade;
import dto.AuxiliarImpresionMasivaDto;
import dto.AuxiliarImpresionServiciosDto;
import entidad.TiposDocumentos;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.*;
import javax.faces.bean.*;
import javax.faces.context.*;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class ImpresionFacturasServiciosBean {
@EJB
private TiposDocumentosFacade tiposDocumentosFacade;
@EJB
private PersonalizedFacade personalizedFacade;
private TiposDocumentos tiposDocumentos;
private List<TiposDocumentos> listaTiposDocumentos;
private AuxiliarImpresionServiciosDto auxiliarImpresionMasivaDto;
private List<AuxiliarImpresionServiciosDto> listaAuxiliarImpresionMasivaDto;
private Integer estabInicial;
private Integer expedInicial;
private Integer SecueInicial;
private Integer SecueFinal;
private String destination = System.getProperty("java.io.tmpdir");
public ImpresionFacturasServiciosBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.tiposDocumentos = new TiposDocumentos();
this.listaTiposDocumentos = new ArrayList<TiposDocumentos>();
estabInicial = 1;
expedInicial = 1;
SecueInicial = 1;
SecueFinal = 1;
}
public List<TiposDocumentos> listarTiposDocummentos() {
listaTiposDocumentos = tiposDocumentosFacade.listarTipoDocumentoImpresionMasivaFacturas();
return listaTiposDocumentos;
}
public void impresion() {
try {
if (this.validarCorrelatividad()) {
int nroInicial = 0;
int nroFinal = 0;
nroInicial = Integer.parseInt(this.estabInicial + String.format("%02d", this.expedInicial) + String.format("%07d", this.SecueInicial));
nroFinal = Integer.parseInt(this.estabInicial + String.format("%02d", this.expedInicial) + String.format("%07d", this.SecueFinal));
System.err.println("nroInicial: " + nroInicial);
System.err.println("nroFinal: " + nroFinal);
LlamarReportes rep = new LlamarReportes();
//generamos los pdf para imprimir
rep.impresionFacturaServicios(nroInicial, nroFinal);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Impresion enviada", "En breve comenzara la impresion, aguarde."));
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error durante la impresion", null));
}
}
public void vistaPrevia() {
try {
if (this.validarCorrelatividad()) {
int nroInicial = 0;
int nroFinal = 0;
nroInicial = Integer.parseInt(this.estabInicial + String.format("%02d", this.expedInicial) + String.format("%07d", this.SecueInicial));
nroFinal = Integer.parseInt(this.estabInicial + String.format("%02d", this.expedInicial) + String.format("%07d", this.SecueFinal));
System.err.println("nroInicial: " + nroInicial);
System.err.println("nroFinal: " + nroFinal);
LlamarReportes rep = new LlamarReportes();
//generamos los pdf para imprimir
rep.vistaPreviaFacturaServicios(nroInicial, nroFinal);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Impresion enviada", "En breve comenzara la impresion, aguarde."));
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error durante la impresion", null));
}
}
//Getters & Setters
public TiposDocumentos getTiposDocumentos() {
return tiposDocumentos;
}
public void setTiposDocumentos(TiposDocumentos tiposDocumentos) {
this.tiposDocumentos = tiposDocumentos;
}
public List<TiposDocumentos> getListaTiposDocumentos() {
return listaTiposDocumentos;
}
public void setListaTiposDocumentos(List<TiposDocumentos> listaTiposDocumentos) {
this.listaTiposDocumentos = listaTiposDocumentos;
}
public Integer getEstabInicial() {
return estabInicial;
}
public void setEstabInicial(Integer estabInicial) {
this.estabInicial = estabInicial;
}
public Integer getExpedInicial() {
return expedInicial;
}
public void setExpedInicial(Integer expedInicial) {
this.expedInicial = expedInicial;
}
public Integer getSecueInicial() {
return SecueInicial;
}
public void setSecueInicial(Integer SecueInicial) {
this.SecueInicial = SecueInicial;
}
public Integer getSecueFinal() {
return SecueFinal;
}
public void setSecueFinal(Integer SecueFinal) {
this.SecueFinal = SecueFinal;
}
public AuxiliarImpresionServiciosDto getAuxiliarImpresionMasivaDto() {
return auxiliarImpresionMasivaDto;
}
public void setAuxiliarImpresionMasivaDto(AuxiliarImpresionServiciosDto auxiliarImpresionMasivaDto) {
this.auxiliarImpresionMasivaDto = auxiliarImpresionMasivaDto;
}
public List<AuxiliarImpresionServiciosDto> getListaAuxiliarImpresionMasivaDto() {
return listaAuxiliarImpresionMasivaDto;
}
public void setListaAuxiliarImpresionMasivaDto(List<AuxiliarImpresionServiciosDto> listaAuxiliarImpresionMasivaDto) {
this.listaAuxiliarImpresionMasivaDto = listaAuxiliarImpresionMasivaDto;
}
public boolean validarCorrelatividad() {
boolean respuesta = true;
try {
int nroInicial = 0;
int nroFinal = 0;
nroInicial = Integer.parseInt(this.estabInicial + String.format("%02d", this.expedInicial) + String.format("%07d", this.SecueInicial));
nroFinal = Integer.parseInt(this.estabInicial + String.format("%02d", this.expedInicial) + String.format("%07d", this.SecueFinal));
System.err.println("nroInicial: " + nroInicial);
System.err.println("nroFinal: " + nroFinal);
this.listaAuxiliarImpresionMasivaDto = personalizedFacade.listarSecuenciasFacturasServicios(nroInicial, nroFinal);
for (int i = 0; i < listaAuxiliarImpresionMasivaDto.size(); i++) {
if ((i + 1) < listaAuxiliarImpresionMasivaDto.size()) {
if ((listaAuxiliarImpresionMasivaDto.get(i + 1).getSecuencia() - listaAuxiliarImpresionMasivaDto.get(i).getSecuencia()) == 1) {
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "La numeracion se interrumpe en " + listaAuxiliarImpresionMasivaDto.get(i).getFactura()));
return false;
}
}
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error al validar correlatividad", null));
}
return respuesta;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/ConceptosDocumentosFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.ConceptosDocumentos;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author admin
*/
@Stateless
public class ConceptosDocumentosFacade extends AbstractFacade<ConceptosDocumentos> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public ConceptosDocumentosFacade() {
super(ConceptosDocumentos.class);
}
public List<ConceptosDocumentos> listarConceptoDocumentoListadoNotaCompras() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from conceptos_documentos\n"
+ "where ctipo_docum in ('NDC','NCC','NDP')", ConceptosDocumentos.class);
System.out.println(q.toString());
List<ConceptosDocumentos> respuesta = new ArrayList<>();
respuesta = q.getResultList();
return respuesta;
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiMercaSinBean.java
package bean.listados;
import dao.ExcelFacade;
import dao.MercaderiasFacade;
import dao.PersonalizedFacade;
import dao.TiposDocumentosFacade;
import dao.ZonasFacade;
import dto.LiMercaSinDto;
import entidad.Mercaderias;
import entidad.MercaderiasPK;
import entidad.Zonas;
import entidad.ZonasPK;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import org.primefaces.model.DualListModel;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiMercaSinBean {
@EJB
private TiposDocumentosFacade tiposDocumentosFacade;
@EJB
private ZonasFacade zonasFacade;
@EJB
private MercaderiasFacade mercaderiasFacade;
@EJB
private PersonalizedFacade personalizedFacade;
@EJB
private ExcelFacade excelFacade;
/*private TiposDocumentos tiposDocumentos;
private List<TiposDocumentos> listaTiposDocumentos;*/
private List<Mercaderias> listaMercaderias;
private List<Mercaderias> listaMercaderiasSeleccionadas;
private DualListModel<Mercaderias> mercaderias;
private Zonas zonas;
private List<Zonas> listaZonas;
private Date desde;
private Date hasta;
private String operacion;
private String tipoDocumento;
public LiMercaSinBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
/*this.tiposDocumentos = new TiposDocumentos();
this.listaTiposDocumentos = new ArrayList<TiposDocumentos>();*/
this.listaMercaderias = new ArrayList<Mercaderias>();
this.listaMercaderiasSeleccionadas = new ArrayList<Mercaderias>();
this.zonas = new Zonas(new ZonasPK());
this.listaZonas = new ArrayList<Zonas>();
this.desde = new Date();
this.hasta = new Date();
setOperacion("M");
setTipoDocumento("TODOS");
//Cities
List<Mercaderias> mercaSource = new ArrayList<Mercaderias>();
List<Mercaderias> mercaTarget = new ArrayList<Mercaderias>();
mercaSource = mercaderiasFacade.listarMercaderiasActivasDepo1();
mercaderias = new DualListModel<Mercaderias>(mercaSource, mercaTarget);
}
public void ejecutar(String tipo) {
try {
personalizedFacade.ejecutarSentenciaSQL("drop table tmp_mercaderias");
personalizedFacade.ejecutarSentenciaSQL("CREATE TABLE tmp_mercaderias (cod_merca CHAR(13), cod_barra CHAR(20), \n"
+ "xdesc CHAR(50), nrelacion SMALLINT, cant_cajas integer, cant_unid integer )");
if (mercaderias.getTarget().size() > 0) {
listaMercaderiasSeleccionadas = mercaderias.getTarget();
for (int i = 0; i < listaMercaderiasSeleccionadas.size(); i++) {
MercaderiasPK pk = listaMercaderiasSeleccionadas.get(i).getMercaderiasPK();
Mercaderias aux = new Mercaderias();
aux = mercaderiasFacade.find(pk);
personalizedFacade.ejecutarSentenciaSQL("INSERT INTO tmp_mercaderias (cod_merca, cod_barra, xdesc, nrelacion,cant_cajas, cant_unid )\n"
+ " VALUES ('" + aux.getMercaderiasPK().getCodMerca() + "', '" + aux.getCodBarra() + "', '" + aux.getXdesc() + "', " + aux.getNrelacion() + ",0,0 )");
}
} else {
personalizedFacade.ejecutarSentenciaSQL("insert into tmp_mercaderias\n"
+ "select m.cod_merca, m.cod_barra, m.xdesc, m.nrelacion, 1, 1\n"
+ "from mercaderias m, existencias e\n"
+ "where m.cod_merca = e.cod_merca\n"
+ "and m.mestado = 'A'\n"
+ "and e.cod_depo = 1");
}
LlamarReportes rep = new LlamarReportes();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
//String tipoDoc = "";
String zona = "";
String descZona = "";
String descTipoDoc = "";
StringBuilder sql = new StringBuilder();
/*if (this.tiposDocumentos == null) {
tipoDoc = "TODOS";
} else {
tipoDoc = this.tiposDocumentos.getCtipoDocum();
}*/
if (this.zonas == null) {
zona = "TODOS";
descZona = "TODOS";
} else {
zona = this.zonas.getZonasPK().getCodZona();
descZona = zonasFacade.find(this.zonas.getZonasPK()).getXdesc();
}
sql.append(" SELECT m.cod_merca, m.xdesc, ISNULL(m.cod_barra,'') as cod_barra, m.mestado,"
+ " t.cant_cajas, t.cant_unid \n"
+ " FROM mercaderias m, tmp_mercaderias t \n"
+ " WHERE \n"
+ " cod_empr = 2 AND (t.cant_cajas > 0 OR t.cant_unid > 0 ) \n"
+ " AND m.cod_merca = t.cod_merca \n"
+ " AND m.cod_merca NOT IN ( SELECT cod_merca \n"
+ " FROM movimientos_merca \n"
+ " WHERE cod_empr = 2 and fmovim BETWEEN '" + fdesde + "' AND '" + fhasta + "'\n");
/*if (this.tipoDocumento.equals("FACTURAS DE COMPRA")) {
sql.append("AND ctipo_docum = '" + tipoDoc + "' \n");
}*/
if (this.tipoDocumento != null) {
if (this.tipoDocumento.equals("FACTURAS DE VENTA")) {
sql.append("AND ctipo_docum IN ('FCR','FCO','CPV') \n");
}
if (this.tipoDocumento.equals("FACTURAS DE COMPRA")) {
sql.append("AND ctipo_docum IN ('FCC','COC') \n");
}
if (this.zonas != null) {
sql.append("AND cod_zona= '" + zona + "' \n ");
}
}
sql.append(") \n");
if (this.tipoDocumento != null) {
if (this.tipoDocumento.equals("FACTURAS DE COMPRA")) {
sql.append(" AND t.cod_merca IN (SELECT DISTINCT M.cod_merca \n"
+ " FROM merca_canales m, canales_vendedores v, empleados em, depositos d2 \n"
+ " WHERE m.cod_canal = v.cod_canal \n"
+ " AND v.cod_vendedor = em.cod_empleado \n"
+ " AND em.ctipo_emp LIKE 'V%' \n"
+ " AND em.mestado = 'A' \n");
if (this.zonas != null) {
sql.append(" AND d2.cod_zona= '" + zona + "' \n");
}
sql.append(" AND em.cod_depo = d2.cod_depo ) \n");
}
}
System.out.println("SQL limercasin: " + sql.toString());
if (tipo.equals("VIST")) {
rep.reporteLiMercaSin(sql.toString(), dateToString2(desde), dateToString2(hasta), tipoDocumento, "admin", descZona, tipo);
} else if (tipo.equals("ARCH")) {
List<LiMercaSinDto> auxExcel = new ArrayList<LiMercaSinDto>();
auxExcel = excelFacade.listarLiMercaSin(sql.toString());
rep.excelLiMercaSin(auxExcel);
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Error", e.getMessage()));
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
//Getters & Setters
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
public String getOperacion() {
return operacion;
}
public void setOperacion(String operacion) {
this.operacion = operacion;
}
public Zonas getZonas() {
return zonas;
}
public void setZonas(Zonas zonas) {
this.zonas = zonas;
}
public List<Zonas> getListaZonas() {
return listaZonas;
}
public void setListaZonas(List<Zonas> listaZonas) {
this.listaZonas = listaZonas;
}
public DualListModel<Mercaderias> getMercaderias() {
return mercaderias;
}
public void setMercaderias(DualListModel<Mercaderias> mercaderias) {
this.mercaderias = mercaderias;
}
public String getTipoDocumento() {
return tipoDocumento;
}
public void setTipoDocumento(String tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
public List<Mercaderias> getListaMercaderias() {
return listaMercaderias;
}
public void setListaMercaderias(List<Mercaderias> listaMercaderias) {
this.listaMercaderias = listaMercaderias;
}
public List<Mercaderias> getListaMercaderiasSeleccionadas() {
return listaMercaderiasSeleccionadas;
}
public void setListaMercaderiasSeleccionadas(List<Mercaderias> listaMercaderiasSeleccionadas) {
this.listaMercaderiasSeleccionadas = listaMercaderiasSeleccionadas;
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/FacturaDetDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import entidad.FacturasDet;
import java.math.BigDecimal;
/**
*
* @author dadob
*/
public class FacturaDetDto {
private BigDecimal pimpues;
private BigDecimal totalImpuestos;
private long totalIgravadas;
private FacturasDet facturasDet;
private Short nRelacion;
private String descPromo;
private Character mPromoPackDet;
private Short codSublineaDet;
private BigDecimal nPesoCajas;
private BigDecimal nPesoUnidad;
public BigDecimal getPimpues() {
return pimpues;
}
public void setPimpues(BigDecimal pimpues) {
this.pimpues = pimpues;
}
public BigDecimal getTotalImpuestos() {
return totalImpuestos;
}
public void setTotalImpuestos(BigDecimal totalImpuestos) {
this.totalImpuestos = totalImpuestos;
}
public long getTotalIgravadas() {
return totalIgravadas;
}
public void setTotalIgravadas(long totalIgravadas) {
this.totalIgravadas = totalIgravadas;
}
public FacturasDet getFacturasDet() {
return facturasDet;
}
public void setFacturasDet(FacturasDet facturasDet) {
this.facturasDet = facturasDet;
}
public Short getnRelacion() {
return nRelacion;
}
public void setnRelacion(Short nRelacion) {
this.nRelacion = nRelacion;
}
public String getDescPromo() {
return descPromo;
}
public void setDescPromo(String descPromo) {
this.descPromo = descPromo;
}
public Character getmPromoPackDet() {
return mPromoPackDet;
}
public void setmPromoPackDet(Character mPromoPackDet) {
this.mPromoPackDet = mPromoPackDet;
}
public Short getCodSublineaDet() {
return codSublineaDet;
}
public void setCodSublineaDet(Short codSublineaDet) {
this.codSublineaDet = codSublineaDet;
}
public BigDecimal getnPesoCajas() {
return nPesoCajas;
}
public void setnPesoCajas(BigDecimal nPesoCajas) {
this.nPesoCajas = nPesoCajas;
}
public BigDecimal getnPesoUnidad() {
return nPesoUnidad;
}
public void setnPesoUnidad(BigDecimal nPesoUnidad) {
this.nPesoUnidad = nPesoUnidad;
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiAplicaBean.java
package bean.listados;
import dao.ExcelFacade;
import dao.PersonalizedFacade;
import dao.RolesFacade;
import dao.UsuariosFacade;
import entidad.Roles;
import entidad.RolesPK;
import entidad.Usuarios;
import entidad.UsuariosPK;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.*;
import javax.faces.bean.*;
import javax.faces.context.*;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiAplicaBean {
@EJB
private UsuariosFacade usuariosFacade;
@EJB
private ExcelFacade excelFacade;
@EJB
private RolesFacade rolesFacade;
private Roles roles;
private List<Roles> listaRoles;
private Usuarios usuarios;
private List<Usuarios> listaUsuarios;
private String destination = System.getProperty("java.io.tmpdir");
public LiAplicaBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.roles = new Roles(new RolesPK());
this.listaRoles = new ArrayList<Roles>();
this.usuarios = new entidad.Usuarios(new UsuariosPK());
this.listaUsuarios = new ArrayList<entidad.Usuarios>();
}
public void ejecutar(String tipo) {
LlamarReportes rep = new LlamarReportes();
int rolCodigo = 0;
String usuaCodigo = "";
String rol = "";
String usuario = "";
if (roles == null) {
rolCodigo = 0;
rol = "TODOS";
} else {
rolCodigo = roles.getRolesPK().getCodRol();
rol = rolesFacade.find(roles.getRolesPK()).getXdesc();
}
if (usuarios == null) {
usuario = "TODOS";
usuaCodigo = "TODOS";
} else {
usuaCodigo = usuarios.getUsuariosPK().getCodUsuario();
usuario = usuariosFacade.find(usuarios.getUsuariosPK()).getXnombre();
}
if (tipo.equals("VIST")) {
rep.reporteLiApli(rolCodigo, usuaCodigo, rol, usuario, tipo, "admin");
} else {
List<Object[]> lista = new ArrayList<Object[]>();
String[] columnas = new String[6];
columnas[0] = "cod_rol";
columnas[1] = "rol_xdesc";
columnas[2] = "cod_aplicacion";
columnas[3] = "app_xdesc";
columnas[4] = "xnombre";
columnas[5] = "cod_usuario";
String sql = "SELECT\n"
+ " ra.cod_rol\n"
+ " ,r.xdesc rol_xdesc\n"
+ " , ra.cod_aplicacion\n"
+ " , a.xdesc app_xdesc\n"
+ " ,u.xnombre\n"
+ " , u.cod_usuario\n"
+ "FROM\n"
+ " roles_aplicaciones ra\n"
+ " , roles_usuarios ru\n"
+ " , aplicaciones a\n"
+ " , roles r\n"
+ " , usuarios u\n"
+ "WHERE\n"
+ " ra.cod_rol = ru.cod_rol\n"
+ " AND a.cod_aplicacion = ra.cod_aplicacion\n"
+ " AND ra.cod_rol = r.cod_rol\n"
+ " AND ru.cod_usuario = u.cod_usuario\n"
+ " AND (ra.cod_rol = "+rolCodigo+" or "+rolCodigo+" = 0)\n"
+ " AND (u.cod_usuario = '"+usuaCodigo+"' or '"+usuaCodigo+"' = 'TODOS')\n"
+ " ORDER BY r.cod_rol, u.cod_usuario, a.cod_aplicacion";
lista = excelFacade.listarParaExcel(sql);
rep.exportarExcel(columnas, lista, "liaplica");
}
}
//Getters & Setters
public Roles getRoles() {
return roles;
}
public void setRoles(Roles roles) {
this.roles = roles;
}
public List<Roles> getListaRoles() {
return listaRoles;
}
public void setListaRoles(List<Roles> listaRoles) {
this.listaRoles = listaRoles;
}
public Usuarios getUsuarios() {
return usuarios;
}
public void setUsuarios(Usuarios usuarios) {
this.usuarios = usuarios;
}
public List<Usuarios> getListaUsuarios() {
return listaUsuarios;
}
public void setListaUsuarios(List<Usuarios> listaUsuarios) {
this.listaUsuarios = listaUsuarios;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/DatosGeneralesPK.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
/**
*
* @author admin
*/
@Embeddable
public class DatosGeneralesPK implements Serializable {
@Basic(optional = false)
@NotNull
@Column(name = "cod_empr")
private short codEmpr;
@Basic(optional = false)
@NotNull
@Column(name = "frige_desde")
@Temporal(TemporalType.TIMESTAMP)
private Date frigeDesde;
public DatosGeneralesPK() {
}
public DatosGeneralesPK(short codEmpr, Date frigeDesde) {
this.codEmpr = codEmpr;
this.frigeDesde = frigeDesde;
}
public short getCodEmpr() {
return codEmpr;
}
public void setCodEmpr(short codEmpr) {
this.codEmpr = codEmpr;
}
public Date getFrigeDesde() {
return frigeDesde;
}
public void setFrigeDesde(Date frigeDesde) {
this.frigeDesde = frigeDesde;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) codEmpr;
hash += (frigeDesde != null ? frigeDesde.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof DatosGeneralesPK)) {
return false;
}
DatosGeneralesPK other = (DatosGeneralesPK) object;
if (this.codEmpr != other.codEmpr) {
return false;
}
if ((this.frigeDesde == null && other.frigeDesde != null) || (this.frigeDesde != null && !this.frigeDesde.equals(other.frigeDesde))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.DatosGeneralesPK[ codEmpr=" + codEmpr + ", frigeDesde=" + frigeDesde + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/RolesFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Roles;
import java.util.Date;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.StoredProcedureQuery;
/**
*
* @author Hugo
*/
@Stateless
public class RolesFacade extends AbstractFacade<Roles> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public RolesFacade() {
super(Roles.class);
}
public void insertarRoles(Roles roles) {
StoredProcedureQuery q = getEntityManager().createStoredProcedureQuery("InsertarRoles");
q.registerStoredProcedureParameter("xdesc", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("falta", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cusuario", String.class, ParameterMode.IN);
q.setParameter("xdesc", roles.getXdesc());
q.setParameter("falta", roles.getFalta());
q.setParameter("cusuario", roles.getCusuario());
q.execute();
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/CanalesCompraPK.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* @author Hugo
*/
@Embeddable
public class CanalesCompraPK implements Serializable {
@Basic(optional = false)
@NotNull
@Column(name = "cod_proveed")
private short codProveed;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 2)
@Column(name = "ccanal_compra")
private String ccanalCompra;
public CanalesCompraPK() {
}
public CanalesCompraPK(short codProveed, String ccanalCompra) {
this.codProveed = codProveed;
this.ccanalCompra = ccanalCompra;
}
public short getCodProveed() {
return codProveed;
}
public void setCodProveed(short codProveed) {
this.codProveed = codProveed;
}
public String getCcanalCompra() {
return ccanalCompra;
}
public void setCcanalCompra(String ccanalCompra) {
this.ccanalCompra = ccanalCompra;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) codProveed;
hash += (ccanalCompra != null ? ccanalCompra.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof CanalesCompraPK)) {
return false;
}
CanalesCompraPK other = (CanalesCompraPK) object;
if (this.codProveed != other.codProveed) {
return false;
}
if ((this.ccanalCompra == null && other.ccanalCompra != null) || (this.ccanalCompra != null && !this.ccanalCompra.equals(other.ccanalCompra))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.CanalesCompraPK[ codProveed=" + codProveed + ", ccanalCompra=" + ccanalCompra + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/ListadoPedidosClientesFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Empleados;
import entidad.CanalesVenta;
import entidad.Clientes;
import entidad.Zonas;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import util.DateUtil;
import util.StringUtil;
/**
*
* @author jvera
*
*/
@Stateless
public class ListadoPedidosClientesFacade {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public ListadoPedidosClientesFacade() {
}
//metodo para armar archivo Excel
public List<Object[]> generarListadoPedidosExcel(Date fechaPedidoDesde,
Date fechaPedidoHasta,
Empleados vendedor,
CanalesVenta canal,
Zonas zona,
long nroPedidoDesde,
long nroPedidoHasta,
String seleccionFecha,
String seleccionTipo,
Boolean conDetalle,
List<Clientes> clientesSeleccionados){
String sql = "";
if (!conDetalle){
sql += "SELECT p.*, c.xnombre, z.cod_zona, z.xdesc as xdesc_zona, e.xnombre as xnomb_vendedor, l.xdesc as xdesc_canal, r.xdesc as xdesc_ruta" +
" FROM pedidos p, clientes c, zonas z, empleados e, canales_venta l, rutas r" +
" WHERE p.cod_empr = 2" +
" AND p.cod_cliente = c.cod_cliente" +
" AND p.cod_ruta = r.cod_ruta" +
" AND r.cod_zona = z.cod_zona" +
" AND p.cod_canal = l.cod_canal" +
" AND p.cod_vendedor = e.cod_empleado" +
" AND p.nro_pedido BETWEEN " + nroPedidoDesde + " AND " + nroPedidoHasta ;
}else{
sql += "SELECT p.*,c.xnombre, z.cod_zona, z.xdesc as xdesc_zona, e.xnombre as xnomb_vendedor, l.xdesc as xdesc_canal," +
" r.xdesc as xdesc_ruta, d.cod_merca, d.xdesc as xdesc_merca, d.cant_cajas, d.cant_unid, d.cajas_bonif, d.unid_bonif," +
" d.iexentas, d.igravadas, d.impuestos, d.pdesc, d.xdesc" +
" FROM pedidos p, clientes c, zonas z, empleados e, canales_venta l, rutas r, pedidos_det d" +
" WHERE p.cod_empr = 2" +
" AND d.cod_empr= 2" +
" AND p.cod_cliente = c.cod_cliente" +
" AND p.cod_ruta = r.cod_ruta" +
" AND r.cod_zona = z.cod_zona" +
" AND p.nro_pedido = d.nro_pedido" +
" AND p.cod_canal = l.cod_canal" +
" AND p.cod_vendedor = e.cod_empleado" +
" AND p.nro_pedido BETWEEN " + nroPedidoDesde + " AND " + nroPedidoHasta;
}
if ("FP".equals(seleccionFecha)) {
sql += " AND p.fpedido BETWEEN '" + DateUtil.dateToString(fechaPedidoDesde) + "' AND '" + DateUtil.dateToString(fechaPedidoHasta) + "'";
}else{
sql += " AND p.falta BETWEEN '" + DateUtil.dateToString(fechaPedidoDesde) + "' AND '" + DateUtil.dateToString(fechaPedidoHasta) + " 23:59:00'";
}
if (vendedor != null) {
sql += " AND p.cod_vendedor = " + vendedor.getEmpleadosPK().getCodEmpleado();
}
if (zona != null) {
sql += " AND r.cod_zona = " + zona.getZonasPK().getCodZona();
}
if (canal != null) {
sql += " AND p.cod_canal = " + canal.getCodCanal();
}
//JLVC 07-05-2020 agregamos el filtro de los clientes seleccionados
if (!clientesSeleccionados.isEmpty()) {
sql += " AND p.cod_cliente IN (" + StringUtil.convertirListaAString(clientesSeleccionados) + ")";
}
if ("AU".equals(seleccionTipo)) {
sql += " AND morigen ='P'";
}else{
if ("MA".equals(seleccionTipo)){
sql += " AND morigen = 'C'";
}
}
//si se discrimina por vendedor
if (vendedor != null){
sql += " ORDER BY p.cod_cliente, p.fpedido, p.nro_pedido";
}
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
return resultados;
}
}<file_sep>/SisVenLog-ejb/src/java/dao/PreciosFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Precios;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author admin
*/
@Stateless
public class PreciosFacade extends AbstractFacade<Precios> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public PreciosFacade() {
super(Precios.class);
}
public List<Precios> obtenerPreciosPorFechaFacturaCodigoMercaYTipoVenta(String lFFactura, String lCodMerca, Character lCTipoVenta){
String sql = "select * from precios " +
"where frige_desde <= '"+lFFactura+"' " +
"and (frige_hasta IS NULL OR frige_hasta >= '"+lFFactura+"') AND COD_DEPO = 1 " + //deposito venlog? o le pasamos por parametro el codigo deposito?
"and upper(COD_MERCA) like upper('"+lCodMerca.trim()+"') AND CTIPO_VTA = '"+lCTipoVenta+"' ";
Query q = em.createNativeQuery(sql, Precios.class);
System.out.println(q.toString());
List<Precios> resultado = q.getResultList();
return resultado;
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiFacServBean.java
package bean.listados;
import dao.CanalesCompraFacade;
import dao.DepositosFacade;
import dao.ClientesFacade;
import dao.ExcelFacade;
import dto.LiMercaSinDto;
import entidad.CanalesCompra;
import entidad.CanalesCompraPK;
import entidad.Depositos;
import entidad.DepositosPK;
import entidad.Clientes;
import entidad.Clientes;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiFacServBean {
@EJB
private ClientesFacade clientesFacade;
@EJB
private ExcelFacade excelFacade;
private Clientes clientes;
private List<Clientes> listaClientes;
private Date desde;
private Date hasta;
private Boolean todos;
private Boolean conDetalles;
private String estados;
private String clientesSel;
public LiFacServBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.clientes = new Clientes();
this.listaClientes = new ArrayList<Clientes>();
this.desde = new Date();
this.hasta = new Date();
setTodos(false);
setClientesSel("");
setEstados("A");
setConDetalles(false);
}
public void ejecutar(String tipo) {
LlamarReportes rep = new LlamarReportes();
StringBuilder sql = new StringBuilder();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
Integer clie = 0;
String descclie = "";
String canal = "";
String desccanal = "";
if (this.clientes.getCodCliente() != null) {
clie = Integer.parseInt(this.clientes.getCodCliente() + "");
descclie = clientesFacade.find(this.clientes.getCodCliente()).getXnombre();
} else {
clie = 0;
descclie = "TODOS";
}
if (conDetalles) { // sin detalles
sql.append(" SELECT f.CTIPO_DOCUM, f.nrofact, f.ffactur, 0 as nro_nota, f.tgravadas, f.texentas, f.timpuestos, f.ttotal, f.mestado, \n"
+ " F.xrazon_social as xnombre, f.isaldo, f.mestado, f.cod_cliente, f.tgravadas_10, f.tgravadas_5, f.timpuestos_10, f.timpuestos_5, f.texentas \n"
+ " FROM facturas f \n"
+ " WHERE f.cod_empr = 2 \n"
+ " AND ctipo_docum IN ('FCS', 'FCP')\n "
+ " AND f.ffactur BETWEEN ?l_finicial AND ?l_ffinal \n");
} else {
sql.append("SELECT f.*,f.xrazon_social as xnombre, d.*, s.xdesc \n"
+ " FROM facturas f, facturas_ser d, servicios s \n"
+ " WHERE f.cod_empr = 2 \n"
+ " AND d.cod_empr = 2 \n"
+ " AND f.ctipo_docum IN ('FCS','FCP') \n"
+ " AND f.cod_empr = d.cod_empr \n"
+ " AND f.nrofact = d.nrofact \n"
+ " AND f.ffactur = d.ffactur \n"
+ " AND d.cod_servicio = s.cod_servicio \n"
+ " AND f.ctipo_docum = d.ctipo_docum \n"
+ " AND f.ffactur BETWEEN '" + fdesde + "' AND '" + fhasta + "' \n");
}
if (estados.equals("A")) {
sql.append(" AND f.mestado = 'A' ");
} else if (estados.equals("X")) {
sql.append(" AND f.mestado = 'X' ");
}
//clientes seleccionados
if (!clientesSel.equals("")) {
sql.append(" AND f.cod_cliente IN (" + clientesSel + ")");
}
if (conDetalles) {
sql.append("GROUP BY n.ctipo_docum, n.nro_nota, n.nrofact, n.fdocum, \n"
+ "f.cod_cliente, f.xrazon_social, \n"
+ "n.tgravadas, n.timpuestos, n.texentas, f.mestado ");
}
if (tipo.equals("VIST")) {
rep.reporteLiFactServ(sql.toString(), dateToString2(desde), dateToString2(hasta), "admin", tipo, conDetalles);
} else if (tipo.equals("ARCH")) {
List<Object[]> auxExcel = new ArrayList<Object[]>();
auxExcel = excelFacade.listarParaExcel(sql.toString());
rep.excelLifactServ(auxExcel);
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
public void todosLosClientes() {
if (this.todos == true) {
this.clientes = new Clientes();
clientesSel = "";
}
}
public void buscadorClienteTab(AjaxBehaviorEvent event) {
try {
if (this.clientes != null) {
if (!this.clientes.getCodCliente().equals("")) {
this.clientes = this.clientesFacade.buscarPorCodigo(this.clientes.getCodCliente() + "");
if (getClientesSel().equals("")) {
setClientesSel(getClientesSel() + clientes.getCodCliente());
} else {
setClientesSel(getClientesSel() + "," + clientes.getCodCliente());
}
if (this.clientes == null) {
this.clientes = new Clientes();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "No encontrado."));
}
}
} else {
this.clientes = new Clientes();
}
} catch (Exception e) {
this.clientes = new Clientes();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error en la busqueda"));
}
}
//Getters & Setters
public Clientes getClientes() {
return clientes;
}
public void setClientes(Clientes sublineas) {
this.clientes = sublineas;
}
public List<Clientes> getListaClientes() {
return listaClientes;
}
public void setListaClientes(List<Clientes> listaClientes) {
this.listaClientes = listaClientes;
}
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
public Boolean getTodos() {
return todos;
}
public void setTodos(Boolean todos) {
this.todos = todos;
}
public String getClientesSel() {
return clientesSel;
}
public void setClientesSel(String clientesSel) {
this.clientesSel = clientesSel;
}
public Boolean getConDetalles() {
return conDetalles;
}
public void setConDetalles(Boolean conDetalles) {
this.conDetalles = conDetalles;
}
public String getEstados() {
return estados;
}
public void setEstados(String estados) {
this.estados = estados;
}
}
<file_sep>/SisVenLog-war/src/java/bean/EnviosBean.java
package bean;
import dao.DepositosFacade;
import dao.EmpleadosFacade;
import dao.EnviosDetFacade;
import dao.EnviosFacade;
import dao.ExistenciasFacade;
import dao.MercaderiasFacade;
import dao.MovimientosMercaFacade;
import entidad.CanalesVenta;
import entidad.Depositos;
import entidad.DepositosPK;
import entidad.Empleados;
import entidad.Empresas;
import entidad.Envios;
import entidad.EnviosDet;
import entidad.EnviosDetPK;
import entidad.EnviosPK;
import entidad.Existencias;
import entidad.ExistenciasPK;
import entidad.MovimientosMerca;
import entidad.Mercaderias;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import java.util.Map;
@ManagedBean
@SessionScoped
public class EnviosBean extends LazyDataModel<Envios> implements Serializable {
@EJB
private EnviosFacade enviosFacade;
@EJB
private EnviosDetFacade enviosDetFacade;
@EJB
private MercaderiasFacade mercaderiasFacade;
@EJB
private ExistenciasFacade existenciasFacade;
@EJB
private EmpleadosFacade empleadosFacade;
@EJB
private DepositosFacade depositosFacade;
@EJB
private MovimientosMercaFacade movimientosMercaFacade;
private LazyDataModel<Envios> model;
private Envios envios = null;
private List<Envios> listaEnvios = null;
private EnviosDet enviosDet = null;
private List<EnviosDet> listaEnviosDet = null;
@SuppressWarnings("FieldMayBeFinal")
private List<EnviosDet> listaEnviosDetCollection = null;
private CanalesVenta canalesVenta = null;
private Depositos origen = null;
private Depositos destino = null;
private Empleados empleados = null;
private MovimientosMerca movimientosMerca = null;
private List<MovimientosMerca> listaMovimientosMerca = null;
private Mercaderias mercaderias = null;
private Existencias existencias = null;
private Empresas empresas = null;
EnviosDetPK enviosDetPkk = null;
EnviosPK enviosPkk = null;
DepositosPK depositoPkk = null;
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
private boolean vaciarCamion;
private Integer cajas;
private Integer unidades;
private Integer cantidadItem;
private Double calculoPesos;
private String articulo = "";
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaEnvios = new ArrayList<Envios>();
this.enviosPkk = new EnviosPK();
this.envios = new Envios();
BigDecimal respuesta = this.enviosFacade.getMaxNroEnvio();
this.enviosPkk.setNroEnvio(respuesta.longValue());
this.envios.setEnviosPK(enviosPkk);
this.listaEnviosDet = new ArrayList<EnviosDet>();
this.empleados = new Empleados();
this.listaEnviosDetCollection = new ArrayList<EnviosDet>();
this.vaciarCamion = false;
model = new LazyDataModel<Envios>() {
private static final long serialVersionUID = 1L;
@Override
public List<Envios> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
//List<Envios> envioss;
int count = 0;
if (filters.size() == 0) {
listaEnvios = enviosFacade.findRangeSort(new int[]{first, pageSize});
count = enviosFacade.count();
} else {
if (filters.size() < 2) {
//dd/MM/yyyy
String filtroNroEnvio = (String) filters.get("enviosPK.nroEnvio");
listaEnvios = enviosFacade.buscarEnviosPorNroEnvioFecha(filtroNroEnvio, new int[]{first, pageSize});
count = enviosFacade.CountBuscarEnviosPorNroEnvioFecha(filtroNroEnvio);
}
}
model.setRowCount(count);
return listaEnvios;
}
@Override
public Envios getRowData(String rowKey) {
String tempIndex = rowKey;
System.out.println("1");
if (tempIndex != null) {
for (Envios inc : listaEnvios) {
if (Long.toString(inc.getEnviosPK().getNroEnvio()).equals(rowKey)) {
return inc;
}
}
}
return null;
}
@Override
public Object getRowKey(Envios enviosss) {
return enviosss.getEnviosPK().getNroEnvio();
}
};
canalesVenta = new CanalesVenta();
origen = new Depositos();
origen.setDepositosPK(new DepositosPK());
destino = new Depositos();
destino.setDepositosPK(new DepositosPK());
//origen = new Depositos(new DepositosPK());
//destino = new Depositos(new DepositosPK());
this.articulo = "";
existencias = new Existencias();
movimientosMerca = new MovimientosMerca();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
envios.setFenvio(new Date());
setCajas(0);
setUnidades(0);
setCantidadItem(0);
setCalculoPesos(0.0);
}
public EnviosBean() {
//instanciar();
}
public List<EnviosDet> getListaEnviosDetCollection() {
return listaEnviosDetCollection;
}
public void setListaEnviosDetCollection(List<EnviosDet> listaEnviosDetCollection) {
this.listaEnviosDetCollection = listaEnviosDetCollection;
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public Envios getEnvios() {
return envios;
}
public void setEnvios(Envios envios) {
this.envios = envios;
}
public List<Envios> getListaEnvios() {
return listaEnvios;
}
public void setListaEnvios(List<Envios> listaEnvios) {
this.listaEnvios = listaEnvios;
}
public EnviosFacade getEnviosFacade() {
return enviosFacade;
}
public void setEnviosFacade(EnviosFacade enviosFacade) {
this.enviosFacade = enviosFacade;
}
public EnviosDetFacade getEnviosDetFacade() {
return enviosDetFacade;
}
public void setEnviosDetFacade(EnviosDetFacade enviosDetFacade) {
this.enviosDetFacade = enviosDetFacade;
}
public EnviosDet getEnviosDet() {
return enviosDet;
}
public void setEnviosDet(EnviosDet EnviosDet) {
this.enviosDet = EnviosDet;
}
public List<EnviosDet> getListaEnviosDet() {
return listaEnviosDet;
}
public void setListaEnviosDet(List<EnviosDet> listaEnviosDet) {
this.listaEnviosDet = listaEnviosDet;
}
public MovimientosMercaFacade getMovimientosMercaFacade() {
return movimientosMercaFacade;
}
public void setMovimientosMercaFacade(MovimientosMercaFacade movimientosMercaFacade) {
this.movimientosMercaFacade = movimientosMercaFacade;
}
public MovimientosMerca getMovimientosMerca() {
return movimientosMerca;
}
public void setMovimientosMerca(MovimientosMerca movimientosMerca) {
this.movimientosMerca = movimientosMerca;
}
public List<MovimientosMerca> getListaMovimientosMerca() {
return listaMovimientosMerca;
}
public void setListaMovimientosMerca(List<MovimientosMerca> listaMovimientosMerca) {
this.listaMovimientosMerca = listaMovimientosMerca;
}
public CanalesVenta getCanalesVenta() {
return canalesVenta;
}
public void setCanalesVenta(CanalesVenta canalesVenta) {
this.canalesVenta = canalesVenta;
}
public Depositos getOrigen() {
return origen;
}
public void setOrigen(Depositos origen) {
this.origen = origen;
}
public Depositos getDestino() {
return destino;
}
public void setDestino(Depositos destino) {
this.destino = destino;
}
public boolean isVaciarCamion() {
return vaciarCamion;
}
public void setVaciarCamion(boolean vaciarCamion) {
this.vaciarCamion = vaciarCamion;
}
public Integer getCajas() {
return cajas;
}
public void setCajas(Integer cajas) {
this.cajas = cajas;
}
public Integer getUnidades() {
return unidades;
}
public void setUnidades(Integer unidades) {
this.unidades = unidades;
}
public Double getCalculoPesos() {
return calculoPesos;
}
public void setCalculoPesos(Double calculoPesos) {
this.calculoPesos = calculoPesos;
}
public Mercaderias getMercaderias() {
return mercaderias;
}
public void setMercaderias(Mercaderias mercaderias) {
this.mercaderias = mercaderias;
}
public void nuevo() {
this.envios = new Envios();
listaEnvios = new ArrayList<Envios>();
}
public void cargarDetalle() {
//System.out.println("ESTOY EN CARGAR DETALLES");
if (cajas <= 0 && unidades <= 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Se requiere que cantidad o unidades sean mayores a cero"));
return;
}
try {
enviosDet = new EnviosDet();
enviosDetPkk = new EnviosDetPK();
enviosDet.setMercaderias(this.existencias.getMercaderias());
enviosDet.setXdesc(this.existencias.getMercaderias().getXdesc());
enviosDet.setCantUnid(unidades);
enviosDet.setCantCajas(cajas);
enviosDetPkk.setCodMerca(this.existencias.getMercaderias().getMercaderiasPK().getCodMerca());
enviosDet.setEnviosDetPK(enviosDetPkk);
/*Verificar duplicados*/
for (EnviosDet enviosDetallesDuplicados : this.listaEnviosDet) {
if (enviosDetallesDuplicados.getEnviosDetPK().getCodMerca().equals(enviosDet.getEnviosDetPK().getCodMerca())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Verifique que la Mercaderia no este duplicada en la grilla"));
/*limpiar campos*/
this.cajas = 0;
this.unidades = 0;
this.existencias = new Existencias();
this.articulo = "";
return;
}
}
this.listaEnviosDet.add(enviosDet);
setCantidadItem(this.cantidadItem + 1);
/*calculo del peso total*/
Mercaderias mercaderiasNew = new Mercaderias();
mercaderiasNew = this.mercaderiasFacade.buscarPorCodigoMercaderia(enviosDet.getEnviosDetPK().getCodMerca());
Double cantidadesCajas = enviosDet.getCantCajas().doubleValue();
Double cantidadesUnidades = enviosDet.getCantUnid().doubleValue();
Double pesosCajas = mercaderiasNew.getNpesoCaja().doubleValue();
Double pesosUnidades = mercaderiasNew.getNpesoUnidad().doubleValue();
Double cajasTotales = 0.0;
Double unidadesTotales = 0.0;
Double pesoReal = 0.0;
cajasTotales = cantidadesCajas * pesosCajas;
unidadesTotales = cantidadesUnidades * pesosUnidades;
pesoReal = cajasTotales + unidadesTotales;
setCalculoPesos(getCalculoPesos() + pesoReal);
/*limpiar campos*/
this.cajas = 0;
this.unidades = 0;
this.existencias = new Existencias();
this.articulo = "";
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Verifique que la Mercaderia tenga npeso y/o nunidad"));
this.listaEnviosDet = new ArrayList<EnviosDet>();
return;
}
}
public void insertar() {
try {
short codigoEntregador;
try {
codigoEntregador = movimientosMerca.getCodEntregador();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Se requiere de un Receptor"));
return;
}
if (origen == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Se requiere de un Deposito Origen"));
return;
}
if (destino == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Se requiere de un Deposito Destino"));
return;
}
if (canalesVenta == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Se requiere de un Canal de Venta"));
return;
}
if (this.calculoPesos <= 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Se requiere de un Total de pesos"));
return;
}
if (this.cantidadItem <= 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Se requiere de al menos un Item"));
return;
}
if ("".equals(this.envios.getXobs())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Se requiere de una observacion"));
return;
}
if ((this.envios.getXobs() == null)) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Se requiere de una observacion"));
return;
}
enviosPkk = new EnviosPK();
enviosPkk.setCodEmpr(origen.getDepositosPK().getCodEmpr());
enviosPkk.setNroEnvio(this.envios.getEnviosPK().getNroEnvio());
this.envios.setEnviosPK(enviosPkk);
this.envios.setCodEntregador(codigoEntregador);
this.envios.setCodCanal(canalesVenta.getCodCanal());
this.envios.setDepoOrigen(origen.getDepositosPK().getCodDepo());
this.envios.setDepoDestino(destino.getDepositosPK().getCodDepo());
this.envios.setFalta(new Date());
this.envios.setCusuario("admin");
this.envios.setMestado('A');
this.envios.setMtipo('D');
this.envios.setTotPeso(BigDecimal.valueOf(this.calculoPesos));
Depositos origenn = this.depositosFacade.getDepositoPorCodigo(origen.getDepositosPK().getCodDepo());
Depositos destinoo = this.depositosFacade.getDepositoPorCodigo(destino.getDepositosPK().getCodDepo());
for (EnviosDet enviosdetalle : listaEnviosDet) {
enviosDetPkk = new EnviosDetPK();
enviosDetPkk.setCodEmpr(origen.getDepositosPK().getCodEmpr());
enviosDetPkk.setCodMerca(enviosdetalle.getEnviosDetPK().getCodMerca());
enviosDetPkk.setNroEnvio(this.envios.getEnviosPK().getNroEnvio());
enviosdetalle.setEnviosDetPK(enviosDetPkk);
enviosdetalle.setEnvios(this.envios);
enviosdetalle.setCodCanal(this.canalesVenta.getCodCanal());
listaEnviosDetCollection.add(enviosdetalle);
//enviosDetFacade.insertarEnviosDetalle(enviosdetalle);
/*MOVIMIENTOS MERCA*/
/**
* ******DEPOSITO DESTINO********
*/
this.movimientosMerca = new MovimientosMerca();
this.movimientosMerca.setNroMovim(1L);
this.movimientosMerca.setCodEmpr(this.envios.getEnviosPK().getCodEmpr());
this.movimientosMerca.setCodMerca(enviosdetalle.getEnviosDetPK().getCodMerca());
this.movimientosMerca.setCodDepo(destino.getDepositosPK().getCodDepo());
this.movimientosMerca.setCantCajas(Long.valueOf(enviosdetalle.getCantCajas()));
this.movimientosMerca.setCodEntregador(this.envios.getCodEntregador());
this.movimientosMerca.setCantUnid(Long.valueOf(enviosdetalle.getCantUnid()));
this.movimientosMerca.setCodZona(destinoo.getZonas().getZonasPK().getCodZona());
Mercaderias mercaderiasNew = new Mercaderias();
mercaderiasNew = this.mercaderiasFacade.buscarPorCodigoMercaderia(enviosdetalle.getEnviosDetPK().getCodMerca());
Double pesosTotales = 0.0;
Double cantidadesCajas = enviosdetalle.getCantCajas().doubleValue();
Double cantidadesUnidades = enviosdetalle.getCantUnid().doubleValue();
Double pesosCajas = mercaderiasNew.getNpesoCaja().doubleValue();
Double pesosUnidades = mercaderiasNew.getNpesoUnidad().doubleValue();
Double cajasTotales = 0.0;
Double unidadesTotales = 0.0;
cajasTotales = cantidadesCajas * pesosCajas;
unidadesTotales = cantidadesUnidades * pesosUnidades;
pesosTotales = cajasTotales + unidadesTotales;
this.movimientosMerca.setNpeso(BigDecimal.valueOf(pesosTotales));
this.movimientosMerca.setManulado(new Short("1"));
this.movimientosMerca.setFmovim(new Date());
this.movimientosMerca.setCtipoDocum("EN");
this.movimientosMerca.setNdocum(enviosdetalle.getEnviosDetPK().getNroEnvio());
this.movimientosMerca.setIexentas(0L);
this.movimientosMerca.setIgravadas(0L);
this.movimientosMerca.setImpuestos(0L);
this.movimientosMerca.setFalta(new Date());
this.movimientosMerca.setCusuario("admin");
this.movimientosMerca.setOldCajas(0L);
movimientosMercaFacade.insertarMovimientosMerca(movimientosMerca);
/**
* ******DEPOSITO ORIGEN********
*/
this.movimientosMerca = new MovimientosMerca();
this.movimientosMerca.setNroMovim(2L);
cantidadesCajas = (enviosdetalle.getCantCajas().doubleValue()) * -1;
cantidadesUnidades = (enviosdetalle.getCantUnid().doubleValue()) * -1;
this.movimientosMerca.setCodEmpr(this.envios.getEnviosPK().getCodEmpr());
this.movimientosMerca.setCodMerca(enviosdetalle.getEnviosDetPK().getCodMerca());
this.movimientosMerca.setCodDepo(origen.getDepositosPK().getCodDepo());
this.movimientosMerca.setCantCajas(cantidadesCajas.longValue());
//this.movimientosMerca.setCodEntregador(this.envios.getCodEntregador());
this.movimientosMerca.setCantUnid(cantidadesUnidades.longValue());
this.movimientosMerca.setCodZona(origenn.getZonas().getZonasPK().getCodZona());
mercaderiasNew = new Mercaderias();
mercaderiasNew = this.mercaderiasFacade.buscarPorCodigoMercaderia(enviosdetalle.getEnviosDetPK().getCodMerca());
pesosTotales = 0.0;
cantidadesCajas = enviosdetalle.getCantCajas().doubleValue();
cantidadesUnidades = enviosdetalle.getCantUnid().doubleValue();
pesosCajas = mercaderiasNew.getNpesoCaja().doubleValue();
pesosUnidades = mercaderiasNew.getNpesoUnidad().doubleValue();
cajasTotales = 0.0;
unidadesTotales = 0.0;
cajasTotales = cantidadesCajas * pesosCajas;
unidadesTotales = cantidadesUnidades * pesosUnidades;
pesosTotales = cajasTotales + unidadesTotales;
this.movimientosMerca.setNpeso(BigDecimal.valueOf(pesosTotales));
this.movimientosMerca.setManulado(new Short("1"));
this.movimientosMerca.setFmovim(new Date());
this.movimientosMerca.setCtipoDocum("EN");
this.movimientosMerca.setNdocum(enviosdetalle.getEnviosDetPK().getNroEnvio());
this.movimientosMerca.setIexentas(0L);
this.movimientosMerca.setIgravadas(0L);
this.movimientosMerca.setImpuestos(0L);
this.movimientosMerca.setFalta(new Date());
this.movimientosMerca.setCusuario("admin");
this.movimientosMerca.setOldCajas(0L);
movimientosMercaFacade.insertarMovimientosMerca(movimientosMerca);
}
this.envios.setEnviosDetCollection(listaEnviosDetCollection);
enviosFacade.insertarEnvios(this.envios);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevEnvios').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editarView() {
try {
if ("".equals(this.envios.getFenvio())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Selecciones un item", "Se necesita seleccionar un item para anular."));
return;
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void anular() {
try {
if ("".equals(this.envios.getFenvio())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Selecciones un item", "Se necesita seleccionar un item para anular."));
return;
} else {
if (this.envios.getMestado().charValue() != 'A') {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Estado Inválido", "Estado Invalido de Nota de Envio."));
return;
} else {
Integer pedidosActivos = 0;
pedidosActivos = enviosFacade.buscarFacturasActivas(this.envios.getEnviosPK().getNroEnvio());
if (pedidosActivos < 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Error", "Error en Busqueda de Facturas Asociadas."));
return;
}
if (pedidosActivos > 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Error", "Existen Facturas Activas."));
return;
}
pedidosActivos = 0;
pedidosActivos = enviosFacade.updatePedidosPorNroEnvio(this.envios.getEnviosPK().getNroEnvio());
if (pedidosActivos < 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Error", "Error en Actualizacion de Estado del Pedido."));
return;
}
Collection<EnviosDet> listaEnviosDetCollectionAnular = new ArrayList<EnviosDet>();
listaEnviosDetCollectionAnular = this.envios.getEnviosDetCollection();
for (EnviosDet enviosDetAnular : listaEnviosDetCollectionAnular) {
this.movimientosMerca = new MovimientosMerca();
this.movimientosMerca.setNroMovim(3L);
Double cantidadesCajasAnular = (enviosDetAnular.getCantCajas().doubleValue());
Double cantidadesUnidadesAnular = (enviosDetAnular.getCantUnid().doubleValue());
this.movimientosMerca.setCodEmpr(this.envios.getEnviosPK().getCodEmpr());
this.movimientosMerca.setCodMerca(enviosDetAnular.getEnviosDetPK().getCodMerca());
this.movimientosMerca.setCodDepo(this.envios.getDepoOrigen());
this.movimientosMerca.setCantCajas(cantidadesCajasAnular.longValue());
this.movimientosMerca.setCantUnid(cantidadesUnidadesAnular.longValue());
Depositos origennAnular = this.depositosFacade.getDepositoPorCodigo(this.envios.getDepoOrigen());
this.movimientosMerca.setCodZona(origennAnular.getZonas().getZonasPK().getCodZona());
Mercaderias mercaderiasAnularNew = new Mercaderias();
mercaderiasAnularNew = this.mercaderiasFacade.buscarPorCodigoMercaderia(enviosDetAnular.getEnviosDetPK().getCodMerca());
Double pesosTotalesAnular = 0.0;
Double pesosCajasAnular = mercaderiasAnularNew.getNpesoCaja().doubleValue();
Double pesosUnidadesAnular = mercaderiasAnularNew.getNpesoUnidad().doubleValue();
Double cajasTotalesAnuluar = 0.0;
Double unidadesTotalesAnular = 0.0;
cajasTotalesAnuluar = cantidadesCajasAnular * pesosCajasAnular;
unidadesTotalesAnular = cantidadesUnidadesAnular * pesosUnidadesAnular;
pesosTotalesAnular = cajasTotalesAnuluar + unidadesTotalesAnular;
this.movimientosMerca.setNpeso(BigDecimal.valueOf(pesosTotalesAnular));
this.movimientosMerca.setManulado(new Short("-1"));
this.movimientosMerca.setFmovim(new Date());
this.movimientosMerca.setCtipoDocum("EN");
this.movimientosMerca.setNdocum(enviosDetAnular.getEnviosDetPK().getNroEnvio());
this.movimientosMerca.setIexentas(0L);
this.movimientosMerca.setIgravadas(0L);
this.movimientosMerca.setImpuestos(0L);
this.movimientosMerca.setFalta(new Date());
this.movimientosMerca.setCusuario("admin");
this.movimientosMerca.setOldCajas(0L);
try {
this.movimientosMercaFacade.insertarMovimientosMerca(this.movimientosMerca);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Error Insercion Movimientos Mercaderias - Origen"));
}
this.movimientosMerca = new MovimientosMerca();
this.movimientosMerca.setNroMovim(4L);
cantidadesCajasAnular = (enviosDetAnular.getCantCajas().doubleValue()) * -1;
cantidadesUnidadesAnular = (enviosDetAnular.getCantUnid().doubleValue()) * -1;
this.movimientosMerca.setCodEmpr(this.envios.getEnviosPK().getCodEmpr());
this.movimientosMerca.setCodMerca(enviosDetAnular.getEnviosDetPK().getCodMerca());
this.movimientosMerca.setCodDepo(this.envios.getDepoDestino());
this.movimientosMerca.setCantCajas(cantidadesCajasAnular.longValue());
this.movimientosMerca.setCantUnid(cantidadesUnidadesAnular.longValue());
Depositos destinoAnular = this.depositosFacade.getDepositoPorCodigo(this.envios.getDepoDestino());
this.movimientosMerca.setCodZona(destinoAnular.getZonas().getZonasPK().getCodZona());
mercaderiasAnularNew = new Mercaderias();
mercaderiasAnularNew = this.mercaderiasFacade.buscarPorCodigoMercaderia(enviosDetAnular.getEnviosDetPK().getCodMerca());
pesosTotalesAnular = 0.0;
pesosCajasAnular = mercaderiasAnularNew.getNpesoCaja().doubleValue();
pesosUnidadesAnular = mercaderiasAnularNew.getNpesoUnidad().doubleValue();
cajasTotalesAnuluar = 0.0;
unidadesTotalesAnular = 0.0;
cajasTotalesAnuluar = cantidadesCajasAnular * pesosCajasAnular;
unidadesTotalesAnular = cantidadesUnidadesAnular * pesosUnidadesAnular;
pesosTotalesAnular = (cajasTotalesAnuluar*-1) + (unidadesTotalesAnular*-1);
this.movimientosMerca.setNpeso(BigDecimal.valueOf(pesosTotalesAnular));
this.movimientosMerca.setManulado(new Short("-1"));
this.movimientosMerca.setFmovim(new Date());
this.movimientosMerca.setCtipoDocum("EN");
this.movimientosMerca.setNdocum(enviosDetAnular.getEnviosDetPK().getNroEnvio());
this.movimientosMerca.setIexentas(0L);
this.movimientosMerca.setIgravadas(0L);
this.movimientosMerca.setImpuestos(0L);
this.movimientosMerca.setFalta(new Date());
this.movimientosMerca.setCusuario("admin");
this.movimientosMerca.setOldCajas(0L);
try {
movimientosMercaFacade.insertarMovimientosMerca(movimientosMerca);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Error Insercion Movimientos Mercaderias - Destino"));
}
}
this.envios.setMestado('X');
enviosFacade.edit(envios);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Nro Envio Anulado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgEditEnvios').hide();");
}
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
try {
if (this.envios.getFenvio() == null) {
this.setHabBtnEdit(true);
} else {
this.setHabBtnEdit(false);
this.canalesVenta = new CanalesVenta();
this.canalesVenta.setCodCanal(this.envios.getCodCanal());
depositoPkk = new DepositosPK();
depositoPkk.setCodDepo(this.envios.getDepoOrigen());
depositoPkk.setCodEmpr(this.envios.getEnviosPK().getCodEmpr());
this.origen = new Depositos();
this.origen.setDepositosPK(new DepositosPK());
this.origen.setDepositosPK(depositoPkk);
depositoPkk = new DepositosPK();
depositoPkk.setCodDepo(this.envios.getDepoDestino());
depositoPkk.setCodEmpr(this.envios.getEnviosPK().getCodEmpr());
this.destino = new Depositos();
this.destino.setDepositosPK(new DepositosPK());
this.destino.setDepositosPK(depositoPkk);
this.destino.setDepositosPK(depositoPkk);
this.movimientosMerca = new MovimientosMerca();
this.movimientosMerca.setCodEntregador(this.envios.getCodEntregador());
this.listaEnviosDet = new ArrayList<EnviosDet>();
this.listaEnviosDet.addAll(this.envios.getEnviosDetCollection());
this.cantidadItem = this.listaEnviosDet.size();
}
} catch (Exception ex) {
this.setHabBtnEdit(true);
}
}
public void verificarCargaDatos() {
boolean cargado = false;
if (envios != null) {
if (envios.getXobs() != null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarEnvios').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevEnvios').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarEnvios').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevEnvios').hide();");
}
public void buscadorArticuloTab(AjaxBehaviorEvent event) {
try {
if (origen.getDepositosPK().getCodDepo() == 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Se requiere deposito origen para continuar."));
this.articulo = "";
return;
}
if (canalesVenta.getCodCanal() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Se requiere canal de venta para continuar."));
this.articulo = "";
return;
}
if ("".equals(canalesVenta.getCodCanal())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Se requiere canal de venta para continuar."));
this.articulo = "";
return;
}
if (!this.articulo.equals("")) {
this.existencias = (this.existenciasFacade.buscarPorCodigoDepositoOrigenMerca(articulo, this.origen.getDepositosPK().getCodDepo(), canalesVenta.getCodCanal())).get(0);
if (this.existencias.getMercaderias().getMercaderiasPK().getCodMerca() == null) {
this.existencias = new Existencias();
this.existencias.setExistenciasPK(new ExistenciasPK());
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Mercaderia no encontrada en el deposito origen o Inactiva."));
this.articulo = "";
}
} else {
this.existencias = new Existencias();
this.existencias.setExistenciasPK(new ExistenciasPK());
}
} catch (Exception e) {
this.articulo = "";
this.existencias = new Existencias();
this.existencias.setExistenciasPK(new ExistenciasPK());
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Mercaderia no encontrada en el deposito origen o Inactiva."));
}
}
public Existencias getExistencias() {
return existencias;
}
public void setExistencias(Existencias existencias) {
this.existencias = existencias;
}
public String getArticulo() {
return this.articulo;
}
public void setArticulo(String articulo) {
this.articulo = articulo;
System.out.println(this.articulo);
}
public EnviosDetPK getEnviosDetPkk() {
return enviosDetPkk;
}
public void setEnviosDetPkk(EnviosDetPK enviosDetPkk) {
this.enviosDetPkk = enviosDetPkk;
}
public EnviosPK getEnviosPkk() {
return enviosPkk;
}
public void setEnviosPkk(EnviosPK enviosPkk) {
this.enviosPkk = enviosPkk;
}
public Empresas getEmpresas() {
return empresas;
}
public void setEmpresas(Empresas empresas) {
this.empresas = empresas;
}
public Integer getCantidadItem() {
return cantidadItem;
}
public void setCantidadItem(Integer cantidadItem) {
this.cantidadItem = cantidadItem;
}
public LazyDataModel<Envios> getModel() {
return model;
}
public void buscadorEntregador(AjaxBehaviorEvent event) {
try {
if ((this.destino.getDepositosPK().getCodDepo()) != 0) {
this.empleados = (this.empleadosFacade.getNombreEmpleadoEntregador(this.destino.getDepositosPK().getCodDepo()));
this.movimientosMerca.setCodEntregador(this.empleados.getEmpleadosPK().getCodEmpleado());
if (this.empleados == null) {
this.empleados = new Empleados();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Receptor No encontrado."));
}
} else {
this.movimientosMerca.setCodEntregador(null);
this.empleados = new Empleados();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error en la busqueda del Receptor"));
}
} catch (Exception e) {
this.movimientosMerca.setCodEntregador(null);
this.empleados = new Empleados();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error existe mas de un Receptor del deposito destino"));
}
}
public Empleados getEmpleados() {
return empleados;
}
public void setEmpleados(Empleados empleados) {
this.empleados = empleados;
}
public void verView() {
try {
if ("".equals(this.envios.getFenvio())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Selecciones un item", "Se necesita seleccionar un item para visualizar."));
return;
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void deleteRows(String codMercaSacarLista) {
try {
Iterator itr = this.listaEnviosDet.iterator();
while (itr.hasNext()) {
EnviosDet enviosDetallesSacar = (EnviosDet) itr.next();
if (enviosDetallesSacar.getEnviosDetPK().getCodMerca().equals(codMercaSacarLista)) {
setCantidadItem(this.cantidadItem - 1);
/*calculo del peso total*/
Mercaderias mercaderiasNew = new Mercaderias();
mercaderiasNew = this.mercaderiasFacade.buscarPorCodigoMercaderia(codMercaSacarLista);
Double cantidadesCajas = enviosDetallesSacar.getCantCajas().doubleValue();
Double cantidadesUnidades = enviosDetallesSacar.getCantUnid().doubleValue();
Double pesosCajas = mercaderiasNew.getNpesoCaja().doubleValue();
Double pesosUnidades = mercaderiasNew.getNpesoUnidad().doubleValue();
Double cajasTotales = 0.0;
Double unidadesTotales = 0.0;
Double pesoReal = 0.0;
cajasTotales = cantidadesCajas * pesosCajas;
unidadesTotales = cantidadesUnidades * pesosUnidades;
pesoReal = cajasTotales + unidadesTotales;
pesoReal = getCalculoPesos()-pesoReal;
if(pesoReal<0.0)
pesoReal=0.0;
setCalculoPesos(pesoReal);
/*ELIMINAR*/
itr.remove();
return;
}
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "No se pudo eliminar de la grilla"));
return;
}
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/CanalesVendedoresFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.CanalesVendedores;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author admin
*/
@Stateless
public class CanalesVendedoresFacade extends AbstractFacade<CanalesVendedores> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public CanalesVendedoresFacade() {
super(CanalesVendedores.class);
}
public List<CanalesVendedores> obtenerCanalesVendedores(short lCodVendedor){
String sql = "SELECT * " +
"FROM canales_vendedores v, canales_venta c " +
"WHERE v.cod_canal = c.cod_canal " +
"AND v.cod_empr = 2 "+
"AND v.cod_vendedor = "+lCodVendedor;
Query q = em.createNativeQuery(sql, CanalesVendedores.class);
return q.getResultList();
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Facturas.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author admin
*/
@Entity
@Table(name = "facturas")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Facturas.findAll", query = "SELECT f FROM Facturas f")
, @NamedQuery(name = "Facturas.findByCodEmpr", query = "SELECT f FROM Facturas f WHERE f.facturasPK.codEmpr = :codEmpr")
, @NamedQuery(name = "Facturas.findByNrofact", query = "SELECT f FROM Facturas f WHERE f.facturasPK.nrofact = :nrofact")
, @NamedQuery(name = "Facturas.findByCtipoDocum", query = "SELECT f FROM Facturas f WHERE f.facturasPK.ctipoDocum = :ctipoDocum")
, @NamedQuery(name = "Facturas.findByFfactur", query = "SELECT f FROM Facturas f WHERE f.facturasPK.ffactur = :ffactur")
, @NamedQuery(name = "Facturas.findByCodRuta", query = "SELECT f FROM Facturas f WHERE f.codRuta = :codRuta")
, @NamedQuery(name = "Facturas.findByCtipoVta", query = "SELECT f FROM Facturas f WHERE f.ctipoVta = :ctipoVta")
, @NamedQuery(name = "Facturas.findByMestado", query = "SELECT f FROM Facturas f WHERE f.mestado = :mestado")
, @NamedQuery(name = "Facturas.findByFvenc", query = "SELECT f FROM Facturas f WHERE f.fvenc = :fvenc")
, @NamedQuery(name = "Facturas.findByTexentas", query = "SELECT f FROM Facturas f WHERE f.texentas = :texentas")
, @NamedQuery(name = "Facturas.findByTgravadas", query = "SELECT f FROM Facturas f WHERE f.tgravadas = :tgravadas")
, @NamedQuery(name = "Facturas.findByTimpuestos", query = "SELECT f FROM Facturas f WHERE f.timpuestos = :timpuestos")
, @NamedQuery(name = "Facturas.findByTdescuentos", query = "SELECT f FROM Facturas f WHERE f.tdescuentos = :tdescuentos")
, @NamedQuery(name = "Facturas.findByTtotal", query = "SELECT f FROM Facturas f WHERE f.ttotal = :ttotal")
, @NamedQuery(name = "Facturas.findByIsaldo", query = "SELECT f FROM Facturas f WHERE f.isaldo = :isaldo")
, @NamedQuery(name = "Facturas.findByXobs", query = "SELECT f FROM Facturas f WHERE f.xobs = :xobs")
, @NamedQuery(name = "Facturas.findByXdirec", query = "SELECT f FROM Facturas f WHERE f.xdirec = :xdirec")
, @NamedQuery(name = "Facturas.findByXruc", query = "SELECT f FROM Facturas f WHERE f.xruc = :xruc")
, @NamedQuery(name = "Facturas.findByXrazonSocial", query = "SELECT f FROM Facturas f WHERE f.xrazonSocial = :xrazonSocial")
, @NamedQuery(name = "Facturas.findByPinteres", query = "SELECT f FROM Facturas f WHERE f.pinteres = :pinteres")
, @NamedQuery(name = "Facturas.findByFalta", query = "SELECT f FROM Facturas f WHERE f.falta = :falta")
, @NamedQuery(name = "Facturas.findByCusuario", query = "SELECT f FROM Facturas f WHERE f.cusuario = :cusuario")
, @NamedQuery(name = "Facturas.findByFanul", query = "SELECT f FROM Facturas f WHERE f.fanul = :fanul")
, @NamedQuery(name = "Facturas.findByCusuarioAnul", query = "SELECT f FROM Facturas f WHERE f.cusuarioAnul = :cusuarioAnul")
, @NamedQuery(name = "Facturas.findByFultimModif", query = "SELECT f FROM Facturas f WHERE f.fultimModif = :fultimModif")
, @NamedQuery(name = "Facturas.findByCusuarioModif", query = "SELECT f FROM Facturas f WHERE f.cusuarioModif = :cusuarioModif")
, @NamedQuery(name = "Facturas.findByXtelef", query = "SELECT f FROM Facturas f WHERE f.xtelef = :xtelef")
, @NamedQuery(name = "Facturas.findByXciudad", query = "SELECT f FROM Facturas f WHERE f.xciudad = :xciudad")
, @NamedQuery(name = "Facturas.findByTnotas", query = "SELECT f FROM Facturas f WHERE f.tnotas = :tnotas")
, @NamedQuery(name = "Facturas.findByInteres", query = "SELECT f FROM Facturas f WHERE f.interes = :interes")
, @NamedQuery(name = "Facturas.findByTgravadas10", query = "SELECT f FROM Facturas f WHERE f.tgravadas10 = :tgravadas10")
, @NamedQuery(name = "Facturas.findByTgravadas5", query = "SELECT f FROM Facturas f WHERE f.tgravadas5 = :tgravadas5")
, @NamedQuery(name = "Facturas.findByTimpuestos10", query = "SELECT f FROM Facturas f WHERE f.timpuestos10 = :timpuestos10")
, @NamedQuery(name = "Facturas.findByTimpuestos5", query = "SELECT f FROM Facturas f WHERE f.timpuestos5 = :timpuestos5")
, @NamedQuery(name = "Facturas.findByNplazoCheque", query = "SELECT f FROM Facturas f WHERE f.nplazoCheque = :nplazoCheque")
, @NamedQuery(name = "Facturas.findByXfactura", query = "SELECT f FROM Facturas f WHERE f.xfactura = :xfactura")
, @NamedQuery(name = "Facturas.findByFvencImpre", query = "SELECT f FROM Facturas f WHERE f.fvencImpre = :fvencImpre")})
public class Facturas implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected FacturasPK facturasPK;
@Column(name = "cod_ruta")
private Short codRuta;
@Column(name = "ctipo_vta")
private Character ctipoVta;
@Basic(optional = false)
@NotNull
@Column(name = "mestado")
private Character mestado;
@Column(name = "fvenc")
@Temporal(TemporalType.TIMESTAMP)
private Date fvenc;
@Basic(optional = false)
@NotNull
@Column(name = "texentas")
private long texentas;
@Basic(optional = false)
@NotNull
@Column(name = "tgravadas")
private long tgravadas;
@Basic(optional = false)
@NotNull
@Column(name = "timpuestos")
private long timpuestos;
@Basic(optional = false)
@NotNull
@Column(name = "tdescuentos")
private long tdescuentos;
@Basic(optional = false)
@NotNull
@Column(name = "ttotal")
private long ttotal;
@Basic(optional = false)
@NotNull
@Column(name = "isaldo")
private long isaldo;
@Size(max = 50)
@Column(name = "xobs")
private String xobs;
@Size(max = 50)
@Column(name = "xdirec")
private String xdirec;
@Size(max = 15)
@Column(name = "xruc")
private String xruc;
@Size(max = 50)
@Column(name = "xrazon_social")
private String xrazonSocial;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Basic(optional = false)
@NotNull
@Column(name = "pinteres")
private BigDecimal pinteres;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "fanul")
@Temporal(TemporalType.TIMESTAMP)
private Date fanul;
@Size(max = 30)
@Column(name = "cusuario_anul")
private String cusuarioAnul;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
@Size(max = 20)
@Column(name = "xtelef")
private String xtelef;
@Size(max = 50)
@Column(name = "xciudad")
private String xciudad;
@Basic(optional = false)
@NotNull
@Column(name = "tnotas")
private long tnotas;
@Basic(optional = false)
@NotNull
@Column(name = "interes")
private long interes;
@Basic(optional = false)
@NotNull
@Column(name = "tgravadas_10")
private long tgravadas10;
@Basic(optional = false)
@NotNull
@Column(name = "tgravadas_5")
private long tgravadas5;
@Basic(optional = false)
@NotNull
@Column(name = "timpuestos_10")
private long timpuestos10;
@Basic(optional = false)
@NotNull
@Column(name = "timpuestos_5")
private long timpuestos5;
@Basic(optional = false)
@NotNull
@Column(name = "nplazo_cheque")
private short nplazoCheque;
@Size(max = 15)
@Column(name = "xfactura")
private String xfactura;
@Column(name = "fvenc_impre")
@Temporal(TemporalType.TIMESTAMP)
private Date fvencImpre;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "facturas")
private Collection<FacturasSer> facturasSerCollection;
@JoinColumn(name = "cod_canal", referencedColumnName = "cod_canal")
@ManyToOne
private CanalesVenta codCanal;
@JoinColumn(name = "cod_cliente", referencedColumnName = "cod_cliente")
@ManyToOne
private Clientes codCliente;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "cod_depo", referencedColumnName = "cod_depo")})
@ManyToOne(optional = false)
private Depositos depositos;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "cod_entregador", referencedColumnName = "cod_empleado")})
@ManyToOne(optional = false)
private Empleados empleados;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "cod_vendedor", referencedColumnName = "cod_empleado")})
@ManyToOne(optional = false)
private Empleados empleados1;
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Empresas empresas;
@JoinColumn(name = "cmotivo", referencedColumnName = "cmotivo")
@ManyToOne
private Motivos cmotivo;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "nro_pedido", referencedColumnName = "nro_pedido")})
@ManyToOne(optional = false)
private Pedidos pedidos;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "cod_zona", referencedColumnName = "cod_zona")})
@ManyToOne(optional = false)
private Zonas zonas;
public Facturas() {
}
public Facturas(FacturasPK facturasPK) {
this.facturasPK = facturasPK;
}
public Facturas(FacturasPK facturasPK, Character mestado, long texentas, long tgravadas, long timpuestos, long tdescuentos, long ttotal, long isaldo, BigDecimal pinteres, long tnotas, long interes, long tgravadas10, long tgravadas5, long timpuestos10, long timpuestos5, short nplazoCheque) {
this.facturasPK = facturasPK;
this.mestado = mestado;
this.texentas = texentas;
this.tgravadas = tgravadas;
this.timpuestos = timpuestos;
this.tdescuentos = tdescuentos;
this.ttotal = ttotal;
this.isaldo = isaldo;
this.pinteres = pinteres;
this.tnotas = tnotas;
this.interes = interes;
this.tgravadas10 = tgravadas10;
this.tgravadas5 = tgravadas5;
this.timpuestos10 = timpuestos10;
this.timpuestos5 = timpuestos5;
this.nplazoCheque = nplazoCheque;
}
public Facturas(short codEmpr, long nrofact, String ctipoDocum, Date ffactur) {
this.facturasPK = new FacturasPK(codEmpr, nrofact, ctipoDocum, ffactur);
}
public FacturasPK getFacturasPK() {
return facturasPK;
}
public void setFacturasPK(FacturasPK facturasPK) {
this.facturasPK = facturasPK;
}
public Short getCodRuta() {
return codRuta;
}
public void setCodRuta(Short codRuta) {
this.codRuta = codRuta;
}
public Character getCtipoVta() {
return ctipoVta;
}
public void setCtipoVta(Character ctipoVta) {
this.ctipoVta = ctipoVta;
}
public Character getMestado() {
return mestado;
}
public void setMestado(Character mestado) {
this.mestado = mestado;
}
public Date getFvenc() {
return fvenc;
}
public void setFvenc(Date fvenc) {
this.fvenc = fvenc;
}
public long getTexentas() {
return texentas;
}
public void setTexentas(long texentas) {
this.texentas = texentas;
}
public long getTgravadas() {
return tgravadas;
}
public void setTgravadas(long tgravadas) {
this.tgravadas = tgravadas;
}
public long getTimpuestos() {
return timpuestos;
}
public void setTimpuestos(long timpuestos) {
this.timpuestos = timpuestos;
}
public long getTdescuentos() {
return tdescuentos;
}
public void setTdescuentos(long tdescuentos) {
this.tdescuentos = tdescuentos;
}
public long getTtotal() {
return ttotal;
}
public void setTtotal(long ttotal) {
this.ttotal = ttotal;
}
public long getIsaldo() {
return isaldo;
}
public void setIsaldo(long isaldo) {
this.isaldo = isaldo;
}
public String getXobs() {
return xobs;
}
public void setXobs(String xobs) {
this.xobs = xobs;
}
public String getXdirec() {
return xdirec;
}
public void setXdirec(String xdirec) {
this.xdirec = xdirec;
}
public String getXruc() {
return xruc;
}
public void setXruc(String xruc) {
this.xruc = xruc;
}
public String getXrazonSocial() {
return xrazonSocial;
}
public void setXrazonSocial(String xrazonSocial) {
this.xrazonSocial = xrazonSocial;
}
public BigDecimal getPinteres() {
return pinteres;
}
public void setPinteres(BigDecimal pinteres) {
this.pinteres = pinteres;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFanul() {
return fanul;
}
public void setFanul(Date fanul) {
this.fanul = fanul;
}
public String getCusuarioAnul() {
return cusuarioAnul;
}
public void setCusuarioAnul(String cusuarioAnul) {
this.cusuarioAnul = cusuarioAnul;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
public String getXtelef() {
return xtelef;
}
public void setXtelef(String xtelef) {
this.xtelef = xtelef;
}
public String getXciudad() {
return xciudad;
}
public void setXciudad(String xciudad) {
this.xciudad = xciudad;
}
public long getTnotas() {
return tnotas;
}
public void setTnotas(long tnotas) {
this.tnotas = tnotas;
}
public long getInteres() {
return interes;
}
public void setInteres(long interes) {
this.interes = interes;
}
public long getTgravadas10() {
return tgravadas10;
}
public void setTgravadas10(long tgravadas10) {
this.tgravadas10 = tgravadas10;
}
public long getTgravadas5() {
return tgravadas5;
}
public void setTgravadas5(long tgravadas5) {
this.tgravadas5 = tgravadas5;
}
public long getTimpuestos10() {
return timpuestos10;
}
public void setTimpuestos10(long timpuestos10) {
this.timpuestos10 = timpuestos10;
}
public long getTimpuestos5() {
return timpuestos5;
}
public void setTimpuestos5(long timpuestos5) {
this.timpuestos5 = timpuestos5;
}
public short getNplazoCheque() {
return nplazoCheque;
}
public void setNplazoCheque(short nplazoCheque) {
this.nplazoCheque = nplazoCheque;
}
public String getXfactura() {
return xfactura;
}
public void setXfactura(String xfactura) {
this.xfactura = xfactura;
}
public Date getFvencImpre() {
return fvencImpre;
}
public void setFvencImpre(Date fvencImpre) {
this.fvencImpre = fvencImpre;
}
@XmlTransient
public Collection<FacturasSer> getFacturasSerCollection() {
return facturasSerCollection;
}
public void setFacturasSerCollection(Collection<FacturasSer> facturasSerCollection) {
this.facturasSerCollection = facturasSerCollection;
}
public CanalesVenta getCodCanal() {
return codCanal;
}
public void setCodCanal(CanalesVenta codCanal) {
this.codCanal = codCanal;
}
public Clientes getCodCliente() {
return codCliente;
}
public void setCodCliente(Clientes codCliente) {
this.codCliente = codCliente;
}
public Depositos getDepositos() {
return depositos;
}
public void setDepositos(Depositos depositos) {
this.depositos = depositos;
}
public Empleados getEmpleados() {
return empleados;
}
public void setEmpleados(Empleados empleados) {
this.empleados = empleados;
}
public Empleados getEmpleados1() {
return empleados1;
}
public void setEmpleados1(Empleados empleados1) {
this.empleados1 = empleados1;
}
public Empresas getEmpresas() {
return empresas;
}
public void setEmpresas(Empresas empresas) {
this.empresas = empresas;
}
public Motivos getCmotivo() {
return cmotivo;
}
public void setCmotivo(Motivos cmotivo) {
this.cmotivo = cmotivo;
}
public Pedidos getPedidos() {
return pedidos;
}
public void setPedidos(Pedidos pedidos) {
this.pedidos = pedidos;
}
public Zonas getZonas() {
return zonas;
}
public void setZonas(Zonas zonas) {
this.zonas = zonas;
}
@Override
public int hashCode() {
int hash = 0;
hash += (facturasPK != null ? facturasPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Facturas)) {
return false;
}
Facturas other = (Facturas) object;
if ((this.facturasPK == null && other.facturasPK != null) || (this.facturasPK != null && !this.facturasPK.equals(other.facturasPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Facturas[ facturasPK=" + facturasPK + " ]";
}
}
<file_sep>/SisVenLog-war/src/java/bean/ActualizarvigenciapromocionesBean.java
package bean;
import dao.PromocionesFacade;
import entidad.Promociones;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import org.primefaces.context.RequestContext;
import util.ExceptionHandlerView;
@Named(value = "actualizarvigenciapromocionesBean")
@ViewScoped
public class ActualizarvigenciapromocionesBean implements Serializable {
@Inject
private PromocionesFacade promocionFacade;
private Promociones promocion;
private Date l_ffinal, l_fnueva;
private String lpromos, nro_promo, x_nro_promo,filtro;
private List<Promociones> listaPromociones;
@PostConstruct
public void init() {
promocion = new Promociones();
this.lpromos = "";
this.nro_promo="";
filtro="";
listaPromociones = promocionFacade.findAllOrderXDesc();
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public ActualizarvigenciapromocionesBean() {
}
public List<Promociones> listar() {
listaPromociones = promocionFacade.findAllOrderXDesc();
return listaPromociones;
}
public List<Promociones> getListaPromociones() {
return listaPromociones;
}
public void setListaPromociones(List<Promociones> listaPromociones) {
this.listaPromociones = listaPromociones;
}
public PromocionesFacade getPromocionFacade() {
return promocionFacade;
}
public void setPromocionFacade(PromocionesFacade promocionFacade) {
this.promocionFacade = promocionFacade;
}
public String getLpromos() {
return lpromos;
}
public void setLpromos(String lpromos) {
this.lpromos = lpromos;
}
public String getNro_promo() {
return nro_promo;
}
public void setNro_promo(String nro_promo) {
this.nro_promo = nro_promo;
}
public String getX_nro_promo() {
return x_nro_promo;
}
public void setX_nro_promo(String x_nro_promo) {
this.x_nro_promo = x_nro_promo;
}
public Date getL_ffinal() {
return l_ffinal;
}
public void setL_ffinal(Date l_ffinal) {
this.l_ffinal = l_ffinal;
}
public Date getL_fnueva() {
return l_fnueva;
}
public void setL_fnueva(Date l_fnueva) {
this.l_fnueva = l_fnueva;
}
public Promociones getPromocion() {
return promocion;
}
public void setPromocion(Promociones promocion) {
this.promocion = promocion;
}
public void actualizarPromocion() {
SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd");
String l_sente = " UPDATE promociones SET frige_hasta = '" + formato.format(this.l_fnueva) + "' WHERE ";
l_sente = l_sente + " nro_promo IN ( " + this.lpromos + ")";
System.out.println("l_sente : " + l_sente);
Integer respuesta = promocionFacade.actualizarVigenciaPromocion(l_sente);
if (respuesta != -1) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso ", "Fin de Actualización"));
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Aviso ", "Error de Actualización"));
}
}
public void onChangePromocion() {
this.nro_promo = String.valueOf(promocion.getPromocionesPK().getNroPromo());
visualizarPromo();
}
public void visualizarPromo() {
if (this.nro_promo.equals("")) {
this.nro_promo = "";
this.x_nro_promo = "";
} else {
List<Promociones> lista = promocionFacade.findByNroPromo(this.nro_promo);
System.out.println(lista);
if (!lista.isEmpty()) {
promocion = lista.get(0);
this.x_nro_promo = promocion.getXdesc();
if (this.lpromos.length() > 0) {
this.lpromos += "," + this.nro_promo;
} else {
this.lpromos = this.nro_promo;
}
} else {
this.nro_promo = "";
this.x_nro_promo = "";
promocion = new Promociones();
}
}
}
public void listarPromocionBuscador(){
try{
listaPromociones = promocionFacade.buscarPorFiltro(filtro);
}catch(Exception e){
System.out.println(e.getStackTrace());
}
}
}
<file_sep>/SisVenLog-war/src/java/bean/GenDocuAnul.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
import dao.TiposDocumentosFacade;
import entidad.TiposDocumentos;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.*;
import javax.faces.bean.*;
import javax.faces.context.*;
/**
*
* @author Asus
*/
@ManagedBean
@SessionScoped
public class GenDocuAnul implements Serializable {
@EJB
private TiposDocumentosFacade tiposDocumentosFacade;
/***
* atributos para manejo del front end
*/
/* Fechas del formulario */
private Date fechaDocumento;
private Date fechaFactura;
/* Tipo de documento de la factura */
private TiposDocumentos tiposDocumentos;
private List<TiposDocumentos> listaTiposDocumentos;
/* Variables para numero de factura */
private Integer estabFactInicial;
private Integer expedFactInicial;
private Integer secueFactFinal;
/* Variables para numeracion de documento */
private Integer estabInicial;
private Integer expedInicial;
private Integer secueInicial;
private Integer secueFinal;
//para manejo de errores
private String contenidoError;
private String tituloError;
public GenDocuAnul() {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.fechaFactura = new Date();
this.fechaDocumento = new Date();
this.tiposDocumentos = new TiposDocumentos();
this.listaTiposDocumentos = new ArrayList<TiposDocumentos>();
estabInicial = 1;
expedInicial = 1;
secueInicial = 1;
secueFinal = 1;
}
public void ejecutar(){
if(!( (estabInicial == null || expedInicial == null || secueInicial == null || secueFinal == null) || (estabInicial == 1 && expedInicial == 1 && secueInicial == 1 && secueFinal == 1 )) ){
if(secueInicial + 50 < secueFinal){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "El rango maximo es solo de 50.", tituloError));
return ;
}
}
if(tiposDocumentos.getCtipoDocum().toUpperCase().equals("NCV")){
if(fechaFactura == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ingrese la fecha de factura.", tituloError));
return ;
}else if( (estabFactInicial == null || expedFactInicial == null || secueFactFinal == null) || (estabFactInicial == 1 && expedFactInicial == 1 && secueFactFinal == 1)){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ingrese Nro.Factura Contado Relacionada.", tituloError));
return ;
}
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Fin de Grabacion.", tituloError));
}
public List<TiposDocumentos> listarTipoDocumentoGenDocuAnul() {
this.listaTiposDocumentos = tiposDocumentosFacade.listarTipoDocumentoGenDocuAnul();
return this.listaTiposDocumentos;
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
public TiposDocumentosFacade getTiposDocumentosFacade() {
return tiposDocumentosFacade;
}
public Date getFechaDocumento() {
return fechaDocumento;
}
public Date getFechaFactura() {
return fechaFactura;
}
public TiposDocumentos getTiposDocumentos() {
return tiposDocumentos;
}
public List<TiposDocumentos> getListaTiposDocumentos() {
return listaTiposDocumentos;
}
public Integer getEstabFactInicial() {
return estabFactInicial;
}
public Integer getExpedFactInicial() {
return expedFactInicial;
}
public Integer getSecueFactFinal() {
return secueFactFinal;
}
public Integer getEstabInicial() {
return estabInicial;
}
public Integer getExpedInicial() {
return expedInicial;
}
public Integer getSecueInicial() {
return secueInicial;
}
public Integer getSecueFinal() {
return secueFinal;
}
public String getContenidoError() {
return contenidoError;
}
public String getTituloError() {
return tituloError;
}
public void setTiposDocumentosFacade(TiposDocumentosFacade tiposDocumentosFacade) {
this.tiposDocumentosFacade = tiposDocumentosFacade;
}
public void setFechaDocumento(Date fechaDocumento) {
this.fechaDocumento = fechaDocumento;
}
public void setFechaFactura(Date fechaFactura) {
this.fechaFactura = fechaFactura;
}
public void setTiposDocumentos(TiposDocumentos tiposDocumentos) {
this.tiposDocumentos = tiposDocumentos;
}
public void setListaTiposDocumentos(List<TiposDocumentos> listaTiposDocumentos) {
this.listaTiposDocumentos = listaTiposDocumentos;
}
public void setEstabFactInicial(Integer estabFactInicial) {
this.estabFactInicial = estabFactInicial;
}
public void setExpedFactInicial(Integer expedFactInicial) {
this.expedFactInicial = expedFactInicial;
}
public void setSecueFactFinal(Integer secueFactFinal) {
this.secueFactFinal = secueFactFinal;
}
public void setEstabInicial(Integer estabInicial) {
this.estabInicial = estabInicial;
}
public void setExpedInicial(Integer expedInicial) {
this.expedInicial = expedInicial;
}
public void setSecueInicial(Integer secueInicial) {
this.secueInicial = secueInicial;
}
public void setSecueFinal(Integer secueFinal) {
this.secueFinal = secueFinal;
}
public void setContenidoError(String contenidoError) {
this.contenidoError = contenidoError;
}
public void setTituloError(String tituloError) {
this.tituloError = tituloError;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/MotivosFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Bancos;
import entidad.Motivos;
import java.util.Date;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.StoredProcedureQuery;
/**
*
* @author admin
*/
@Stateless
public class MotivosFacade extends AbstractFacade<Motivos> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public MotivosFacade() {
super(Motivos.class);
}
public void insertarMotivos(Motivos motivos) {
StoredProcedureQuery q = getEntityManager().createStoredProcedureQuery("InsertarMotivos");
q.registerStoredProcedureParameter("xdesc", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("falta", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cusuario", String.class, ParameterMode.IN);
q.setParameter("xdesc", motivos.getXdesc());
q.setParameter("falta", motivos.getFalta());
q.setParameter("cusuario", motivos.getCusuario());
q.execute();
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/ClientesAgrupados.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "clientes_agrupados")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "ClientesAgrupados.findAll", query = "SELECT c FROM ClientesAgrupados c")
, @NamedQuery(name = "ClientesAgrupados.findByCodGrupo", query = "SELECT c FROM ClientesAgrupados c WHERE c.clientesAgrupadosPK.codGrupo = :codGrupo")
, @NamedQuery(name = "ClientesAgrupados.findByCodCliente", query = "SELECT c FROM ClientesAgrupados c WHERE c.clientesAgrupadosPK.codCliente = :codCliente")
, @NamedQuery(name = "ClientesAgrupados.findByCusuario", query = "SELECT c FROM ClientesAgrupados c WHERE c.cusuario = :cusuario")
, @NamedQuery(name = "ClientesAgrupados.findByFalta", query = "SELECT c FROM ClientesAgrupados c WHERE c.falta = :falta")})
public class ClientesAgrupados implements Serializable {
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
private static final long serialVersionUID = 1L;
@EmbeddedId
protected ClientesAgrupadosPK clientesAgrupadosPK;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@JoinColumn(name = "cod_cliente", referencedColumnName = "cod_cliente", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Clientes clientes;
@JoinColumn(name = "cod_grupo", referencedColumnName = "cod_grupo", insertable = false, updatable = false)
@ManyToOne(optional = false)
private GruposClientes gruposClientes;
public ClientesAgrupados() {
}
public ClientesAgrupados(ClientesAgrupadosPK clientesAgrupadosPK) {
this.clientesAgrupadosPK = clientesAgrupadosPK;
}
public ClientesAgrupados(short codGrupo, int codCliente) {
this.clientesAgrupadosPK = new ClientesAgrupadosPK(codGrupo, codCliente);
}
public ClientesAgrupadosPK getClientesAgrupadosPK() {
return clientesAgrupadosPK;
}
public void setClientesAgrupadosPK(ClientesAgrupadosPK clientesAgrupadosPK) {
this.clientesAgrupadosPK = clientesAgrupadosPK;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public Clientes getClientes() {
return clientes;
}
public void setClientes(Clientes clientes) {
this.clientes = clientes;
}
public GruposClientes getGruposClientes() {
return gruposClientes;
}
public void setGruposClientes(GruposClientes gruposClientes) {
this.gruposClientes = gruposClientes;
}
@Override
public int hashCode() {
int hash = 0;
hash += (clientesAgrupadosPK != null ? clientesAgrupadosPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ClientesAgrupados)) {
return false;
}
ClientesAgrupados other = (ClientesAgrupados) object;
if ((this.clientesAgrupadosPK == null && other.clientesAgrupadosPK != null) || (this.clientesAgrupadosPK != null && !this.clientesAgrupadosPK.equals(other.clientesAgrupadosPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.ClientesAgrupados[ clientesAgrupadosPK=" + clientesAgrupadosPK + " ]";
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
}
<file_sep>/SisVenLog-war/src/java/bean/ConductoresBean.java
package bean;
import dao.ConductoresFacade;
import entidad.Conductores;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class ConductoresBean implements Serializable {
@EJB
private ConductoresFacade conductoresFacade;
private String filtro = "";
private Conductores conductores = new Conductores();
private List<Conductores> listaConductores = new ArrayList<Conductores>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public ConductoresBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public Conductores getConductores() {
return conductores;
}
public void setConductores(Conductores conductores) {
this.conductores = conductores;
}
public List<Conductores> getListaConductores() {
return listaConductores;
}
public void setListaConductores(List<Conductores> listaConductores) {
this.listaConductores = listaConductores;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaConductores = new ArrayList<Conductores>();
this.conductores = new Conductores();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
this.filtro = "";
listar();
RequestContext.getCurrentInstance().update("formConductores");
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public void nuevo() {
this.conductores = new Conductores();
}
public List<Conductores> listar() {
listaConductores = conductoresFacade.findAll();
return listaConductores;
}
public void insertar() {
try {
conductores.setXconductor(conductores.getXconductor().toUpperCase());
conductores.setXdocum(conductores.getXdocum().toUpperCase());
conductores.setXdomicilio(conductores.getXdomicilio().toUpperCase());
conductores.setFalta(new Date());
conductores.setCusuario("admin");
conductoresFacade.insertarConductores(conductores);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevConductores').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editar() {
try {
if ("".equals(this.conductores.getXconductor())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
conductores.setXconductor(conductores.getXconductor().toUpperCase());
conductoresFacade.edit(conductores);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditConductores').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void borrar() {
try {
conductoresFacade.remove(conductores);
this.conductores = new Conductores();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacConductores').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
if ("" != this.conductores.getXconductor()) {
this.setHabBtnEdit(false);
} else {
this.setHabBtnEdit(true);
}
}
public void verificarCargaDatos() {
boolean cargado = false;
if (conductores != null) {
if (conductores.getXconductor()!= null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarConductores').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevConductores').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarConductores').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevConductores').hide();");
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/TransportistasFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Transportistas;
import entidad.Transportistas;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
@Stateless
public class TransportistasFacade extends AbstractFacade<Transportistas> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public TransportistasFacade() {
super(Transportistas.class);
}
public Transportistas buscarPorCodigo(String filtro) {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from transportistas\n"
+ "where cod_transp = " + filtro + " ", Transportistas.class);
//System.out.println(q.toString());
Transportistas respuesta = new Transportistas();
if (q.getResultList().size() <= 0) {
respuesta = null;
} else {
respuesta = (Transportistas) q.getSingleResult();
}
return respuesta;
}
public List<Transportistas> buscarPorFiltro(String filtro) {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from transportistas\n"
+ "where (xtransp like '%" + filtro + "%'\n"
+ " or xruc like '%" + filtro + "%')", Transportistas.class);
//System.out.println(q.toString());
List<Transportistas> respuesta = new ArrayList<Transportistas>();
respuesta = q.getResultList();
return respuesta;
}
public void insertarTransportistas(Transportistas transportistas) {
StoredProcedureQuery q = getEntityManager().createStoredProcedureQuery("InsertarTransportistas");
q.registerStoredProcedureParameter("xtransp", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("falta", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cusuario", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xruc", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xdomicilio", String.class, ParameterMode.IN);
q.setParameter("xtransp", transportistas.getXtransp());
q.setParameter("falta", transportistas.getFalta());
q.setParameter("cusuario", transportistas.getCusuario());
q.setParameter("xruc", transportistas.getXruc());
q.setParameter("xdomicilio", transportistas.getXdomicilio());
q.execute();
}
public List<Transportistas> listaTransportistasPorDeposito(Short cod_depo) {
Query q = getEntityManager().createNativeQuery("select t.*\n"
+ "from transportistas t\n"
+ "inner join depositos d on d.cod_transp=t.cod_transp\n"
+ "where d.cod_depo=" + Short.toString(cod_depo), Transportistas.class);
System.out.println(q.toString());
List<Transportistas> respuesta = new ArrayList<Transportistas>();
respuesta = q.getResultList();
return respuesta;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/RecibosDet.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "recibos_det")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "RecibosDet.findAll", query = "SELECT r FROM RecibosDet r")
, @NamedQuery(name = "RecibosDet.findByCodEmpr", query = "SELECT r FROM RecibosDet r WHERE r.recibosDetPK.codEmpr = :codEmpr")
, @NamedQuery(name = "RecibosDet.findByNrecibo", query = "SELECT r FROM RecibosDet r WHERE r.recibosDetPK.nrecibo = :nrecibo")
, @NamedQuery(name = "RecibosDet.findByNdocum", query = "SELECT r FROM RecibosDet r WHERE r.recibosDetPK.ndocum = :ndocum")
, @NamedQuery(name = "RecibosDet.findByCtipoDocum", query = "SELECT r FROM RecibosDet r WHERE r.recibosDetPK.ctipoDocum = :ctipoDocum")
, @NamedQuery(name = "RecibosDet.findByItotal", query = "SELECT r FROM RecibosDet r WHERE r.itotal = :itotal")
, @NamedQuery(name = "RecibosDet.findByTtotal", query = "SELECT r FROM RecibosDet r WHERE r.ttotal = :ttotal")
, @NamedQuery(name = "RecibosDet.findByIsaldo", query = "SELECT r FROM RecibosDet r WHERE r.isaldo = :isaldo")
, @NamedQuery(name = "RecibosDet.findByFfactur", query = "SELECT r FROM RecibosDet r WHERE r.ffactur = :ffactur")
, @NamedQuery(name = "RecibosDet.findByInteres", query = "SELECT r FROM RecibosDet r WHERE r.interes = :interes")
, @NamedQuery(name = "RecibosDet.findByFalta", query = "SELECT r FROM RecibosDet r WHERE r.falta = :falta")
, @NamedQuery(name = "RecibosDet.findByCusuario", query = "SELECT r FROM RecibosDet r WHERE r.cusuario = :cusuario")})
public class RecibosDet implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected RecibosDetPK recibosDetPK;
@Basic(optional = false)
@NotNull
@Column(name = "itotal")
private long itotal;
@Basic(optional = false)
@NotNull
@Column(name = "ttotal")
private long ttotal;
@Basic(optional = false)
@NotNull
@Column(name = "isaldo")
private long isaldo;
@Basic(optional = false)
@NotNull
@Column(name = "ffactur")
@Temporal(TemporalType.TIMESTAMP)
private Date ffactur;
@Basic(optional = false)
@NotNull
@Column(name = "interes")
private long interes;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "nrecibo", referencedColumnName = "nrecibo", insertable = false, updatable = false)})
@ManyToOne(optional = false)
private Recibos recibos;
public RecibosDet() {
}
public RecibosDet(RecibosDetPK recibosDetPK) {
this.recibosDetPK = recibosDetPK;
}
public RecibosDet(RecibosDetPK recibosDetPK, long itotal, long ttotal, long isaldo, Date ffactur, long interes) {
this.recibosDetPK = recibosDetPK;
this.itotal = itotal;
this.ttotal = ttotal;
this.isaldo = isaldo;
this.ffactur = ffactur;
this.interes = interes;
}
public RecibosDet(short codEmpr, long nrecibo, long ndocum, String ctipoDocum) {
this.recibosDetPK = new RecibosDetPK(codEmpr, nrecibo, ndocum, ctipoDocum);
}
public RecibosDetPK getRecibosDetPK() {
return recibosDetPK;
}
public void setRecibosDetPK(RecibosDetPK recibosDetPK) {
this.recibosDetPK = recibosDetPK;
}
public long getItotal() {
return itotal;
}
public void setItotal(long itotal) {
this.itotal = itotal;
}
public long getTtotal() {
return ttotal;
}
public void setTtotal(long ttotal) {
this.ttotal = ttotal;
}
public long getIsaldo() {
return isaldo;
}
public void setIsaldo(long isaldo) {
this.isaldo = isaldo;
}
public Date getFfactur() {
return ffactur;
}
public void setFfactur(Date ffactur) {
this.ffactur = ffactur;
}
public long getInteres() {
return interes;
}
public void setInteres(long interes) {
this.interes = interes;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Recibos getRecibos() {
return recibos;
}
public void setRecibos(Recibos recibos) {
this.recibos = recibos;
}
@Override
public int hashCode() {
int hash = 0;
hash += (recibosDetPK != null ? recibosDetPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof RecibosDet)) {
return false;
}
RecibosDet other = (RecibosDet) object;
if ((this.recibosDetPK == null && other.recibosDetPK != null) || (this.recibosDetPK != null && !this.recibosDetPK.equals(other.recibosDetPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.RecibosDet[ recibosDetPK=" + recibosDetPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/EmpleadosPK.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
/**
*
* @author Hugo
*/
@Embeddable
public class EmpleadosPK implements Serializable {
@Basic(optional = false)
//@NotNull
@Column(name = "cod_empr")
private short codEmpr;
@Basic(optional = false)
//@NotNull
@Column(name = "cod_empleado")
private short codEmpleado;
public EmpleadosPK() {
}
public EmpleadosPK(short codEmpr, short codEmpleado) {
this.codEmpr = codEmpr;
this.codEmpleado = codEmpleado;
}
public short getCodEmpr() {
return codEmpr;
}
public void setCodEmpr(short codEmpr) {
this.codEmpr = codEmpr;
}
public short getCodEmpleado() {
return codEmpleado;
}
public void setCodEmpleado(short codEmpleado) {
this.codEmpleado = codEmpleado;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) codEmpr;
hash += (int) codEmpleado;
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof EmpleadosPK)) {
return false;
}
EmpleadosPK other = (EmpleadosPK) object;
if (this.codEmpr != other.codEmpr) {
return false;
}
if (this.codEmpleado != other.codEmpleado) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.EmpleadosPK[ codEmpr=" + codEmpr + ", codEmpleado=" + codEmpleado + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/DatosGenerales.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "datos_generales")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "DatosGenerales.findAll", query = "SELECT d FROM DatosGenerales d")
, @NamedQuery(name = "DatosGenerales.findByCodEmpr", query = "SELECT d FROM DatosGenerales d WHERE d.datosGeneralesPK.codEmpr = :codEmpr")
, @NamedQuery(name = "DatosGenerales.findByTempPath", query = "SELECT d FROM DatosGenerales d WHERE d.tempPath = :tempPath")
, @NamedQuery(name = "DatosGenerales.findByFrigeDesde", query = "SELECT d FROM DatosGenerales d WHERE d.datosGeneralesPK.frigeDesde = :frigeDesde")
, @NamedQuery(name = "DatosGenerales.findByFrigeHasta", query = "SELECT d FROM DatosGenerales d WHERE d.frigeHasta = :frigeHasta")
, @NamedQuery(name = "DatosGenerales.findByPalmpath", query = "SELECT d FROM DatosGenerales d WHERE d.palmpath = :palmpath")
, @NamedQuery(name = "DatosGenerales.findByCusuario", query = "SELECT d FROM DatosGenerales d WHERE d.cusuario = :cusuario")
, @NamedQuery(name = "DatosGenerales.findByFalta", query = "SELECT d FROM DatosGenerales d WHERE d.falta = :falta")
, @NamedQuery(name = "DatosGenerales.findByPcostoFinan", query = "SELECT d FROM DatosGenerales d WHERE d.pcostoFinan = :pcostoFinan")})
public class DatosGenerales implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected DatosGeneralesPK datosGeneralesPK;
@Size(max = 30)
@Column(name = "tempPath")
private String tempPath;
@Column(name = "frige_hasta")
@Temporal(TemporalType.TIMESTAMP)
private Date frigeHasta;
@Size(max = 50)
@Column(name = "palmpath")
private String palmpath;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "pcosto_finan")
private BigDecimal pcostoFinan;
public DatosGenerales() {
}
public DatosGenerales(DatosGeneralesPK datosGeneralesPK) {
this.datosGeneralesPK = datosGeneralesPK;
}
public DatosGenerales(short codEmpr, Date frigeDesde) {
this.datosGeneralesPK = new DatosGeneralesPK(codEmpr, frigeDesde);
}
public DatosGeneralesPK getDatosGeneralesPK() {
return datosGeneralesPK;
}
public void setDatosGeneralesPK(DatosGeneralesPK datosGeneralesPK) {
this.datosGeneralesPK = datosGeneralesPK;
}
public String getTempPath() {
return tempPath;
}
public void setTempPath(String tempPath) {
this.tempPath = tempPath;
}
public Date getFrigeHasta() {
return frigeHasta;
}
public void setFrigeHasta(Date frigeHasta) {
this.frigeHasta = frigeHasta;
}
public String getPalmpath() {
return palmpath;
}
public void setPalmpath(String palmpath) {
this.palmpath = palmpath;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public BigDecimal getPcostoFinan() {
return pcostoFinan;
}
public void setPcostoFinan(BigDecimal pcostoFinan) {
this.pcostoFinan = pcostoFinan;
}
@Override
public int hashCode() {
int hash = 0;
hash += (datosGeneralesPK != null ? datosGeneralesPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof DatosGenerales)) {
return false;
}
DatosGenerales other = (DatosGenerales) object;
if ((this.datosGeneralesPK == null && other.datosGeneralesPK != null) || (this.datosGeneralesPK != null && !this.datosGeneralesPK.equals(other.datosGeneralesPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.DatosGenerales[ datosGeneralesPK=" + datosGeneralesPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/CanalesVendedores.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "canales_vendedores")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "CanalesVendedores.findAll", query = "SELECT c FROM CanalesVendedores c")
, @NamedQuery(name = "CanalesVendedores.findByCodEmpr", query = "SELECT c FROM CanalesVendedores c WHERE c.canalesVendedoresPK.codEmpr = :codEmpr")
, @NamedQuery(name = "CanalesVendedores.findByCodVendedor", query = "SELECT c FROM CanalesVendedores c WHERE c.canalesVendedoresPK.codVendedor = :codVendedor")
, @NamedQuery(name = "CanalesVendedores.findByCodCanal", query = "SELECT c FROM CanalesVendedores c WHERE c.canalesVendedoresPK.codCanal = :codCanal")
, @NamedQuery(name = "CanalesVendedores.findByCusuario", query = "SELECT c FROM CanalesVendedores c WHERE c.cusuario = :cusuario")
, @NamedQuery(name = "CanalesVendedores.findByFalta", query = "SELECT c FROM CanalesVendedores c WHERE c.falta = :falta")
, @NamedQuery(name = "CanalesVendedores.findByCusuarioModif", query = "SELECT c FROM CanalesVendedores c WHERE c.cusuarioModif = :cusuarioModif")
, @NamedQuery(name = "CanalesVendedores.findByFultimModif", query = "SELECT c FROM CanalesVendedores c WHERE c.fultimModif = :fultimModif")})
public class CanalesVendedores implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected CanalesVendedoresPK canalesVendedoresPK;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@JoinColumn(name = "cod_canal", referencedColumnName = "cod_canal", insertable = false, updatable = false)
@ManyToOne(optional = false)
private CanalesVenta canalesVenta;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "cod_vendedor", referencedColumnName = "cod_empleado", insertable = false, updatable = false)})
@ManyToOne(optional = false)
private Empleados empleados;
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Empresas empresas;
public CanalesVendedores() {
}
public CanalesVendedores(CanalesVendedoresPK canalesVendedoresPK) {
this.canalesVendedoresPK = canalesVendedoresPK;
}
public CanalesVendedores(short codEmpr, short codVendedor, String codCanal) {
this.canalesVendedoresPK = new CanalesVendedoresPK(codEmpr, codVendedor, codCanal);
}
public CanalesVendedoresPK getCanalesVendedoresPK() {
return canalesVendedoresPK;
}
public void setCanalesVendedoresPK(CanalesVendedoresPK canalesVendedoresPK) {
this.canalesVendedoresPK = canalesVendedoresPK;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public CanalesVenta getCanalesVenta() {
return canalesVenta;
}
public void setCanalesVenta(CanalesVenta canalesVenta) {
this.canalesVenta = canalesVenta;
}
public Empleados getEmpleados() {
return empleados;
}
public void setEmpleados(Empleados empleados) {
this.empleados = empleados;
}
public Empresas getEmpresas() {
return empresas;
}
public void setEmpresas(Empresas empresas) {
this.empresas = empresas;
}
@Override
public int hashCode() {
int hash = 0;
hash += (canalesVendedoresPK != null ? canalesVendedoresPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof CanalesVendedores)) {
return false;
}
CanalesVendedores other = (CanalesVendedores) object;
if ((this.canalesVendedoresPK == null && other.canalesVendedoresPK != null) || (this.canalesVendedoresPK != null && !this.canalesVendedoresPK.equals(other.canalesVendedoresPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.CanalesVendedores[ canalesVendedoresPK=" + canalesVendedoresPK + " ]";
}
}
<file_sep>/SisVenLog-war/src/java/bean/RecibosProveedoresBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
import dao.BancosFacade;
import dao.ChequesEmitidosFacade;
import dao.ComprasFacade;
import dao.CuentasProveedoresFacade;
import dao.NotasComprasFacade;
import dao.ProveedoresFacade;
import dao.RecibosProvChequesFacade;
import dao.RecibosProvDetFacade;
import dao.RecibosProvFacade;
import dao.TiposDocumentosFacade;
import dto.ChequeProveedorDto;
import dto.CompraDto;
import dto.DocumentoCompraDto;
import dto.NotasComprasDto;
import entidad.Bancos;
import entidad.ChequesEmitidos;
import entidad.ChequesEmitidosPK;
import entidad.Proveedores;
import entidad.RecibosProv;
import entidad.RecibosProvCheques;
import entidad.RecibosProvDet;
import entidad.TiposDocumentos;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.SelectEvent;
import util.DateUtil;
import util.ExceptionHandlerView;
/**
*
* @author dadob
*/
@ManagedBean
@SessionScoped
public class RecibosProveedoresBean implements Serializable{
@EJB
private RecibosProvFacade recibosProvFacade;
@EJB
private ProveedoresFacade proveedoresFacade;
@EJB
private TiposDocumentosFacade tiposDocumentosFacade;
@EJB
private ComprasFacade comprasFacade;
@EJB
private NotasComprasFacade notasComprasFacade;
@EJB
private RecibosProvDetFacade recibosProvDetFacade;
@EJB
private CuentasProveedoresFacade cuentasProveedoresFacade;
@EJB
private ChequesEmitidosFacade chequesEmitidosFacade;
@EJB
private RecibosProvChequesFacade recibosProvChequesFacade;
@EJB
private BancosFacade bancosFacade;
private List<RecibosProv> listadoRecibosProv;
private RecibosProv reciboProvSeleccionado;
private List<Proveedores> listadoProveedores;
private List<TiposDocumentos> listadoTiposDocumentos;
private List<DocumentoCompraDto> listadoDocumentoCompraDto;
private List<CompraDto> listadoCompraDto;
private List<CompraDto> listadoCompraAuxiliarDto;
private List<NotasComprasDto> listadoNotasComprasDto;
private List<NotasComprasDto> listadoNotasComprasAuxiliarDto;
private List<ChequeProveedorDto> listadoChequesEmitidos;
private String contenidoError;
private String tituloError;
private boolean agregar;
private boolean anular;
private boolean eliminar;
private Proveedores proveedorSeleccionadoLbl;
private Date fechaReciboLbl;
private long nroReciboLbl;
private String observacionLbl;
private Character estadoLbl;
private int estadoLblSeleccionado;
private long totalReciboLbl;
private TiposDocumentos tipoDocumentoSeleccionadoDet;
private Date fechaDocumentoDet;
private long nroDocumentoDet;
private long montoAPagarDet;
private long montoFacturaDet;
private long saldoDocumento;
private DocumentoCompraDto documentoCompraDto;
private long totalEfectivo;
private long totalRetencion;
private long totalCheques;
private Bancos bancoSeleccionadoDet;
private String nroChequeDet;
private String nroCtaBancaria;
private Date fechaChequeDet;
private Date fechaEmisionDet;
private long importeChequeDet;
private ChequesEmitidos chequeEmitidoSeleccionadoDet;
private long importeAPagarChequeDet;
private String comCtipoDocum;
private long comNrofact;
private Date comFfactur;
private String canalCompraDet;
private Date fechaVencDet;
private boolean habilitaBotonEliminar;
@PostConstruct
public void init(){
limpiarFormulario();
}
private void limpiarFormulario(){
listadoRecibosProv = new ArrayList<>();
listadoProveedores = new ArrayList<>();
listadoTiposDocumentos = new ArrayList<>();
contenidoError = "";
tituloError = "";
agregar = false;
anular = false;
eliminar = false;
reciboProvSeleccionado = new RecibosProv();
proveedorSeleccionadoLbl = new Proveedores();
fechaReciboLbl = null;
nroReciboLbl = 0;
observacionLbl = null;
estadoLblSeleccionado = 0;
totalReciboLbl = 0;
tipoDocumentoSeleccionadoDet = new TiposDocumentos();
listadoDocumentoCompraDto = new ArrayList<>();
listadoCompraDto = new ArrayList<>();
saldoDocumento = 0;
comCtipoDocum = "";
comFfactur = null;
comNrofact = 0;
listadoNotasComprasDto = new ArrayList<>();
documentoCompraDto = new DocumentoCompraDto();
calcularTotalRecibo();
totalEfectivo = 0;
totalRetencion = 0;
totalCheques = 0;
bancoSeleccionadoDet = new Bancos();
nroChequeDet = "";
nroCtaBancaria = "";
fechaChequeDet = null;
fechaEmisionDet = null;
importeChequeDet = 0;
listadoChequesEmitidos = new ArrayList<>();
chequeEmitidoSeleccionadoDet = new ChequesEmitidos();
importeAPagarChequeDet = 0;
listadoCompraAuxiliarDto = new ArrayList<>();
listadoNotasComprasAuxiliarDto = new ArrayList<>();
canalCompraDet = null;
fechaVencDet = null;
fechaDocumentoDet = null;
nroDocumentoDet = 0;
habilitaBotonEliminar = true;
listarRecibosProv();
}
public static String convertidorFecha(Date fecha){
return DateUtil.formaterDateToString(fecha);
}
public void listarRecibosProv(){
try{
listadoRecibosProv = recibosProvFacade.listadoRecibosProveedores();
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de recibos del proveedor.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public void limpiarReciboProveedor(){
limpiarFormulario();
}
public String agregarReciboProveedor(){
agregar = true;
try{
if(nroReciboLbl == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Nro. de recibo inválido."));
return null;
}else{
try{
String fechaReciboLblStr = dateToString(fechaReciboLbl);
long cantidadRecibos = recibosProvFacade.obtenerCantidadRecibosDelProveedor(nroReciboLbl, fechaReciboLblStr, proveedorSeleccionadoLbl.getCodProveed());
if(cantidadRecibos > 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Ya existe este nro. de recibo."));
return null;
}else{
if(!agregar){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "No existe este nro. de recibo."));
return null;
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la validación de nro. de recibo.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
if(proveedorSeleccionadoLbl == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Proveedor inválido."));
return null;
}else{
if(proveedorSeleccionadoLbl.getCodProveed() == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Proveedor inválido."));
return null;
}else{
if(fechaReciboLbl == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Fecha inálida de recibo."));
return null;
}else{
for (DocumentoCompraDto dc : listadoDocumentoCompraDto) {
if (dc.getNroDcumento() != 0) {
if (dc.getTipoDocumento().getCtipoDocum().equals("FCC")) {
try{
String fechaDocumentoDetStr = dateToString(dc.getFechaDocumento());
listadoCompraAuxiliarDto = comprasFacade.buscarFacturaCompraPorNroProveedorFechaFactura(dc.getNroDcumento(), dc.getProveedor().getCodProveed(), fechaDocumentoDetStr);
if(listadoCompraAuxiliarDto.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "No existe factura crédito."));
return null;
}else{
if(!verificarFacturasEnRegistros(dc)){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "La factura "+dc.getNroDcumento()+" está repetida en el recibo."));
return null;
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de compras.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
} else if (dc.getTipoDocumento().getCtipoDocum().equals("NCC")) {
try {
String fechaDocumentoDetStr = dateToString(dc.getFechaDocumento());
listadoNotasComprasAuxiliarDto = notasComprasFacade.comprasCreditoPorNroNotaFechaProveedor(dc.getNroDcumento(), dc.getProveedor().getCodProveed(), fechaDocumentoDetStr);
if (listadoNotasComprasAuxiliarDto.isEmpty()) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "No existe nota de crédito."));
return null;
}
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de notas de créditos de compras.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
} else if (dc.getTipoDocumento().getCtipoDocum().equals("NDC")) {
try {
String fechaDocumentoDetStr = dateToString(dc.getFechaDocumento());
listadoNotasComprasAuxiliarDto = notasComprasFacade.comprasDebitoPorNroNotaFechaProveedor(dc.getNroDcumento(), dc.getProveedor().getCodProveed(), fechaDocumentoDetStr);
if (listadoNotasComprasAuxiliarDto.isEmpty()) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "No existe nota de débito."));
return null;
}
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de notas de débitos de compras.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}
}
//validar totales
if((totalRetencion + totalEfectivo + totalCheques) != totalReciboLbl){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Total recibo no coincide con total forma de pago."));
return null;
}
long lTotal = 0;
for(DocumentoCompraDto dc: listadoDocumentoCompraDto){
lTotal += dc.getMontoAPagarDocumento();
}
if(lTotal != totalReciboLbl){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Detalles de facturas no coincide con total recibo."));
return null;
}
//validar montos de cheques
for(ChequeProveedorDto cp: listadoChequesEmitidos){
try{
long totalPagadoDelProveedor = recibosProvFacade.obtenerImportePagadoDeProveedores(cp.getChequeEmitido().getChequesEmitidosPK().getNroCheque(), cp.getChequeEmitido().getBancos().getCodBanco());
if((totalPagadoDelProveedor + cp.getImporteAPagar()) > cp.getChequeEmitido().getIcheque()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "El cheque nro. "+cp.getChequeEmitido().getChequesEmitidosPK().getNroCheque()+" ya tiene utilizado "+totalPagadoDelProveedor+" en otras facturas."));
return null;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en el control de totales de cheques.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
//insertar y/o actualizar
if(agregar){
//insertar
try{
String fReciboStr = dateToString(fechaReciboLbl);
recibosProvFacade.insertarReciboProveedor( Short.parseShort("2"),
nroReciboLbl,
fReciboStr,
proveedorSeleccionadoLbl.getCodProveed(),
totalReciboLbl,
totalRetencion,
totalEfectivo,
totalCheques,
observacionLbl);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en inserción de recibos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
for (DocumentoCompraDto dc : listadoDocumentoCompraDto) {
try {
String fFactura = dateToString(dc.getFechaDocumento());
String fRecibo = dateToString(dc.getFechaRecibo());
recibosProvDetFacade.insertarReciboProveedorDetalle(Short.parseShort("2"),
dc.getProveedor().getCodProveed(),
dc.getNroRecibo(),
dc.getNroDcumento(),
dc.getTipoDocumento().getCtipoDocum(),
dc.getMontoAPagarDocumento(),
fFactura,
0,
dc.getMontoDocumento(),
dc.getSaldoDocumento(),
fRecibo);
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en inserción de detalles de recibos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
dc.setTipoDocumento(tiposDocumentosFacade.find(dc.getTipoDocumento().getCtipoDocum()));
if(dc.getTipoDocumento().getMafectaCtacte() == 'S'){
try{
String lFMovim = dateToString(dc.getFechaRecibo());
String nroReciboStr = String.valueOf(dc.getNroRecibo());
String lFvenc = dateToString(dc.getFechaVencimiento());
String otraFechaDocumStr = dateToString(dc.getFechaDocumento());
String fFacturaStr = dateToString(dc.getComFfactur());
short mIndice = dc.getTipoDocumento().getMindice() == null ? 0 : dc.getTipoDocumento().getMindice().shortValue();
cuentasProveedoresFacade.insertarCuentaProveedor( Short.parseShort("2"),
"REP",
dc.getProveedor().getCodProveed(),
lFMovim,
nroReciboStr,
dc.getComCtipoDocum(),
dc.getComNrofact(),
dc.getMontoAPagarDocumento(),
0,
0,
0,
0,
dc.getSaldoDocumento(),
mIndice,
lFvenc,
dc.getTipoDocumento().getCtipoDocum(),
dc.getNroDcumento(),
otraFechaDocumStr,
dc.getCanalCompra() == null ? "" : dc.getCanalCompra(),
fFacturaStr);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en inserción de cuentas proveedores.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
//cerar NCC sin factura
if(dc.getTipoDocumento().getCtipoDocum().equals("NCC")){
try{
String fFactura = dateToString(dc.getFechaDocumento());
notasComprasFacade.disminuyeSaldoNotasCompras(dc.getMontoAPagarDocumento(), fFactura, dc.getNroDcumento(), dc.getProveedor().getCodProveed());
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en actualización de notas de créditos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}
//cheques
for (ChequeProveedorDto cp : listadoChequesEmitidos) {
try {
String fCheque = dateToString(cp.getChequeEmitido().getFcheque());
String fEmision = dateToString(cp.getChequeEmitido().getFemision());
chequesEmitidosFacade.insertarChequeEmitido(Short.parseShort("2"),
cp.getChequeEmitido().getChequesEmitidosPK().getCodBanco(),
cp.getChequeEmitido().getChequesEmitidosPK().getNroCheque(),
cp.getChequeEmitido().getXcuentaBco(),
fCheque,
fEmision,
cp.getChequeEmitido().getIcheque(),
cp.getChequeEmitido().getCodProveed().getCodProveed());
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la inserción de nuevos cheques.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
String nroCheque = null;
try{
nroCheque = cuentasProveedoresFacade.obtenerNroDocumentoCheque( cp.getChequeEmitido().getChequesEmitidosPK().getNroCheque(),
cp.getChequeEmitido().getChequesEmitidosPK().getCodBanco());
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en lectura de movimiento cta. cte. proveedor de cheque.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
if(nroCheque == null){
//insertar solamente si aun no existe el movimiento cheque
try{
String fFMovim = dateToString(fechaReciboLbl);
String fFechaCheque = dateToString(cp.getChequeEmitido().getFcheque());
cuentasProveedoresFacade.insertarCuentaProveedor( fFMovim,
cp.getChequeEmitido().getChequesEmitidosPK().getNroCheque(),
cp.getChequeEmitido().getIcheque(),
cp.getChequeEmitido().getChequesEmitidosPK().getCodBanco(),
cp.getChequeEmitido().getCodProveed().getCodProveed(),
Short.parseShort("1"),
fFechaCheque,
"",
0,
"");
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en inserción de cuentas proveedores.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
try{
String lFRecibo = dateToString(fechaReciboLbl);
recibosProvChequesFacade.insertarChequeReciboProveedor( Short.parseShort("2"),
cp.getChequeEmitido().getCodProveed().getCodProveed(),
nroReciboLbl,
cp.getChequeEmitido().getChequesEmitidosPK().getCodBanco(),
cp.getChequeEmitido().getChequesEmitidosPK().getNroCheque(),
cp.getImporteAPagar(),
lFRecibo);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en inserción de recibos y cheques.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}
}else{
//actualizar
try{
String lFRecibo = dateToString(fechaReciboLbl);
recibosProvFacade.actualizarReciboProveedor(lFRecibo,
totalReciboLbl,
totalRetencion,
observacionLbl,
proveedorSeleccionadoLbl.getCodProveed(),
nroReciboLbl);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en actualización de recibos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
//datos grabados
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Datos Grabados"));
limpiarFormulario(); //volvemos a instanciar
RequestContext.getCurrentInstance().execute("PF('dlgNuevReciboCompra').hide();");
return null;
}
}
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al agregar un recibo compra.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
private boolean verificarFacturasEnRegistros(DocumentoCompraDto doc){
long contador = 0;
if(!listadoDocumentoCompraDto.isEmpty()){
for(DocumentoCompraDto dc: listadoDocumentoCompraDto){
if( dc.getNroDcumento() == doc.getNroDcumento() &&
dc.getNroRecibo() == doc.getNroRecibo() &&
dc.getProveedor().getCodProveed().compareTo(doc.getProveedor().getCodProveed()) == 0){
contador += 1;
}
}
}
if(contador > 1){
return false;
}
return true;
}
public String borrarReciboProveedor(){
eliminar = true;
Collection<RecibosProvDet> recibosProveedoresABorrar = reciboProvSeleccionado.getRecibosProvDetCollection();
Collection<RecibosProvCheques> recibosChequesDeProveedoresABorrar = reciboProvSeleccionado.getRecibosProvChequesCollection();
try{
recibosProvFacade.borrarRecibosDelProveedor(reciboProvSeleccionado.getProveedores().getCodProveed(), reciboProvSeleccionado.getRecibosProvPK().getNrecibo());
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al eliminar un recibo compra.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
for(RecibosProvDet reciboDet: recibosProveedoresABorrar){
try{
if(reciboDet.getRecibosProvDetPK().getCtipoDocum().equals("FCC")){
String nroReciboStr = String.valueOf(reciboDet.getRecibosProvDetPK().getNrecibo());
cuentasProveedoresFacade.borrarRecibosProveedores(reciboDet.getRecibosProvDetPK().getCodProveed(), nroReciboStr, reciboDet.getRecibosProvDetPK().getNrofact(), reciboDet.getRecibosProvDetPK().getCtipoDocum());
}else{
String nroReciboStr = String.valueOf(reciboDet.getRecibosProvDetPK().getNrecibo());
cuentasProveedoresFacade.borrarOtrosRecibosProveedores(reciboDet.getRecibosProvDetPK().getCodProveed(), nroReciboStr, reciboDet.getRecibosProvDetPK().getNrofact(), reciboDet.getRecibosProvDetPK().getCtipoDocum());
}
if(reciboDet.getRecibosProvDetPK().getCtipoDocum().equals("NCC")){
try{
String lFFactura = dateToString(reciboDet.getFfactur());
notasComprasFacade.aumentaSaldoNotasCompras(reciboDet.getItotal(), lFFactura, reciboDet.getRecibosProvDetPK().getNrofact(), reciboDet.getRecibosProvDetPK().getCodProveed());
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al actualizar notas de créditos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en eliminación de cuentas proveedores.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
for(RecibosProvCheques reciboChequeDet: recibosChequesDeProveedoresABorrar){
try{
cuentasProveedoresFacade.borrarChequesProveedores( reciboChequeDet.getRecibosProvChequesPK().getCodProveed(),
reciboChequeDet.getRecibosProvChequesPK().getNroCheque(),
reciboChequeDet.getRecibosProvChequesPK().getCodBanco());
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en eliminación de cheques en cuentas proveedores.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
limpiarFormulario();
RequestContext.getCurrentInstance().execute("PF('dlgAnularReciboCompra').hide();");
return null;
}
public List<TiposDocumentos> listarTiposDocumentos(){
listadoTiposDocumentos = new ArrayList<>();
try{
listadoTiposDocumentos = tiposDocumentosFacade.listarTipoDocumentoParaReciboCompraProveedor();
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de tipos de documentos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
return listadoTiposDocumentos;
}
public void onRowSelect(SelectEvent event) {
if(reciboProvSeleccionado != null){
if(reciboProvSeleccionado.getRecibosProvPK().getNrecibo() != 0){
setHabilitaBotonEliminar(false);
}else{
setHabilitaBotonEliminar(true);
}
}
}
private void estabecerEstado(){
switch(estadoLblSeleccionado){
case 1: estadoLbl = 'A';
break;
case 2: estadoLbl = 'I';
break;
case 3: estadoLbl = 0;
break;
}
}
public void cargarDetalleDocumentos(){
try{
if(validarNroDocumentoDet()){
switch (tipoDocumentoSeleccionadoDet.getCtipoDocum()) {
case "FCC":
if(procesarFacturaCompra()){
//cargar en la lista de documentos
DocumentoCompraDto dcdto = new DocumentoCompraDto();
dcdto.setTipoDocumento(tipoDocumentoSeleccionadoDet);
dcdto.setProveedor(proveedorSeleccionadoLbl);
dcdto.setFechaDocumento(fechaDocumentoDet);
dcdto.setFechaRecibo(fechaReciboLbl);
dcdto.setMontoAPagarDocumento(montoAPagarDet);
dcdto.setMontoDocumento(montoFacturaDet);
dcdto.setSaldoDocumento(saldoDocumento);
dcdto.setNroDcumento(nroDocumentoDet);
dcdto.setNroRecibo(nroReciboLbl);
dcdto.setObservacion(observacionLbl);
dcdto.setComCtipoDocum(comCtipoDocum);
dcdto.setComFfactur(comFfactur);
dcdto.setComNrofact(comNrofact);
dcdto.setCanalCompra(canalCompraDet);
dcdto.setFechaVencimiento(fechaVencDet);
listadoDocumentoCompraDto.add(dcdto);
calcularTotalRecibo();
//limpiar
tipoDocumentoSeleccionadoDet = null;
fechaDocumentoDet = null;
nroDocumentoDet = 0;
}
break;
case "NCC":
if(procesarNotaCredito()){
//cargar en la lista de documentos
DocumentoCompraDto dcdto = new DocumentoCompraDto();
dcdto.setTipoDocumento(tipoDocumentoSeleccionadoDet);
dcdto.setProveedor(proveedorSeleccionadoLbl);
dcdto.setFechaDocumento(fechaDocumentoDet);
dcdto.setFechaRecibo(fechaReciboLbl);
dcdto.setMontoAPagarDocumento(montoAPagarDet);
dcdto.setMontoDocumento(montoFacturaDet);
dcdto.setSaldoDocumento(saldoDocumento);
dcdto.setNroDcumento(nroDocumentoDet);
dcdto.setNroRecibo(nroReciboLbl);
dcdto.setObservacion(observacionLbl);
dcdto.setComCtipoDocum(comCtipoDocum);
dcdto.setComFfactur(comFfactur);
dcdto.setComNrofact(comNrofact);
dcdto.setCanalCompra(canalCompraDet);
dcdto.setFechaVencimiento(fechaVencDet);
listadoDocumentoCompraDto.add(dcdto);
calcularTotalRecibo();
}
break;
case "NDC":
if(procesarNotaDebito()){
//cargar en la lista de documentos
DocumentoCompraDto dcdto = new DocumentoCompraDto();
dcdto.setTipoDocumento(tipoDocumentoSeleccionadoDet);
dcdto.setProveedor(proveedorSeleccionadoLbl);
dcdto.setFechaDocumento(fechaDocumentoDet);
dcdto.setFechaRecibo(fechaReciboLbl);
dcdto.setMontoAPagarDocumento(montoAPagarDet);
dcdto.setMontoDocumento(montoFacturaDet);
dcdto.setSaldoDocumento(saldoDocumento);
dcdto.setNroDcumento(nroDocumentoDet);
dcdto.setNroRecibo(nroReciboLbl);
dcdto.setObservacion(observacionLbl);
dcdto.setComCtipoDocum(comCtipoDocum);
dcdto.setComFfactur(comFfactur);
dcdto.setComNrofact(comNrofact);
dcdto.setCanalCompra(canalCompraDet);
dcdto.setFechaVencimiento(fechaVencDet);
listadoDocumentoCompraDto.add(dcdto);
calcularTotalRecibo();
}
break;
default:
break;
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al cargar un detalle de documentos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public void cargarDetalleCheques(){
try{
//listadoChequesEmitidos = new ArrayList<>();
if(validarIngresoCheques()){
ChequesEmitidosPK chequeEmitidoPK = new ChequesEmitidosPK();
chequeEmitidoPK.setCodEmpr(Short.parseShort("2"));
chequeEmitidoPK.setCodBanco(bancoSeleccionadoDet.getCodBanco());
chequeEmitidoPK.setNroCheque(nroChequeDet);
ChequesEmitidos chequeEmitido = new ChequesEmitidos();
chequeEmitido.setChequesEmitidosPK(chequeEmitidoPK);
chequeEmitido.setXcuentaBco(nroCtaBancaria);
chequeEmitido.setIcheque(importeChequeDet);
chequeEmitido.setFemision(fechaEmisionDet);
chequeEmitido.setFcheque(fechaChequeDet);
chequeEmitido.setCodProveed(proveedoresFacade.find(proveedorSeleccionadoLbl.getCodProveed()));
chequeEmitido.setBancos(bancosFacade.find(bancoSeleccionadoDet.getCodBanco()));
ChequeProveedorDto cpdto = new ChequeProveedorDto();
cpdto.setChequeEmitido(chequeEmitido);
cpdto.setImporteAPagar(importeAPagarChequeDet);
listadoChequesEmitidos.add(cpdto);
calcularTotalCheque();
bancoSeleccionadoDet = null;
nroChequeDet = null;
nroCtaBancaria = null;
fechaChequeDet = null;
fechaEmisionDet = null;
importeChequeDet = 0;
importeAPagarChequeDet = 0;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al cargar un detalle de cheques.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
private boolean validarIngresoCheques(){
if(bancoSeleccionadoDet == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe seleccionar un banco."));
return false;
}else{
if(bancoSeleccionadoDet.getCodBanco() == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe seleccionar un banco."));
return false;
}else{
if(nroChequeDet.equals("") || nroChequeDet == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe ingresar un nro. de cheque."));
return false;
}else{
if(nroCtaBancaria.equals("") || nroCtaBancaria == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe ingresar un nro. de cuenta bancaria."));
return false;
}else{
if(fechaChequeDet == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe ingresar la fecha del cheque."));
return false;
}else{
if(fechaEmisionDet == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe ingresar la fecha de emisión del cheque."));
return false;
}else{
if(importeChequeDet == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe ingresar el importe del cheque."));
return false;
}else{
if(proveedorSeleccionadoLbl == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe seleccionar un proveedor."));
return false;
}else{
if(proveedorSeleccionadoLbl.getCodProveed() == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe seleccionar un proveedor."));
return false;
}
}
}
}
}
}
}
}
}
return true;
}
public void borrarFilaDocumento(DocumentoCompraDto documentoCompraDtoABorrar){
try{
Iterator itr = listadoDocumentoCompraDto.iterator();
while (itr.hasNext()) {
DocumentoCompraDto documentoComptaDtoEnLista = (DocumentoCompraDto) itr.next();
if( documentoComptaDtoEnLista.getTipoDocumento().getCtipoDocum().equals(documentoCompraDtoABorrar.getTipoDocumento().getCtipoDocum()) &&
documentoComptaDtoEnLista.getProveedor().getCodProveed().compareTo(documentoCompraDtoABorrar.getProveedor().getCodProveed()) == 0 &&
documentoComptaDtoEnLista.getNroRecibo() == documentoCompraDtoABorrar.getNroRecibo() &&
documentoComptaDtoEnLista.getNroDcumento() == documentoCompraDtoABorrar.getNroDcumento() ){
itr.remove();
calcularTotalRecibo();
return;
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al borrar un detalle de la grilla de documentos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public void borrarFilaCheque(ChequeProveedorDto chequeABorrar){
try{
Iterator itr = listadoChequesEmitidos.iterator();
while (itr.hasNext()) {
ChequeProveedorDto chequeProveedorEnLista = (ChequeProveedorDto) itr.next();
if( chequeProveedorEnLista.getChequeEmitido().getChequesEmitidosPK().getCodBanco() == chequeABorrar.getChequeEmitido().getChequesEmitidosPK().getCodBanco() &&
chequeProveedorEnLista.getChequeEmitido().getChequesEmitidosPK().getNroCheque().equals(chequeABorrar.getChequeEmitido().getChequesEmitidosPK().getNroCheque()) &&
chequeProveedorEnLista.getChequeEmitido().getChequesEmitidosPK().getCodEmpr() == chequeABorrar.getChequeEmitido().getChequesEmitidosPK().getCodEmpr()){
itr.remove();
calcularTotalCheque();
return;
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al borrar un detalle de la grilla de cheques.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
private boolean validarNroDocumentoDet() {
try {
if(nroReciboLbl == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe ingresar el nro. de recibo de compra."));
return false;
}else{
if(nroDocumentoDet == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe ingresar el nro. de factura."));
return false;
}else{
if(proveedorSeleccionadoLbl == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe seleccionar un proveedor."));
return false;
}else{
if(proveedorSeleccionadoLbl.getCodProveed() == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe seleccionar un proveedor."));
return false;
}else{
if(tipoDocumentoSeleccionadoDet == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe seleccionar un tipo de documento."));
return false;
}else{
if(tipoDocumentoSeleccionadoDet.getCtipoDocum() == null || tipoDocumentoSeleccionadoDet.getCtipoDocum().equals("")){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Debe seleccionar un tipo de documento."));
return false;
}else{
if(verificarDuplicadosEnListadoDeDetalle()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "Este documento ya ha sido registrado."));
return false;
}else{
return true;
}
}
}
}
}
}
}
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la validacion del nro. de documento.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
}
private boolean procesarNotaDebito(){
//listadoNotasComprasDto = new ArrayList<>();
try{
if (fechaDocumentoDet == null) {
listadoNotasComprasDto = notasComprasFacade.maximaCompraDebitoDelProveedor(nroDocumentoDet, proveedorSeleccionadoLbl.getCodProveed());
}else{
String fechaDocumentoDetStr = fechaDocumentoDet == null ? "" : dateToString(fechaDocumentoDet);
listadoNotasComprasDto = notasComprasFacade.comprasDebitoPorNroNotaFechaProveedor(nroDocumentoDet, proveedorSeleccionadoLbl.getCodProveed(), fechaDocumentoDetStr);
}
if(listadoNotasComprasDto.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "No existe nota de credito."));
return false;
}else{
for(NotasComprasDto ncdto: listadoNotasComprasDto){
montoFacturaDet = ncdto.getNotaCompra().getTtotal();
montoAPagarDet = ncdto.getNotaCompra().getIsaldo();
comCtipoDocum = ncdto.getNotaCompra().getCompras().getComprasPK().getCtipoDocum();
comFfactur = ncdto.getNotaCompra().getCompras().getComprasPK().getFfactur();
comNrofact = ncdto.getNotaCompra().getCompras().getComprasPK().getNrofact();
fechaDocumentoDet = ncdto.getNotaCompra().getNotasComprasPK().getFdocum(); //está bien?
montoAPagarDet = ncdto.getNotaCompra().getTtotal();
montoFacturaDet = ncdto.getNotaCompra().getTtotal();
saldoDocumento = ncdto.getNotaCompra().getIsaldo();
canalCompraDet = ncdto.getNotaCompra().getCompras().getCcanalCompra();
fechaVencDet = ncdto.getNotaCompra().getCompras().getFvenc();
}
}
return true;
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de notas de debitos de compras.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
}
private boolean procesarNotaCredito(){
//listadoNotasComprasDto = new ArrayList<>();
try{
if (fechaDocumentoDet == null) {
listadoNotasComprasDto = notasComprasFacade.maximaCompraCreditoDelProveedor(nroDocumentoDet, proveedorSeleccionadoLbl.getCodProveed());
}else{
String fechaDocumentoDetStr = fechaDocumentoDet == null ? "" : dateToString(fechaDocumentoDet);
listadoNotasComprasDto = notasComprasFacade.comprasCreditoPorNroNotaFechaProveedor(nroDocumentoDet, proveedorSeleccionadoLbl.getCodProveed(), fechaDocumentoDetStr);
}
if(listadoNotasComprasDto.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "No existe nota de credito."));
return false;
}else{
for(NotasComprasDto ncdto: listadoNotasComprasDto){
montoFacturaDet = ncdto.getNotaCompra().getTtotal();
montoAPagarDet = ncdto.getNotaCompra().getIsaldo();
comCtipoDocum = ncdto.getNotaCompra().getCompras().getComprasPK().getCtipoDocum();
comFfactur = ncdto.getNotaCompra().getCompras().getComprasPK().getFfactur();
comNrofact = ncdto.getNotaCompra().getCompras().getComprasPK().getNrofact();
fechaDocumentoDet = ncdto.getNotaCompra().getNotasComprasPK().getFdocum(); //está bien?
montoAPagarDet = ncdto.getNotaCompra().getTtotal() * -1;
montoFacturaDet = ncdto.getNotaCompra().getTtotal() * -1;
saldoDocumento = ncdto.getNotaCompra().getIsaldo();
canalCompraDet = ncdto.getNotaCompra().getCompras().getCcanalCompra();
fechaVencDet = ncdto.getNotaCompra().getCompras().getFvenc();
}
}
return true;
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de notas de creditos de compras.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
}
private boolean procesarFacturaCompra() {
//listadoDocumentoCompraDto = new ArrayList<>();
try {
if (fechaDocumentoDet == null) {
listadoCompraDto = comprasFacade.maximaCompraContadoDelProveedor(nroDocumentoDet, proveedorSeleccionadoLbl.getCodProveed());
}else {
String fechaDocumentoDetStr = fechaDocumentoDet == null ? "" : dateToString(fechaDocumentoDet);
listadoCompraDto = comprasFacade.comprasContadoPorFechaNroFacturaProveedor(nroDocumentoDet, proveedorSeleccionadoLbl.getCodProveed(), fechaDocumentoDetStr);
}
if(listadoCompraDto.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención ", "No existe factura credito."));
return false;
}else{
for(CompraDto cdto: listadoCompraDto){
montoFacturaDet = cdto.getCompra().getTtotal();
montoAPagarDet = cdto.getCompra().getIsaldo();
saldoDocumento = cdto.getCompra().getIsaldo();
//cargar al detalle
comCtipoDocum = cdto.getCompra().getComprasPK().getCtipoDocum();
comFfactur = cdto.getCompra().getComprasPK().getFfactur();
comNrofact = cdto.getCompra().getComprasPK().getNrofact();
canalCompraDet = cdto.getCompra().getCcanalCompra();
fechaVencDet = cdto.getCompra().getFvenc();
}
}
return true;
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de facturas de compras.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private boolean verificarDuplicadosEnListadoDeDetalle(){
for(DocumentoCompraDto dcdto: listadoDocumentoCompraDto){
if( dcdto.getNroRecibo() == nroReciboLbl &&
dcdto.getNroDcumento() == nroDocumentoDet &&
dcdto.getProveedor().getCodProveed().compareTo(proveedorSeleccionadoLbl.getCodProveed()) == 0 &&
dcdto.getTipoDocumento().getCtipoDocum().equals(tipoDocumentoSeleccionadoDet.getCtipoDocum())){
return true;
}
}
return false;
}
private void calcularTotalRecibo(){
totalReciboLbl = 0;
if(!listadoDocumentoCompraDto.isEmpty()){
for(DocumentoCompraDto dcdto: listadoDocumentoCompraDto){
totalReciboLbl += dcdto.getMontoDocumento();
}
}
}
private void calcularTotalCheque(){
totalCheques = 0;
if(!listadoChequesEmitidos.isEmpty()){
for(ChequeProveedorDto ce: listadoChequesEmitidos){
totalCheques += ce.getChequeEmitido().getIcheque();
}
}
}
public void cerrarDialogoSinGuardar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarRecibos').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevReciboCompra').hide();");
}
public void onCellEdit(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if(!oldValue.equals(newValue)){
DataTable table = (DataTable) event.getSource();
DocumentoCompraDto documentoDtoRow = (DocumentoCompraDto) table.getRowData();
getDocumentoCompraDto().setMontoAPagarDocumento(documentoDtoRow.getMontoAPagarDocumento());
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO,"Monto a pagar actualizado.", ""));
}
}
public List<RecibosProv> getListadoRecibosProv() {
return listadoRecibosProv;
}
public void setListadoRecibosProv(List<RecibosProv> listadoRecibosProv) {
this.listadoRecibosProv = listadoRecibosProv;
}
public String getContenidoError() {
return contenidoError;
}
public void setContenidoError(String contenidoError) {
this.contenidoError = contenidoError;
}
public String getTituloError() {
return tituloError;
}
public void setTituloError(String tituloError) {
this.tituloError = tituloError;
}
public boolean isAgregar() {
return agregar;
}
public void setAgregar(boolean agregar) {
this.agregar = agregar;
}
public boolean isAnular() {
return anular;
}
public void setAnular(boolean anular) {
this.anular = anular;
}
public boolean isEliminar() {
return eliminar;
}
public void setEliminar(boolean eliminar) {
this.eliminar = eliminar;
}
public List<Proveedores> getListadoProveedores() {
return listadoProveedores;
}
public void setListadoProveedores(List<Proveedores> listadoProveedores) {
this.listadoProveedores = listadoProveedores;
}
public List<TiposDocumentos> getListadoTiposDocumentos() {
return listadoTiposDocumentos;
}
public void setListadoTiposDocumentos(List<TiposDocumentos> listadoTiposDocumentos) {
this.listadoTiposDocumentos = listadoTiposDocumentos;
}
public RecibosProv getReciboProvSeleccionado() {
return reciboProvSeleccionado;
}
public void setReciboProvSeleccionado(RecibosProv reciboProvSeleccionado) {
this.reciboProvSeleccionado = reciboProvSeleccionado;
}
public Proveedores getProveedorSeleccionadoLbl() {
return proveedorSeleccionadoLbl;
}
public void setProveedorSeleccionadoLbl(Proveedores proveedorSeleccionadoLbl) {
this.proveedorSeleccionadoLbl = proveedorSeleccionadoLbl;
}
public Date getFechaReciboLbl() {
return fechaReciboLbl;
}
public void setFechaReciboLbl(Date fechaReciboLbl) {
this.fechaReciboLbl = fechaReciboLbl;
}
public long getNroReciboLbl() {
return nroReciboLbl;
}
public void setNroReciboLbl(long nroReciboLbl) {
this.nroReciboLbl = nroReciboLbl;
}
public String getObservacionLbl() {
return observacionLbl;
}
public void setObservacionLbl(String observacionLbl) {
this.observacionLbl = observacionLbl;
}
public Character getEstadoLbl() {
return estadoLbl;
}
public void setEstadoLbl(Character estadoLbl) {
this.estadoLbl = estadoLbl;
}
public int getEstadoLblSeleccionado() {
return estadoLblSeleccionado;
}
public void setEstadoLblSeleccionado(int estadoLblSeleccionado) {
this.estadoLblSeleccionado = estadoLblSeleccionado;
}
public long getTotalReciboLbl() {
return totalReciboLbl;
}
public void setTotalReciboLbl(long totalReciboLbl) {
this.totalReciboLbl = totalReciboLbl;
}
public TiposDocumentos getTipoDocumentoSeleccionadoDet() {
return tipoDocumentoSeleccionadoDet;
}
public void setTipoDocumentoSeleccionadoDet(TiposDocumentos tipoDocumentoSeleccionadoDet) {
this.tipoDocumentoSeleccionadoDet = tipoDocumentoSeleccionadoDet;
}
public Date getFechaDocumentoDet() {
return fechaDocumentoDet;
}
public void setFechaDocumentoDet(Date fechaDocumentoDet) {
this.fechaDocumentoDet = fechaDocumentoDet;
}
public long getNroDocumentoDet() {
return nroDocumentoDet;
}
public void setNroDocumentoDet(long nroDocumentoDet) {
this.nroDocumentoDet = nroDocumentoDet;
}
public long getMontoAPagarDet() {
return montoAPagarDet;
}
public void setMontoAPagarDet(long montoAPagarDet) {
this.montoAPagarDet = montoAPagarDet;
}
public long getMontoFacturaDet() {
return montoFacturaDet;
}
public void setMontoFacturaDet(long montoFacturaDet) {
this.montoFacturaDet = montoFacturaDet;
}
public List<DocumentoCompraDto> getListadoDocumentoCompraDto() {
return listadoDocumentoCompraDto;
}
public void setListadoDocumentoCompraDto(List<DocumentoCompraDto> listadoDocumentoCompraDto) {
this.listadoDocumentoCompraDto = listadoDocumentoCompraDto;
}
public long getSaldoDocumento() {
return saldoDocumento;
}
public void setSaldoDocumento(long saldoDocumento) {
this.saldoDocumento = saldoDocumento;
}
public DocumentoCompraDto getDocumentoCompraDto() {
return documentoCompraDto;
}
public void setDocumentoCompraDto(DocumentoCompraDto documentoCompraDto) {
this.documentoCompraDto = documentoCompraDto;
}
public long getTotalEfectivo() {
return totalEfectivo;
}
public void setTotalEfectivo(long totalEfectivo) {
this.totalEfectivo = totalEfectivo;
}
public long getTotalRetencion() {
return totalRetencion;
}
public void setTotalRetencion(long totalRetencion) {
this.totalRetencion = totalRetencion;
}
public long getTotalCheques() {
return totalCheques;
}
public void setTotalCheques(long totalCheques) {
this.totalCheques = totalCheques;
}
public Bancos getBancoSeleccionadoDet() {
return bancoSeleccionadoDet;
}
public void setBancoSeleccionadoDet(Bancos bancoSeleccionadoDet) {
this.bancoSeleccionadoDet = bancoSeleccionadoDet;
}
public String getNroChequeDet() {
return nroChequeDet;
}
public void setNroChequeDet(String nroChequeDet) {
this.nroChequeDet = nroChequeDet;
}
public String getNroCtaBancaria() {
return nroCtaBancaria;
}
public void setNroCtaBancaria(String nroCtaBancaria) {
this.nroCtaBancaria = nroCtaBancaria;
}
public Date getFechaChequeDet() {
return fechaChequeDet;
}
public void setFechaChequeDet(Date fechaChequeDet) {
this.fechaChequeDet = fechaChequeDet;
}
public Date getFechaEmisionDet() {
return fechaEmisionDet;
}
public void setFechaEmisionDet(Date fechaEmisionDet) {
this.fechaEmisionDet = fechaEmisionDet;
}
public long getImporteChequeDet() {
return importeChequeDet;
}
public void setImporteChequeDet(long importeChequeDet) {
this.importeChequeDet = importeChequeDet;
}
public List<ChequeProveedorDto> getListadoChequesEmitidos() {
return listadoChequesEmitidos;
}
public void setListadoChequesEmitidos(List<ChequeProveedorDto> listadoChequesEmitidos) {
this.listadoChequesEmitidos = listadoChequesEmitidos;
}
public ChequesEmitidos getChequeEmitidoSeleccionadoDet() {
return chequeEmitidoSeleccionadoDet;
}
public void setChequeEmitidoSeleccionadoDet(ChequesEmitidos chequeEmitidoSeleccionadoDet) {
this.chequeEmitidoSeleccionadoDet = chequeEmitidoSeleccionadoDet;
}
public long getImporteAPagarChequeDet() {
return importeAPagarChequeDet;
}
public void setImporteAPagarChequeDet(long importeAPagarChequeDet) {
this.importeAPagarChequeDet = importeAPagarChequeDet;
}
public boolean isHabilitaBotonEliminar() {
return habilitaBotonEliminar;
}
public void setHabilitaBotonEliminar(boolean habilitaBotonEliminar) {
this.habilitaBotonEliminar = habilitaBotonEliminar;
}
}<file_sep>/SisVenLog-ejb/src/java/entidad/SaldosProveedores.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "saldos_proveedores")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "SaldosProveedores.findAll", query = "SELECT s FROM SaldosProveedores s")
, @NamedQuery(name = "SaldosProveedores.findByCodEmpr", query = "SELECT s FROM SaldosProveedores s WHERE s.saldosProveedoresPK.codEmpr = :codEmpr")
, @NamedQuery(name = "SaldosProveedores.findByCodProveed", query = "SELECT s FROM SaldosProveedores s WHERE s.saldosProveedoresPK.codProveed = :codProveed")
, @NamedQuery(name = "SaldosProveedores.findByFmovim", query = "SELECT s FROM SaldosProveedores s WHERE s.saldosProveedoresPK.fmovim = :fmovim")
, @NamedQuery(name = "SaldosProveedores.findByNmes", query = "SELECT s FROM SaldosProveedores s WHERE s.nmes = :nmes")
, @NamedQuery(name = "SaldosProveedores.findByIsaldo", query = "SELECT s FROM SaldosProveedores s WHERE s.isaldo = :isaldo")
, @NamedQuery(name = "SaldosProveedores.findByAcumDebi", query = "SELECT s FROM SaldosProveedores s WHERE s.acumDebi = :acumDebi")
, @NamedQuery(name = "SaldosProveedores.findByAcumCredi", query = "SELECT s FROM SaldosProveedores s WHERE s.acumCredi = :acumCredi")
, @NamedQuery(name = "SaldosProveedores.findByCcanalCompra", query = "SELECT s FROM SaldosProveedores s WHERE s.ccanalCompra = :ccanalCompra")})
public class SaldosProveedores implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected SaldosProveedoresPK saldosProveedoresPK;
@Basic(optional = false)
@NotNull
@Column(name = "nmes")
private short nmes;
@Basic(optional = false)
@NotNull
@Column(name = "isaldo")
private long isaldo;
@Basic(optional = false)
@NotNull
@Column(name = "acum_debi")
private long acumDebi;
@Basic(optional = false)
@NotNull
@Column(name = "acum_credi")
private long acumCredi;
@Size(max = 2)
@Column(name = "ccanal_compra")
private String ccanalCompra;
public SaldosProveedores() {
}
public SaldosProveedores(SaldosProveedoresPK saldosProveedoresPK) {
this.saldosProveedoresPK = saldosProveedoresPK;
}
public SaldosProveedores(SaldosProveedoresPK saldosProveedoresPK, short nmes, long isaldo, long acumDebi, long acumCredi) {
this.saldosProveedoresPK = saldosProveedoresPK;
this.nmes = nmes;
this.isaldo = isaldo;
this.acumDebi = acumDebi;
this.acumCredi = acumCredi;
}
public SaldosProveedores(short codEmpr, short codProveed, Date fmovim) {
this.saldosProveedoresPK = new SaldosProveedoresPK(codEmpr, codProveed, fmovim);
}
public SaldosProveedoresPK getSaldosProveedoresPK() {
return saldosProveedoresPK;
}
public void setSaldosProveedoresPK(SaldosProveedoresPK saldosProveedoresPK) {
this.saldosProveedoresPK = saldosProveedoresPK;
}
public short getNmes() {
return nmes;
}
public void setNmes(short nmes) {
this.nmes = nmes;
}
public long getIsaldo() {
return isaldo;
}
public void setIsaldo(long isaldo) {
this.isaldo = isaldo;
}
public long getAcumDebi() {
return acumDebi;
}
public void setAcumDebi(long acumDebi) {
this.acumDebi = acumDebi;
}
public long getAcumCredi() {
return acumCredi;
}
public void setAcumCredi(long acumCredi) {
this.acumCredi = acumCredi;
}
public String getCcanalCompra() {
return ccanalCompra;
}
public void setCcanalCompra(String ccanalCompra) {
this.ccanalCompra = ccanalCompra;
}
@Override
public int hashCode() {
int hash = 0;
hash += (saldosProveedoresPK != null ? saldosProveedoresPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof SaldosProveedores)) {
return false;
}
SaldosProveedores other = (SaldosProveedores) object;
if ((this.saldosProveedoresPK == null && other.saldosProveedoresPK != null) || (this.saldosProveedoresPK != null && !this.saldosProveedoresPK.equals(other.saldosProveedoresPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.SaldosProveedores[ saldosProveedoresPK=" + saldosProveedoresPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/FacturasSer.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "facturas_ser")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "FacturasSer.findAll", query = "SELECT f FROM FacturasSer f")
, @NamedQuery(name = "FacturasSer.findByCodEmpr", query = "SELECT f FROM FacturasSer f WHERE f.facturasSerPK.codEmpr = :codEmpr")
, @NamedQuery(name = "FacturasSer.findByNrofact", query = "SELECT f FROM FacturasSer f WHERE f.facturasSerPK.nrofact = :nrofact")
, @NamedQuery(name = "FacturasSer.findByCtipoDocum", query = "SELECT f FROM FacturasSer f WHERE f.facturasSerPK.ctipoDocum = :ctipoDocum")
, @NamedQuery(name = "FacturasSer.findByFfactur", query = "SELECT f FROM FacturasSer f WHERE f.facturasSerPK.ffactur = :ffactur")
, @NamedQuery(name = "FacturasSer.findByCodServicio", query = "SELECT f FROM FacturasSer f WHERE f.facturasSerPK.codServicio = :codServicio")
, @NamedQuery(name = "FacturasSer.findByIexentas", query = "SELECT f FROM FacturasSer f WHERE f.iexentas = :iexentas")
, @NamedQuery(name = "FacturasSer.findByIgravadas", query = "SELECT f FROM FacturasSer f WHERE f.igravadas = :igravadas")
, @NamedQuery(name = "FacturasSer.findByIdescuentos", query = "SELECT f FROM FacturasSer f WHERE f.idescuentos = :idescuentos")
, @NamedQuery(name = "FacturasSer.findByItotal", query = "SELECT f FROM FacturasSer f WHERE f.itotal = :itotal")
, @NamedQuery(name = "FacturasSer.findByImpuestos", query = "SELECT f FROM FacturasSer f WHERE f.impuestos = :impuestos")
, @NamedQuery(name = "FacturasSer.findByPimpues", query = "SELECT f FROM FacturasSer f WHERE f.pimpues = :pimpues")})
public class FacturasSer implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected FacturasSerPK facturasSerPK;
@Column(name = "iexentas")
private Long iexentas;
@Column(name = "igravadas")
private Long igravadas;
@Column(name = "idescuentos")
private Long idescuentos;
@Column(name = "itotal")
private Long itotal;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "impuestos")
private BigDecimal impuestos;
@Column(name = "pimpues")
private BigDecimal pimpues;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "nrofact", referencedColumnName = "nrofact", insertable = false, updatable = false)
, @JoinColumn(name = "ctipo_docum", referencedColumnName = "ctipo_docum", insertable = false, updatable = false)
, @JoinColumn(name = "ffactur", referencedColumnName = "ffactur", insertable = false, updatable = false)})
@ManyToOne(optional = false)
private Facturas facturas;
public FacturasSer() {
}
public FacturasSer(FacturasSerPK facturasSerPK) {
this.facturasSerPK = facturasSerPK;
}
public FacturasSer(short codEmpr, long nrofact, String ctipoDocum, Date ffactur, short codServicio) {
this.facturasSerPK = new FacturasSerPK(codEmpr, nrofact, ctipoDocum, ffactur, codServicio);
}
public FacturasSerPK getFacturasSerPK() {
return facturasSerPK;
}
public void setFacturasSerPK(FacturasSerPK facturasSerPK) {
this.facturasSerPK = facturasSerPK;
}
public Long getIexentas() {
return iexentas;
}
public void setIexentas(Long iexentas) {
this.iexentas = iexentas;
}
public Long getIgravadas() {
return igravadas;
}
public void setIgravadas(Long igravadas) {
this.igravadas = igravadas;
}
public Long getIdescuentos() {
return idescuentos;
}
public void setIdescuentos(Long idescuentos) {
this.idescuentos = idescuentos;
}
public Long getItotal() {
return itotal;
}
public void setItotal(Long itotal) {
this.itotal = itotal;
}
public BigDecimal getImpuestos() {
return impuestos;
}
public void setImpuestos(BigDecimal impuestos) {
this.impuestos = impuestos;
}
public BigDecimal getPimpues() {
return pimpues;
}
public void setPimpues(BigDecimal pimpues) {
this.pimpues = pimpues;
}
public Facturas getFacturas() {
return facturas;
}
public void setFacturas(Facturas facturas) {
this.facturas = facturas;
}
@Override
public int hashCode() {
int hash = 0;
hash += (facturasSerPK != null ? facturasSerPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof FacturasSer)) {
return false;
}
FacturasSer other = (FacturasSer) object;
if ((this.facturasSerPK == null && other.facturasSerPK != null) || (this.facturasSerPK != null && !this.facturasSerPK.equals(other.facturasSerPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.FacturasSer[ facturasSerPK=" + facturasSerPK + " ]";
}
}
<file_sep>/SisVenLog-war/src/java/bean/ImpresionOrdenPagoBean.java
package bean;
import java.io.IOException;
import javax.annotation.PostConstruct;
import javax.faces.application.*;
import javax.faces.bean.*;
import javax.faces.context.*;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class ImpresionOrdenPagoBean {
private Integer nroinicial;
private Integer nrofinal;
private String destination = System.getProperty("java.io.tmpdir");
public ImpresionOrdenPagoBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
nroinicial = 1;
nrofinal = 1;
}
public void impresion() {
try {
LlamarReportes rep = new LlamarReportes();
//generamos los pdf para imprimir
rep.impresionOrdenPago(nroinicial, nrofinal);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atencion.", "Proceso de impresion correcto."));
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error durante la impresion", null));
}
}
public void vistaPrevia() {
try {
LlamarReportes rep = new LlamarReportes();
//generamos los pdf para imprimir
rep.vistaPreviaOrdenPago(nroinicial, nrofinal);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atencion.", "Proceso de impresion correcto."));
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error durante la impresion", null));
}
}
//Getters & Setters
public Integer getNroinicial() {
return nroinicial;
}
public void setNroinicial(Integer nroinicial) {
this.nroinicial = nroinicial;
}
public Integer getNrofinal() {
return nrofinal;
}
public void setNrofinal(Integer nrofinal) {
this.nrofinal = nrofinal;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Envios.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author admin
*/
@Entity
@Table(name = "envios")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Envios.findAll", query = "SELECT e FROM Envios e")
, @NamedQuery(name = "Envios.findByCodEmpr", query = "SELECT e FROM Envios e WHERE e.enviosPK.codEmpr = :codEmpr")
, @NamedQuery(name = "Envios.findByNroEnvio", query = "SELECT e FROM Envios e WHERE e.enviosPK.nroEnvio = :nroEnvio")
, @NamedQuery(name = "Envios.findByCodEntregador", query = "SELECT e FROM Envios e WHERE e.codEntregador = :codEntregador")
, @NamedQuery(name = "Envios.findByCodCanal", query = "SELECT e FROM Envios e WHERE e.codCanal = :codCanal")
, @NamedQuery(name = "Envios.findByDepoOrigen", query = "SELECT e FROM Envios e WHERE e.depoOrigen = :depoOrigen")
, @NamedQuery(name = "Envios.findByDepoDestino", query = "SELECT e FROM Envios e WHERE e.depoDestino = :depoDestino")
, @NamedQuery(name = "Envios.findByFenvio", query = "SELECT e FROM Envios e WHERE e.fenvio = :fenvio")
, @NamedQuery(name = "Envios.findByFanul", query = "SELECT e FROM Envios e WHERE e.fanul = :fanul")
, @NamedQuery(name = "Envios.findByFfactur", query = "SELECT e FROM Envios e WHERE e.ffactur = :ffactur")
, @NamedQuery(name = "Envios.findByTotPeso", query = "SELECT e FROM Envios e WHERE e.totPeso = :totPeso")
, @NamedQuery(name = "Envios.findByMestado", query = "SELECT e FROM Envios e WHERE e.mestado = :mestado")
, @NamedQuery(name = "Envios.findByXobs", query = "SELECT e FROM Envios e WHERE e.xobs = :xobs")
, @NamedQuery(name = "Envios.findByCusuario", query = "SELECT e FROM Envios e WHERE e.cusuario = :cusuario")
, @NamedQuery(name = "Envios.findByFalta", query = "SELECT e FROM Envios e WHERE e.falta = :falta")
, @NamedQuery(name = "Envios.findByCusuarioModif", query = "SELECT e FROM Envios e WHERE e.cusuarioModif = :cusuarioModif")
, @NamedQuery(name = "Envios.findByFultimModif", query = "SELECT e FROM Envios e WHERE e.fultimModif = :fultimModif")
, @NamedQuery(name = "Envios.findByMtipo", query = "SELECT e FROM Envios e WHERE e.mtipo = :mtipo")})
public class Envios implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected EnviosPK enviosPK;
@Column(name = "cod_entregador")
private Short codEntregador;
@Size(max = 2)
@Column(name = "cod_canal")
private String codCanal;
@Basic(optional = false)
@NotNull(message="Se debe especificar el deposito origen.")
@Column(name = "depo_origen")
private short depoOrigen;
@Basic(optional = false)
@NotNull(message="Se debe especificar el deposito destino.")
@Column(name = "depo_destino")
private short depoDestino;
@Basic(optional = false)
@NotNull(message="Se debe especificar la fecha de envio.")
@Column(name = "fenvio")
@Temporal(TemporalType.TIMESTAMP)
private Date fenvio;
@Column(name = "fanul")
@Temporal(TemporalType.TIMESTAMP)
private Date fanul;
@Column(name = "ffactur")
@Temporal(TemporalType.TIMESTAMP)
private Date ffactur;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Basic(optional = false)
@NotNull(message="Se debe especificar el total peso.")
@Column(name = "tot_peso")
private BigDecimal totPeso;
@Basic(optional = false)
@NotNull(message="Se debe especificar el estado de envio.")
@Column(name = "mestado")
private Character mestado;
@Size(max = 250)
@Column(name = "xobs")
private String xobs;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@Basic(optional = false)
@NotNull(message="Se debe especificar el tipo de envio.")
@Column(name = "mtipo")
private Character mtipo;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "envios")
private Collection<EnviosDet> enviosDetCollection;
public Envios() {
}
public Envios(EnviosPK enviosPK) {
this.enviosPK = enviosPK;
}
public Envios(EnviosPK enviosPK, short depoOrigen, short depoDestino, Date fenvio, BigDecimal totPeso, Character mestado, Character mtipo) {
this.enviosPK = enviosPK;
this.depoOrigen = depoOrigen;
this.depoDestino = depoDestino;
this.fenvio = fenvio;
this.totPeso = totPeso;
this.mestado = mestado;
this.mtipo = mtipo;
}
public Envios(short codEmpr, long nroEnvio) {
this.enviosPK = new EnviosPK(codEmpr, nroEnvio);
}
public EnviosPK getEnviosPK() {
return enviosPK;
}
public void setEnviosPK(EnviosPK enviosPK) {
this.enviosPK = enviosPK;
}
public Short getCodEntregador() {
return codEntregador;
}
public void setCodEntregador(Short codEntregador) {
this.codEntregador = codEntregador;
}
public String getCodCanal() {
return codCanal;
}
public void setCodCanal(String codCanal) {
this.codCanal = codCanal;
}
public short getDepoOrigen() {
return depoOrigen;
}
public void setDepoOrigen(short depoOrigen) {
this.depoOrigen = depoOrigen;
}
public short getDepoDestino() {
return depoDestino;
}
public void setDepoDestino(short depoDestino) {
this.depoDestino = depoDestino;
}
public Date getFenvio() {
return fenvio;
}
public void setFenvio(Date fenvio) {
this.fenvio = fenvio;
}
public Date getFanul() {
return fanul;
}
public void setFanul(Date fanul) {
this.fanul = fanul;
}
public Date getFfactur() {
return ffactur;
}
public void setFfactur(Date ffactur) {
this.ffactur = ffactur;
}
public BigDecimal getTotPeso() {
return totPeso;
}
public void setTotPeso(BigDecimal totPeso) {
this.totPeso = totPeso;
}
public Character getMestado() {
return mestado;
}
public void setMestado(Character mestado) {
this.mestado = mestado;
}
public String getXobs() {
return xobs;
}
public void setXobs(String xobs) {
this.xobs = xobs;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public Character getMtipo() {
return mtipo;
}
public void setMtipo(Character mtipo) {
this.mtipo = mtipo;
}
@XmlTransient
public Collection<EnviosDet> getEnviosDetCollection() {
return enviosDetCollection;
}
public void setEnviosDetCollection(Collection<EnviosDet> enviosDetCollection) {
this.enviosDetCollection = enviosDetCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (enviosPK != null ? enviosPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Envios)) {
return false;
}
Envios other = (Envios) object;
if ((this.enviosPK == null && other.enviosPK != null) || (this.enviosPK != null && !this.enviosPK.equals(other.enviosPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Envios[ enviosPK=" + enviosPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/SublineasVendedores.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "sublineas_vendedores")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "SublineasVendedores.findAll", query = "SELECT s FROM SublineasVendedores s")
, @NamedQuery(name = "SublineasVendedores.findByCodEmpr", query = "SELECT s FROM SublineasVendedores s WHERE s.sublineasVendedoresPK.codEmpr = :codEmpr")
, @NamedQuery(name = "SublineasVendedores.findByCodVendedor", query = "SELECT s FROM SublineasVendedores s WHERE s.sublineasVendedoresPK.codVendedor = :codVendedor")
, @NamedQuery(name = "SublineasVendedores.findByFalta", query = "SELECT s FROM SublineasVendedores s WHERE s.falta = :falta")
, @NamedQuery(name = "SublineasVendedores.findByCusuario", query = "SELECT s FROM SublineasVendedores s WHERE s.cusuario = :cusuario")})
public class SublineasVendedores implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected SublineasVendedoresPK sublineasVendedoresPK;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 10)
@Column(name = "cusuario")
private String cusuario;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "cod_vendedor", referencedColumnName = "cod_empleado", insertable = false, updatable = false)})
@OneToOne(optional = false)
private Empleados empleados;
@JoinColumn(name = "cod_sublinea", referencedColumnName = "cod_sublinea")
@ManyToOne(optional = false)
private Sublineas codSublinea;
public SublineasVendedores() {
}
public SublineasVendedores(SublineasVendedoresPK sublineasVendedoresPK) {
this.sublineasVendedoresPK = sublineasVendedoresPK;
}
public SublineasVendedores(short codEmpr, short codVendedor) {
this.sublineasVendedoresPK = new SublineasVendedoresPK(codEmpr, codVendedor);
}
public SublineasVendedoresPK getSublineasVendedoresPK() {
return sublineasVendedoresPK;
}
public void setSublineasVendedoresPK(SublineasVendedoresPK sublineasVendedoresPK) {
this.sublineasVendedoresPK = sublineasVendedoresPK;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Empleados getEmpleados() {
return empleados;
}
public void setEmpleados(Empleados empleados) {
this.empleados = empleados;
}
public Sublineas getCodSublinea() {
return codSublinea;
}
public void setCodSublinea(Sublineas codSublinea) {
this.codSublinea = codSublinea;
}
@Override
public int hashCode() {
int hash = 0;
hash += (sublineasVendedoresPK != null ? sublineasVendedoresPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof SublineasVendedores)) {
return false;
}
SublineasVendedores other = (SublineasVendedores) object;
if ((this.sublineasVendedoresPK == null && other.sublineasVendedoresPK != null) || (this.sublineasVendedoresPK != null && !this.sublineasVendedoresPK.equals(other.sublineasVendedoresPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.SublineasVendedores[ sublineasVendedoresPK=" + sublineasVendedoresPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/EscalaCategc.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "escala_categc")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "EscalaCategc.findAll", query = "SELECT e FROM EscalaCategc e")
, @NamedQuery(name = "EscalaCategc.findByCodMerca", query = "SELECT e FROM EscalaCategc e WHERE e.escalaCategcPK.codMerca = :codMerca")
, @NamedQuery(name = "EscalaCategc.findByCodZona", query = "SELECT e FROM EscalaCategc e WHERE e.escalaCategcPK.codZona = :codZona")
, @NamedQuery(name = "EscalaCategc.findByCantCajas", query = "SELECT e FROM EscalaCategc e WHERE e.cantCajas = :cantCajas")
, @NamedQuery(name = "EscalaCategc.findByFrigeDesde", query = "SELECT e FROM EscalaCategc e WHERE e.escalaCategcPK.frigeDesde = :frigeDesde")
, @NamedQuery(name = "EscalaCategc.findByFrigeHasta", query = "SELECT e FROM EscalaCategc e WHERE e.frigeHasta = :frigeHasta")})
public class EscalaCategc implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected EscalaCategcPK escalaCategcPK;
@Basic(optional = false)
@NotNull
@Column(name = "cant_cajas")
private short cantCajas;
@Column(name = "frige_hasta")
@Temporal(TemporalType.TIMESTAMP)
private Date frigeHasta;
public EscalaCategc() {
}
public EscalaCategc(EscalaCategcPK escalaCategcPK) {
this.escalaCategcPK = escalaCategcPK;
}
public EscalaCategc(EscalaCategcPK escalaCategcPK, short cantCajas) {
this.escalaCategcPK = escalaCategcPK;
this.cantCajas = cantCajas;
}
public EscalaCategc(String codMerca, String codZona, Date frigeDesde) {
this.escalaCategcPK = new EscalaCategcPK(codMerca, codZona, frigeDesde);
}
public EscalaCategcPK getEscalaCategcPK() {
return escalaCategcPK;
}
public void setEscalaCategcPK(EscalaCategcPK escalaCategcPK) {
this.escalaCategcPK = escalaCategcPK;
}
public short getCantCajas() {
return cantCajas;
}
public void setCantCajas(short cantCajas) {
this.cantCajas = cantCajas;
}
public Date getFrigeHasta() {
return frigeHasta;
}
public void setFrigeHasta(Date frigeHasta) {
this.frigeHasta = frigeHasta;
}
@Override
public int hashCode() {
int hash = 0;
hash += (escalaCategcPK != null ? escalaCategcPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof EscalaCategc)) {
return false;
}
EscalaCategc other = (EscalaCategc) object;
if ((this.escalaCategcPK == null && other.escalaCategcPK != null) || (this.escalaCategcPK != null && !this.escalaCategcPK.equals(other.escalaCategcPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.EscalaCategc[ escalaCategcPK=" + escalaCategcPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/RecibosVentasDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import java.io.Serializable;
import java.util.Date;
/**
*
* @author Asus
*/
public class RecibosVentasDto implements Serializable {
private String ctipoDocum;
private long ncuota;
private Date frecibo;
private long nrecibo;
private String ctipo;
private long ndocum;
private Date ffactur;
private long iefectivo;
private String nroCheque;
private long ipagado;
private long moneda;
private long cotizacion;
public RecibosVentasDto(String ctipoDocum, long ncuota, Date frecibo, long nrecibo, String ctipo, long ndocum, Date ffactur, long iefectivo, String nroCheque, long ipagado, long moneda, long cotizacion) {
this.ctipoDocum = ctipoDocum;
this.ncuota = ncuota;
this.frecibo = frecibo;
this.nrecibo = nrecibo;
this.ctipo = ctipo;
this.ndocum = ndocum;
this.ffactur = ffactur;
this.iefectivo = iefectivo;
this.nroCheque = nroCheque;
this.ipagado = ipagado;
this.moneda = moneda;
this.cotizacion = cotizacion;
}
public RecibosVentasDto() {
}
public String getCtipoDocum() {
return ctipoDocum;
}
public long getNcuota() {
return ncuota;
}
public Date getFrecibo() {
return frecibo;
}
public long getNrecibo() {
return nrecibo;
}
public String getCtipo() {
return ctipo;
}
public long getNdocum() {
return ndocum;
}
public Date getFfactur() {
return ffactur;
}
public long getIefectivo() {
return iefectivo;
}
public String getNroCheque() {
return nroCheque;
}
public long getIpagado() {
return ipagado;
}
public long getMoneda() {
return moneda;
}
public long getCotizacion() {
return cotizacion;
}
public void setCtipoDocum(String ctipoDocum) {
this.ctipoDocum = ctipoDocum;
}
public void setNcuota(long ncuota) {
this.ncuota = ncuota;
}
public void setFrecibo(Date frecibo) {
this.frecibo = frecibo;
}
public void setNrecibo(long nrecibo) {
this.nrecibo = nrecibo;
}
public void setCtipo(String ctipo) {
this.ctipo = ctipo;
}
public void setNdocum(long ndocum) {
this.ndocum = ndocum;
}
public void setFfactur(Date ffactur) {
this.ffactur = ffactur;
}
public void setIefectivo(long iefectivo) {
this.iefectivo = iefectivo;
}
public void setNroCheque(String nroCheque) {
this.nroCheque = nroCheque;
}
public void setIpagado(long ipagado) {
this.ipagado = ipagado;
}
public void setMoneda(long moneda) {
this.moneda = moneda;
}
public void setCotizacion(long cotizacion) {
this.cotizacion = cotizacion;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/CuposVendedor.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "cupos_vendedor")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "CuposVendedor.findAll", query = "SELECT c FROM CuposVendedor c")
, @NamedQuery(name = "CuposVendedor.findByCodEmpr", query = "SELECT c FROM CuposVendedor c WHERE c.cuposVendedorPK.codEmpr = :codEmpr")
, @NamedQuery(name = "CuposVendedor.findByCodVendedor", query = "SELECT c FROM CuposVendedor c WHERE c.cuposVendedorPK.codVendedor = :codVendedor")
, @NamedQuery(name = "CuposVendedor.findByCodMerca", query = "SELECT c FROM CuposVendedor c WHERE c.cuposVendedorPK.codMerca = :codMerca")
, @NamedQuery(name = "CuposVendedor.findByCodZona", query = "SELECT c FROM CuposVendedor c WHERE c.codZona = :codZona")
, @NamedQuery(name = "CuposVendedor.findByFrigeDesde", query = "SELECT c FROM CuposVendedor c WHERE c.cuposVendedorPK.frigeDesde = :frigeDesde")
, @NamedQuery(name = "CuposVendedor.findByKcajas", query = "SELECT c FROM CuposVendedor c WHERE c.kcajas = :kcajas")
, @NamedQuery(name = "CuposVendedor.findByKunid", query = "SELECT c FROM CuposVendedor c WHERE c.kunid = :kunid")
, @NamedQuery(name = "CuposVendedor.findByFalta", query = "SELECT c FROM CuposVendedor c WHERE c.falta = :falta")
, @NamedQuery(name = "CuposVendedor.findByCusuario", query = "SELECT c FROM CuposVendedor c WHERE c.cusuario = :cusuario")
, @NamedQuery(name = "CuposVendedor.findByFultimModif", query = "SELECT c FROM CuposVendedor c WHERE c.fultimModif = :fultimModif")
, @NamedQuery(name = "CuposVendedor.findByCusuarioModif", query = "SELECT c FROM CuposVendedor c WHERE c.cusuarioModif = :cusuarioModif")})
public class CuposVendedor implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected CuposVendedorPK cuposVendedorPK;
@Size(max = 2)
@Column(name = "cod_zona")
private String codZona;
@Basic(optional = false)
@NotNull
@Column(name = "kcajas")
private short kcajas;
@Basic(optional = false)
@NotNull
@Column(name = "kunid")
private short kunid;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
public CuposVendedor() {
}
public CuposVendedor(CuposVendedorPK cuposVendedorPK) {
this.cuposVendedorPK = cuposVendedorPK;
}
public CuposVendedor(CuposVendedorPK cuposVendedorPK, short kcajas, short kunid) {
this.cuposVendedorPK = cuposVendedorPK;
this.kcajas = kcajas;
this.kunid = kunid;
}
public CuposVendedor(short codEmpr, short codVendedor, String codMerca, Date frigeDesde) {
this.cuposVendedorPK = new CuposVendedorPK(codEmpr, codVendedor, codMerca, frigeDesde);
}
public CuposVendedorPK getCuposVendedorPK() {
return cuposVendedorPK;
}
public void setCuposVendedorPK(CuposVendedorPK cuposVendedorPK) {
this.cuposVendedorPK = cuposVendedorPK;
}
public String getCodZona() {
return codZona;
}
public void setCodZona(String codZona) {
this.codZona = codZona;
}
public short getKcajas() {
return kcajas;
}
public void setKcajas(short kcajas) {
this.kcajas = kcajas;
}
public short getKunid() {
return kunid;
}
public void setKunid(short kunid) {
this.kunid = kunid;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
@Override
public int hashCode() {
int hash = 0;
hash += (cuposVendedorPK != null ? cuposVendedorPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof CuposVendedor)) {
return false;
}
CuposVendedor other = (CuposVendedor) object;
if ((this.cuposVendedorPK == null && other.cuposVendedorPK != null) || (this.cuposVendedorPK != null && !this.cuposVendedorPK.equals(other.cuposVendedorPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.CuposVendedor[ cuposVendedorPK=" + cuposVendedorPK + " ]";
}
}
<file_sep>/SisVenLog-war/src/java/bean/ServiciosBean.java
package bean;
import dao.ServiciosFacade;
import entidad.Servicios;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class ServiciosBean implements Serializable {
@EJB
private ServiciosFacade serviciosFacade;
private Servicios servicios = new Servicios();
private List<Servicios> listaServicios = new ArrayList<Servicios>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public ServiciosBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public Servicios getServicios() {
return servicios;
}
public void setServicios(Servicios servicios) {
this.servicios = servicios;
}
public List<Servicios> getListaServicios() {
return listaServicios;
}
public void setListaServicios(List<Servicios> listaServicios) {
this.listaServicios = listaServicios;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaServicios = new ArrayList<Servicios>();
this.servicios = new Servicios();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
listar();
//RequestContext.getCurrentInstance().update("formPersonas");
}
public void nuevo() {
this.servicios = new Servicios();
listaServicios = new ArrayList<Servicios>();
}
public List<Servicios> listar() {
listaServicios = serviciosFacade.findAll();
return listaServicios;
}
/*public Boolean validarDeposito() {
boolean valido = true;
try {
List<Servicios> aux = new ArrayList<Servicios>();
if ("".equals(this.servicios.getXdesc())) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
} else {
// aux = serviciosFacade.buscarPorDescripcion(servicios.getXdesc());
/*if (aux.size() > 0) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Ya existe."));
}
}
} catch (Exception e) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al validar los datos."));
}
return valido;
}
*/
public void insertar() {
try {
servicios.setXdesc(servicios.getXdesc().toUpperCase());
servicios.setFalta(new Date());
servicios.setCsuario("admin");
serviciosFacade.insertarServicios(servicios);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevServicios').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editar() {
try {
if ("".equals(this.servicios.getXdesc())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
servicios.setXdesc(servicios.getXdesc().toUpperCase());
serviciosFacade.edit(servicios);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditServicios').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void borrar() {
try {
serviciosFacade.remove(servicios);
this.servicios = new Servicios();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacServicios').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
if ("" != this.servicios.getXdesc()) {
this.setHabBtnEdit(false);
} else {
this.setHabBtnEdit(true);
}
}
public void verificarCargaDatos() {
boolean cargado = false;
if (servicios != null) {
if (servicios.getXdesc() != null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarServicios').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevServicios').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarServicios').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevServicios').hide();");
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/GenDatosContablesFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Recibos;
import dto.RecibosVentasDto;
import dto.RecibosComprasDto;
import dto.RecibosFacturasVentasIvaInclNoIncl;
import dto.RecibosFacturasComprasIvaInclNoIncl;
import entidad.DatosGenerales;
import dao.DatosGeneralesFacade;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.sql.Timestamp;
import javax.annotation.PreDestroy;
import javax.ejb.Stateless;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author WORK
*/
@Stateless
public class GenDatosContablesFacade extends AbstractFacade<Recibos> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
@EJB
DatosGeneralesFacade datosGeneralesFacade;
public GenDatosContablesFacade() {
super(Recibos.class);
}
@PreDestroy
public void destruct() {
getEntityManager().close();
}
public List<Object[]> busquedaDatosRecibosVentas(String fechaInicial, String fechaFinal) throws Exception {
Query q = getEntityManager().createNativeQuery(" SELECT 'REC' as ctipo_docum, 1 as nro_cuota,"
+ " CONVERT(char(10),f.frecibo,103) as frecibo, f.nrecibo, d.ctipo_docum as ctipo, d.ndocum , "
+ " d.ffactur, f.iefectivo AS iefectivo, ch.nro_cheque, ch.ipagado, 0 as moneda, 0 as cotizacion "
+ " FROM recibos f INNER JOIN recibos_det d "
+ " ON f.nrecibo = d.nrecibo , "
+ " recibos_cheques ch, cheques cq "
+ " WHERE (f.frecibo BETWEEN '"+ fechaInicial +"' AND '"+ fechaFinal +"') "
+ " AND (f.mestado = 'A') "
+ " AND ch.cod_banco = cq.cod_banco "
+ " AND ch.nro_cheque = cq.nro_cheque "
+ " AND f.nrecibo = ch.nrecibo "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " AND ch.cod_empr = 2 "
+ " AND f.iefectivo > 0 ");
System.out.println(q.toString());
return q.getResultList();
}
public List<Object[]> busquedaDatosRecibosCompras(String fechaInicial, String fechaFinal) throws Exception {
Query q = getEntityManager().createNativeQuery(" SELECT 'REP' as ctipo_docum, 1 as nro_cuota, CONVERT(char(10),f.frecibo,103) as frecibo, f.nrecibo, d.nrofact , d.ctipo_docum as ctipo, "
+ " d.ffactur, 0 AS iefectivo, ch.nro_cheque, ch.ipagado, cb.cod_contable, 0 as moneda, 0 as cotizacion, f.cod_proveed, d.itotal, 0 as ntimbrado, 0 as fact_timbrado, 0 as ntimbrado, 0 as nota_timbrado "
+ " FROM recibos_prov f INNER JOIN recibos_prov_det d "
+ " ON f.nrecibo = d.nrecibo AND f.cod_proveed = d.cod_proveed LEFT OUTER JOIN compras c "
+ " ON d.ctipo_docum = c.ctipo_docum AND d.cod_proveed = c.cod_proveed AND d.nrofact = c.nrofact And c.cod_empr = 2 LEFT OUTER JOIN notas_compras n "
+ " ON d.ctipo_docum = n.ctipo_docum AND d.cod_proveed = n.cod_proveed AND d.nrofact = c.nrofact AND d.ffactur = c.ffactur AND n.cod_empr = 2 , "
+ " recibos_prov_cheques ch, ctas_bancarias cb, cheques_emitidos cq "
+ " WHERE (f.frecibo BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') "
+ " AND cq.xcuenta_bco = cb.xcuenta_bco "
+ " AND cq.cod_banco = cb.cod_banco "
+ " AND ch.cod_banco = cq.cod_banco "
+ " AND ch.nro_cheque = cq.nro_cheque "
+ " AND f.nrecibo = ch.nrecibo "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " AND ch.cod_empr = 2 "
+ " AND f.iCHEQUES > 0 "
+ " UNION ALL "
+ " SELECT 'REP' as ctipo_docum, 1 as nro_cuota, CONVERT(char(10),f.frecibo,103) as frecibo, f.nrecibo, d.nrofact, d.ctipo_docum as ctipo, "
+ " d.ffactur, f.iefectivo, '' as nro_cheque, 0 as ipagado, 0 as cod_contable, 0 as moneda, 0 as cotizacion, f.cod_proveed, d.itotal, 0 as ntimbrado as fact_timbrado, 0 as ntimbrado as nota_timbrado "
+ " FROM recibos_prov f INNER JOIN recibos_prov_det d "
+ " ON f.nrecibo = d.nrecibo AND f.cod_proveed = d.cod_proveed LEFT OUTER JOIN compras c "
+ " ON d.nrofact = c.nrofact AND d.ctipo_docum = c.ctipo_docum AND d.ffactur = c.ffactur AND f.cod_proveed = c.cod_proveed LEFT OUTER JOIN notas_compras n "
+ " ON d.nrofact = n.nro_nota AND d.ctipo_docum = n.ctipo_docum AND f.cod_proveed = n.cod_proveed AND d.ffactur = n.fdocum "
+ " WHERE (f.frecibo BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " AND f.iefectivo > 0 ");
System.out.println(q.toString());
return q.getResultList();
}
public List<Object[]> busquedaDatosFacturasVentas(String fechaInicial, String fechaFinal) throws Exception {
Query qActivaIvaNoIncl = getEntityManager().createNativeQuery(" SELECT * FROM (SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, r.ntimbrado, "
+ " F.TTOTAL, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " SUM(d.igravadas) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos > 0 AND d.pimpues = 10 AND r.mtipo_papel = 'F' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, F.Xfactura , r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, r.ntimbrado, "
+ " f.ttotal, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, SUM(d.igravadas) AS tgravadas_5, 0 "
+ " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos > 0 AND d.pimpues = 5 AND r.mtipo_papel = 'F' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10), f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, r.ntimbrado, "
+ " f.ttotal, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, 0 as tgravadas_5, 0 "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos = 0 AND d.pimpues = 0 and r.mtipo_papel = 'F' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10), f.ffactur,10) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, r.ntimbrado, "
+ " f.ttotal, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " SUM(d.igravadas) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos > 0 AND d.pimpues = 10 AND r.mtipo_papel = 'M' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10), f.ffactur, 103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, r.ntimbrado, "
+ " f.ttotal, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, SUM(d.igravadas) AS tgravadas_5, 0 "
+ " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos > 0 AND d.pimpues = 5 AND r.mtipo_papel = 'M' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, r.ntimbrado, "
+ " f.ttotal, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, 0 as tgravadas_5, 0 "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos = 0 AND d.pimpues = 0 and r.mtipo_papel = 'M' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura , r.ntimbrado "
+ " ) AS t ORDER BY t.ffactur, t.mtipo_papel, t.nro_docum_ini, t.nro_docum_fin ");
System.out.println(qActivaIvaNoIncl.toString());
List<Object[]> lista;
lista = qActivaIvaNoIncl.getResultList();
Query qInactivaIvaNoIncl = getEntityManager().createNativeQuery(" SELECT * FROM (SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, r.ntimbrado, "
+ " F.TTOTAL, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " SUM(d.igravadas) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'X') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos > 0 AND d.pimpues = 10 AND r.mtipo_papel = 'F' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, F.Xfactura , r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, r.ntimbrado, "
+ " f.ttotal, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, SUM(d.igravadas) AS tgravadas_5, 0 "
+ " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'X') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos > 0 AND d.pimpues = 5 AND r.mtipo_papel = 'F' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura , r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10), f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin,r.ntimbrado, "
+ " f.ttotal, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, 0 as tgravadas_5, 0 "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'X') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos = 0 AND d.pimpues = 0 and r.mtipo_papel = 'F' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10), f.ffactur,10) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin,r.ntimbrado, "
+ " f.ttotal, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " SUM(d.igravadas) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'X') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos > 0 AND d.pimpues = 10 AND r.mtipo_papel = 'M' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10), f.ffactur, 103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, r.ntimbrado, "
+ " f.ttotal, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, SUM(d.igravadas) AS tgravadas_5, 0 "
+ " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'X') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos > 0 AND d.pimpues = 5 AND r.mtipo_papel = 'M' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin,r.ntimbrado, "
+ " f.ttotal, f.xruc, f.xfactura, SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, 0 as tgravadas_5, 0 "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'X') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos = 0 AND d.pimpues = 0 and r.mtipo_papel = 'M' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura , r.ntimbrado "
+ " ) AS t ORDER BY t.ffactur, t.mtipo_papel, t.nro_docum_ini, t.nro_docum_fin ");
System.out.println(qInactivaIvaNoIncl.toString());
lista.addAll(qInactivaIvaNoIncl.getResultList());
Query qActivaIvaIncl = getEntityManager().createNativeQuery(" SELECT * FROM (SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado, "
+ " SUM(d.iexentas) AS texentas, "
+ " SUM(d.igravadas + d.impuestos) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos < 0 AND d.pimpues = 10 AND r.mtipo_papel = 'F' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura , r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado,"
+ " SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, SUM(d.igravadas + d.impuestos) AS tgravadas_5, 0 "
+ " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos < 0 AND d.pimpues = 5 AND r.mtipo_papel = 'F' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10), f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado, "
+ " SUM(d.iexentas) AS texentas, "
+ " SUM(d.igravadas + d.impuestos) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos < 0 AND d.pimpues = 10 AND r.mtipo_papel = 'M' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura,r.ntimbrado, "
+ " SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, SUM(d.igravadas + d.impuestos) AS tgravadas_5, 0 "
+ " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " AND d.impuestos < 0 AND d.pimpues = 5 AND r.mtipo_papel = 'M' "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " ) AS t ORDER BY t.ffactur, t.mtipo_papel, t.nro_docum_ini, t.nro_docum_fin ");
System.out.println(qActivaIvaIncl.toString());
lista.addAll(qActivaIvaIncl.getResultList());
Query qInactivaIvaIncl = getEntityManager().createNativeQuery(" SELECT * FROM (SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura,r.ntimbrado, "
+ " SUM(d.iexentas) AS texentas, "
+ " SUM(d.igravadas + d.impuestos) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'X') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos < 0 AND d.pimpues = 10 AND r.mtipo_papel = 'F' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado, "
+ " SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, SUM(d.igravadas + d.impuestos) AS tgravadas_5, 0 "
+ " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'X') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos < 0 AND d.pimpues = 5 AND r.mtipo_papel = 'F' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10), f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado, "
+ " SUM(d.iexentas) AS texentas, "
+ " SUM(d.igravadas + d.impuestos) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'X') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND d.impuestos < 0 AND d.pimpues = 10 AND r.mtipo_papel = 'M' "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " UNION ALL "
+ " SELECT f.xrazon_social, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado, "
+ " SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, SUM(d.igravadas + d.impuestos) AS tgravadas_5, 0 "
+ " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
+ " FROM facturas f INNER JOIN "
+ " rangos_documentos r ON f.ctipo_docum = r.ctipo_docum AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final INNER JOIN facturas_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'X') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " AND d.impuestos < 0 AND d.pimpues = 5 AND r.mtipo_papel = 'M' "
+ " GROUP BY f.xrazon_social, f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, f.xruc, f.xfactura, r.ntimbrado "
+ " ) AS t ORDER BY t.ffactur, t.mtipo_papel, t.nro_docum_ini, t.nro_docum_fin ");
System.out.println(qInactivaIvaIncl.toString());
lista.addAll(qInactivaIvaIncl.getResultList());
// Query qNotasCreditoInactivaIvaNoIncl = getEntityManager().createNativeQuery(" SELECT f.xrazon_social, f.xruc, n.fac_ctipo_docum, convert(char(10), "
// + " n.fdocum,103) as ffactur, n.ctipo_docum, n.nro_nota, n.cconc, n.ttotal, 'F' as mtipo_papel, "
// + " 0 as nro_docum_ini, 0 as nro_docum_fin, n.xnro_nota, SUM(d.iexentas) AS texentas, "
// + " SUM(d.igravadas) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
// + " AS timpuestos_10, 0 AS timpuestos_5 "
// + " FROM notas_ventas n INNER JOIN notas_ventas_det d "
// + " ON N.nro_nota = d.nro_nota and n.ctipo_docum = d.ctipo_docum AND n.fdocum = d.fdocum , facturas f "
// + " WHERE (n.fdocum BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
// + " AND (n.mestado = 'A') "
// + " AND d.impuestos > 0 AND d.pimpues = 10 "
// + " AND f.cod_empr = 2 "
// + " AND f.nrofact = n.nrofact "
// + " AND f.ctipo_docum = n.fac_ctipo_docum "
// + " AND f.ffactur = n.ffactur "
// + " AND n.cod_empr = 2 and d.cod_empr = 2 "
// + " GROUP BY f.xrazon_social, f.xruc, n.fac_ctipo_docum, n.fdocum, n.ctipo_docum, n.cconc, n.nro_nota, n.ttotal, n.xnro_nota "
// + " UNION ALL "
// + " SELECT f.xrazon_social, f.xruc, n.fac_ctipo_docum, CONVERT(char(10),n.fdocum,103) as ffactur, "
// + " n.ctipo_docum, n.nro_nota, n.cconc, n.ttotal, 'F' as mtipo_papel, 0 AS nro_docum_ini, 0 as nro_docum_fin, n.xnro_nota, "
// + " SUM(d.iexentas) AS texentas, "
// + " 0 AS tgravadas_10, SUM(d.igravadas) AS tgravadas_5, 0 "
// + " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
// + " FROM notas_ventas n INNER JOIN notas_ventas_det d "
// + " ON n.nro_nota = d.nro_nota AND n.ctipo_docum = d.ctipo_docum AND n.fdocum = d.fdocum, facturas f "
// + " WHERE (n.fdocum BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
// + " AND (n.mestado = 'A') "
// + " AND f.cod_empr = 2 "
// + " AND f.nrofact = n.nrofact "
// + " AND f.ctipo_docum = n.fac_ctipo_docum "
// + " AND f.ffactur = n.ffactur "
// + " AND n.cod_empr = 2 and d.cod_empr = 2 "
// + " AND d.impuestos > 0 AND d.pimpues = 5 "
// + " GROUP BY f.xrazon_social, f.xruc, n.fac_ctipo_docum, n.fdocum, n.ctipo_docum, N.CCONC, n.nro_nota,n.ttotal , n.xnro_nota "
// + " ORDER BY 4, n.ctipo_docum, n.cconc ");
// System.out.println(qNotasCreditoInactivaIvaNoIncl.toString());
//
// lista.addAll(qNotasCreditoInactivaIvaNoIncl.getResultList());
// Query qNotasCreditoInactivaIvaIncl = getEntityManager().createNativeQuery(" SELECT f.xrazon_social, f.xruc, n.fac_ctipo_docum, CONVERT(char(10), n.fdocum,103) as ffactur, "
// + " n.ctipo_docum, n.nro_nota, n.cconc, n.ttotal, 'F' as mtipo_papel, 0 as nro_docum_ini, 0 as nro_docum_fin, n.xnro_nota, SUM(d.iexentas) AS texentas, "
// + " SUM(d.igravadas + d.impuestos) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
// + " AS timpuestos_10, 0 AS timpuestos_5 "
// + " FROM notas_ventas n INNER JOIN notas_ventas_det d "
// + " ON N.nro_nota = d.nro_nota AND n.ctipo_docum = d.ctipo_docum AND n.fdocum = d.fdocum, facturas f "
// + " WHERE (n.fdocum BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
// + " AND (n.mestado = 'A') "
// + " AND d.impuestos < 0 AND d.pimpues = 10 "
// + " AND f.cod_empr = 2 "
// + " AND n.nrofact = f.nrofact "
// + " AND n.fac_ctipo_docum = f.ctipo_docum "
// + " AND f.ffactur = n.ffactur "
// + " AND n.cod_empr = 2 and d.cod_empr = 2 "
// + " GROUP BY f.xrazon_social, f.xruc, n.fac_ctipo_docum,n.fdocum, n.ctipo_docum, n.cconc, n.nro_nota, n.ttotal, n.xnro_nota "
// + " UNION ALL "
// + " SELECT f.xrazon_social, f.xruc, n.fac_ctipo_docum, CONVERT(char(10),n.fdocum,103) as ffactur, n.ctipo_docum, n.nro_nota, n.cconc, n.ttotal, "
// + " 'F' as mtipo_papel, 0 AS nro_docum_ini, 0 as nro_docum_fin, n.xnro_nota, SUM(d.iexentas) AS texentas, "
// + " 0 AS tgravadas_10, SUM(d.igravadas + d.impuestos) AS tgravadas_5, 0 "
// + " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
// + " FROM notas_ventas n INNER JOIN notas_ventas_det d "
// + " ON n.nro_nota = d.nro_nota AND n.ctipo_docum = d.ctipo_docum AND n.fdocum = d.fdocum, facturas f "
// + " WHERE (n.fdocum BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
// + " AND (n.mestado = 'A') "
// + " AND d.impuestos < 0 AND d.pimpues = 5 "
// + " AND f.cod_empr = 2 "
// + " AND n.nrofact = f.nrofact "
// + " AND n.fac_ctipo_docum = f.ctipo_docum "
// + " AND f.ffactur = n.ffactur "
// + " AND n.cod_empr = 2 and d.cod_empr = 2 "
// + " GROUP BY f.xrazon_social, f.xruc, n.fac_ctipo_docum,n.fdocum, n.ctipo_docum, N.CCONC, n.nro_nota, n.ttotal, n.xnro_nota "
// + " UNION ALL "
// + " SELECT f.xrazon_social, f.xruc, n.fac_ctipo_docum, CONVERT(char(10),n.fdocum,103) as ffactur, n.ctipo_docum, n.nro_nota, n.cconc, n.ttotal, "
// + " 'F' as mtipo_papel, 0 AS nro_docum_ini, 0 as nro_docum_fin, n.xnro_nota, SUM(d.iexentas) AS texentas, "
// + " 0 AS tgravadas_10, 0 AS tgravadas_5, 0 "
// + " AS timpuestos_10, 0 AS timpuestos_5 "
// + " FROM notas_ventas n INNER JOIN notas_ventas_det d "
// + " ON n.nro_nota = d.nro_nota AND n.ctipo_docum = d.ctipo_docum AND n.fdocum = d.fdocum, facturas f "
// + " WHERE (n.fdocum BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
// + " AND (n.mestado = 'A') "
// + " AND d.impuestos = 0 AND d.pimpues = 0 "
// + " AND f.cod_empr = 2 "
// + " AND n.nrofact = f.nrofact "
// + " AND f.ffactur = n.ffactur "
// + " AND n.fac_ctipo_docum = f.ctipo_docum "
// + " GROUP BY f.xrazon_social, f.xruc, n.fac_ctipo_docum,n.fdocum, n.ctipo_docum, N.CCONC, n.nro_nota, n.ttotal, n.xnro_nota "
// + " ORDER BY 4, n.ctipo_docum, n.cconc ");
//
// System.out.println(qNotasCreditoInactivaIvaIncl.toString());
//
// lista.addAll(qNotasCreditoInactivaIvaIncl.getResultList());
return lista;
}
public List<Object[]> busquedaDatosFacturasCompras(String fechaInicial, String fechaFinal) throws Exception {
Query qIvaNoIncl = getEntityManager().createNativeQuery(" SELECT p.xnombre, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, "
+ " F.TTOTAL, P.xruc, f.xfactura, f.ntimbrado, SUM(d.iexentas) AS texentas, "
+ " SUM(d.itotal) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM compras f INNER JOIN compras_det d "
+ " ON f.nrofact = d.nrofact AND f.cod_proveed = d.cod_proveed AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur, proveedores p "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') "
+ " AND f.cod_proveed = p.cod_proveed "
+ " AND d.impuestos > 0 AND d.pimpues = 10 "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY p.xnombre, f.ffactur, f.nrofact, f.ntimbrado,f.ctipo_docum, f.ttotal, p.xruc, F.xfactura "
+ " UNION ALL "
+ " SELECT p.xnombre, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, "
+ " f.ttotal, p.xruc, f.xfactura, f.ntimbrado, SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, SUM(d.itotal) AS tgravadas_5, 0 "
+ " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
+ " FROM compras f INNER JOIN compras_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum and f.cod_proveed = d.cod_proveed AND f.ffactur = d.ffactur, PROVEEDORES P "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') "
+ " AND f.cod_proveed = p.cod_proveed "
+ " AND d.impuestos > 0 AND d.pimpues = 5 "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY p.xnombre, f.ffactur, f.nrofact, f.ntimbrado, f.ctipo_docum, f.ttotal, p.xruc, f.xfactura "
+ " UNION ALL "
+ " SELECT p.xnombre, CONVERT(char(10), f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, "
+ " f.ttotal, p.xruc, f.xfactura, f.ntimbrado, SUM(d.itotal) AS texentas, "
+ " 0 AS tgravadas_10, 0 as tgravadas_5, 0 "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM compras f INNER JOIN compras_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.cod_proveed = d.cod_proveed AND f.ffactur = d.ffactur, PROVEEDORES P "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND f.cod_proveed = p.cod_proveed "
+ " AND (f.mestado = 'A') "
+ " AND d.impuestos = 0 AND d.pimpues = 0 "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY p.xnombre, f.ffactur, f.nrofact, f.ntimbrado, f.ctipo_docum, f.ttotal, p.xruc, f.xfactura ");
System.out.println(qIvaNoIncl.toString());
List<Object[]> lista = qIvaNoIncl.getResultList();
// List<RecibosFacturasComprasIvaInclNoIncl> listadoFacturas = new ArrayList<RecibosFacturasComprasIvaInclNoIncl>();
//
// for(Object[] resultado: resultadoIvaNoIncl){
// RecibosFacturasComprasIvaInclNoIncl rfcdto = new RecibosFacturasComprasIvaInclNoIncl();
// rfcdto.setCtipoDocum(resultado[0].toString());
// rfcdto.setNrofact(Long.parseLong(resultado[1].toString()));
// if(resultado[2] != null){
// Timestamp timeStamp_2 = (Timestamp) resultado[2];
// java.util.Date dateResult_2 = new Date(timeStamp_2.getTime());
// rfcdto.setFfactur(dateResult_2);
// }else{
// rfcdto.setFfactur(null);
// }
// rfcdto.setXnombre(resultado[3].toString());
// rfcdto.setCtipoDocum(resultado[4].toString());
// rfcdto.setTgravadas10(Long.parseLong(resultado[7].toString()));
// rfcdto.setXfactura(resultado[8].toString());
// rfcdto.setTexentas(Long.parseLong(resultado[9].toString()));
// rfcdto.setTtotal(Long.parseLong(resultado[10].toString()));
// rfcdto.setTimpuestos5(Long.parseLong(resultado[11].toString()));
// listadoFacturas.add(rfcdto);
// }
Query qIvaIncl = getEntityManager().createNativeQuery(" SELECT p.xnombre, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, "
+ " F.TTOTAL, p.xruc, f.xfactura, f.ntimbrado, SUM(d.iexentas) AS texentas, "
+ " SUM(d.itotal+d.impuestos)AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
+ " AS timpuestos_10, 0 AS timpuestos_5 "
+ " FROM compras f INNER JOIN compras_det d "
+ " ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.cod_proveed = d.cod_proveed AND f.ffactur = d.ffactur, "
+ " proveedores p "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') "
+ " AND f.cod_proveed = p.cod_proveed "
+ " AND d.impuestos < 0 AND d.pimpues = 10 "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY p.xnombre, f.ffactur, f.nrofact, f.ntimbrado, f.ctipo_docum, f.ttotal, p.xruc, F.xfactura "
+ " UNION ALL "
+ " SELECT p.xnombre, CONVERT(char(10),f.ffactur,103) as ffactur, f.nrofact, f.ctipo_docum, "
+ " f.ttotal, p.xruc, f.xfactura, f.ntimbrado, SUM(d.iexentas) AS texentas, "
+ " 0 AS tgravadas_10, SUM(d.itotal+d.impuestos ) AS tgravadas_5, 0 "
+ " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
+ " FROM compras f INNER JOIN compras_det d "
+ " ON f.nrofact = d.nrofact AND f.cod_proveed = d.cod_proveed AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur, proveedores p "
+ " WHERE (f.ffactur BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
+ " AND (f.mestado = 'A') "
+ " AND f.cod_proveed = p.cod_proveed "
+ " AND d.impuestos < 0 AND d.pimpues = 5 "
+ " AND f.cod_empr = 2 and d.cod_empr = 2 "
+ " GROUP BY p.xnombre, f.ffactur, f.nrofact, f.ntimbrado, f.ctipo_docum, f.ttotal, p.xruc, f.xfactura ");
System.out.println(qIvaIncl.toString());
// List<Object[]> resultadoIvaIncl =
lista.addAll(qIvaIncl.getResultList());
// for(Object[] resultado: resultadoIvaIncl){
// RecibosFacturasComprasIvaInclNoIncl rfcdto = new RecibosFacturasComprasIvaInclNoIncl();
// rfcdto.setCtipoDocum(resultado[0].toString());
// rfcdto.setNrofact(Long.parseLong(resultado[1].toString()));
// if(resultado[2] != null){
// Timestamp timeStamp_2 = (Timestamp) resultado[2];
// java.util.Date dateResult_2 = new Date(timeStamp_2.getTime());
// rfcdto.setFfactur(dateResult_2);
// }else{
// rfcdto.setFfactur(null);
// }
// rfcdto.setXnombre(resultado[3].toString());
// rfcdto.setCtipoDocum(resultado[4].toString());
// rfcdto.setTgravadas10(Long.parseLong(resultado[7].toString()));
// rfcdto.setXfactura(resultado[8].toString());
// rfcdto.setTexentas(Long.parseLong(resultado[9].toString()));
// rfcdto.setTtotal(Long.parseLong(resultado[10].toString()));
// rfcdto.setTimpuestos5(Long.parseLong(resultado[11].toString()));
// listadoFacturas.add(rfcdto);
// }
// Query qNotasCreditoIvaNoIncl = getEntityManager().createNativeQuery(" SELECT p.xnombre , p.xruc, n.ctipo_docum, convert(char(10), n.fdocum,103) as fdocum, "
// + " n.nro_nota, n.cconc, n.ttotal, n.ntimbrado, "
// + " SUM(d.iexentas) AS texentas, "
// + " SUM(d.igravadas) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
// + " AS timpuestos_10, 0 AS timpuestos_5 "
// + " FROM notas_compras n INNER JOIN notas_compras_det d "
// + " ON N.nro_nota = d.nro_nota and n.ctipo_docum = d.ctipo_docum AND n.cod_proveed = d.cod_proveed AND n.fdocum = d.fdocum, proveedores p "
// + " WHERE (n.fdocum BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
// + " AND (n.mestado = 'A') "
// + " AND n.ctipo_docum IN ('NCC','NDC') "
// + " AND n.cod_proveed = p.cod_proveed "
// + " AND d.impuestos > 0 AND d.pimpues = 10 "
// + " AND n.cod_empr = 2 and d.cod_empr = 2 "
// + " GROUP BY p.xnombre, p.xruc, n.fdocum, n.ctipo_docum, n.cconc, n.nro_nota, n.ttotal, n.ntimbrado "
// + " UNION ALL "
// + " SELECT p.xnombre, p.xruc, n.ctipo_docum, CONVERT(char(10),n.fdocum,103) as fdocum, n.nro_nota, n.cconc, n.ttotal, n.ntimbrado, "
// + " SUM(d.iexentas) AS texentas, "
// + " 0 AS tgravadas_10, SUM(d.igravadas) AS tgravadas_5, 0 "
// + " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
// + " FROM notas_compras n INNER JOIN notas_compras_det d "
// + " ON n.nro_nota = d.nro_nota AND n.ctipo_docum = d.ctipo_docum AND n.cod_proveed = d.cod_proveed AND n.fdocum = d.fdocum, proveedores p "
// + " WHERE (n.fdocum BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
// + " AND (n.mestado = 'A') "
// + " AND n.ctipo_docum IN ('NCC','NDC') "
// + " AND p.cod_proveed = n.cod_proveed "
// + " AND n.cod_empr = 2 and d.cod_empr = 2 "
// + " AND d.impuestos > 0 AND d.pimpues = 5 "
// + " GROUP BY p.xnombre, p.xruc, n.fdocum, n.ctipo_docum, N.CCONC, n.nro_nota,n.ttotal, n.ntimbrado ");
//
// System.out.println(qNotasCreditoIvaNoIncl.toString());
// List<Object[]> resultadoNotasCreditoIvaNoIncl =
// lista.addAll(qNotasCreditoIvaNoIncl.getResultList());
// for(Object[] resultado: resultadoNotasCreditoIvaNoIncl){
// RecibosFacturasComprasIvaInclNoIncl rfcdto = new RecibosFacturasComprasIvaInclNoIncl();
// rfcdto.setCtipoDocum(resultado[0].toString());
// rfcdto.setNrofact(Long.parseLong(resultado[1].toString()));
// if(resultado[2] != null){
// Timestamp timeStamp_2 = (Timestamp) resultado[2];
// java.util.Date dateResult_2 = new Date(timeStamp_2.getTime());
// rfcdto.setFfactur(dateResult_2);
// }else{
// rfcdto.setFfactur(null);
// }
// rfcdto.setXnombre(resultado[3].toString());
// rfcdto.setCtipoDocum(resultado[4].toString());
// rfcdto.setTgravadas10(Long.parseLong(resultado[7].toString()));
// rfcdto.setXfactura(resultado[8].toString());
// rfcdto.setTexentas(Long.parseLong(resultado[9].toString()));
// rfcdto.setTtotal(Long.parseLong(resultado[10].toString()));
// rfcdto.setTimpuestos5(Long.parseLong(resultado[11].toString()));
// listadoFacturas.add(rfcdto);
// }
// Query qNotasCreditoIvaIncl = getEntityManager().createNativeQuery(" SELECT p.xnombre , p.xruc, convert(char(10), n.fdocum,103) as fdocum, "
// + " n.ctipo_docum, n.nro_nota, n.cconc, n.ttotal, n.ntimbrado, "
// + " SUM(d.iexentas) AS texentas, "
// + " SUM(d.igravadas + d.impuestos) AS tgravadas_10, 0 AS tgravadas_5, SUM(ABS(d.impuestos)) "
// + " AS timpuestos_10, 0 AS timpuestos_5 "
// + " FROM notas_compras n INNER JOIN notas_compras_det d "
// + " ON N.nro_nota = d.nro_nota AND n.ctipo_docum = d.ctipo_docum AND n.cod_proveed = d.cod_proveed AND n.fdocum = d.fdocum, proveedores p "
// + " WHERE (n.fdocum BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
// + " AND (n.mestado = 'A') "
// + " AND p.cod_proveed = n.cod_proveed "
// + " AND n.ctipo_docum IN ('NCC','NDC') "
// + " AND d.impuestos < 0 AND d.pimpues = 10 "
// + " AND n.cod_empr = 2 and d.cod_empr = 2 "
// + " GROUP BY p.xnombre, p.xruc, n.fdocum, n.ctipo_docum, n.cconc, n.nro_nota, n.ttotal,n.ntimbrado "
// + " UNION ALL "
// + " SELECT p.xnombre, p.xruc, CONVERT(char(10),n.fdocum,103) as fdocum, n.ctipo_docum, n.nro_nota, n.cconc, n.ttotal, n.ntimbrado, "
// + " SUM(d.iexentas) AS texentas, "
// + " 0 AS tgravadas_10, SUM(d.igravadas + d.impuestos) AS tgravadas_5, 0 "
// + " AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "
// + " FROM notas_compras n INNER JOIN notas_compras_det d "
// + " ON n.nro_nota = d.nro_nota AND n.ctipo_docum = d.ctipo_docum AND n.cod_proveed = d.cod_proveed AND n.fdocum = d.fdocum, proveedores p "
// + " WHERE (n.fdocum BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
// + " AND (n.mestado = 'A') "
// + " AND d.impuestos < 0 AND d.pimpues = 5 "
// + " AND n.ctipo_docum IN ('NCC','NDC') "
// + " AND p.cod_proveed = n.cod_proveed "
// + " AND n.cod_empr = 2 and d.cod_empr = 2 "
// + " GROUP BY p.xnombre, p.xruc, n.fdocum, n.ctipo_docum, N.CCONC, n.nro_nota, n.ttotal, n.ntimbrado "
// + " UNION ALL "
// + " SELECT p.xnombre, p.xruc, CONVERT(char(10),n.fdocum,103) as fdocum, n.ctipo_docum, n.nro_nota, n.cconc, n.ttotal, n.ntimbrado, "
// + " SUM(d.iexentas) AS texentas, "
// + " 0 AS tgravadas_10, 0 AS tgravadas_5, 0 "
// + " AS timpuestos_10, 0 AS timpuestos_5 "
// + " FROM notas_compras n INNER JOIN notas_compras_det d "
// + " ON n.nro_nota = d.nro_nota AND n.ctipo_docum = d.ctipo_docum AND n.cod_proveed = d.cod_proveed AND n.fdocum = d.fdocum, proveedores p "
// + " WHERE (n.fdocum BETWEEN '" + fechaInicial + "' AND '" + fechaFinal + "') "
// + " AND (n.mestado = 'A') "
// + " AND n.ctipo_docum IN ('NCC','NDC') "
// + " AND p.cod_proveed = n.cod_proveed "
// + " AND d.impuestos = 0 AND d.pimpues = 0 "
// + " GROUP BY p.xnombre, p.xruc, n.fdocum, n.ctipo_docum, N.CCONC, n.nro_nota, n.ttotal, n.ntimbrado ");
//
// System.out.println(qNotasCreditoIvaIncl.toString());
//
// List<Object[]> resultadoNotasCreditoIvaIncl = qNotasCreditoIvaIncl.getResultList();
// for(Object[] resultado: resultadoNotasCreditoIvaIncl){
// RecibosFacturasComprasIvaInclNoIncl rfcdto = new RecibosFacturasComprasIvaInclNoIncl();
// rfcdto.setCtipoDocum(resultado[0].toString());
// rfcdto.setNrofact(Long.parseLong(resultado[1].toString()));
// if(resultado[2] != null){
// Timestamp timeStamp_2 = (Timestamp) resultado[2];
// java.util.Date dateResult_2 = new Date(timeStamp_2.getTime());
// rfcdto.setFfactur(dateResult_2);
// }else{
// rfcdto.setFfactur(null);
// }
// rfcdto.setXnombre(resultado[3].toString());
// rfcdto.setCtipoDocum(resultado[4].toString());
// rfcdto.setTgravadas10(Long.parseLong(resultado[7].toString()));
// rfcdto.setXfactura(resultado[8].toString());
// rfcdto.setTexentas(Long.parseLong(resultado[9].toString()));
// rfcdto.setTtotal(Long.parseLong(resultado[10].toString()));
// rfcdto.setTimpuestos5(Long.parseLong(resultado[11].toString()));
// listadoFacturas.add(rfcdto);
// }
return lista;
}
public String obtenerPath(){
return datosGeneralesFacade.findAll().get(0).getTempPath();
}
}
<file_sep>/SisVenLog-war/src/java/util/FileWritter.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package util;
import dto.RecibosComprasDto;
import dto.RecibosFacturasComprasIvaInclNoIncl;
import dto.RecibosFacturasVentasIvaInclNoIncl;
import dto.RecibosVentasDto;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
/**
*
* @author Asus
*/
public class FileWritter {
public static void guardarDatosRecibosVentas(String path, List<RecibosVentasDto> datos) {
String nombreArchivo = "revtacont.txt"; //contenido en formato csv
String saltoDeLinea = "\n";
String separador = ",";
String aGuardarEnArchivo = "ctipo_docum,nro_cuota,frecibo,nrecibo,ctipo,ndocum ,ffactur,iefectivo,nro_cheque,ipagado,moneda,cotizacion";
int i = 0;
while (datos.size() > 0) {
String linea = datos.get(i).getCtipoDocum()
+ separador + Long.toString(datos.get(i).getNcuota())
+ separador + dateToString(datos.get(i).getFrecibo())
+ separador + Long.toString(datos.get(i).getNrecibo())
+ separador + datos.get(i).getCtipo()
+ separador + Long.toString(datos.get(i).getNdocum())
+ separador + dateToString(datos.get(i).getFfactur())
+ separador + Long.toString(datos.get(i).getIefectivo())
+ separador + datos.get(i).getNroCheque()
+ separador + Long.toString(datos.get(i).getIpagado())
+ separador + Long.toString(datos.get(i).getMoneda())
+ separador + Long.toString(datos.get(i).getCotizacion());
aGuardarEnArchivo += saltoDeLinea + linea;
i++;
}
writeUsingFileWriter(path + nombreArchivo, aGuardarEnArchivo);
}
public static void guardarDatosRecibosCompras(String path, List<RecibosComprasDto> datos) {
String nombreArchivo = "recomcont.txt"; //contenido en formato csv
String saltoDeLinea = "\n";
String separador = ",";
String aGuardarEnArchivo = "ctipo_docum,nro_cuota,frecibo,nrecibo,nrofact,ctipo,ffactur,iefectivo,nro_cheque,ipagado,"
+ "cod_contable,moneda,cotizacion,cod_proveed,itotal,ntimbrado,fact_timbrado,ntimbrado,nota_timbrado";
int i = 0;
while (datos.size() > 0) {
String linea = datos.get(i).getCtipoDocum()
+ separador + Long.toString(datos.get(i).getNcuota())
+ separador + dateToString(datos.get(i).getFrecibo())
+ separador + Long.toString(datos.get(i).getNrecibo())
+ separador + datos.get(i).getNrofact()
+ separador + datos.get(i).getCtipo()
+ separador + dateToString(datos.get(i).getFfactur())
+ separador + Long.toString(datos.get(i).getIefectivo())
+ separador + datos.get(i).getNroCheque()
+ separador + Long.toString(datos.get(i).getIpagado())
+ separador + Long.toString(datos.get(i).getMoneda())
+ separador + Long.toString(datos.get(i).getCotizacion())
+ separador + Short.toString(datos.get(i).getCodProveed())
+ separador + Long.toString(datos.get(i).getItotal())
+ separador + datos.get(i).getNtimbrado().toString()
+ separador + datos.get(i).getFactTimbrado().toString()
+ separador + datos.get(i).getNotaTimbrado();
aGuardarEnArchivo += saltoDeLinea + linea;
i++;
}
writeUsingFileWriter(path + nombreArchivo, aGuardarEnArchivo);
}
public static void guardarDatosFacturasVentas(String path, List<RecibosFacturasVentasIvaInclNoIncl> datos) {
String nombreArchivo = "vtascont.txt"; //contenido en formato csv
String saltoDeLinea = "\n";
String separador = ",";
String aGuardarEnArchivo = "xrazon_social,ffactur,nrofact,ctipo_docum,mtipo_papel,nro_docum_ini,nro_docum_fin,"
+ "ntimbrado,TTOTAL,xruc,xfactura,texentas,tgravadas_10,tgravadas_5,timpuestos_10,timpuestos_5";
int i = 0;
while (datos.size() > 0) {
String linea = datos.get(i).getXrazonSocial()
+ separador + dateToString(datos.get(i).getFfactur())
+ separador + Long.toString(datos.get(i).getNrofact())
+ separador + datos.get(i).getCtipoDocum()
+ separador + Character.toString(datos.get(i).getMtipoPapel())
+ separador + Long.toString(datos.get(i).getNroDocumIni())
+ separador + Long.toString(datos.get(i).getNroDocumFin())
+ separador + datos.get(i).getNtimbrado()
+ separador + Long.toString(datos.get(i).getTtotal())
+ separador + datos.get(i).getXruc()
+ separador + datos.get(i).getXfactura()
+ separador + Long.toString(datos.get(i).getTexentas())
+ separador + Long.toString(datos.get(i).getTgravadas10())
+ separador + Long.toString(datos.get(i).getTgravadas5())
+ separador + Long.toString(datos.get(i).getTimpuestos10())
+ separador + Long.toString(datos.get(i).getTimpuestos5());
aGuardarEnArchivo += saltoDeLinea + linea;
i++;
}
writeUsingFileWriter(path + nombreArchivo, aGuardarEnArchivo);
}
public static void guardarDatosFacturasCompras(String path, List<RecibosFacturasComprasIvaInclNoIncl> datos) {
String nombreArchivo = "compcont.txt"; //contenido en formato csv
String saltoDeLinea = "\n";
String separador = ",";
String aGuardarEnArchivo = "xnombre,ffactur,nrofact,ctipo_docum,TTOTAL,xruc,xfactura,"
+ "ntimbrado,texentas,tgravadas_10,tgravadas_5,timpuestos_10,timpuestos_5";
int i = 0;
while (datos.size() > 0) {
String linea = datos.get(i).getXnombre()
+ separador + dateToString(datos.get(i).getFfactur())
+ separador + Long.toString(datos.get(i).getNrofact())
+ separador + datos.get(i).getCtipoDocum()
+ separador + Long.toString(datos.get(i).getTtotal())
+ separador + datos.get(i).getXruc()
+ separador + datos.get(i).getXfactura()
+ separador + datos.get(i).getNtimbrado()
+ separador + Long.toString(datos.get(i).getTexentas())
+ separador + Long.toString(datos.get(i).getTgravadas10())
+ separador + Long.toString(datos.get(i).getTgravadas5())
+ separador + Long.toString(datos.get(i).getTimpuestos10())
+ separador + Long.toString(datos.get(i).getTimpuestos5());
aGuardarEnArchivo += saltoDeLinea + linea;
i++;
}
writeUsingFileWriter(path + nombreArchivo, aGuardarEnArchivo);
}
private static void writeUsingFileWriter(String path, String data) {
File file = new File(path);
FileWriter fr = null;
try {
fr = new FileWriter(file);
fr.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
//close resources
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/AuxiliarImpresionMasivaDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
/**
*
* @author WORK
*/
public class AuxiliarImpresionMasivaDto {
private Integer secuencia;
private String factura;
private String estado;
public AuxiliarImpresionMasivaDto() {
}
public Integer getSecuencia() {
return secuencia;
}
public void setSecuencia(Integer secuencia) {
this.secuencia = secuencia;
}
public String getFactura() {
return factura;
}
public void setFactura(String factura) {
this.factura = factura;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiAnudocBean.java
package bean.listados;
import dao.ExcelFacade;
import dao.TiposDocumentosFacade;
import entidad.TiposDocumentos;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiAnudocBean {
@EJB
private TiposDocumentosFacade tiposDocumentosFacade;
private TiposDocumentos tiposDocumentos;
private List<TiposDocumentos> listaTiposDocumentos;
private Date desde;
private Date hasta;
private String operacion;
@EJB
private ExcelFacade excelFacade;
public LiAnudocBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.tiposDocumentos = new TiposDocumentos();
this.listaTiposDocumentos = new ArrayList<TiposDocumentos>();
this.desde = new Date();
this.hasta = new Date();
setOperacion("A");
}
public List<TiposDocumentos> listarTiposDocumentosAnudoc() {
this.listaTiposDocumentos = tiposDocumentosFacade.listarTipoDocumentoLiAnudoc();
return this.listaTiposDocumentos;
}
public void ejecutar(String tipo) {
LlamarReportes rep = new LlamarReportes();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
String tipoDoc = "";
StringBuilder sql = new StringBuilder();
if (this.tiposDocumentos == null) {
tipoDoc = "TODOS";
} else {
tipoDoc = this.tiposDocumentos.getCtipoDocum();
}
if (this.tiposDocumentos == null
|| this.tiposDocumentos.getCtipoDocum().equals("FCO")
|| this.tiposDocumentos.getCtipoDocum().equals("FCR")
|| this.tiposDocumentos.getCtipoDocum().equals("CPV")) {
sql.append("SELECT \n"
+ "f.ctipo_docum, f.nrofact as ndocum, f.ffactur as fdocum,\n"
+ "f.cod_cliente as cod_persona, \n"
+ "f.xrazon_social as xnombre, "
+ "f.ttotal as ttotal, f.fanul as fanul, \n"
+ "f.cusuario_anul, '' as origen, '' as destino, '' as cconc\n");
if (this.operacion.equals("A")) {
sql.append("from facturas f \n"
+ "where f.mestado = 'X'\n"
+ "and f.cod_empr = 2\n"
+ "and f.ctipo_docum = '" + tipoDoc + "'\n"
+ "and f.ffactur between '" + fdesde + "' and '" + fhasta + "'");
} else if (this.operacion.equals("E")) {
sql.append("from hfacturas f \n"
+ "where f.cod_empr = 2\n"
+ "and f.ctipo_docum = '" + tipoDoc + "'\n"
+ "and f.ffactur between '" + fdesde + "' and '" + fhasta + "'");
}
}
if (this.tiposDocumentos == null
|| this.tiposDocumentos.getCtipoDocum().equals("FCC")
|| this.tiposDocumentos.getCtipoDocum().equals("CVC")
|| this.tiposDocumentos.getCtipoDocum().equals("COC")) {
if (this.tiposDocumentos == null) {
sql.append("\n UNION ALL \n");
}
sql.append("SELECT c.ctipo_docum, c.nrofact as ndocum, "
+ "c.ffactur as fdocum, \n"
+ "c.cod_proveed as cod_persona, \n"
+ "p.xnombre, c.ttotal as ttotal, c.fanul as fanul, c.cusuario_anul, '' as origen, '' as destino, '' as cconc\n");
if (this.operacion.equals("A")) {
sql.append("from compras c, proveedores p \n"
+ "where c.mestado = 'X'\n"
+ "and c.cod_proveed = p.cod_proveed and c.cod_empr = 2\n"
+ "and c.ctipo_docum = '" + tipoDoc + "'\n"
+ "and c.ffactur between '" + fdesde + "' and '" + fhasta + "'");
} else if (this.operacion.equals("E")) {
sql.append("from hcompras c, proveedores p \n"
+ "where c.cod_proveed = p.cod_proveed and c.cod_empr = 2\n"
+ "and c.ctipo_docum = '" + tipoDoc + "'\n"
+ "and c.ffactur between '" + fdesde + "' and '" + fhasta + "'");
}
}
if (this.tiposDocumentos == null
|| this.tiposDocumentos.getCtipoDocum().equals("PED")) {
if (this.operacion.equals("A")) {
if (this.tiposDocumentos == null) {
sql.append("\n UNION ALL \n");
}
sql.append("SELECT 'PED' as ctipo_docum, p.nro_pedido as ndocum, \n"
+ "p.fpedido as fdocum, \n"
+ "p.cod_cliente as cod_persona, \n"
+ "c.xnombre, p.ttotal as ttotal, p.fanul as fanul, \n"
+ "p.cusuario_modif as cusuario_anul, '' as origen, \n"
+ "'' as destino, '' as cconc \n");
sql.append("FROM pedidos p, clientes c \n"
+ "WHERE CONVERT(char(10), p.fanul, 103) BETWEEN '" + fdesde + "' AND '" + fhasta + "'\n"
+ "AND p.cod_cliente = c.cod_cliente \n"
+ "AND p.mestado = 'X' \n"
+ "AND p.ctipo_docum = '" + tipoDoc + "'\n"
+ "AND p.cod_empr = 2 ");
}
}
if (this.tiposDocumentos == null
|| this.tiposDocumentos.getCtipoDocum().equals("EN")) {
if (this.tiposDocumentos == null) {
sql.append("\n UNION ALL \n");
}
sql.append("SELECT 'EN' as ctipo_docum, e.nro_envio as ndocum, e.fenvio as fdocum, \n"
+ " 0 as cod_persona, \n"
+ " '' as xnombre, 0 as ttotal, fanul as fanul, e.cusuario_modif as cusuario_anul, d1.xdesc as origen, \n"
+ " d2.xdesc as destino, '' as cconc\n");
if (this.operacion.equals("A")) {
sql.append("from envios e, depositos d1, depositos d2\n"
+ "where e.depo_origen = d1.cod_depo \n"
+ " AND e.depo_destino = d2.cod_depo \n"
+ " AND e.cod_empr = 2 \n"
+ " and e.mestado = 'X'\n"
+ " and e.fenvio between '" + fdesde + "' and '" + fhasta + "'");
}
if (this.operacion.equals("E")) {
sql.append("from henvios e, depositos d1, depositos d2\n"
+ "where e.depo_origen = d1.cod_depo \n"
+ " AND e.depo_destino = d2.cod_depo \n"
+ " AND e.cod_empr = 2 \n"
+ " and e.fenvio between '" + fdesde + "' and '" + fhasta + "'");
}
}
if (this.tiposDocumentos == null
|| this.tiposDocumentos.getCtipoDocum().equals("NCV")
|| this.tiposDocumentos.getCtipoDocum().equals("NDV")) {
if (this.tiposDocumentos == null) {
sql.append("\n UNION ALL \n");
}
sql.append("SELECT n.ctipo_docum as ctipo_docum, n.nro_nota as ndocum, n.fdocum as fdocum ,\n"
+ " n.cod_cliente as cod_persona, \n"
+ "c.xnombre, n.ttotal as ttotal, n.fanul as fanul, n.cusuario_anul, d1.xdesc as origen, '' as destino, n.cconc\n");
if (this.operacion.equals("A")) {
sql.append("from notas_ventas n, depositos d1, clientes c\n"
+ "where n.cod_depo = d1.cod_depo \n"
+ "and n.cod_cliente = c.cod_cliente\n"
+ "and n.mestado = 'X'\n"
+ "and n.cod_empr = 2\n"
+ "and n.ctipo_docum = '" + tipoDoc + "'\n"
+ "and n.fdocum between '" + fdesde + "' and '" + fhasta + "'");
}
if (this.operacion.equals("E")) {
sql.append("from hnotas_ventas n, depositos d1, clientes c\n"
+ "where n.cod_depo = d1.cod_depo \n"
+ "and n.cod_cliente = c.cod_cliente\n"
+ "and n.cod_empr = 2\n"
+ "and n.ctipo_docum = '" + tipoDoc + "'\n"
+ "and n.fdocum between '" + fdesde + "' and '" + fhasta + "'");
}
}
if (this.tiposDocumentos == null
|| this.tiposDocumentos.getCtipoDocum().equals("NCC")
|| this.tiposDocumentos.getCtipoDocum().equals("NDC")
|| this.tiposDocumentos.getCtipoDocum().equals("NDP")) {
if (this.tiposDocumentos == null) {
sql.append("\n UNION ALL \n");
}
sql.append("SELECT n.ctipo_docum as ctipo_docum, n.nro_nota as ndocum,\n"
+ " n.fdocum as fdocum ,\n"
+ "n.cod_proveed as cod_persona, \n"
+ "p.xnombre, n.ttotal as ttotal, fanul as fanul, n.cusuario as cusuario_anul, d1.xdesc as origen, '' as destino, n.cconc\n");
if (this.operacion.equals("A")) {
sql.append("from notas_compras n, proveedores p, depositos d1\n"
+ "where n.cod_proveed = p.cod_proveed\n"
+ "and n.cod_depo = d1.cod_depo\n"
+ "and n.cod_empr = 2\n"
+ "and n.mestado = 'X'\n"
+ "and n.ctipo_docum = '" + tipoDoc + "'\n"
+ "and n.fdocum between '" + fdesde + "' and '" + fhasta + "'");
}
if (this.operacion.equals("E")) {
sql.append("from hnotas_compras n, proveedores p, depositos d1\n"
+ "where n.cod_proveed = p.cod_proveed\n"
+ "and n.cod_depo = d1.cod_depo\n"
+ "and n.cod_empr = 2\n"
+ "and n.ctipo_docum = '" + tipoDoc + "'\n"
+ "and n.fdocum between '" + fdesde + "' and '" + fhasta + "'");
}
}
if (this.tiposDocumentos == null
|| this.tiposDocumentos.getCtipoDocum().equals("AJ")
|| this.tiposDocumentos.getCtipoDocum().equals("RM")) {
if (this.operacion.equals("A")) {
if (this.tiposDocumentos == null) {
sql.append("\n UNION ALL \n");
}
sql.append("SELECT n.ctipo_docum as ctipo_docum, n.ndocum, n.fdocum as fdocum, \n"
+ "n.cod_cliente as cod_persona, \n"
+ "c.xnombre, 0 as ttotal, fanul as fanul, n.cusuario_modif as cusuario_anul, d1.xdesc as origen,'' as destino, '' as cconc\n");
sql.append("from \n"
+ "docum_varios n\n"
+ "left outer join depositos d1 on (n.cod_depo = d1.cod_depo)\n"
+ "left outer join clientes c on (n.cod_cliente = c.cod_cliente)\n"
+ "where n.mestado = 'X'\n"
+ "and n.ctipo_docum = '" + tipoDoc + "'\n"
+ "and n.fdocum between '" + fdesde + "' and '" + fhasta + "'\n"
+ "and n.cod_empr = 2");
}
if (this.operacion.equals("E")) {
if (this.tiposDocumentos == null) {
sql.append("\n UNION ALL \n");
}
sql.append("SELECT n.ctipo_docum as ctipo_docum, n.nro_nota as ndocum, n.fdocum as fdocum, \n"
+ "n.cod_proveed as cod_persona, \n"
+ "c.xnombre, 0 as ttotal, fanul as fanul, n.cusuario_elim as cusuario_anul, d1.xdesc as origen,'' as destino, '' as cconc\n");
sql.append("from \n"
+ "hnotas_compras n\n"
+ "left outer join depositos d1 on (n.cod_depo = d1.cod_depo)\n"
+ "left outer join proveedores c on (c.cod_proveed = c.cod_proveed)\n"
+ "where n.fdocum between '" + fdesde + "' and '" + fhasta + "'\n"
+ "and n.ctipo_docum = '" + tipoDoc + "'\n"
+ "and n.cod_empr = 2");
}
}
if (this.tiposDocumentos == null
|| this.tiposDocumentos.getCtipoDocum().equals("REC")) {
if (this.tiposDocumentos == null) {
sql.append("\n UNION ALL \n");
}
sql.append("SELECT 'REC' as ctipo_docum, r.nrecibo as ndocum, r.frecibo as fdocum ,\n"
+ "r.cod_cliente as cod_persona, \n"
+ "c.xnombre, r.irecibo as ttotal , fanul as fanul, r.cusuario as cusuario_anul, '' as origen, '' as destino, '' as cconc\n");
if (this.operacion.equals("A")) {
sql.append("from recibos r, clientes c\n"
+ "where r.cod_cliente = c.cod_cliente\n"
+ "and r.cod_empr = 2\n"
+ "and r.mestado = 'X'\n"
+ "and r.frecibo between '" + fdesde + "' and '" + fhasta + "'");
}
if (this.operacion.equals("E")) {
sql.append("from hrecibos r, clientes c\n"
+ "where r.cod_cliente = c.cod_cliente\n"
+ "and r.cod_empr = 2\n"
+ "and r.frecibo between '" + fdesde + "' and '" + fhasta + "'");
}
}
if (this.tiposDocumentos == null
|| this.tiposDocumentos.getCtipoDocum().equals("REP")) {
if (this.tiposDocumentos == null) {
sql.append("\n UNION ALL \n");
}
sql.append("SELECT 'REP' as ctipo_docum, r.nrecibo as ndocum, r.frecibo as fdocum , \n"
+ " r.cod_proveed as cod_persona, \n"
+ "p.xnombre, r.irecibo as ttotal , fanul as fanul, r.cusuario as cusuario_anul, '' as origen, '' as destino, '' as cconc\n");
if (this.operacion.equals("A")) {
sql.append("from recibos_prov r, proveedores p\n"
+ "where r.cod_proveed = p.cod_proveed\n"
+ "and r.cod_empr = 2\n"
+ "and r.mestado = 'X'\n"
+ "and r.frecibo between '" + fdesde + "' and '" + fhasta + "'");
}
if (this.operacion.equals("E")) {
sql.append("from hrecibos_prov r, proveedores p\n"
+ "where r.cod_proveed = p.cod_proveed\n"
+ "and r.cod_empr = 2\n"
+ "and r.frecibo between '" + fdesde + "' and '" + fhasta + "'");
}
}
//verificar la parte de cheques en el AT
/*if (this.tiposDocumentos == null
sql.append("\n UNION ALL \n");
sql.append("\n");
if (this.operacion.equals("A")) {
sql.append("");
|| this.tiposDocumentos.getCtipoDocum().equals("CHQ")) {
}
if (this.operacion.equals("E")) {
sql.append("");
}
}*/
System.out.println("SQL lianudoc: " + sql.toString());
if (tipo.equals("VIST")) {
rep.reporteLiAnudoc(sql.toString(), dateToString2(desde), dateToString2(hasta), tipoDoc, "admin", this.operacion, tipo);
} else {
List<Object[]> lista = new ArrayList<Object[]>();
String[] columnas = new String[11];
columnas[0] = "ctipo_docum";
columnas[1] = "ndocum";
columnas[2] = "fdocum";
columnas[3] = "cod_persona";
columnas[4] = "xnombre";
columnas[5] = "ttotal";
columnas[6] = "fanul";
columnas[7] = "cusuario_anul";
columnas[8] = "origen";
columnas[9] = "destino";
columnas[10] = "cconc";
lista = excelFacade.listarParaExcel(sql.toString());
rep.exportarExcel(columnas, lista, "lianudoc");
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
//Getters & Setters
public TiposDocumentos getTiposDocumentos() {
return tiposDocumentos;
}
public void setTiposDocumentos(TiposDocumentos tiposDocumentos) {
this.tiposDocumentos = tiposDocumentos;
}
public List<TiposDocumentos> getListaTiposDocumentos() {
return listaTiposDocumentos;
}
public void setListaTiposDocumentos(List<TiposDocumentos> listaTiposDocumentos) {
this.listaTiposDocumentos = listaTiposDocumentos;
}
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
public String getOperacion() {
return operacion;
}
public void setOperacion(String operacion) {
this.operacion = operacion;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Pedidos.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author admin
*/
@Entity
@Table(name = "pedidos")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Pedidos.findAll", query = "SELECT p FROM Pedidos p")
, @NamedQuery(name = "Pedidos.findByCodEmpr", query = "SELECT p FROM Pedidos p WHERE p.pedidosPK.codEmpr = :codEmpr")
, @NamedQuery(name = "Pedidos.findByNroPedido", query = "SELECT p FROM Pedidos p WHERE p.pedidosPK.nroPedido = :nroPedido")
, @NamedQuery(name = "Pedidos.findByCtipoDocum", query = "SELECT p FROM Pedidos p WHERE p.ctipoDocum = :ctipoDocum")
, @NamedQuery(name = "Pedidos.findByCtipoVta", query = "SELECT p FROM Pedidos p WHERE p.ctipoVta = :ctipoVta")
, @NamedQuery(name = "Pedidos.findByCodVendedor", query = "SELECT p FROM Pedidos p WHERE p.codVendedor = :codVendedor")
, @NamedQuery(name = "Pedidos.findByCodDepoEnvio", query = "SELECT p FROM Pedidos p WHERE p.codDepoEnvio = :codDepoEnvio")
, @NamedQuery(name = "Pedidos.findByCodEntregador", query = "SELECT p FROM Pedidos p WHERE p.codEntregador = :codEntregador")
, @NamedQuery(name = "Pedidos.findByCodCanal", query = "SELECT p FROM Pedidos p WHERE p.codCanal = :codCanal")
, @NamedQuery(name = "Pedidos.findByCodRuta", query = "SELECT p FROM Pedidos p WHERE p.codRuta = :codRuta")
, @NamedQuery(name = "Pedidos.findByCodCliente", query = "SELECT p FROM Pedidos p WHERE p.codCliente = :codCliente")
, @NamedQuery(name = "Pedidos.findByCodDepo", query = "SELECT p FROM Pedidos p WHERE p.codDepo = :codDepo")
, @NamedQuery(name = "Pedidos.findByFpedido", query = "SELECT p FROM Pedidos p WHERE p.fpedido = :fpedido")
, @NamedQuery(name = "Pedidos.findByNpesoAcum", query = "SELECT p FROM Pedidos p WHERE p.npesoAcum = :npesoAcum")
, @NamedQuery(name = "Pedidos.findByFanul", query = "SELECT p FROM Pedidos p WHERE p.fanul = :fanul")
, @NamedQuery(name = "Pedidos.findByFfactur", query = "SELECT p FROM Pedidos p WHERE p.ffactur = :ffactur")
, @NamedQuery(name = "Pedidos.findByFenvio", query = "SELECT p FROM Pedidos p WHERE p.fenvio = :fenvio")
, @NamedQuery(name = "Pedidos.findByTgravadas", query = "SELECT p FROM Pedidos p WHERE p.tgravadas = :tgravadas")
, @NamedQuery(name = "Pedidos.findByTexentas", query = "SELECT p FROM Pedidos p WHERE p.texentas = :texentas")
, @NamedQuery(name = "Pedidos.findByTimpuestos", query = "SELECT p FROM Pedidos p WHERE p.timpuestos = :timpuestos")
, @NamedQuery(name = "Pedidos.findByTdescuentos", query = "SELECT p FROM Pedidos p WHERE p.tdescuentos = :tdescuentos")
, @NamedQuery(name = "Pedidos.findByTtotal", query = "SELECT p FROM Pedidos p WHERE p.ttotal = :ttotal")
, @NamedQuery(name = "Pedidos.findByMestado", query = "SELECT p FROM Pedidos p WHERE p.mestado = :mestado")
, @NamedQuery(name = "Pedidos.findByCusuario", query = "SELECT p FROM Pedidos p WHERE p.cusuario = :cusuario")
, @NamedQuery(name = "Pedidos.findByFalta", query = "SELECT p FROM Pedidos p WHERE p.falta = :falta")
, @NamedQuery(name = "Pedidos.findByCusuarioModif", query = "SELECT p FROM Pedidos p WHERE p.cusuarioModif = :cusuarioModif")
, @NamedQuery(name = "Pedidos.findByFultimModif", query = "SELECT p FROM Pedidos p WHERE p.fultimModif = :fultimModif")
, @NamedQuery(name = "Pedidos.findByFinicioAlta", query = "SELECT p FROM Pedidos p WHERE p.finicioAlta = :finicioAlta")
, @NamedQuery(name = "Pedidos.findByMorigen", query = "SELECT p FROM Pedidos p WHERE p.morigen = :morigen")
, @NamedQuery(name = "Pedidos.findByNplazoCheque", query = "SELECT p FROM Pedidos p WHERE p.nplazoCheque = :nplazoCheque")
, @NamedQuery(name = "Pedidos.findByFfinalAlta", query = "SELECT p FROM Pedidos p WHERE p.ffinalAlta = :ffinalAlta")})
public class Pedidos implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected PedidosPK pedidosPK;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 3)
@Column(name = "ctipo_docum")
private String ctipoDocum;
@Basic(optional = false)
@NotNull
@Column(name = "ctipo_vta")
private Character ctipoVta;
@Column(name = "cod_vendedor")
private Short codVendedor;
@Column(name = "cod_depo_envio")
private Short codDepoEnvio;
@Column(name = "cod_entregador")
private Short codEntregador;
@Size(max = 2)
@Column(name = "cod_canal")
private String codCanal;
@Column(name = "cod_ruta")
private Short codRuta;
@Column(name = "cod_cliente")
private Integer codCliente;
@Column(name = "cod_depo")
private Short codDepo;
@Basic(optional = false)
@NotNull
@Column(name = "fpedido")
@Temporal(TemporalType.TIMESTAMP)
private Date fpedido;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "npeso_acum")
private BigDecimal npesoAcum;
@Column(name = "fanul")
@Temporal(TemporalType.TIMESTAMP)
private Date fanul;
@Column(name = "ffactur")
@Temporal(TemporalType.TIMESTAMP)
private Date ffactur;
@Column(name = "fenvio")
@Temporal(TemporalType.TIMESTAMP)
private Date fenvio;
@Column(name = "tgravadas")
private Long tgravadas;
@Column(name = "texentas")
private Long texentas;
@Column(name = "timpuestos")
private Long timpuestos;
@Column(name = "tdescuentos")
private Long tdescuentos;
@Column(name = "ttotal")
private Long ttotal;
@Basic(optional = false)
@NotNull
@Column(name = "mestado")
private Character mestado;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@Column(name = "finicio_alta")
@Temporal(TemporalType.TIMESTAMP)
private Date finicioAlta;
@Basic(optional = false)
@NotNull
@Column(name = "morigen")
private Character morigen;
@Basic(optional = false)
@NotNull
@Column(name = "nplazo_cheque")
private short nplazoCheque;
@Column(name = "ffinal_alta")
@Temporal(TemporalType.TIMESTAMP)
private Date ffinalAlta;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "pedidos")
private Collection<Facturas> facturasCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "pedidos")
private Collection<PedidosDet> pedidosDetCollection;
public Pedidos() {
}
public Pedidos(PedidosPK pedidosPK) {
this.pedidosPK = pedidosPK;
}
public Pedidos(PedidosPK pedidosPK, String ctipoDocum, Character ctipoVta, Date fpedido, Character mestado, Character morigen, short nplazoCheque) {
this.pedidosPK = pedidosPK;
this.ctipoDocum = ctipoDocum;
this.ctipoVta = ctipoVta;
this.fpedido = fpedido;
this.mestado = mestado;
this.morigen = morigen;
this.nplazoCheque = nplazoCheque;
}
public Pedidos(short codEmpr, long nroPedido) {
this.pedidosPK = new PedidosPK(codEmpr, nroPedido);
}
public PedidosPK getPedidosPK() {
return pedidosPK;
}
public void setPedidosPK(PedidosPK pedidosPK) {
this.pedidosPK = pedidosPK;
}
public String getCtipoDocum() {
return ctipoDocum;
}
public void setCtipoDocum(String ctipoDocum) {
this.ctipoDocum = ctipoDocum;
}
public Character getCtipoVta() {
return ctipoVta;
}
public void setCtipoVta(Character ctipoVta) {
this.ctipoVta = ctipoVta;
}
public Short getCodVendedor() {
return codVendedor;
}
public void setCodVendedor(Short codVendedor) {
this.codVendedor = codVendedor;
}
public Short getCodDepoEnvio() {
return codDepoEnvio;
}
public void setCodDepoEnvio(Short codDepoEnvio) {
this.codDepoEnvio = codDepoEnvio;
}
public Short getCodEntregador() {
return codEntregador;
}
public void setCodEntregador(Short codEntregador) {
this.codEntregador = codEntregador;
}
public String getCodCanal() {
return codCanal;
}
public void setCodCanal(String codCanal) {
this.codCanal = codCanal;
}
public Short getCodRuta() {
return codRuta;
}
public void setCodRuta(Short codRuta) {
this.codRuta = codRuta;
}
public Integer getCodCliente() {
return codCliente;
}
public void setCodCliente(Integer codCliente) {
this.codCliente = codCliente;
}
public Short getCodDepo() {
return codDepo;
}
public void setCodDepo(Short codDepo) {
this.codDepo = codDepo;
}
public Date getFpedido() {
return fpedido;
}
public void setFpedido(Date fpedido) {
this.fpedido = fpedido;
}
public BigDecimal getNpesoAcum() {
return npesoAcum;
}
public void setNpesoAcum(BigDecimal npesoAcum) {
this.npesoAcum = npesoAcum;
}
public Date getFanul() {
return fanul;
}
public void setFanul(Date fanul) {
this.fanul = fanul;
}
public Date getFfactur() {
return ffactur;
}
public void setFfactur(Date ffactur) {
this.ffactur = ffactur;
}
public Date getFenvio() {
return fenvio;
}
public void setFenvio(Date fenvio) {
this.fenvio = fenvio;
}
public Long getTgravadas() {
return tgravadas;
}
public void setTgravadas(Long tgravadas) {
this.tgravadas = tgravadas;
}
public Long getTexentas() {
return texentas;
}
public void setTexentas(Long texentas) {
this.texentas = texentas;
}
public Long getTimpuestos() {
return timpuestos;
}
public void setTimpuestos(Long timpuestos) {
this.timpuestos = timpuestos;
}
public Long getTdescuentos() {
return tdescuentos;
}
public void setTdescuentos(Long tdescuentos) {
this.tdescuentos = tdescuentos;
}
public Long getTtotal() {
return ttotal;
}
public void setTtotal(Long ttotal) {
this.ttotal = ttotal;
}
public Character getMestado() {
return mestado;
}
public void setMestado(Character mestado) {
this.mestado = mestado;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public Date getFinicioAlta() {
return finicioAlta;
}
public void setFinicioAlta(Date finicioAlta) {
this.finicioAlta = finicioAlta;
}
public Character getMorigen() {
return morigen;
}
public void setMorigen(Character morigen) {
this.morigen = morigen;
}
public short getNplazoCheque() {
return nplazoCheque;
}
public void setNplazoCheque(short nplazoCheque) {
this.nplazoCheque = nplazoCheque;
}
public Date getFfinalAlta() {
return ffinalAlta;
}
public void setFfinalAlta(Date ffinalAlta) {
this.ffinalAlta = ffinalAlta;
}
@XmlTransient
public Collection<Facturas> getFacturasCollection() {
return facturasCollection;
}
public void setFacturasCollection(Collection<Facturas> facturasCollection) {
this.facturasCollection = facturasCollection;
}
@XmlTransient
public Collection<PedidosDet> getPedidosDetCollection() {
return pedidosDetCollection;
}
public void setPedidosDetCollection(Collection<PedidosDet> pedidosDetCollection) {
this.pedidosDetCollection = pedidosDetCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (pedidosPK != null ? pedidosPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Pedidos)) {
return false;
}
Pedidos other = (Pedidos) object;
if ((this.pedidosPK == null && other.pedidosPK != null) || (this.pedidosPK != null && !this.pedidosPK.equals(other.pedidosPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Pedidos[ pedidosPK=" + pedidosPK + " ]";
}
}
<file_sep>/SisVenLog-war/src/java/bean/GenDatosContables.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
import dao.GenDatosContablesFacade;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.*;
import javax.faces.bean.*;
import javax.faces.context.*;
import org.primefaces.context.RequestContext;
import util.ExceptionHandlerView;
import util.LlamarReportes;
/**
*
* @author Asus
*/
@ManagedBean
@SessionScoped
public class GenDatosContables implements Serializable {
@EJB
private GenDatosContablesFacade genDatosContablesFacade;
/**
* *
* atributos para manejo del front end
*/
private Date fechaInicial;
private Date fechaFinal;
private String documentosAnulados;
//para manejo de errores
private String contenidoError;
private String tituloError;
public GenDatosContables() {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.fechaInicial = new Date();
this.fechaFinal = new Date();
setDocumentosAnulados("DV");
}
public void generarDatos() {
List<Object[]> listaRecibosVentas;
List<Object[]> listaRecibosCompras;
List<Object[]> listaRecibosFacturasVentasIvaInclNoIncl;
List<Object[]> listaRecibosFacturasComprasIvaInclNoIncl;
try {
String path = genDatosContablesFacade.obtenerPath();
if (documentosAnulados.equals("RV")) {
listaRecibosVentas = genDatosContablesFacade.busquedaDatosRecibosVentas(dateToString(getFechaInicial()), dateToString(getFechaFinal()));
if (listaRecibosVentas.isEmpty()) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Datos no encontrados, lista vacia!.", tituloError));
} else {
String[] columnas = {"ctipo_docum", "nro_cuota", "frecibo", "nrecibo", "ctipo", "ndocum", "ffactur", "iefectivo", "nro_cheque", "ipagado", "moneda", "cotizacion"};
LlamarReportes rep = new LlamarReportes();
rep.exportarExcel(columnas, listaRecibosVentas, "revtacont");
//FileWritter.guardarDatosRecibosVentas(path, listaRecibosVentas);
}
} else if (documentosAnulados.equals("RC")) {
listaRecibosCompras = genDatosContablesFacade.busquedaDatosRecibosCompras(dateToString(getFechaInicial()), dateToString(getFechaFinal()));
if (listaRecibosCompras.isEmpty()) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Datos no encontrados, lista vacia!.", tituloError));
} else {
String[] columnas = {"ctipo_docum", "nro_cuota", "frecibo", "nrecibo", "nrofact", "ctipo", "ffactur", "iefectivo", "nro_cheque", "ipagado", "cod_contable", "moneda", "cotizacion", "cod_proveed", "itotal", "ntimbrado", "fact_timbrado", "ntimbrado", "nota_timbrado"};
LlamarReportes rep = new LlamarReportes();
rep.exportarExcel(columnas, listaRecibosCompras, "recomcont");
//FileWritter.guardarDatosRecibosCompras(path, listaRecibosCompras);
}
} else if (documentosAnulados.equals("DV")) {
listaRecibosFacturasVentasIvaInclNoIncl = genDatosContablesFacade.busquedaDatosFacturasVentas(dateToString(getFechaInicial()), dateToString(getFechaFinal()));
if (listaRecibosFacturasVentasIvaInclNoIncl.isEmpty()) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Datos no encontrados, lista vacia!.", tituloError));
} else {
String[] columnas = {"xrazon_social", "ffactur", "nrofact", "ctipo_docum", "mtipo_papel", "nro_docum_ini", "nro_docum_fin", "ntimbrado", "TTOTAL", "xruc", "xfactura", "texentas", "tgravadas_10", "tgravadas_5", "timpuestos_10", "timpuestos_5"};
LlamarReportes rep = new LlamarReportes();
rep.exportarExcel(columnas, listaRecibosFacturasVentasIvaInclNoIncl, "vtascont");
//FileWritter.guardarDatosFacturasVentas(path, listaRecibosFacturasVentasIvaInclNoIncl);
}
} else if (documentosAnulados.equals("DC")) {
listaRecibosFacturasComprasIvaInclNoIncl = genDatosContablesFacade.busquedaDatosFacturasCompras(dateToString(getFechaInicial()), dateToString(getFechaFinal()));
if (listaRecibosFacturasComprasIvaInclNoIncl.isEmpty()) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Datos no encontrados, lista vacia!.", tituloError));
} else {
String[] columnas = {"xnombre", "ffactur", "nrofact", "ctipo_docum", "TTOTAL", "xruc", "xfactura", "ntimbrado", "texentas", "tgravadas_10", "tgravadas_5", "timpuestos_10", "timpuestos_5"};
LlamarReportes rep = new LlamarReportes();
rep.exportarExcel(columnas, listaRecibosFacturasComprasIvaInclNoIncl, "compcont");
//FileWritter.guardarDatosFacturasCompras(path, listaRecibosFacturasComprasIvaInclNoIncl);
}
}
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error en la lectura de datos.", tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
public GenDatosContablesFacade getGenDatosContablesFacade() {
return genDatosContablesFacade;
}
public Date getFechaInicial() {
return fechaInicial;
}
public Date getFechaFinal() {
return fechaFinal;
}
public String getDocumentosAnulados() {
return documentosAnulados;
}
public String getContenidoError() {
return contenidoError;
}
public String getTituloError() {
return tituloError;
}
public void setGenDatosContablesFacade(GenDatosContablesFacade genDatosContablesFacade) {
this.genDatosContablesFacade = genDatosContablesFacade;
}
public void setFechaInicial(Date fechaInicial) {
this.fechaInicial = fechaInicial;
}
public void setFechaFinal(Date fechaFinal) {
this.fechaFinal = fechaFinal;
}
public void setDocumentosAnulados(String documentosAnulados) {
this.documentosAnulados = documentosAnulados;
}
public void setContenidoError(String contenidoError) {
this.contenidoError = contenidoError;
}
public void setTituloError(String tituloError) {
this.tituloError = tituloError;
}
}
<file_sep>/SisVenLog-war/src/java/bean/FacturasSerBean.java
package bean;
import dao.ClientesAgrupadosFacade;
import dao.ClientesCaracteristicasFacade;
import dao.ClientesFacade;
import dao.CuentasCorrientesFacade;
import dao.FacturasDetFacade;
import dao.FacturasFacade;
import dao.FacturasSerFacade;
import dao.MovimientosMercaFacade;
import dao.ProveedoresFacade;
import entidad.Clientes;
import entidad.ClientesAgrupados;
import entidad.ClientesCaracteristicas;
import entidad.CuentasCorrientes;
import entidad.Facturas;
import entidad.FacturasDet;
import entidad.FacturasSer;
import entidad.MovimientosMerca;
import entidad.Proveedores;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class FacturasSerBean implements Serializable {
@EJB
private FacturasDetFacade facturaDetFacade;
private FacturasSerFacade facturasSerFacade;
private ProveedoresFacade proveedoresFacade;
private FacturasFacade facturasFacade;
private ClientesFacade clientesFacade;
private CuentasCorrientesFacade cuentasCorrientesFacade;
private MovimientosMercaFacade movimientosMercaFacade;
private Facturas facturas = new Facturas();
private List<Facturas> listaFacturas = new ArrayList<Facturas>();
private FacturasDet facturasDet = new FacturasDet();
private List<FacturasDet> listaFacturasDet = new ArrayList<FacturasDet>();
private FacturasSer facturasSer = new FacturasSer();
private List<FacturasSer> listaFacturasSer = new ArrayList<FacturasSer>();
private Proveedores proveedores = new Proveedores();
private List<Proveedores> listaProveedores = new ArrayList<Proveedores>();
private Clientes clientes = new Clientes();
private List<Clientes> listaClientes = new ArrayList<Clientes>();
private CuentasCorrientes cuentasCorrientes = new CuentasCorrientes();
private List<CuentasCorrientes> listaCuentasCorrientes = new ArrayList<CuentasCorrientes>();
private MovimientosMerca movimientosMerca = new MovimientosMerca();
private List<MovimientosMerca> listaMovimientosMerca = new ArrayList<MovimientosMerca>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public FacturasSerBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public Facturas getFacturas() {
return facturas;
}
public void setFacturas(Facturas facturas) {
this.facturas = facturas;
}
public List<Facturas> getListaFacturas() {
return listaFacturas;
}
public void setListaFacturas(List<Facturas> listaFacturas) {
this.listaFacturas = listaFacturas;
}
public FacturasFacade getFacturasFacade() {
return facturasFacade;
}
public void setFacturasFacade(FacturasFacade facturasFacade) {
this.facturasFacade = facturasFacade;
}
public FacturasDetFacade getFacturaDetFacade() {
return facturaDetFacade;
}
public void setFacturaDetFacade(FacturasDetFacade facturaDetFacade) {
this.facturaDetFacade = facturaDetFacade;
}
public FacturasSerFacade getFacturasSerFacade() {
return facturasSerFacade;
}
public void setFacturasSerFacade(FacturasSerFacade facturasSerFacade) {
this.facturasSerFacade = facturasSerFacade;
}
public FacturasDet getFacturasDet() {
return facturasDet;
}
public void setFacturasDet(FacturasDet facturasDet) {
this.facturasDet = facturasDet;
}
public List<FacturasDet> getListaFacturasDet() {
return listaFacturasDet;
}
public void setListaFacturasDet(List<FacturasDet> listaFacturasDet) {
this.listaFacturasDet = listaFacturasDet;
}
public FacturasSer getFacturasSer() {
return facturasSer;
}
public void setFacturasSer(FacturasSer facturasSer) {
this.facturasSer = facturasSer;
}
public List<FacturasSer> getListaFacturasSer() {
return listaFacturasSer;
}
public void setListaFacturasSer(List<FacturasSer> listaFacturasSer) {
this.listaFacturasSer = listaFacturasSer;
}
public ProveedoresFacade getProveedoresFacade() {
return proveedoresFacade;
}
public void setProveedoresFacade(ProveedoresFacade proveedoresFacade) {
this.proveedoresFacade = proveedoresFacade;
}
public Proveedores getProveedores() {
return proveedores;
}
public void setProveedores(Proveedores proveedores) {
this.proveedores = proveedores;
}
public List<Proveedores> getListaProveedores() {
return listaProveedores;
}
public void setListaProveedores(List<Proveedores> listaProveedores) {
this.listaProveedores = listaProveedores;
}
public ClientesFacade getClientesFacade() {
return clientesFacade;
}
public void setClientesFacade(ClientesFacade clientesFacade) {
this.clientesFacade = clientesFacade;
}
public Clientes getClientes() {
return clientes;
}
public void setClientes(Clientes clientes) {
this.clientes = clientes;
}
public List<Clientes> getListaClientes() {
return listaClientes;
}
public void setListaClientes(List<Clientes> listaClientes) {
this.listaClientes = listaClientes;
}
public CuentasCorrientesFacade getCuentasCorrientesFacade() {
return cuentasCorrientesFacade;
}
public void setCuentasCorrientesFacade(CuentasCorrientesFacade cuentasCorrientesFacade) {
this.cuentasCorrientesFacade = cuentasCorrientesFacade;
}
public MovimientosMercaFacade getMovimientosMercaFacade() {
return movimientosMercaFacade;
}
public void setMovimientosMercaFacade(MovimientosMercaFacade movimientosMercaFacade) {
this.movimientosMercaFacade = movimientosMercaFacade;
}
public CuentasCorrientes getCuentasCorrientes() {
return cuentasCorrientes;
}
public void setCuentasCorrientes(CuentasCorrientes cuentasCorrientes) {
this.cuentasCorrientes = cuentasCorrientes;
}
public List<CuentasCorrientes> getListaCuentasCorrientes() {
return listaCuentasCorrientes;
}
public void setListaCuentasCorrientes(List<CuentasCorrientes> listaCuentasCorrientes) {
this.listaCuentasCorrientes = listaCuentasCorrientes;
}
public MovimientosMerca getMovimientosMerca() {
return movimientosMerca;
}
public void setMovimientosMerca(MovimientosMerca movimientosMerca) {
this.movimientosMerca = movimientosMerca;
}
public List<MovimientosMerca> getListaMovimientosMerca() {
return listaMovimientosMerca;
}
public void setListaMovimientosMerca(List<MovimientosMerca> listaMovimientosMerca) {
this.listaMovimientosMerca = listaMovimientosMerca;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaFacturas = new ArrayList<Facturas>();
this.facturas = new Facturas();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
listar();
//RequestContext.getCurrentInstance().update("formPersonas");
}
public void nuevo() {
this.facturas = new Facturas();
listaFacturas = new ArrayList<Facturas>();
}
public List<Facturas> listar() {
listaFacturas = facturasFacade.findAll();
return listaFacturas;
}
/*public Boolean validarDeposito() {
boolean valido = true;
try {
List<Facturas> aux = new ArrayList<Facturas>();
if ("".equals(this.facturas.getXdesc())) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
} else {
// aux = facturasFacade.buscarPorDescripcion(facturas.getXdesc());
/*if (aux.size() > 0) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Ya existe."));
}
}
} catch (Exception e) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al validar los datos."));
}
return valido;
}
*/
public void insertar() {
try {
facturas.setXrazonSocial(facturas.getXrazonSocial().toUpperCase());
facturas.setFalta(new Date());
facturas.setCusuario("admin");
// facturasFacade.insertarFacturas(facturas);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevFactSer').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editar() {
try {
if ("".equals(this.facturas.getXrazonSocial())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
facturas.setXrazonSocial(facturas.getXrazonSocial().toUpperCase());
facturasFacade.edit(facturas);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditFactSer').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void borrar() {
try {
facturasFacade.remove(facturas);
this.facturas = new Facturas();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacFactSer').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
if ("" != this.facturas.getXrazonSocial()) {
this.setHabBtnEdit(false);
} else {
this.setHabBtnEdit(true);
}
}
public void verificarCargaDatos() {
boolean cargado = false;
if (facturas != null) {
if (facturas.getXrazonSocial() != null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarFactSer').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevFactSer').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarFactSer').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevFactSer').hide();");
}
}
<file_sep>/SisVenLog-war/src/java/bean/ConsultaChequeBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
import dao.ChequesFacade;
import dao.ClientesFacade;
import dto.ChequeNoCobrado;
import entidad.Bancos;
import entidad.Cheques;
import entidad.ChequesPK;
import entidad.Clientes;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import util.ExceptionHandlerView;
/**
*
* @author Edu
*/
@ManagedBean
@SessionScoped
public class ConsultaChequeBean implements Serializable{
@EJB
private ChequesFacade chequesFacade;
@EJB
private ClientesFacade clientesFacade;
private List<ChequeNoCobrado> listaChequesNoCobrados;
private ChequeNoCobrado chequeNoCobrado;
private Cheques cheque;
private Bancos banco;
private short codigoBanco;
private String numeroCheque;
private Long montoCheque;
private Date fechaCobro;
private Date fechaInicio;
private Date fechaFin;
private Integer codigoCliente;
private String nombreCliente;
private Clientes clientes;
private List<Clientes> listaClientes;
private String filtro;
private String contenidoError;
private String tituloError;
public ConsultaChequeBean() {
}
@PostConstruct
public void instanciar(){
limpiarVariables();
listaChequesNoCobrados = new ArrayList<>();
cheque = new Cheques();
cheque.setChequesPK(new ChequesPK());
chequeNoCobrado = new ChequeNoCobrado();
chequeNoCobrado.setCheque(new Cheques());
banco = new Bancos();
}
private void limpiarVariables(){
this.codigoBanco = 0;
this.numeroCheque = "";
this.montoCheque = new Long("0");
this.fechaCobro = null;
this.fechaInicio = null;
this.fechaFin = null;
this.codigoCliente = new Integer("0");
this.nombreCliente = "";
}
public String limpiarFormulario(){
limpiarVariables();
listaChequesNoCobrados = new ArrayList<>();
cheque = new Cheques();
cheque.setChequesPK(new ChequesPK());
chequeNoCobrado = new ChequeNoCobrado();
chequeNoCobrado.setCheque(new Cheques());
banco = new Bancos();
return null;
}
public void inicializarBuscadorClientes(){
listaClientes = new ArrayList<>();
clientes = new Clientes();
filtro = "";
listarClientesBuscador();
}
public void listarClientesBuscador(){
try{
listaClientes = clientesFacade.buscarPorFiltro(filtro);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de clientes.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public void listarCheques(){
try{
codigoBanco = banco == null ? 0 : banco.getCodBanco();
listaChequesNoCobrados.clear();
listaChequesNoCobrados = chequesFacade.listadoCheques( Short.parseShort("2"),
codigoBanco,
numeroCheque,
montoCheque,
fechaInicio,
fechaFin,
codigoCliente,
fechaCobro);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de cheques.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public void verificarCliente(){
if(codigoCliente != null){
if(codigoCliente == 0){
//mostrar busqueda de clientes
RequestContext.getCurrentInstance().execute("PF('dlgBusClieConsultaCheque').show();");
}else{
try{
Clientes clienteBuscado = clientesFacade.find(codigoCliente);
if(clienteBuscado == null){
//mostrar busqueda de clientes
RequestContext.getCurrentInstance().execute("PF('dlgBusClieConsultaCheque').show();");
}else{
this.nombreCliente = clienteBuscado.getXnombre();
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de clientes.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
}
}
public void onRowSelect(SelectEvent event) {
if (getClientes() != null) {
if (getClientes().getXnombre() != null) {
codigoCliente = getClientes().getCodCliente();
nombreCliente = getClientes().getXnombre();
RequestContext.getCurrentInstance().update("panel_buscador_cheques");
RequestContext.getCurrentInstance().execute("PF('dlgBusClieConsultaCheque').hide();");
}
}
}
public List<ChequeNoCobrado> getListaChequesNoCobrados() {
return listaChequesNoCobrados;
}
public void setListaChequesNoCobrados(List<ChequeNoCobrado> listaChequesNoCobrados) {
this.listaChequesNoCobrados = listaChequesNoCobrados;
}
public short getCodigoBanco() {
return codigoBanco;
}
public void setCodigoBanco(short codigoBanco) {
this.codigoBanco = codigoBanco;
}
public String getNumeroCheque() {
return numeroCheque;
}
public void setNumeroCheque(String numeroCheque) {
this.numeroCheque = numeroCheque;
}
public Long getMontoCheque() {
return montoCheque;
}
public void setMontoCheque(Long montoCheque) {
this.montoCheque = montoCheque;
}
public Date getFechaCobro() {
return fechaCobro;
}
public void setFechaCobro(Date fechaCobro) {
this.fechaCobro = fechaCobro;
}
public Date getFechaInicio() {
return fechaInicio;
}
public void setFechaInicio(Date fechaInicio) {
this.fechaInicio = fechaInicio;
}
public Date getFechaFin() {
return fechaFin;
}
public void setFechaFin(Date fechaFin) {
this.fechaFin = fechaFin;
}
public Integer getCodigoCliente() {
return codigoCliente;
}
public void setCodigoCliente(Integer codigoCliente) {
this.codigoCliente = codigoCliente;
}
public ChequeNoCobrado getChequeNoCobrado() {
return chequeNoCobrado;
}
public void setChequeNoCobrado(ChequeNoCobrado chequeNoCobrado) {
this.chequeNoCobrado = chequeNoCobrado;
}
public String getNombreCliente() {
return nombreCliente;
}
public void setNombreCliente(String nombreCliente) {
this.nombreCliente = nombreCliente;
}
public Bancos getBanco() {
return banco;
}
public void setBanco(Bancos banco) {
this.banco = banco;
}
public Clientes getClientes() {
return clientes;
}
public void setClientes(Clientes clientes) {
this.clientes = clientes;
}
public List<Clientes> getListaClientes() {
return listaClientes;
}
public void setListaClientes(List<Clientes> listaClientes) {
this.listaClientes = listaClientes;
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public String getContenidoError() {
return contenidoError;
}
public void setContenidoError(String contenidoError) {
this.contenidoError = contenidoError;
}
public String getTituloError() {
return tituloError;
}
public void setTituloError(String tituloError) {
this.tituloError = tituloError;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/TiposVentasFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.TiposVentas;
import entidad.TiposVentasPK;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author admin
*/
@Stateless
public class TiposVentasFacade extends AbstractFacade<TiposVentas> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public TiposVentasFacade() {
super(TiposVentas.class);
}
public List<TiposVentas> obtenerTiposVentasDelCliente(Integer lCodCliente){
String sql = "SELECT t.ctipo_vta, t.xdesc FROM ventas_clientes v, tipos_ventas t WHERE " +
"cod_cliente = "+lCodCliente+" AND v.ctipo_vta = t.ctipo_vta";
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
List<TiposVentas> listado = new ArrayList<>();
for(Object[] resultado: resultados){
char cEstado = resultado[0] == null ? 0 : resultado[0].toString().charAt(0);
TiposVentas tv = new TiposVentas();
TiposVentasPK tvPK = new TiposVentasPK();
tvPK.setCtipoVta(cEstado);
tvPK.setCodEmpr(Short.parseShort("2"));
tv.setTiposVentasPK(tvPK);
tv.setXdesc(resultado[1] == null ? "" : resultado[1].toString());
listado.add(tv);
}
return listado;
}
}
<file_sep>/SisVenLog-war/src/java/bean/ListadoRecibosProveedoresBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
import dao.ProveedoresFacade;
import dao.RecibosProvFacade;
import entidad.Proveedores;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import util.DateUtil;
import util.LlamarReportes;
/**
*
* @author jvera
*/
@ManagedBean
@SessionScoped
public class ListadoRecibosProveedoresBean implements Serializable{
private Date fechaReciboDesde;
private Date fechaReciboHasta;
private long nroReciboDesde;
private long nroReciboHasta;
private String discriminar;
private Boolean conDetalle;
private Proveedores proveedorSeleccionado;
@EJB
private ProveedoresFacade proveedoresFacade;
@EJB
private RecibosProvFacade recibosProvFacade;
@PostConstruct
public void instanciar(){
limpiarFormulario();
proveedorSeleccionado = new Proveedores();
setDiscriminar("ND");
setConDetalle(false);
}
public void limpiarFormulario(){
fechaReciboDesde = null;
fechaReciboHasta = null;
nroReciboDesde = 0;
nroReciboHasta = 0;
}
public void ejecutar(String tipo) {
if (validar()) {
try {
LlamarReportes rep = new LlamarReportes();
if (tipo.equals("VIST")) {
if (conDetalle) {
String nombreRepo = "ND".equals(discriminar) ? "reciboProvDetND" : "reciboProvDetPP";
String sqlConDet = armarSqlConDetalle(fechaReciboDesde, fechaReciboHasta, nroReciboDesde, nroReciboHasta, discriminar, proveedorSeleccionado);
String sqlReciboProDet = armarSqlReciboProvDet(fechaReciboDesde, fechaReciboHasta, nroReciboDesde, nroReciboHasta, discriminar, proveedorSeleccionado);
String sqlReciboProDetRec = armarSqlReciboProvDetRec(fechaReciboDesde, fechaReciboHasta, nroReciboDesde, nroReciboHasta, discriminar, proveedorSeleccionado);
rep.reporteLiRecibosCom(sqlConDet,
fechaReciboDesde,
fechaReciboHasta,
nroReciboDesde,
nroReciboHasta,
proveedorSeleccionado,
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("usuario").toString(), tipo, nombreRepo, "Rreciboscomdet",
sqlReciboProDet,
sqlReciboProDetRec);
}else { //sin detalle
String nombreRepo = "ND".equals(discriminar) ? "reciboProvND" : "reciboProvPP";
String sqlSinDet = armarSqlSinDetalle(fechaReciboDesde, fechaReciboHasta, nroReciboDesde, nroReciboHasta, discriminar, proveedorSeleccionado);
rep.reporteLiRecibosCom(sqlSinDet,
fechaReciboDesde, fechaReciboHasta, nroReciboDesde, nroReciboHasta, proveedorSeleccionado,
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("usuario").toString(), tipo, nombreRepo, "Rreciboscom", null, null);
}
} else { //Excel
if (conDetalle) {
List<Object[]> lista = new ArrayList<>();
String[] columnas = new String[18];
columnas[0] = "nrecibo";
columnas[1] = "cod_proveed";
columnas[2] = "frecibo";
columnas[3] = "irecibo";
columnas[4] = "iefectivo";
columnas[5] = "iretencion";
columnas[6] = "icheques";
columnas[7] = "xobs";
columnas[8] = "mestado";
columnas[9] = "xnombre";
columnas[10] = "ctipo_docum";
columnas[11] = "ndocum";
columnas[12] = "xdesc_banco";
columnas[13] = "fanul";
columnas[14] = "tipodet";
columnas[15] = "cod_proveed2";
columnas[16] = "xnombre2";
columnas[17] = "itotal";
lista = recibosProvFacade.listaProveedores(fechaReciboDesde,
fechaReciboHasta,
nroReciboDesde,
nroReciboHasta,
discriminar,
conDetalle,
proveedorSeleccionado);
rep.exportarExcel(columnas, lista, "Rreciboscomdet");
} else { //sin detalle
List<Object[]> lista = new ArrayList<>();
String[] columnas = new String[16];
columnas[0] = "cod_empr";
columnas[1] = "nrecibo";
columnas[2] = "cod_proveed";
columnas[3] = "frecibo";
columnas[4] = "cusuario";
columnas[5] = "falta";
columnas[6] = "fanul";
columnas[7] = "irecibo";
columnas[8] = "iefectivo";
columnas[9] = "iretencion";
columnas[10] = "icheques";
columnas[11] = "xobs";
columnas[12] = "mestado";
columnas[13] = "cod_proveed2";
columnas[14] = "xnombre";
columnas[15] = "xnombre2";
lista = recibosProvFacade.listaProveedores(fechaReciboDesde,
fechaReciboHasta,
nroReciboDesde,
nroReciboHasta,
discriminar,
conDetalle,
proveedorSeleccionado);
rep.exportarExcel(columnas, lista, "Rreciboscom");
}
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error al generar archivo.", "Error al generar archivo."));
}
}
}
private Boolean validar(){
if (fechaReciboDesde == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Debe ingresar fecha desde.", "Debe ingresar fecha desde."));
return false;
}else{
if (fechaReciboHasta == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Debe ingresar fecha hasta.", "Debe ingresar fecha hasta."));
return false;
}else{
if (nroReciboDesde < 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Debe ingresar un número de recibo desde.", "Debe ingresar un número de recibo desde."));
return false;
}else{
if (nroReciboHasta <= 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Debe ingresar un número de recibo hasta.", "Debe ingresar un número de recibo hasta."));
return false;
}
}
}
}
return true;
}
private String armarSqlSinDetalle(Date fechaReciboDesde,
Date fechaReciboHasta,
long nroReciboDesde,
long nroReciboHasta,
String discriminar,
Proveedores provSeleccionado){
String sql = "";
try {
if ("ND".equals(discriminar)) {
sql += "SELECT r.*, t.cod_proveed as cod_proveed2, t.xnombre as xnombre, t.xnombre as xnombre2" +
" FROM recibos_prov r, proveedores t" +
" WHERE r.cod_empr = 2" +
" AND r.cod_proveed = t.cod_proveed" +
" AND r.fanul IS NULL" +
" AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta;
if (provSeleccionado != null){
sql += " AND r.cod_proveed = " + provSeleccionado.getCodProveed();
}
sql += " ORDER BY nrecibo, frecibo";
}else{ //discriminar por Proveedor
sql += ";WITH principalCTE" +
" AS(" +
" SELECT r.*, t.cod_proveed as cod_proveed2, t.xnombre as xnombre, t.xnombre as xnombre2" +
" FROM recibos_prov r, proveedores t" +
" WHERE r.cod_empr = 2" +
" AND r.cod_proveed = t.cod_proveed" +
" AND r.fanul IS NULL" +
" AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta;
if (provSeleccionado != null){
sql += " AND r.cod_proveed = " + provSeleccionado.getCodProveed();
}
sql += " ) SELECT DISTINCT cod_proveed from principalCTE ORDER BY cod_proveed;";
}
}catch (Exception e) {
System.out.println("Error al generar sql sin detalle: " + e.getMessage());
}
return sql;
}
private String armarSqlConDetalle(Date fechaReciboDesde,
Date fechaReciboHasta,
long nroReciboDesde,
long nroReciboHasta,
String discriminar,
Proveedores provSeleccionado){
String sql = "";
try {
if ("ND".equals(discriminar)) {
sql += ";WITH principalCTE" +
" AS(" +
" SELECT r.nrecibo, r.cod_proveed, r.frecibo, r.irecibo, r.iefectivo, r.iretencion, r.icheques," +
" r.xobs, r.mestado, c.xnombre, d.ctipo_docum, d.nrofact as ndocum, '' as xdesc_banco, r.fanul," +
" 'F' as tipodet, c.cod_proveed as cod_proveed2, c.xnombre as xnombre2, d.itotal" +
" FROM recibos_prov r, recibos_prov_det d, proveedores c" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.frecibo = d.frecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND r.cod_empr = 2" +
" AND r.fanul IS NULL" +
" AND r.cod_proveed = c.cod_proveed";
if (provSeleccionado != null) {
sql += " AND r.cod_proveed = " + provSeleccionado.getCodProveed();
}
sql += " AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta +
" UNION ALL" +
" SELECT r.nrecibo, r.cod_proveed, r.frecibo, r.irecibo, r.iefectivo," +
" r.iretencion, r.icheques, r.xobs, r.mestado, c.xnombre, '' as ctipo_docum, nro_cheque as ndocum," +
" b.xdesc as xdesc_banco, r.fanul, 'C' as tipodet, c.cod_proveed as cod_proveed2, c.xnombre as xnombre2," +
" d.ipagado as itotal" +
" FROM recibos_prov r, recibos_prov_cheques d, bancos b, proveedores c" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.frecibo = d.frecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND r.cod_empr = 2" +
" AND d.cod_banco = b.cod_banco" +
" AND r.cod_proveed = c.cod_proveed";
if (provSeleccionado != null) {
sql += " AND r.cod_proveed = " + provSeleccionado.getCodProveed();
}
sql += " AND r.fanul IS NULL" +
" AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta +
" AND r.icheques > 0";
sql += " )" +
" SELECT DISTINCT nrecibo, frecibo, mestado, iefectivo, icheques, iretencion, irecibo, xnombre2, cod_proveed2, xobs from principalCTE ORDER BY nrecibo;";
}else{ //discriminar por Proveedor
sql += ";WITH principalCTE" +
" AS(" +
" SELECT r.nrecibo, r.cod_proveed, r.frecibo, r.irecibo, r.iefectivo, r.iretencion, r.icheques," +
" r.xobs, r.mestado, c.xnombre, d.ctipo_docum, d.nrofact as ndocum, '' as xdesc_banco, r.fanul," +
" 'F' as tipodet, c.cod_proveed as cod_proveed2, c.xnombre as xnombre2, d.itotal" +
" FROM recibos_prov r, recibos_prov_det d, proveedores c" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.frecibo = d.frecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND r.cod_empr = 2" +
" AND r.fanul IS NULL" +
" AND r.cod_proveed = c.cod_proveed";
if (provSeleccionado != null) {
sql += " AND r.cod_proveed = " + provSeleccionado.getCodProveed();
}
sql += " AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta +
" UNION ALL" +
" SELECT r.nrecibo, r.cod_proveed, r.frecibo, r.irecibo, r.iefectivo," +
" r.iretencion, r.icheques, r.xobs, r.mestado, c.xnombre, '' as ctipo_docum, nro_cheque as ndocum," +
" b.xdesc as xdesc_banco, r.fanul, 'C' as tipodet, c.cod_proveed as cod_proveed2, c.xnombre as xnombre2," +
" d.ipagado as itotal" +
" FROM recibos_prov r, recibos_prov_cheques d, bancos b, proveedores c" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.frecibo = d.frecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND r.cod_empr = 2" +
" AND d.cod_banco = b.cod_banco" +
" AND r.cod_proveed = c.cod_proveed";
if (provSeleccionado != null) {
sql += " AND r.cod_proveed = " + provSeleccionado.getCodProveed();
}
sql += " AND r.fanul IS NULL" +
" AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta +
" AND r.icheques > 0";
sql += " )" +
" SELECT DISTINCT cod_proveed from principalCTE ORDER BY cod_proveed;";
}
}catch (Exception e) {
System.out.println("Error al generar sql con detalle: " + e.getMessage());
}
return sql;
}
private String armarSqlReciboProvDet(Date fechaReciboDesde,
Date fechaReciboHasta,
long nroReciboDesde,
long nroReciboHasta,
String discriminar,
Proveedores provSeleccionado){
String sql = "";
try {
if ("ND".equals(discriminar)) {
sql += ";WITH principalCTE" +
" AS(" +
" SELECT r.nrecibo, r.cod_proveed, r.frecibo, r.irecibo, r.iefectivo, r.iretencion, r.icheques," +
" r.xobs, r.mestado, c.xnombre, d.ctipo_docum, d.nrofact as ndocum, '' as xdesc_banco, r.fanul," +
" 'F' as tipodet, c.cod_proveed as cod_proveed2, c.xnombre as xnombre2, d.itotal" +
" FROM recibos_prov r, recibos_prov_det d, proveedores c" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.frecibo = d.frecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND r.cod_empr = 2" +
" AND r.fanul IS NULL" +
" AND r.cod_proveed = c.cod_proveed" +
" AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta +
" UNION ALL" +
" SELECT r.nrecibo, r.cod_proveed, r.frecibo, r.irecibo, r.iefectivo," +
" r.iretencion, r.icheques, r.xobs, r.mestado, c.xnombre, '' as ctipo_docum, nro_cheque as ndocum," +
" b.xdesc as xdesc_banco, r.fanul, 'C' as tipodet, c.cod_proveed as cod_proveed2, c.xnombre as xnombre2," +
" d.ipagado as itotal" +
" FROM recibos_prov r, recibos_prov_cheques d, bancos b, proveedores c" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.frecibo = d.frecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND r.cod_empr = 2" +
" AND d.cod_banco = b.cod_banco" +
" AND r.cod_proveed = c.cod_proveed" +
" AND r.fanul IS NULL" +
" AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta +
" AND r.icheques > 0";
if (provSeleccionado != null){
sql += " AND r.cod_proveed = " + provSeleccionado.getCodProveed();
}
sql += " )" +
" SELECT DISTINCT * from principalCTE WHERE nrecibo = ";
}else{ //discriminar por Proveedor
sql += ";WITH principalCTE" +
" AS(" +
" SELECT r.nrecibo, r.cod_proveed, r.frecibo, r.irecibo, r.iefectivo, r.iretencion, r.icheques," +
" r.xobs, r.mestado, c.xnombre, d.ctipo_docum, d.nrofact as ndocum, '' as xdesc_banco, r.fanul," +
" 'F' as tipodet, c.cod_proveed as cod_proveed2, c.xnombre as xnombre2, d.itotal" +
" FROM recibos_prov r, recibos_prov_det d, proveedores c" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.frecibo = d.frecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND r.cod_empr = 2" +
" AND r.fanul IS NULL" +
" AND r.cod_proveed = c.cod_proveed" +
" AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta +
" UNION ALL" +
" SELECT r.nrecibo, r.cod_proveed, r.frecibo, r.irecibo, r.iefectivo," +
" r.iretencion, r.icheques, r.xobs, r.mestado, c.xnombre, '' as ctipo_docum, nro_cheque as ndocum," +
" b.xdesc as xdesc_banco, r.fanul, 'C' as tipodet, c.cod_proveed as cod_proveed2, c.xnombre as xnombre2," +
" d.ipagado as itotal" +
" FROM recibos_prov r, recibos_prov_cheques d, bancos b, proveedores c" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.frecibo = d.frecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND r.cod_empr = 2" +
" AND d.cod_banco = b.cod_banco" +
" AND r.cod_proveed = c.cod_proveed" +
" AND r.fanul IS NULL" +
" AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta +
" AND r.icheques > 0";
if (provSeleccionado != null){
sql += " AND r.cod_proveed = " + provSeleccionado.getCodProveed();
}
sql += " )" +
" SELECT DISTINCT nrecibo, xnombre, cod_proveed, frecibo, mestado, iefectivo, icheques, iretencion, irecibo, xnombre2, cod_proveed2, xobs from principalCTE Where cod_proveed = ";
}
}catch (Exception e) {
System.out.println("Error al generar el detale del reporte de proveedores: " + e.getMessage());
}
return sql;
}
private String armarSqlReciboProvDetRec(Date fechaReciboDesde,
Date fechaReciboHasta,
long nroReciboDesde,
long nroReciboHasta,
String discriminar,
Proveedores provSeleccionado){
String sql = "";
try {
if ("ND".equals(discriminar)) {
sql = null;
}else{ //discriminar por Proveedor
sql += ";WITH principalCTE" +
" AS(" +
" SELECT r.nrecibo, r.cod_proveed, r.frecibo, r.irecibo, r.iefectivo, r.iretencion, r.icheques," +
" r.xobs, r.mestado, c.xnombre, d.ctipo_docum, d.nrofact as ndocum, '' as xdesc_banco, r.fanul," +
" 'F' as tipodet, c.cod_proveed as cod_proveed2, c.xnombre as xnombre2, d.itotal" +
" FROM recibos_prov r, recibos_prov_det d, proveedores c" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.frecibo = d.frecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND r.cod_empr = 2" +
" AND r.fanul IS NULL" +
" AND r.cod_proveed = c.cod_proveed" +
" AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta +
" UNION ALL" +
" SELECT r.nrecibo, r.cod_proveed, r.frecibo, r.irecibo, r.iefectivo," +
" r.iretencion, r.icheques, r.xobs, r.mestado, c.xnombre, '' as ctipo_docum, nro_cheque as ndocum," +
" b.xdesc as xdesc_banco, r.fanul, 'C' as tipodet, c.cod_proveed as cod_proveed2, c.xnombre as xnombre2," +
" d.ipagado as itotal" +
" FROM recibos_prov r, recibos_prov_cheques d, bancos b, proveedores c" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.frecibo = d.frecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND r.cod_empr = 2\n" +
" AND d.cod_banco = b.cod_banco" +
" AND r.cod_proveed = c.cod_proveed" +
" AND r.fanul IS NULL" +
" AND r.frecibo BETWEEN '" + DateUtil.dateToString(fechaReciboDesde) + "' AND '" + DateUtil.dateToString(fechaReciboHasta) + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta +
" AND r.icheques > 0";
if (provSeleccionado != null){
sql += " AND r.cod_proveed = " + provSeleccionado.getCodProveed();
}
sql += " )" +
" SELECT DISTINCT * from principalCTE WHERE nrecibo = ";
}
}catch (Exception e) {
System.out.println("Error al generar el detale del reporte de proveedores: " + e.getMessage());
}
return sql;
}
public Date getFechaReciboDesde() {
return fechaReciboDesde;
}
public void setFechaReciboDesde(Date fechaReciboDesde) {
this.fechaReciboDesde = fechaReciboDesde;
}
public Date getFechaReciboHasta() {
return fechaReciboHasta;
}
public void setFechaReciboHasta(Date fechaReciboHasta) {
this.fechaReciboHasta = fechaReciboHasta;
}
public String getDiscriminar() {
return discriminar;
}
public void setDiscriminar(String discriminar) {
this.discriminar = discriminar;
}
public Boolean getConDetalle() {
return conDetalle;
}
public void setConDetalle(Boolean conDetalle) {
this.conDetalle = conDetalle;
}
public long getNroReciboDesde() {
return nroReciboDesde;
}
public void setNroReciboDesde(long nroReciboDesde) {
this.nroReciboDesde = nroReciboDesde;
}
public long getNroReciboHasta() {
return nroReciboHasta;
}
public void setNroReciboHasta(long nroReciboHasta) {
this.nroReciboHasta = nroReciboHasta;
}
public Proveedores getProveedorSeleccionado() {
return proveedorSeleccionado;
}
public void setProveedorSeleccionado(Proveedores proveedorSeleccionado) {
if (proveedorSeleccionado != null) {
this.proveedorSeleccionado = proveedoresFacade.proveedorById(proveedorSeleccionado.getCodProveed());
}else{
this.proveedorSeleccionado = proveedorSeleccionado;
}
}
}<file_sep>/SisVenLog-ejb/src/java/entidad/GruposCarga.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author admin
*/
@Entity
@Table(name = "grupos_carga")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "GruposCarga.findAll", query = "SELECT g FROM GruposCarga g")
, @NamedQuery(name = "GruposCarga.findByCodGcarga", query = "SELECT g FROM GruposCarga g WHERE g.codGcarga = :codGcarga")
, @NamedQuery(name = "GruposCarga.findByXdesc", query = "SELECT g FROM GruposCarga g WHERE g.xdesc = :xdesc")
, @NamedQuery(name = "GruposCarga.findByFalta", query = "SELECT g FROM GruposCarga g WHERE g.falta = :falta")
, @NamedQuery(name = "GruposCarga.findByCusuario", query = "SELECT g FROM GruposCarga g WHERE g.cusuario = :cusuario")
, @NamedQuery(name = "GruposCarga.findByFultimModif", query = "SELECT g FROM GruposCarga g WHERE g.fultimModif = :fultimModif")
, @NamedQuery(name = "GruposCarga.findByCusuarioModif", query = "SELECT g FROM GruposCarga g WHERE g.cusuarioModif = :cusuarioModif")})
public class GruposCarga implements Serializable {
@Size(max = 30)
@Column(name = "xdesc")
private String xdesc;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "cod_gcarga")
private Short codGcarga;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@OneToMany(mappedBy = "codGcarga")
private Collection<Sublineas> sublineasCollection;
public GruposCarga() {
}
public GruposCarga(Short codGcarga) {
this.codGcarga = codGcarga;
}
public Short getCodGcarga() {
return codGcarga;
}
public void setCodGcarga(Short codGcarga) {
this.codGcarga = codGcarga;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
@XmlTransient
public Collection<Sublineas> getSublineasCollection() {
return sublineasCollection;
}
public void setSublineasCollection(Collection<Sublineas> sublineasCollection) {
this.sublineasCollection = sublineasCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (codGcarga != null ? codGcarga.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof GruposCarga)) {
return false;
}
GruposCarga other = (GruposCarga) object;
if ((this.codGcarga == null && other.codGcarga != null) || (this.codGcarga != null && !this.codGcarga.equals(other.codGcarga))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.GruposCarga[ codGcarga=" + codGcarga + " ]";
}
public String getXdesc() {
return xdesc;
}
public void setXdesc(String xdesc) {
this.xdesc = xdesc;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/OrdenesPagos.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "ORDENES_PAGOS")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "OrdenesPagos.findAll", query = "SELECT o FROM OrdenesPagos o")
, @NamedQuery(name = "OrdenesPagos.findByNroOrden", query = "SELECT o FROM OrdenesPagos o WHERE o.nroOrden = :nroOrden")
, @NamedQuery(name = "OrdenesPagos.findByForden", query = "SELECT o FROM OrdenesPagos o WHERE o.forden = :forden")
, @NamedQuery(name = "OrdenesPagos.findByCodProveed", query = "SELECT o FROM OrdenesPagos o WHERE o.codProveed = :codProveed")
, @NamedQuery(name = "OrdenesPagos.findByMEstado", query = "SELECT o FROM OrdenesPagos o WHERE o.mEstado = :mEstado")
, @NamedQuery(name = "OrdenesPagos.findByXnroCheque", query = "SELECT o FROM OrdenesPagos o WHERE o.xnroCheque = :xnroCheque")
, @NamedQuery(name = "OrdenesPagos.findByCodBanco", query = "SELECT o FROM OrdenesPagos o WHERE o.codBanco = :codBanco")
, @NamedQuery(name = "OrdenesPagos.findByITotalOrden", query = "SELECT o FROM OrdenesPagos o WHERE o.iTotalOrden = :iTotalOrden")
, @NamedQuery(name = "OrdenesPagos.findByITotalRetencion", query = "SELECT o FROM OrdenesPagos o WHERE o.iTotalRetencion = :iTotalRetencion")
, @NamedQuery(name = "OrdenesPagos.findByXobs", query = "SELECT o FROM OrdenesPagos o WHERE o.xobs = :xobs")})
public class OrdenesPagos implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "Nro_Orden")
private Long nroOrden;
@Basic(optional = false)
@NotNull
@Column(name = "forden")
@Temporal(TemporalType.TIMESTAMP)
private Date forden;
@Column(name = "Cod_Proveed")
private Short codProveed;
@Column(name = "mEstado")
private Character mEstado;
@Size(max = 15)
@Column(name = "xnro_cheque")
private String xnroCheque;
@Column(name = "cod_Banco")
private Short codBanco;
@Column(name = "iTotal_Orden")
private Long iTotalOrden;
@Column(name = "iTotal_Retencion")
private Long iTotalRetencion;
@Size(max = 50)
@Column(name = "xobs")
private String xobs;
public OrdenesPagos() {
}
public OrdenesPagos(Long nroOrden) {
this.nroOrden = nroOrden;
}
public OrdenesPagos(Long nroOrden, Date forden) {
this.nroOrden = nroOrden;
this.forden = forden;
}
public Long getNroOrden() {
return nroOrden;
}
public void setNroOrden(Long nroOrden) {
this.nroOrden = nroOrden;
}
public Date getForden() {
return forden;
}
public void setForden(Date forden) {
this.forden = forden;
}
public Short getCodProveed() {
return codProveed;
}
public void setCodProveed(Short codProveed) {
this.codProveed = codProveed;
}
public Character getMEstado() {
return mEstado;
}
public void setMEstado(Character mEstado) {
this.mEstado = mEstado;
}
public String getXnroCheque() {
return xnroCheque;
}
public void setXnroCheque(String xnroCheque) {
this.xnroCheque = xnroCheque;
}
public Short getCodBanco() {
return codBanco;
}
public void setCodBanco(Short codBanco) {
this.codBanco = codBanco;
}
public Long getITotalOrden() {
return iTotalOrden;
}
public void setITotalOrden(Long iTotalOrden) {
this.iTotalOrden = iTotalOrden;
}
public Long getITotalRetencion() {
return iTotalRetencion;
}
public void setITotalRetencion(Long iTotalRetencion) {
this.iTotalRetencion = iTotalRetencion;
}
public String getXobs() {
return xobs;
}
public void setXobs(String xobs) {
this.xobs = xobs;
}
@Override
public int hashCode() {
int hash = 0;
hash += (nroOrden != null ? nroOrden.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof OrdenesPagos)) {
return false;
}
OrdenesPagos other = (OrdenesPagos) object;
if ((this.nroOrden == null && other.nroOrden != null) || (this.nroOrden != null && !this.nroOrden.equals(other.nroOrden))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.OrdenesPagos[ nroOrden=" + nroOrden + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/SerieFacturas.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "serie_facturas")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "SerieFacturas.findAll", query = "SELECT s FROM SerieFacturas s")
, @NamedQuery(name = "SerieFacturas.findByFfinal", query = "SELECT s FROM SerieFacturas s WHERE s.serieFacturasPK.ffinal = :ffinal")
, @NamedQuery(name = "SerieFacturas.findByNdocumFinal", query = "SELECT s FROM SerieFacturas s WHERE s.serieFacturasPK.ndocumFinal = :ndocumFinal")
, @NamedQuery(name = "SerieFacturas.findByNserie", query = "SELECT s FROM SerieFacturas s WHERE s.nserie = :nserie")
, @NamedQuery(name = "SerieFacturas.findByCtipoDocum", query = "SELECT s FROM SerieFacturas s WHERE s.ctipoDocum = :ctipoDocum")
, @NamedQuery(name = "SerieFacturas.findByFalta", query = "SELECT s FROM SerieFacturas s WHERE s.falta = :falta")
, @NamedQuery(name = "SerieFacturas.findByCusuario", query = "SELECT s FROM SerieFacturas s WHERE s.cusuario = :cusuario")
, @NamedQuery(name = "SerieFacturas.findByFultimModif", query = "SELECT s FROM SerieFacturas s WHERE s.fultimModif = :fultimModif")
, @NamedQuery(name = "SerieFacturas.findByCusuarioModif", query = "SELECT s FROM SerieFacturas s WHERE s.cusuarioModif = :cusuarioModif")})
public class SerieFacturas implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected SerieFacturasPK serieFacturasPK;
@Basic(optional = false)
@NotNull
@Column(name = "nserie")
private int nserie;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 3)
@Column(name = "ctipo_docum")
private String ctipoDocum;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
public SerieFacturas() {
}
public SerieFacturas(SerieFacturasPK serieFacturasPK) {
this.serieFacturasPK = serieFacturasPK;
}
public SerieFacturas(SerieFacturasPK serieFacturasPK, int nserie, String ctipoDocum) {
this.serieFacturasPK = serieFacturasPK;
this.nserie = nserie;
this.ctipoDocum = ctipoDocum;
}
public SerieFacturas(Date ffinal, long ndocumFinal) {
this.serieFacturasPK = new SerieFacturasPK(ffinal, ndocumFinal);
}
public SerieFacturasPK getSerieFacturasPK() {
return serieFacturasPK;
}
public void setSerieFacturasPK(SerieFacturasPK serieFacturasPK) {
this.serieFacturasPK = serieFacturasPK;
}
public int getNserie() {
return nserie;
}
public void setNserie(int nserie) {
this.nserie = nserie;
}
public String getCtipoDocum() {
return ctipoDocum;
}
public void setCtipoDocum(String ctipoDocum) {
this.ctipoDocum = ctipoDocum;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
@Override
public int hashCode() {
int hash = 0;
hash += (serieFacturasPK != null ? serieFacturasPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof SerieFacturas)) {
return false;
}
SerieFacturas other = (SerieFacturas) object;
if ((this.serieFacturasPK == null && other.serieFacturasPK != null) || (this.serieFacturasPK != null && !this.serieFacturasPK.equals(other.serieFacturasPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.SerieFacturas[ serieFacturasPK=" + serieFacturasPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/MovimientoMercaDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
/**
*
* @author dadob
*/
public class MovimientoMercaDto {
private String codMerca;
private Long cantCajas;
private Long cantUnid;
public String getCodMerca() {
return codMerca;
}
public void setCodMerca(String codMerca) {
this.codMerca = codMerca;
}
public Long getCantCajas() {
return cantCajas;
}
public void setCantCajas(Long cantCajas) {
this.cantCajas = cantCajas;
}
public Long getCantUnid() {
return cantUnid;
}
public void setCantUnid(Long cantUnid) {
this.cantUnid = cantUnid;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/SublineasFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.GruposCarga;
import entidad.Sublineas;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
/**
*
* @author admin
*/
@Stateless
public class SublineasFacade extends AbstractFacade<Sublineas> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public SublineasFacade() {
super(Sublineas.class);
}
public List<Sublineas> listarSublineasConMercaderias() {
Query q = getEntityManager().createNativeQuery("SELECT DISTINCT s.cod_sublinea, s.xdesc \n"
+ " FROM sublineas s, mercaderias m WHERE s.cod_sublinea = m.cod_sublinea \n"
+ "AND m.mestado = 'A' ORDER BY s.xdesc ", Sublineas.class);
//System.out.println(q.toString());
List<Sublineas> respuesta = new ArrayList<Sublineas>();
respuesta = q.getResultList();
return respuesta;
}
public List<Sublineas> listarSublineasOrdenadoXSublineas() {
Query q = getEntityManager().createNativeQuery("select s.*\n"
+ "from sublineas s, lineas l\n"
+ "where s.cod_linea = l.cod_linea\n"
+ "order by l.xdesc asc", Sublineas.class);
System.out.println(q.toString());
List<Sublineas> respuesta = new ArrayList<Sublineas>();
respuesta = q.getResultList();
return respuesta;
}
public List<GruposCarga> listarGruposCargaOrdenadoXGruposCarga() {
Query q = getEntityManager().createNativeQuery("select s.*\n"
+ "from sublineas s, grupos_carga g\n"
+ "where s.cod_gcarga = g.cod_gcarga\n"
+ "order by g.xdesc asc", GruposCarga.class);
System.out.println(q.toString());
List<GruposCarga> respuesta = new ArrayList<GruposCarga>();
respuesta = q.getResultList();
return respuesta;
}
public void insertarSublineas(Sublineas sublineas) {
StoredProcedureQuery q = getEntityManager().createStoredProcedureQuery("InsertarSublineas");
q.registerStoredProcedureParameter("xdesc", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cod_linea", Short.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cod_gcarga", Short.class, ParameterMode.IN);
q.registerStoredProcedureParameter("falta", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cusuario", String.class, ParameterMode.IN);
q.setParameter("xdesc", sublineas.getXdesc());
q.setParameter("cod_linea", sublineas.getCodLinea().getCodLinea());
q.setParameter("cod_gcarga", sublineas.getCodGcarga().getCodGcarga());
q.setParameter("falta", sublineas.getFalta());
q.setParameter("cusuario", sublineas.getCusuario());
q.execute();
}
public List<Sublineas> listarSublineas() {
return getEntityManager().createNativeQuery("SELECT * FROM sublineas ", Sublineas.class).getResultList();
}
public Sublineas subLineaById(Integer id) {
List<Sublineas> lista = getEntityManager().createNativeQuery("SELECT * FROM sublineas WHERE cod_sublinea=" + id, Sublineas.class).getResultList();
if (lista.isEmpty()) {//Si no hay elemento
return null;
} else {
return lista.get(0);
}
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiControlPedBean.java
package bean.listados;
import dao.DepositosFacade;
import dao.EmpleadosFacade;
import dao.ExcelFacade;
import entidad.Depositos;
import entidad.DepositosPK;
import entidad.Empleados;
import entidad.EmpleadosPK;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiControlPedBean {
@EJB
private EmpleadosFacade empleadosFacade;
@EJB
private ExcelFacade excelFacade;
private Empleados empleados;
private List<Empleados> listaEmpleados;
@EJB
private DepositosFacade depositosFacade;
private Depositos depositos;
private List<Depositos> listaDepositos;
private Date desde;
private Date hasta;
public LiControlPedBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.empleados = new Empleados(new EmpleadosPK());
this.listaEmpleados = new ArrayList<Empleados>();
this.depositos = new Depositos(new DepositosPK());
this.listaDepositos = new ArrayList<Depositos>();
this.desde = new Date();
this.hasta = new Date();
}
public List<Empleados> listarEmpleados() {
this.listaEmpleados = empleadosFacade.listarEmpleadosActivos();
return this.listaEmpleados;
}
public List<Depositos> listarDepositos() {
this.listaDepositos = depositosFacade.listarDepositosActivos();
return this.listaDepositos;
}
public void ejecutar(String tipo) {
LlamarReportes rep = new LlamarReportes();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
Integer empleado = 0;
String nomEmple = "";
Integer deposito = 0;
String descDepo = "";
Empleados auxEmple = new Empleados();
Depositos auxDepo = new Depositos();
if (this.empleados == null) {
empleado = 0;
nomEmple = "TODOS";
} else {
empleado = Integer.parseInt(this.empleados.getEmpleadosPK().getCodEmpleado() + "");
auxEmple = empleadosFacade.getNombreEmpleado(empleado);
nomEmple = auxEmple.getXnombre();
}
if (this.depositos == null) {
deposito = 0;
descDepo = "TODOS";
} else {
deposito = Integer.parseInt(this.depositos.getDepositosPK().getCodDepo() + "");
auxDepo = depositosFacade.getNombreDeposito(deposito);
descDepo = auxDepo.getXdesc();
}
if (tipo.equals("VIST")) {
rep.reporteLiConsDoc(dateToString(desde), dateToString(hasta), dateToString2(desde), dateToString2(hasta), empleado, "admin", tipo, nomEmple, descDepo, deposito);
} else {
List<Object[]> lista = new ArrayList<Object[]>();
String[] columnas = new String[4];
columnas[0] = "cod_zona";
columnas[1] = "xdesc_zona";
columnas[2] = "mestado";
columnas[3] = "kfilas";
String sql = "SELECT r.cod_zona, z.xdesc as xdesc_zona, p.mestado, ISNULL(COUNT(*),0) as kfilas\n"
+ " FROM pedidos p, RUTAS R, clientes c, zonas z\n"
+ " WHERE p.cod_cliente = c.cod_cliente\n"
+ " AND c.cod_ruta = r.cod_ruta\n"
+ " AND r.cod_zona = z.cod_zona\n"
+ " AND p.fpedido BETWEEN '"+fdesde+"' AND '"+fhasta+"'\n"
+ " AND (p.cod_depo = "+deposito+" or "+deposito+"=0)\n"
+ " AND (p.cod_vendedor = "+empleado+" or "+empleado+"=0)\n"
+ "GROUP BY r.cod_zona, z.xdesc, p.mestado\n"
+ "UNION ALL\n"
+ "\n"
+ "SELECT r.cod_zona, z.xdesc as xdesc_zona, 'S' as mestado, ISNULL(COUNT(*),0) as kfilas\n"
+ " FROM pedidos p, RUTAS R, clientes c, zonas z\n"
+ " WHERE p.cod_cliente = c.cod_cliente\n"
+ " AND c.cod_ruta = r.cod_ruta\n"
+ " AND r.cod_zona = z.cod_zona\n"
+ " AND p.fpedido BETWEEN '"+fdesde+"' AND '"+fhasta+"'\n"
+ " AND p.mestado = 'E'\n"
+ " AND p.ffactur IS NULL\n"
+ " AND (p.cod_depo = "+deposito+" or "+deposito+"=0)\n"
+ " AND (p.cod_vendedor = "+empleado+" or "+empleado+"=0)\n"
+ "GROUP BY r.cod_zona, z.xdesc, p.mestado";
lista = excelFacade.listarParaExcel(sql);
rep.exportarExcel(columnas, lista, "locontrolped");
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
//Getters & Setters
public Empleados getEmpleados() {
return empleados;
}
public void setEmpleados(Empleados empleados) {
this.empleados = empleados;
}
public List<Empleados> getListaEmpleados() {
return listaEmpleados;
}
public void setListaEmpleados(List<Empleados> listaEmpleados) {
this.listaEmpleados = listaEmpleados;
}
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
public Depositos getDepositos() {
return depositos;
}
public void setDepositos(Depositos depositos) {
this.depositos = depositos;
}
public List<Depositos> getListaDepositos() {
return listaDepositos;
}
public void setListaDepositos(List<Depositos> listaDepositos) {
this.listaDepositos = listaDepositos;
}
}
<file_sep>/SisVenLog-war/src/java/bean/ConceptoDocumentoBean.java
package bean;
import dao.ConceptosDocumentosFacade;
import dao.TiposDocumentosFacade;
import entidad.ConceptosDocumentos;
import entidad.ConceptosDocumentosPK;
import entidad.TiposDocumentos;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class ConceptoDocumentoBean implements Serializable {
@EJB
private ConceptosDocumentosFacade conceptoDocumentoFacade;
@EJB
private TiposDocumentosFacade tiposDocumentosFacade;
private TiposDocumentos tiposDocumentos = new TiposDocumentos();
private String filtro = "";
private ConceptosDocumentos conceptoDocumento = new ConceptosDocumentos();
private List<ConceptosDocumentos> listaConceptoDocumento = new ArrayList<ConceptosDocumentos>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public ConceptoDocumentoBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public ConceptosDocumentos getConceptoDocumento() {
return conceptoDocumento;
}
public void setConceptoDocumento(ConceptosDocumentos conceptoDocumento) {
this.conceptoDocumento = conceptoDocumento;
}
public List<ConceptosDocumentos> getListaConceptoDocumento() {
return listaConceptoDocumento;
}
public void setListaConceptoDocumento(List<ConceptosDocumentos> listaConceptoDocumento) {
this.listaConceptoDocumento = listaConceptoDocumento;
}
public TiposDocumentos getTiposDocumentos() {
return tiposDocumentos;
}
public void setTiposDocumentos(TiposDocumentos tiposDocumentos) {
this.tiposDocumentos = tiposDocumentos;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaConceptoDocumento = new ArrayList<ConceptosDocumentos>();
this.conceptoDocumento = new ConceptosDocumentos(new ConceptosDocumentosPK());
this.tiposDocumentos = new TiposDocumentos();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
this.filtro = "";
conceptoDocumento.setMafectaStock('S');
listar();
RequestContext.getCurrentInstance().update("formConceptoDocumento");
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public void nuevo() {
this.conceptoDocumento = new ConceptosDocumentos();
}
public List<ConceptosDocumentos> listar() {
listaConceptoDocumento = conceptoDocumentoFacade.findAll();
return listaConceptoDocumento;
}
public List<ConceptosDocumentos> listarTiposDocumentosLiNotasComp2() {
listaConceptoDocumento = conceptoDocumentoFacade.listarConceptoDocumentoListadoNotaCompras();
return listaConceptoDocumento;
}
public void insertar() {
try {
conceptoDocumento.getConceptosDocumentosPK().setCtipoDocum(tiposDocumentos.getCtipoDocum());
conceptoDocumento.setXdesc(conceptoDocumento.getXdesc().toUpperCase());
conceptoDocumento.setFalta(new Date());
conceptoDocumento.setCusuario("admin");
conceptoDocumentoFacade.create(conceptoDocumento);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevConceptoDocumento').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editar() {
try {
if ("".equals(this.conceptoDocumento.getXdesc())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
conceptoDocumento.setXdesc(conceptoDocumento.getXdesc().toUpperCase());
conceptoDocumentoFacade.edit(conceptoDocumento);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditConceptoDocumento').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void borrar() {
try {
conceptoDocumentoFacade.remove(conceptoDocumento);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacConceptoDocumento').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
if ("" != this.conceptoDocumento.getXdesc()) {
this.setHabBtnEdit(false);
this.tiposDocumentos = tiposDocumentosFacade.find(conceptoDocumento.getConceptosDocumentosPK().getCtipoDocum());
} else {
this.setHabBtnEdit(true);
}
}
public String conceptoDocumentoDC(Float indice) {
String retorno = "";
Float aux = indice;
if (aux < 0) {
retorno = "CREDITO";
}
if (aux >= 0) {
retorno = "DEBITO";
}
return retorno;
}
public void verificarCargaDatos() {
boolean cargado = false;
if (conceptoDocumento != null) {
if (conceptoDocumento.getXdesc() != null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarConceptoDocumento').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevConceptoDocumento').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarConceptoDocumento').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevConceptoDocumento').hide();");
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/TiposDocumentosFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.TiposDocumentos;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author WORK
*/
@Stateless
public class TiposDocumentosFacade extends AbstractFacade<TiposDocumentos> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public TiposDocumentosFacade() {
super(TiposDocumentos.class);
}
public List<TiposDocumentos> listarTipoDocumentoImpresionMasivaFacturas() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('FCO','FCR','CPV')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoLiAnudoc() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('FCR','FCO','CPV','CVC','COC', 'FCC','PED','EN','NCV','NDV', 'NDP', 'NCC', 'NDC','AJ','RM','REC','CHQ','REP','CHE')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoLiFacBonif() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('FCO','CPV','FCR')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoParaConsultaDeVentas() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('FCO','CPV','FCR', 'PED', 'NCV', 'NDV')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoParaConsultaDeCompras() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('FCC', 'COC', 'CVC', 'NCC', 'NDC', 'NDP')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoCambiarEntregador() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('FCO','CPV','FCR', 'NCV', 'EN')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoReciboProveedor() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('REP')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoParaReciboCompraProveedor() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('FCC', 'NCC', 'NDC')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoParaReciboVentaCliente() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('FCR','NCV','FCP')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoReciboCliente() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('REC')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoGenDocuAnul() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('FCO', 'EN', 'NCV', 'REM')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoFactura() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('FCO','FCR')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public List<TiposDocumentos> listarTipoDocumentoListadoNotaCompras() {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum in ('NDC','NCC','NDP')", TiposDocumentos.class);
System.out.println(q.toString());
List<TiposDocumentos> respuesta = new ArrayList<TiposDocumentos>();
respuesta = q.getResultList();
return respuesta;
}
public TiposDocumentos getTipoDocumentoById(String ctipoDocum){
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from tipos_documentos\n"
+ "where ctipo_docum = upper('" + ctipoDocum + "')", TiposDocumentos.class);
System.out.println(q.toString());
TiposDocumentos respuesta = new TiposDocumentos();
if (q.getResultList().size() <= 0) {
respuesta = null;
} else {
respuesta = (TiposDocumentos)q.getSingleResult();
}
return respuesta;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/BuscadorFacade.java
package dao;
import dto.AuxiliarImpresionMasivaDto;
import dto.AuxiliarImpresionRemisionDto;
import dto.AuxiliarImpresionServiciosDto;
import dto.buscadorDto;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.*;
@Stateless
public class BuscadorFacade {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public BuscadorFacade() {
}
public List<buscadorDto> buscar(String sql) {
List<buscadorDto> respuesta = new ArrayList<buscadorDto>();
try {
Query q = getEntityManager().createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultList = q.getResultList();
if (resultList.size() <= 0) {
respuesta = new ArrayList<buscadorDto>();
return respuesta;
} else {
for (Object[] obj : resultList) {
buscadorDto aux = new buscadorDto();
aux.setDato1(obj[0].toString());
aux.setDato2(obj[2].toString());
aux.setDato3(obj[1].toString());
respuesta.add(aux);
}
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al listar secuencias."));
}
return respuesta;
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiCamionesBean.java
package bean.listados;
import dao.ExcelFacade;
import dao.MercaderiasFacade;
import dao.PersonalizedFacade;
import dao.TiposDocumentosFacade;
import dao.DepositosFacade;
import dto.LiMercaSinDto;
import entidad.Mercaderias;
import entidad.MercaderiasPK;
import entidad.Depositos;
import entidad.DepositosPK;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import org.primefaces.model.DualListModel;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiCamionesBean {
@EJB
private MercaderiasFacade mercaderiasFacade;
@EJB
private DepositosFacade depositosFacade;
@EJB
private PersonalizedFacade personalizedFacade;
@EJB
private ExcelFacade excelFacade;
private Depositos depositos;
private List<Depositos> listaDepositos;
private Date desde;
private Date hasta;
private List<Mercaderias> listaMercaderias;
private List<Mercaderias> listaMercaderiasSeleccionadas;
private DualListModel<Mercaderias> mercaderias;
public LiCamionesBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.depositos = new Depositos(new DepositosPK());
this.listaDepositos = new ArrayList<Depositos>();
this.desde = new Date();
this.hasta = new Date();
//Cities
List<Mercaderias> mercaSource = new ArrayList<Mercaderias>();
List<Mercaderias> mercaTarget = new ArrayList<Mercaderias>();
mercaSource = mercaderiasFacade.listarMercaderiasActivasDepo1();
mercaderias = new DualListModel<Mercaderias>(mercaSource, mercaTarget);
}
public void ejecutar(String tipo) {
try {
personalizedFacade.ejecutarSentenciaSQL("drop table tmp_mercaderias");
personalizedFacade.ejecutarSentenciaSQL("CREATE TABLE tmp_mercaderias (cod_merca CHAR(13), cod_barra CHAR(20), \n"
+ "xdesc CHAR(50), nrelacion SMALLINT, cant_cajas integer, cant_unid integer )");
if (mercaderias.getTarget().size() > 0) {
listaMercaderiasSeleccionadas = mercaderias.getTarget();
for (int i = 0; i < listaMercaderiasSeleccionadas.size(); i++) {
MercaderiasPK pk = listaMercaderiasSeleccionadas.get(i).getMercaderiasPK();
Mercaderias aux = new Mercaderias();
aux = mercaderiasFacade.find(pk);
personalizedFacade.ejecutarSentenciaSQL("INSERT INTO tmp_mercaderias (cod_merca, cod_barra, xdesc, nrelacion,cant_cajas, cant_unid )\n"
+ " VALUES ('" + aux.getMercaderiasPK().getCodMerca() + "', '" + aux.getCodBarra() + "', '" + aux.getXdesc() + "', " + aux.getNrelacion() + ",0,0 )");
}
} else {
personalizedFacade.ejecutarSentenciaSQL("insert into tmp_mercaderias\n"
+ "select m.cod_merca, m.cod_barra, m.xdesc, m.nrelacion, 1, 1\n"
+ "from mercaderias m, existencias e\n"
+ "where m.cod_merca = e.cod_merca\n"
+ "and m.mestado = 'A'\n"
+ "and e.cod_depo = 1");
}
LlamarReportes rep = new LlamarReportes();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
//String tipoDoc = "";
String depo = "";
String descDepo = "";
String descTipoDoc = "";
StringBuilder sql = new StringBuilder();
if (this.depositos == null) {
depo = "0";
descDepo = "TODOS";
} else {
depo = this.depositos.getDepositosPK().getCodDepo() + "";
descDepo = depositosFacade.find(this.depositos.getDepositosPK()).getXdesc();
}
/*if (this.depositos != null) {
personalizedFacade.ejecutarSentenciaSQL("SELECT a.cod_merca, a.fmovim, a.cod_depo, a.cant_cajas as cajas_ini, a.cant_unid as unid_ini \n"
+ " INTO tmp_saldos FROM existencias_saldos a \n"
+ " WHERE a.cod_empr = 2 \n"
+ " AND a.cod_depo = " + depo + "\n"
+ " AND fmovim = (SELECT MAX(fmovim) \n"
+ " FROM existencias_saldos b\n"
+ " WHERE a.cod_empr = b.cod_empr \n"
+ " AND a.cod_merca = b.cod_merca \n"
+ " AND a.cod_depo = b.cod_depo \n"
+ " AND fmovim <= '" + fhasta + "') ");
}*/
sql.append("SELECT E.cod_merca, m.xdesc, m.cod_barra, m.nrelacion, \n"
+ " e.cant_cajas, e.cant_unid, e.reser_cajas, e.reser_unid, m.mestado \n"
+ " FROM existencias e, mercaderias m\n"
+ " WHERE e.cod_empr = 2 \n"
+ " AND (cod_depo = "+depo+" or "+depo+" = 0)\n"
+ " AND e.cod_empr = m.cod_empr \n"
+ " AND (e.cant_cajas <> 0 OR e.cant_unid <> 0) \n"
+ " AND e.cod_merca = m.cod_merca \n"
+ " ORDER BY e.cod_merca ");
System.out.println("SQL limercasin: " + sql.toString());
if (tipo.equals("VIST")) {
rep.reporteLiCamiones(sql.toString(), dateToString(desde), dateToString(hasta), "admin", tipo);
} else if (tipo.equals("ARCH")) {
List<Object[]> auxExcel = new ArrayList<Object[]>();
auxExcel = excelFacade.listarParaExcel(sql.toString());
rep.excelLiCamiones(auxExcel);
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Error", e.getMessage()));
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
//Getters & Setters
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
public Depositos getDepositos() {
return depositos;
}
public void setDepositos(Depositos depositos) {
this.depositos = depositos;
}
public List<Depositos> getListaDepositos() {
return listaDepositos;
}
public void setListaDepositos(List<Depositos> listaDepositos) {
this.listaDepositos = listaDepositos;
}
public List<Mercaderias> getListaMercaderias() {
return listaMercaderias;
}
public void setListaMercaderias(List<Mercaderias> listaMercaderias) {
this.listaMercaderias = listaMercaderias;
}
public List<Mercaderias> getListaMercaderiasSeleccionadas() {
return listaMercaderiasSeleccionadas;
}
public void setListaMercaderiasSeleccionadas(List<Mercaderias> listaMercaderiasSeleccionadas) {
this.listaMercaderiasSeleccionadas = listaMercaderiasSeleccionadas;
}
public DualListModel<Mercaderias> getMercaderias() {
return mercaderias;
}
public void setMercaderias(DualListModel<Mercaderias> mercaderias) {
this.mercaderias = mercaderias;
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiDatosMercaderiasBean.java
package bean.listados;
import dao.DivisionesFacade;
import dao.ExcelFacade;
import dao.MercaderiasFacade;
import dao.PersonalizedFacade;
import dao.SublineasFacade;
import entidad.Divisiones;
import entidad.Mercaderias;
import entidad.MercaderiasPK;
import entidad.Sublineas;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import org.primefaces.model.DualListModel;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiDatosMercaderiasBean {
@EJB
private MercaderiasFacade mercaderiasFacade;
@EJB
private SublineasFacade sublineasFacade;
@EJB
private DivisionesFacade divisionesFacade;
@EJB
private PersonalizedFacade personalizedFacade;
@EJB
private ExcelFacade excelFacade;
private Sublineas sublineas;
private Divisiones divisiones;
private List<Sublineas> listaSublineas = new ArrayList<Sublineas>();
private List<Divisiones> listaDivisiones = new ArrayList<Divisiones>();
String estado = "";
/*private List<Mercaderias> listaMercaderias;
private List<Mercaderias> listaMercaderiasSeleccionadas;
private DualListModel<Mercaderias> mercaderias;*/
public LiDatosMercaderiasBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.sublineas = new Sublineas();
this.divisiones = new Divisiones();
estado = "";
//Cities
/*List<Mercaderias> mercaSource = new ArrayList<Mercaderias>();
List<Mercaderias> mercaTarget = new ArrayList<Mercaderias>();
mercaSource = mercaderiasFacade.listarMercaderiasActivasDepo1();
mercaderias = new DualListModel<Mercaderias>(mercaSource, mercaTarget);*/
}
public List<Sublineas> listarSublineas() {
this.listaSublineas = sublineasFacade.listarSublineasConMercaderias();
return this.listaSublineas;
}
public List<Divisiones> listarDivisiones() {
this.listaDivisiones = divisionesFacade.listarSubdiviciones();
return this.listaDivisiones;
}
public void ejecutar(String tipo) {
/* personalizedFacade.ejecutarSentenciaSQL("drop table tmp_mercaderias");
personalizedFacade.ejecutarSentenciaSQL("CREATE TABLE tmp_mercaderias (cod_merca CHAR(13), cod_barra CHAR(20), \n"
+ "xdesc CHAR(50), nrelacion SMALLINT, cant_cajas integer, cant_unid integer )");
if (mercaderias.getTarget().size() > 0) {
listaMercaderiasSeleccionadas = mercaderias.getTarget();
for (int i = 0; i < listaMercaderiasSeleccionadas.size(); i++) {
MercaderiasPK pk = listaMercaderiasSeleccionadas.get(i).getMercaderiasPK();
Mercaderias aux = new Mercaderias();
aux = mercaderiasFacade.find(pk);
personalizedFacade.ejecutarSentenciaSQL("INSERT INTO tmp_mercaderias (cod_merca, cod_barra, xdesc, nrelacion,cant_cajas, cant_unid )\n"
+ " VALUES ('" + aux.getMercaderiasPK().getCodMerca() + "', '" + aux.getCodBarra() + "', '" + aux.getXdesc() + "', " + aux.getNrelacion() + ",0,0 )");
}
} else {
personalizedFacade.ejecutarSentenciaSQL("insert into tmp_mercaderias\n"
+ "select m.cod_merca, m.cod_barra, m.xdesc, m.nrelacion, 1, 1\n"
+ "from mercaderias m, existencias e\n"
+ "where m.cod_merca = e.cod_merca\n"
+ "and m.mestado = 'A'\n"
+ "and e.cod_depo = 1");
}
*/
Integer codSublinea = 0;
String descSublinea = "";
Integer codDivision = 0;
String descDivision = "";
if (sublineas == null) {
codSublinea = 0;
descSublinea = "TODOS";
} else {
codSublinea = Integer.parseInt(sublineas.getCodSublinea() + "");
descSublinea = sublineasFacade.find(sublineas.getCodSublinea()).getXdesc();
}
if (divisiones == null) {
codDivision = 0;
descDivision = "TODOS";
} else {
codDivision = Integer.parseInt(divisiones.getCodDivision() + "");
descDivision = divisionesFacade.find(divisiones.getCodDivision()).getXdesc();
}
estado = "TODOS";
LlamarReportes rep = new LlamarReportes();
if (tipo.equals("VIST")) {
rep.reporteLiDatosMer(codSublinea, descSublinea, codDivision, descDivision, estado, "admin", tipo);
} else {
List<Object[]> lista = new ArrayList<Object[]>();
String[] columnas = new String[12];
columnas[0] = "cod_division";
columnas[1] = "xdesc_division";
columnas[2] = "cod_categoria";
columnas[3] = "xdesc_categoria";
columnas[4] = "cod_linea";
columnas[5] = "xdesc_linea";
columnas[6] = "cod_sublinea";
columnas[7] = "xdesc_sublinea";
columnas[8] = "cod_merca";
columnas[9] = "xdesc";
columnas[10] = "mestado";
columnas[11] = "mexiste";
String sql = "SELECT d.cod_division, d.xdesc as xdesc_division, g.cod_categoria,\n"
+ "g.xdesc as xdesc_categoria, l.cod_linea, l.xdesc as xdesc_linea,\n"
+ "s.cod_sublinea, s.xdesc as xdesc_sublinea, m.cod_merca, m.xdesc, m.mestado, m.mexiste\n"
+ "FROM mercaderias m, sublineas s, lineas l, categorias g, divisiones d\n"
+ "WHERE m.cod_sublinea = s.cod_sublinea\n"
+ "AND s.cod_linea = l.cod_linea\n"
+ "AND l.cod_categoria = g.cod_categoria\n"
+ "AND g.cod_division = d.cod_division\n"
+ "AND (d.cod_division = "+codDivision+" or "+codDivision+"=0)\n"
+ "AND (s.cod_sublinea = "+codSublinea+" or "+codSublinea+"=0)\n"
+ "AND (m.mestado = $P{estado} or $P{estado} = 'TODOS')\n"
+ "ORDER BY d.cod_division, g.cod_categoria, l.cod_linea, s.cod_sublinea, m.cod_merca";
lista = excelFacade.listarParaExcel(sql);
rep.exportarExcel(columnas, lista, "lidatosmerca");
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
//Getters & Setters
public Sublineas getSublineas() {
return sublineas;
}
public void setSublineas(Sublineas sublineas) {
this.sublineas = sublineas;
}
public Divisiones getDivisiones() {
return divisiones;
}
public void setDivisiones(Divisiones divisiones) {
this.divisiones = divisiones;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public List<Sublineas> getListaSublineas() {
return listaSublineas;
}
public void setListaSublineas(List<Sublineas> listaSublineas) {
this.listaSublineas = listaSublineas;
}
public List<Divisiones> getListaDivisiones() {
return listaDivisiones;
}
public void setListaDivisiones(List<Divisiones> listaDivisiones) {
this.listaDivisiones = listaDivisiones;
}
/*public List<Mercaderias> getListaMercaderias() {
return listaMercaderias;
}
public void setListaMercaderias(List<Mercaderias> listaMercaderias) {
this.listaMercaderias = listaMercaderias;
}
public List<Mercaderias> getListaMercaderiasSeleccionadas() {
return listaMercaderiasSeleccionadas;
}
public void setListaMercaderiasSeleccionadas(List<Mercaderias> listaMercaderiasSeleccionadas) {
this.listaMercaderiasSeleccionadas = listaMercaderiasSeleccionadas;
}
public DualListModel<Mercaderias> getMercaderias() {
return mercaderias;
}
public void setMercaderias(DualListModel<Mercaderias> mercaderias) {
this.mercaderias = mercaderias;
}*/
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Inventario.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "inventario")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Inventario.findAll", query = "SELECT i FROM Inventario i")
, @NamedQuery(name = "Inventario.findByCodEmpr", query = "SELECT i FROM Inventario i WHERE i.inventarioPK.codEmpr = :codEmpr")
, @NamedQuery(name = "Inventario.findByNroInven", query = "SELECT i FROM Inventario i WHERE i.inventarioPK.nroInven = :nroInven")
, @NamedQuery(name = "Inventario.findByCodDepo", query = "SELECT i FROM Inventario i WHERE i.codDepo = :codDepo")
, @NamedQuery(name = "Inventario.findByFmovim", query = "SELECT i FROM Inventario i WHERE i.fmovim = :fmovim")
, @NamedQuery(name = "Inventario.findByMtipoInv", query = "SELECT i FROM Inventario i WHERE i.mtipoInv = :mtipoInv")
, @NamedQuery(name = "Inventario.findByCusuario", query = "SELECT i FROM Inventario i WHERE i.cusuario = :cusuario")
, @NamedQuery(name = "Inventario.findByFalta", query = "SELECT i FROM Inventario i WHERE i.falta = :falta")})
public class Inventario implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected InventarioPK inventarioPK;
@Basic(optional = false)
@NotNull
@Column(name = "cod_depo")
private short codDepo;
@Column(name = "fmovim")
@Temporal(TemporalType.TIMESTAMP)
private Date fmovim;
@Column(name = "mtipo_inv")
private Character mtipoInv;
@Size(max = 10)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Empresas empresas;
public Inventario() {
}
public Inventario(InventarioPK inventarioPK) {
this.inventarioPK = inventarioPK;
}
public Inventario(InventarioPK inventarioPK, short codDepo) {
this.inventarioPK = inventarioPK;
this.codDepo = codDepo;
}
public Inventario(short codEmpr, int nroInven) {
this.inventarioPK = new InventarioPK(codEmpr, nroInven);
}
public InventarioPK getInventarioPK() {
return inventarioPK;
}
public void setInventarioPK(InventarioPK inventarioPK) {
this.inventarioPK = inventarioPK;
}
public short getCodDepo() {
return codDepo;
}
public void setCodDepo(short codDepo) {
this.codDepo = codDepo;
}
public Date getFmovim() {
return fmovim;
}
public void setFmovim(Date fmovim) {
this.fmovim = fmovim;
}
public Character getMtipoInv() {
return mtipoInv;
}
public void setMtipoInv(Character mtipoInv) {
this.mtipoInv = mtipoInv;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public Empresas getEmpresas() {
return empresas;
}
public void setEmpresas(Empresas empresas) {
this.empresas = empresas;
}
@Override
public int hashCode() {
int hash = 0;
hash += (inventarioPK != null ? inventarioPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Inventario)) {
return false;
}
Inventario other = (Inventario) object;
if ((this.inventarioPK == null && other.inventarioPK != null) || (this.inventarioPK != null && !this.inventarioPK.equals(other.inventarioPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Inventario[ inventarioPK=" + inventarioPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/EmpresasFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Empresas;
import entidad.Proveedores;
import java.util.Date;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.StoredProcedureQuery;
/**
*
* @author Hugo
*/
@Stateless
public class EmpresasFacade extends AbstractFacade<Empresas> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public EmpresasFacade() {
super(Empresas.class);
}
public void insertarEmpresa(Empresas empresas) {
StoredProcedureQuery q = getEntityManager().createStoredProcedureQuery("InsertarEmpresa");
q.registerStoredProcedureParameter("xrazon_social", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xruc", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xtelef", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xdirec", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xcontacto", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("falta", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cusuario", String.class, ParameterMode.IN);
q.setParameter("xrazon_social", empresas.getXrazonSocial());
q.setParameter("xruc", empresas.getXruc());
q.setParameter("xtelef", empresas.getXtelef());
q.setParameter("xdirec", empresas.getXdirec());
q.setParameter("xcontacto", empresas.getXcontacto());
q.setParameter("falta", empresas.getFalta());
q.setParameter("cusuario", empresas.getCusuario());
q.execute();
}
}
<file_sep>/SisVenLog-war/src/java/bean/CanalesVenBean.java
package bean;
import dao.CanalesVentaFacade;
import entidad.CanalesVenta;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class CanalesVenBean implements Serializable {
@EJB
private CanalesVentaFacade canalesVenFacade;
private CanalesVenta canalesVen = new CanalesVenta();
private List<CanalesVenta> listaCanalesVen = new ArrayList<CanalesVenta>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public CanalesVenBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public CanalesVenta getCanales() {
return canalesVen;
}
public void setCanales(CanalesVenta canalesVen) {
this.canalesVen = canalesVen;
}
public List<CanalesVenta> getListaCanales() {
return listaCanalesVen;
}
public void setListaCanales(List<CanalesVenta> listaCanalesVen) {
this.listaCanalesVen = listaCanalesVen;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaCanalesVen = new ArrayList<CanalesVenta>();
this.canalesVen = new CanalesVenta();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
listar();
//RequestContext.getCurrentInstance().update("formPersonas");
}
public void nuevo() {
this.canalesVen = new CanalesVenta();
listaCanalesVen = new ArrayList<CanalesVenta>();
}
public List<CanalesVenta> listar() {
listaCanalesVen = canalesVenFacade.findAll();
return listaCanalesVen;
}
/*public Boolean validarDeposito() {
boolean valido = true;
try {
List<Canales> aux = new ArrayList<Canales>();
if ("".equals(this.canalesVen.getXdesc())) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
} else {
// aux = canalesVenFacade.buscarPorDescripcion(canalesVen.getXdesc());
/*if (aux.size() > 0) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Ya existe."));
}
}
} catch (Exception e) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al validar los datos."));
}
return valido;
}
*/
public void insertar() {
try {
canalesVen.setXdesc(canalesVen.getXdesc().toUpperCase());
canalesVen.setFalta(new Date());
canalesVen.setCusuario("admin");
canalesVenFacade.create(canalesVen);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevCanalesVen').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editar() {
try {
if ("".equals(this.canalesVen.getXdesc())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
canalesVen.setXdesc(canalesVen.getXdesc().toUpperCase());
canalesVenFacade.edit(canalesVen);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditCanalesVen').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void borrar() {
try {
canalesVenFacade.remove(canalesVen);
this.canalesVen = new CanalesVenta();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacCanalesVen').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
if ("" != this.canalesVen.getXdesc()) {
this.setHabBtnEdit(false);
} else {
this.setHabBtnEdit(true);
}
}
public void verificarCargaDatos() {
boolean cargado = false;
if (canalesVen != null) {
if (canalesVen.getXdesc() != null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarCanalesVen').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevCanalesVen').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarCanales').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevCanales').hide();");
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/RecibosFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Clientes;
import entidad.Recibos;
import entidad.Zonas;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import util.StringUtil;
/**
*
* @author admin
* @author jvera
* @author dadob
*
*/
@Stateless
public class RecibosFacade extends AbstractFacade<Recibos> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public RecibosFacade() {
super(Recibos.class);
}
public List<Object[]> listaRecibosSinDetalle(String fechaReciboDesde,
String fechaReciboHasta,
long nroReciboDesde,
long nroReciboHasta,
List<Clientes> listaCodCliente,
Zonas zona,
String discriminar,
Boolean todosClientes){
String sql = "SELECT r.nrecibo, r.cod_cliente, r.frecibo, r.irecibo, r.iefectivo, r.iretencion, r.icheques, r.xobs, r.mestado," +
" t.cod_cliente as cod_cliente2, t.xnombre as xnombre" +
" FROM recibos r , clientes t, rutas a WHERE r.cod_empr = 2" +
" AND r.cod_cliente = t.cod_cliente" +
" AND t.cod_ruta = a.cod_ruta" +
" AND r.fanul IS NULL" +
" AND r.frecibo BETWEEN " + "'" + fechaReciboDesde + "'" + " AND " + "'" + fechaReciboHasta + "'" + " AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta;
if (!todosClientes) {
if (!listaCodCliente.isEmpty()) {
sql += " AND r.cod_cliente IN (" + StringUtil.convertirListaAString(listaCodCliente) + ")";
}
}
if (zona != null) {
sql += " AND a.cod_zona = " + zona.getZonasPK().getCodZona();
}
if ("ND".equals(discriminar)) {
//ordenar por Nro Recibo y fecha recibo
sql += " ORDER BY r.nrecibo, r.frecibo";
}else if ("PC".equals(discriminar)) {
//ordenar por código cliente
sql += " ORDER BY r.cod_cliente";
}
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
return resultados;
}
public List<Object[]> listaRecibosConDetalle(String fechaReciboDesde,
String fechaReciboHasta,
long nroReciboDesde,
long nroReciboHasta,
List<Clientes> listaCodCliente,
Zonas zona,
String discriminar,
Boolean todosClientes){
String sql = "SELECT r.nrecibo, r.cod_cliente, r.frecibo, r.irecibo, r.iefectivo, r.iretencion, r.icheques, r.xobs, r.mestado," +
" c.xnombre, d.ctipo_docum, d.ndocum, '' as xdesc_banco, r.fanul, 'F' as tipodet, c.cod_cliente as cod_cliente2," +
" c.xnombre as xnombre2, d.itotal" +
" FROM recibos r , recibos_det d, clientes c, rutas a" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND c.cod_ruta = a.cod_ruta" +
" AND r.cod_empr = 2" +
" AND r.fanul IS NULL" +
" AND r.cod_cliente = c.cod_cliente" +
" AND r.frecibo BETWEEN " + "'" + fechaReciboDesde + "'" + " AND " + "'" + fechaReciboHasta + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta;
if (!todosClientes) {
if (!listaCodCliente.isEmpty()) {
sql += " AND r.cod_cliente IN (" + StringUtil.convertirListaAString(listaCodCliente) + ")";
}
}
if (zona != null) {
sql += " AND a.cod_zona = " + zona.getZonasPK().getCodZona();
}
sql += " UNION ALL" +
" SELECT r.nrecibo, r.cod_cliente, r.frecibo, r.irecibo, r.iefectivo, r.iretencion, r.icheques, r.xobs, r.mestado," +
" c.xnombre, 'CHQ' as ctipo_docum, nro_cheque as ndocum, b.xdesc as xdesc_banco, r.fanul," +
" 'C' as tipodet, c.cod_cliente as cod_cliente2, c.xnombre as xnombre2, d.ipagado as itotal" +
" FROM recibos r , recibos_cheques d, bancos b, clientes c, rutas a" +
" WHERE r.nrecibo = d.nrecibo" +
" AND r.cod_empr = d.cod_empr" +
" AND c.cod_ruta = a.cod_ruta" +
" AND r.cod_empr = 2" +
" AND d.cod_banco = b.cod_banco" +
" AND r.cod_cliente = c.cod_cliente" +
" AND r.fanul IS NULL" +
" AND r.frecibo BETWEEN " + "'" + fechaReciboDesde + "'" + " AND " + "'" + fechaReciboHasta + "'" +
" AND r.nrecibo BETWEEN " + nroReciboDesde + " AND " + nroReciboHasta +
" AND r.icheques > 0 ";
if (!todosClientes) {
if (!listaCodCliente.isEmpty()) {
sql += " AND r.cod_cliente IN (" + StringUtil.convertirListaAString(listaCodCliente) + ")";
}
}
if (zona != null) {
sql += " AND a.cod_zona = " + zona.getZonasPK().getCodZona();
}
if ("ND".equals(discriminar)) {
//ordenar por Nro Recibo y fecha recibo
sql += " ORDER BY r.nrecibo, r.frecibo";
}else if ("PC".equals(discriminar)) {
//ordenar por código cliente
sql += " ORDER BY r.cod_cliente";
}
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
return resultados;
}
public long obtenerCantidadRecibos(long lNroRecibo){
String sql = "SELECT * FROM recibos " +
"WHERE nrecibo = "+lNroRecibo+" "+
"AND cod_empr = 2";
Query q = em.createNativeQuery(sql, Recibos.class);
System.out.println(q.toString());
long cantidadRegistros = q.getResultList().size();
return cantidadRegistros;
}
public void insertarRecibo( long lNroRecibo,
String lFRecibo,
Integer lCodCliente,
long lIRecibo,
long lIRetencion,
long lIEfectivo,
long lICheque,
String lXObs){
String sql = "INSERT INTO recibos(cod_empr, nrecibo, " +
"frecibo, cod_cliente, irecibo, iretencion, iefectivo, icheques, mestado, xobs) " +
"values (2, "+lNroRecibo+", " +
"'"+lFRecibo+"', "+lCodCliente+", "+lIRecibo+", "+lIRetencion+", "+lIEfectivo+", " +
""+lICheque+", 'A', '"+lXObs+"')";
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
q.executeUpdate();
}
public void actualizarEstadoRegistro(long lNroRecibo){
String sql = "UPDATE recibos SET mestado = 'X' " +
"WHERE nrecibo = "+lNroRecibo+" AND cod_empr = 2";
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
q.executeUpdate();
}
public List<Recibos> obtenerRecibos(){
Query q = getEntityManager().createNativeQuery("select * from recibos order by frecibo desc ",
Recibos.class);
return q.getResultList();
}
public List<Recibos> findRangeSort(int[] range) {
Query q = getEntityManager().createNativeQuery("select * from recibos order by nrecibo desc ",
Recibos.class);
q.setMaxResults(range[1]);
q.setFirstResult(range[0]);
return q.getResultList();
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/PedPromoDet.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "ped_promo_det")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "PedPromoDet.findAll", query = "SELECT p FROM PedPromoDet p")
, @NamedQuery(name = "PedPromoDet.findByCodEmpr", query = "SELECT p FROM PedPromoDet p WHERE p.pedPromoDetPK.codEmpr = :codEmpr")
, @NamedQuery(name = "PedPromoDet.findByNroPedido", query = "SELECT p FROM PedPromoDet p WHERE p.pedPromoDetPK.nroPedido = :nroPedido")
, @NamedQuery(name = "PedPromoDet.findByCodMerca", query = "SELECT p FROM PedPromoDet p WHERE p.pedPromoDetPK.codMerca = :codMerca")
, @NamedQuery(name = "PedPromoDet.findByNroPromo", query = "SELECT p FROM PedPromoDet p WHERE p.pedPromoDetPK.nroPromo = :nroPromo")
, @NamedQuery(name = "PedPromoDet.findByBonifCajas", query = "SELECT p FROM PedPromoDet p WHERE p.bonifCajas = :bonifCajas")
, @NamedQuery(name = "PedPromoDet.findByBonifUnid", query = "SELECT p FROM PedPromoDet p WHERE p.bonifUnid = :bonifUnid")
, @NamedQuery(name = "PedPromoDet.findByPdesc", query = "SELECT p FROM PedPromoDet p WHERE p.pdesc = :pdesc")})
public class PedPromoDet implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected PedPromoDetPK pedPromoDetPK;
@Column(name = "bonif_cajas")
private Integer bonifCajas;
@Column(name = "bonif_unid")
private Integer bonifUnid;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "pdesc")
private BigDecimal pdesc;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "nro_pedido", referencedColumnName = "nro_pedido", insertable = false, updatable = false)
, @JoinColumn(name = "cod_merca", referencedColumnName = "cod_merca", insertable = false, updatable = false)})
@ManyToOne(optional = false)
private HpedidosDet hpedidosDet;
public PedPromoDet() {
}
public PedPromoDet(PedPromoDetPK pedPromoDetPK) {
this.pedPromoDetPK = pedPromoDetPK;
}
public PedPromoDet(short codEmpr, long nroPedido, String codMerca, short nroPromo) {
this.pedPromoDetPK = new PedPromoDetPK(codEmpr, nroPedido, codMerca, nroPromo);
}
public PedPromoDetPK getPedPromoDetPK() {
return pedPromoDetPK;
}
public void setPedPromoDetPK(PedPromoDetPK pedPromoDetPK) {
this.pedPromoDetPK = pedPromoDetPK;
}
public Integer getBonifCajas() {
return bonifCajas;
}
public void setBonifCajas(Integer bonifCajas) {
this.bonifCajas = bonifCajas;
}
public Integer getBonifUnid() {
return bonifUnid;
}
public void setBonifUnid(Integer bonifUnid) {
this.bonifUnid = bonifUnid;
}
public BigDecimal getPdesc() {
return pdesc;
}
public void setPdesc(BigDecimal pdesc) {
this.pdesc = pdesc;
}
public HpedidosDet getHpedidosDet() {
return hpedidosDet;
}
public void setHpedidosDet(HpedidosDet hpedidosDet) {
this.hpedidosDet = hpedidosDet;
}
@Override
public int hashCode() {
int hash = 0;
hash += (pedPromoDetPK != null ? pedPromoDetPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PedPromoDet)) {
return false;
}
PedPromoDet other = (PedPromoDet) object;
if ((this.pedPromoDetPK == null && other.pedPromoDetPK != null) || (this.pedPromoDetPK != null && !this.pedPromoDetPK.equals(other.pedPromoDetPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.PedPromoDet[ pedPromoDetPK=" + pedPromoDetPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Zonas.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Hugo
*/
@Entity
@Table(name = "zonas")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Zonas.findAll", query = "SELECT z FROM Zonas z")
, @NamedQuery(name = "Zonas.findByCodEmpr", query = "SELECT z FROM Zonas z WHERE z.zonasPK.codEmpr = :codEmpr")
, @NamedQuery(name = "Zonas.findByCodZona", query = "SELECT z FROM Zonas z WHERE z.zonasPK.codZona = :codZona")
, @NamedQuery(name = "Zonas.findByXdesc", query = "SELECT z FROM Zonas z WHERE z.xdesc = :xdesc")
, @NamedQuery(name = "Zonas.findByCusuario", query = "SELECT z FROM Zonas z WHERE z.cusuario = :cusuario")
, @NamedQuery(name = "Zonas.findByFalta", query = "SELECT z FROM Zonas z WHERE z.falta = :falta")
, @NamedQuery(name = "Zonas.findByCusuarioModif", query = "SELECT z FROM Zonas z WHERE z.cusuarioModif = :cusuarioModif")
, @NamedQuery(name = "Zonas.findByFultimModif", query = "SELECT z FROM Zonas z WHERE z.fultimModif = :fultimModif")})
public class Zonas implements Serializable {
@OneToMany(cascade = CascadeType.ALL, mappedBy = "zonas")
private Collection<Rutas> rutasCollection;
private static final long serialVersionUID = 1L;
@EmbeddedId
protected ZonasPK zonasPK;
//@Size(max = 50)
@Column(name = "xdesc")
private String xdesc;
//@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
//@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "zonas")
private Collection<Depositos> depositosCollection;
public Zonas() {
}
public Zonas(ZonasPK zonasPK) {
this.zonasPK = zonasPK;
}
public Zonas(short codEmpr, String codZona) {
this.zonasPK = new ZonasPK(codEmpr, codZona);
}
public ZonasPK getZonasPK() {
return zonasPK;
}
public void setZonasPK(ZonasPK zonasPK) {
this.zonasPK = zonasPK;
}
public String getXdesc() {
return xdesc;
}
public void setXdesc(String xdesc) {
this.xdesc = xdesc;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
@XmlTransient
public Collection<Depositos> getDepositosCollection() {
return depositosCollection;
}
public void setDepositosCollection(Collection<Depositos> depositosCollection) {
this.depositosCollection = depositosCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (zonasPK != null ? zonasPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Zonas)) {
return false;
}
Zonas other = (Zonas) object;
if ((this.zonasPK == null && other.zonasPK != null) || (this.zonasPK != null && !this.zonasPK.equals(other.zonasPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Zonas[ zonasPK=" + zonasPK + " ]";
}
@XmlTransient
public Collection<Rutas> getRutasCollection() {
return rutasCollection;
}
public void setRutasCollection(Collection<Rutas> rutasCollection) {
this.rutasCollection = rutasCollection;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/CanalesVentaFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.CanalesVenta;
import java.util.Date;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.StoredProcedureQuery;
import javax.persistence.Query;
/**
*
* @author admin
*/
@Stateless
public class CanalesVentaFacade extends AbstractFacade<CanalesVenta> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public CanalesVentaFacade() {
super(CanalesVenta.class);
}
public CanalesVenta getCanalVentaPorCodigo(String codigo) {
Query q = getEntityManager().createNativeQuery("select * from canales_venta where cod_canal = '" + codigo + "'" , CanalesVenta.class);
System.out.println(q.toString());
CanalesVenta canalVenta = new CanalesVenta();
canalVenta = (CanalesVenta)q.getSingleResult();
return canalVenta;
}
//JLVC 15-04-2020
public CanalesVenta buscarPorCodigo(String filtro) {
Query q = getEntityManager().createNativeQuery("select * from canales_venta where cod_canal = upper('" + filtro + "') ", CanalesVenta.class);
//System.out.println(q.toString());
CanalesVenta respuesta = new CanalesVenta();
if (q.getResultList().size() <= 0) {
respuesta = null;
} else {
respuesta = (CanalesVenta) q.getSingleResult();
}
return respuesta;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/DepositosPK.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
/**
*
* @author Administrador
*/
@Embeddable
public class DepositosPK implements Serializable {
@Basic(optional = false)
@NotNull
@Column(name = "cod_empr")
private short codEmpr;
@Basic(optional = false)
@NotNull
@Column(name = "cod_depo")
private short codDepo;
public DepositosPK() {
}
public DepositosPK(short codEmpr, short codDepo) {
this.codEmpr = codEmpr;
this.codDepo = codDepo;
}
public short getCodEmpr() {
return codEmpr;
}
public void setCodEmpr(short codEmpr) {
this.codEmpr = codEmpr;
}
public short getCodDepo() {
return codDepo;
}
public void setCodDepo(short codDepo) {
this.codDepo = codDepo;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) codEmpr;
hash += (int) codDepo;
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof DepositosPK)) {
return false;
}
DepositosPK other = (DepositosPK) object;
if (this.codEmpr != other.codEmpr) {
return false;
}
if (this.codDepo != other.codDepo) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.DepositosPK[ codEmpr=" + codEmpr + ", codDepo=" + codDepo + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/FacturaDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import entidad.Facturas;
/**
*
* @author dadob
*/
public class FacturaDto {
private Facturas factura;
private String nombreDeposito;
private String nombreVendedor;
private String descripcionCanal;
public Facturas getFactura() {
return factura;
}
public void setFactura(Facturas factura) {
this.factura = factura;
}
public String getNombreDeposito() {
return nombreDeposito;
}
public void setNombreDeposito(String nombreDeposito) {
this.nombreDeposito = nombreDeposito;
}
public String getNombreVendedor() {
return nombreVendedor;
}
public void setNombreVendedor(String nombreVendedor) {
this.nombreVendedor = nombreVendedor;
}
public String getDescripcionCanal() {
return descripcionCanal;
}
public void setDescripcionCanal(String descripcionCanal) {
this.descripcionCanal = descripcionCanal;
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/DocumentoCompraDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import entidad.Proveedores;
import entidad.TiposDocumentos;
import java.util.Date;
/**
*
* @author dadob
*/
public class DocumentoCompraDto {
private TiposDocumentos tipoDocumento;
private Date fechaDocumento;
private long nroDcumento;
private long montoDocumento;
private long montoAPagarDocumento;
private long saldoDocumento;
private long nroRecibo;
private Date fechaRecibo;
private Proveedores proveedor;
private String observacion;
private String canalCompra;
private Date fechaVencimiento;
private String comCtipoDocum;
private Date comFfactur;
private long comNrofact;
private String canalCompraDet;
private Date fechaVencDet;
public TiposDocumentos getTipoDocumento() {
return tipoDocumento;
}
public void setTipoDocumento(TiposDocumentos tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
public Date getFechaDocumento() {
return fechaDocumento;
}
public void setFechaDocumento(Date fechaDocumento) {
this.fechaDocumento = fechaDocumento;
}
public long getNroDcumento() {
return nroDcumento;
}
public void setNroDcumento(long nroDcumento) {
this.nroDcumento = nroDcumento;
}
public long getMontoDocumento() {
return montoDocumento;
}
public void setMontoDocumento(long montoDocumento) {
this.montoDocumento = montoDocumento;
}
public long getMontoAPagarDocumento() {
return montoAPagarDocumento;
}
public void setMontoAPagarDocumento(long montoAPagarDocumento) {
this.montoAPagarDocumento = montoAPagarDocumento;
}
public long getSaldoDocumento() {
return saldoDocumento;
}
public void setSaldoDocumento(long saldoDocumento) {
this.saldoDocumento = saldoDocumento;
}
public long getNroRecibo() {
return nroRecibo;
}
public void setNroRecibo(long nroRecibo) {
this.nroRecibo = nroRecibo;
}
public Date getFechaRecibo() {
return fechaRecibo;
}
public void setFechaRecibo(Date fechaRecibo) {
this.fechaRecibo = fechaRecibo;
}
public Proveedores getProveedor() {
return proveedor;
}
public void setProveedor(Proveedores proveedor) {
this.proveedor = proveedor;
}
public String getObservacion() {
return observacion;
}
public void setObservacion(String observacion) {
this.observacion = observacion;
}
public String getCanalCompra() {
return canalCompra;
}
public void setCanalCompra(String canalCompra) {
this.canalCompra = canalCompra;
}
public Date getFechaVencimiento() {
return fechaVencimiento;
}
public void setFechaVencimiento(Date fechaVencimiento) {
this.fechaVencimiento = fechaVencimiento;
}
public String getComCtipoDocum() {
return comCtipoDocum;
}
public void setComCtipoDocum(String comCtipoDocum) {
this.comCtipoDocum = comCtipoDocum;
}
public Date getComFfactur() {
return comFfactur;
}
public void setComFfactur(Date comFfactur) {
this.comFfactur = comFfactur;
}
public long getComNrofact() {
return comNrofact;
}
public void setComNrofact(long comNrofact) {
this.comNrofact = comNrofact;
}
public String getCanalCompraDet() {
return canalCompraDet;
}
public void setCanalCompraDet(String canalCompraDet) {
this.canalCompraDet = canalCompraDet;
}
public Date getFechaVencDet() {
return fechaVencDet;
}
public void setFechaVencDet(Date fechaVencDet) {
this.fechaVencDet = fechaVencDet;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/DepositosFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Depositos;
import entidad.DepositosPK;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
/**
*
* @author Hugo
*/
@Stateless
public class DepositosFacade extends AbstractFacade<Depositos> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public DepositosFacade() {
super(Depositos.class);
}
public List<Depositos> buscarPorDescripcion(String filtro) {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from dbo.depositos\n"
+ "where xdesc = '" + filtro + "' ", Depositos.class);
//System.out.println(q.toString());
List<Depositos> respuesta = new ArrayList<Depositos>();
respuesta = q.getResultList();
return respuesta;
}
public void insertarDeposito(Depositos depositos) {
StoredProcedureQuery q = getEntityManager().createStoredProcedureQuery("InsertarDeposito");
q.registerStoredProcedureParameter("xdesc", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cod_zona", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("mtipo", Character.class, ParameterMode.IN);
q.registerStoredProcedureParameter("npeso_max", Double.class, ParameterMode.IN);
q.registerStoredProcedureParameter("fultim_inven", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("falta", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cusuario", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("fultim_modif", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cusuario_modif", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("npunto_est", Integer.class, ParameterMode.IN);
q.registerStoredProcedureParameter("npunto_exp", Integer.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cod_conductor", Integer.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cod_transp", Integer.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xchapa", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xmarca", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xobs", String.class, ParameterMode.IN);
q.setParameter("xdesc", depositos.getXdesc());
q.setParameter("cod_zona", depositos.getZonas().getZonasPK().getCodZona());
q.setParameter("mtipo", depositos.getMtipo());
q.setParameter("npeso_max", depositos.getNpesoMax());
q.setParameter("fultim_inven", depositos.getFultimInven());
q.setParameter("falta", depositos.getFalta());
q.setParameter("cusuario", depositos.getCusuario());
q.setParameter("fultim_modif", depositos.getFultimModif());
q.setParameter("cusuario_modif", depositos.getCusuarioModif());
q.setParameter("npunto_est", depositos.getNpuntoEst());
q.setParameter("npunto_exp", depositos.getNpuntoExp());
q.setParameter("cod_conductor", depositos.getCodConductor().getCodConductor());
q.setParameter("cod_transp", depositos.getCodTransp().getCodTransp());
q.setParameter("xchapa", depositos.getXchapa());
q.setParameter("xmarca", depositos.getXmarca());
q.setParameter("xobs", depositos.getXobs());
q.execute();
}
public List<Depositos> listarDepositosActivos() {
Query q = getEntityManager().createNativeQuery("SELECT * FROM depositos ", Depositos.class);
System.out.println(q.toString());
List<Depositos> respuesta = new ArrayList<Depositos>();
respuesta = q.getResultList();
return respuesta;
}
public List<Depositos> listarDepositosMercaSin() {
Query q = getEntityManager().createNativeQuery("SELECT * FROM depositos where mtipo = 'M' ", Depositos.class);
System.out.println(q.toString());
List<Depositos> respuesta = new ArrayList<Depositos>();
respuesta = q.getResultList();
return respuesta;
}
public Depositos getNombreDeposito(Integer codigo) {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from depositos\n"
+ "where cod_depo = "+ codigo , Depositos.class);
System.out.println(q.toString());
Depositos respuesta = new Depositos();
respuesta = (Depositos)q.getSingleResult();
return respuesta;
}
public Depositos getDepositoPorCodigo(short codigo) {
Query q = getEntityManager().createNativeQuery("select *\n"
+ "from depositos\n"
+ "where cod_depo = "+ codigo , Depositos.class);
System.out.println(q.toString());
Depositos respuesta = new Depositos();
respuesta = (Depositos)q.getSingleResult();
return respuesta;
}
public List<Depositos> obtenerDepositosPorTipoCliente(Character lTipoCliente){
String sql = "SELECT c.cod_depo, d.xdesc FROM tipocli_depositos as c, depositos as d WHERE d.cod_depo = c.cod_depo " +
"AND c.ctipo_cliente = '"+lTipoCliente+"' "+
"AND c.cod_empr = 2";
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
List<Depositos> listado = new ArrayList<>();
for(Object[] resultado: resultados){
DepositosPK depositoPK = new DepositosPK();
depositoPK.setCodEmpr(Short.parseShort("2"));
depositoPK.setCodDepo(resultado[0] == null ? 0 : Short.parseShort(resultado[0].toString()));
Depositos d = new Depositos();
d.setDepositosPK(depositoPK);
d.setXdesc(resultado[1] == null ? "" : resultado[1].toString());
listado.add(d);
}
return listado;
}
}
<file_sep>/SisVenLog-war/src/java/bean/GrupoCargaBean.java
package bean;
import dao.GruposCargaFacade;
import entidad.GruposCarga;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class GrupoCargaBean implements Serializable {
@EJB
private GruposCargaFacade gruposCargaFacade;
private GruposCarga gruposCarga = new GruposCarga();
private List<GruposCarga> listaGruposCarga = new ArrayList<GruposCarga>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public GrupoCargaBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public GruposCarga getGruposCarga() {
return gruposCarga;
}
public void setGruposCarga(GruposCarga gruposCarga) {
this.gruposCarga = gruposCarga;
}
public List<GruposCarga> getListaGruposCarga() {
return listaGruposCarga;
}
public void setListaGruposCarga(List<GruposCarga> listaGruposCarga) {
this.listaGruposCarga = listaGruposCarga;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaGruposCarga = new ArrayList<GruposCarga>();
this.gruposCarga = new GruposCarga();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
listar();
//RequestContext.getCurrentInstance().update("formPersonas");
}
public void nuevo() {
this.gruposCarga = new GruposCarga();
listaGruposCarga = new ArrayList<GruposCarga>();
}
public List<GruposCarga> listar() {
listaGruposCarga = gruposCargaFacade.findAll();
return listaGruposCarga;
}
/*public Boolean validarDeposito() {
boolean valido = true;
try {
List<GruposCarga> aux = new ArrayList<GruposCarga>();
if ("".equals(this.gruposCarga.getXdesc())) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
} else {
// aux = gruposCargaFacade.buscarPorDescripcion(gruposCarga.getXdesc());
/*if (aux.size() > 0) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Ya existe."));
}
}
} catch (Exception e) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al validar los datos."));
}
return valido;
}
*/
public void insertar() {
try {
gruposCarga.setXdesc(gruposCarga.getXdesc().toUpperCase());
gruposCarga.setFalta(new Date());
gruposCarga.setCusuario("admin");
// gruposCargaFacade.insertarGruposCarga(gruposCarga);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevGruposCarga').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editar() {
try {
if ("".equals(this.gruposCarga.getXdesc())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
gruposCarga.setXdesc(gruposCarga.getXdesc().toUpperCase());
gruposCargaFacade.edit(gruposCarga);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditGruposCarga').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void borrar() {
try {
gruposCargaFacade.remove(gruposCarga);
this.gruposCarga = new GruposCarga();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacGruposCarga').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
if ("" != this.gruposCarga.getXdesc()) {
this.setHabBtnEdit(false);
} else {
this.setHabBtnEdit(true);
}
}
public void verificarCargaDatos() {
boolean cargado = false;
if (gruposCarga != null) {
if (gruposCarga.getXdesc() != null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarGruposCarga').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevGruposCarga').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarGruposCarga').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevGruposCarga').hide();");
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Recaudacion.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author admin
*/
@Entity
@Table(name = "recaudacion")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Recaudacion.findAll", query = "SELECT r FROM Recaudacion r")
, @NamedQuery(name = "Recaudacion.findByCodEmpr", query = "SELECT r FROM Recaudacion r WHERE r.recaudacionPK.codEmpr = :codEmpr")
, @NamedQuery(name = "Recaudacion.findByNroPlanilla", query = "SELECT r FROM Recaudacion r WHERE r.recaudacionPK.nroPlanilla = :nroPlanilla")
, @NamedQuery(name = "Recaudacion.findByFplanilla", query = "SELECT r FROM Recaudacion r WHERE r.fplanilla = :fplanilla")
, @NamedQuery(name = "Recaudacion.findByCodEntregador", query = "SELECT r FROM Recaudacion r WHERE r.codEntregador = :codEntregador")
, @NamedQuery(name = "Recaudacion.findByTventas", query = "SELECT r FROM Recaudacion r WHERE r.tventas = :tventas")
, @NamedQuery(name = "Recaudacion.findByTnotasDev", query = "SELECT r FROM Recaudacion r WHERE r.tnotasDev = :tnotasDev")
, @NamedQuery(name = "Recaudacion.findByTchequesDia", query = "SELECT r FROM Recaudacion r WHERE r.tchequesDia = :tchequesDia")
, @NamedQuery(name = "Recaudacion.findByKcheques", query = "SELECT r FROM Recaudacion r WHERE r.kcheques = :kcheques")
, @NamedQuery(name = "Recaudacion.findByNroBoleta", query = "SELECT r FROM Recaudacion r WHERE r.nroBoleta = :nroBoleta")
, @NamedQuery(name = "Recaudacion.findByCodBanco", query = "SELECT r FROM Recaudacion r WHERE r.codBanco = :codBanco")
, @NamedQuery(name = "Recaudacion.findByTefectivo", query = "SELECT r FROM Recaudacion r WHERE r.tefectivo = :tefectivo")
, @NamedQuery(name = "Recaudacion.findByTmonedas", query = "SELECT r FROM Recaudacion r WHERE r.tmonedas = :tmonedas")
, @NamedQuery(name = "Recaudacion.findByTcreditos", query = "SELECT r FROM Recaudacion r WHERE r.tcreditos = :tcreditos")
, @NamedQuery(name = "Recaudacion.findByTgastos", query = "SELECT r FROM Recaudacion r WHERE r.tgastos = :tgastos")
, @NamedQuery(name = "Recaudacion.findByTnotasOtras", query = "SELECT r FROM Recaudacion r WHERE r.tnotasOtras = :tnotasOtras")
, @NamedQuery(name = "Recaudacion.findByTdiferencia", query = "SELECT r FROM Recaudacion r WHERE r.tdiferencia = :tdiferencia")
, @NamedQuery(name = "Recaudacion.findByFalta", query = "SELECT r FROM Recaudacion r WHERE r.falta = :falta")
, @NamedQuery(name = "Recaudacion.findByCusuario", query = "SELECT r FROM Recaudacion r WHERE r.cusuario = :cusuario")
, @NamedQuery(name = "Recaudacion.findByFultimModif", query = "SELECT r FROM Recaudacion r WHERE r.fultimModif = :fultimModif")
, @NamedQuery(name = "Recaudacion.findByCusuarioModif", query = "SELECT r FROM Recaudacion r WHERE r.cusuarioModif = :cusuarioModif")
, @NamedQuery(name = "Recaudacion.findByTchequesDif", query = "SELECT r FROM Recaudacion r WHERE r.tchequesDif = :tchequesDif")
, @NamedQuery(name = "Recaudacion.findByCodZona", query = "SELECT r FROM Recaudacion r WHERE r.codZona = :codZona")
, @NamedQuery(name = "Recaudacion.findByNplanillaCob", query = "SELECT r FROM Recaudacion r WHERE r.nplanillaCob = :nplanillaCob")
, @NamedQuery(name = "Recaudacion.findByTpagares", query = "SELECT r FROM Recaudacion r WHERE r.tpagares = :tpagares")
, @NamedQuery(name = "Recaudacion.findByTdepositos", query = "SELECT r FROM Recaudacion r WHERE r.tdepositos = :tdepositos")
, @NamedQuery(name = "Recaudacion.findByTnotasAtras", query = "SELECT r FROM Recaudacion r WHERE r.tnotasAtras = :tnotasAtras")})
public class Recaudacion implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected RecaudacionPK recaudacionPK;
@Basic(optional = false)
@NotNull
@Column(name = "fplanilla")
@Temporal(TemporalType.TIMESTAMP)
private Date fplanilla;
@Basic(optional = false)
@NotNull
@Column(name = "cod_entregador")
private short codEntregador;
@Basic(optional = false)
@NotNull
@Column(name = "tventas")
private long tventas;
@Basic(optional = false)
@NotNull
@Column(name = "tnotas_dev")
private long tnotasDev;
@Basic(optional = false)
@NotNull
@Column(name = "tcheques_dia")
private long tchequesDia;
@Basic(optional = false)
@NotNull
@Column(name = "kcheques")
private long kcheques;
@Basic(optional = false)
@NotNull
@Column(name = "nro_boleta")
private long nroBoleta;
@Column(name = "cod_banco")
private Short codBanco;
@Basic(optional = false)
@NotNull
@Column(name = "tefectivo")
private long tefectivo;
@Basic(optional = false)
@NotNull
@Column(name = "tmonedas")
private long tmonedas;
@Basic(optional = false)
@NotNull
@Column(name = "tcreditos")
private long tcreditos;
@Basic(optional = false)
@NotNull
@Column(name = "tgastos")
private long tgastos;
@Basic(optional = false)
@NotNull
@Column(name = "tnotas_otras")
private long tnotasOtras;
@Basic(optional = false)
@NotNull
@Column(name = "tdiferencia")
private long tdiferencia;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
@Basic(optional = false)
@NotNull
@Column(name = "tcheques_dif")
private long tchequesDif;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 2)
@Column(name = "cod_zona")
private String codZona;
@Column(name = "nplanilla_cob")
private Long nplanillaCob;
@Column(name = "tpagares")
private Long tpagares;
@Column(name = "tdepositos")
private Long tdepositos;
@Column(name = "tnotas_atras")
private Long tnotasAtras;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "recaudacion")
private Collection<RecaudacionDet> recaudacionDetCollection;
public Recaudacion() {
}
public Recaudacion(RecaudacionPK recaudacionPK) {
this.recaudacionPK = recaudacionPK;
}
public Recaudacion(RecaudacionPK recaudacionPK, Date fplanilla, short codEntregador, long tventas, long tnotasDev, long tchequesDia, long kcheques, long nroBoleta, long tefectivo, long tmonedas, long tcreditos, long tgastos, long tnotasOtras, long tdiferencia, long tchequesDif, String codZona) {
this.recaudacionPK = recaudacionPK;
this.fplanilla = fplanilla;
this.codEntregador = codEntregador;
this.tventas = tventas;
this.tnotasDev = tnotasDev;
this.tchequesDia = tchequesDia;
this.kcheques = kcheques;
this.nroBoleta = nroBoleta;
this.tefectivo = tefectivo;
this.tmonedas = tmonedas;
this.tcreditos = tcreditos;
this.tgastos = tgastos;
this.tnotasOtras = tnotasOtras;
this.tdiferencia = tdiferencia;
this.tchequesDif = tchequesDif;
this.codZona = codZona;
}
public Recaudacion(short codEmpr, long nroPlanilla) {
this.recaudacionPK = new RecaudacionPK(codEmpr, nroPlanilla);
}
public RecaudacionPK getRecaudacionPK() {
return recaudacionPK;
}
public void setRecaudacionPK(RecaudacionPK recaudacionPK) {
this.recaudacionPK = recaudacionPK;
}
public Date getFplanilla() {
return fplanilla;
}
public void setFplanilla(Date fplanilla) {
this.fplanilla = fplanilla;
}
public short getCodEntregador() {
return codEntregador;
}
public void setCodEntregador(short codEntregador) {
this.codEntregador = codEntregador;
}
public long getTventas() {
return tventas;
}
public void setTventas(long tventas) {
this.tventas = tventas;
}
public long getTnotasDev() {
return tnotasDev;
}
public void setTnotasDev(long tnotasDev) {
this.tnotasDev = tnotasDev;
}
public long getTchequesDia() {
return tchequesDia;
}
public void setTchequesDia(long tchequesDia) {
this.tchequesDia = tchequesDia;
}
public long getKcheques() {
return kcheques;
}
public void setKcheques(long kcheques) {
this.kcheques = kcheques;
}
public long getNroBoleta() {
return nroBoleta;
}
public void setNroBoleta(long nroBoleta) {
this.nroBoleta = nroBoleta;
}
public Short getCodBanco() {
return codBanco;
}
public void setCodBanco(Short codBanco) {
this.codBanco = codBanco;
}
public long getTefectivo() {
return tefectivo;
}
public void setTefectivo(long tefectivo) {
this.tefectivo = tefectivo;
}
public long getTmonedas() {
return tmonedas;
}
public void setTmonedas(long tmonedas) {
this.tmonedas = tmonedas;
}
public long getTcreditos() {
return tcreditos;
}
public void setTcreditos(long tcreditos) {
this.tcreditos = tcreditos;
}
public long getTgastos() {
return tgastos;
}
public void setTgastos(long tgastos) {
this.tgastos = tgastos;
}
public long getTnotasOtras() {
return tnotasOtras;
}
public void setTnotasOtras(long tnotasOtras) {
this.tnotasOtras = tnotasOtras;
}
public long getTdiferencia() {
return tdiferencia;
}
public void setTdiferencia(long tdiferencia) {
this.tdiferencia = tdiferencia;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
public long getTchequesDif() {
return tchequesDif;
}
public void setTchequesDif(long tchequesDif) {
this.tchequesDif = tchequesDif;
}
public String getCodZona() {
return codZona;
}
public void setCodZona(String codZona) {
this.codZona = codZona;
}
public Long getNplanillaCob() {
return nplanillaCob;
}
public void setNplanillaCob(Long nplanillaCob) {
this.nplanillaCob = nplanillaCob;
}
public Long getTpagares() {
return tpagares;
}
public void setTpagares(Long tpagares) {
this.tpagares = tpagares;
}
public Long getTdepositos() {
return tdepositos;
}
public void setTdepositos(Long tdepositos) {
this.tdepositos = tdepositos;
}
public Long getTnotasAtras() {
return tnotasAtras;
}
public void setTnotasAtras(Long tnotasAtras) {
this.tnotasAtras = tnotasAtras;
}
@XmlTransient
public Collection<RecaudacionDet> getRecaudacionDetCollection() {
return recaudacionDetCollection;
}
public void setRecaudacionDetCollection(Collection<RecaudacionDet> recaudacionDetCollection) {
this.recaudacionDetCollection = recaudacionDetCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (recaudacionPK != null ? recaudacionPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Recaudacion)) {
return false;
}
Recaudacion other = (Recaudacion) object;
if ((this.recaudacionPK == null && other.recaudacionPK != null) || (this.recaudacionPK != null && !this.recaudacionPK.equals(other.recaudacionPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Recaudacion[ recaudacionPK=" + recaudacionPK + " ]";
}
}
<file_sep>/SisVenLog-war/src/java/bean/LineasBean.java
package bean;
import dao.CategoriasFacade;
import dao.LineasFacade;
import entidad.Categorias;
import entidad.Lineas;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class LineasBean implements Serializable {
@EJB
private LineasFacade xdescFacade;
@EJB
private CategoriasFacade categoriasFacade;
private String filtro = "";
private Lineas xdesc = new Lineas();
private Categorias categorias = new Categorias();
private List<Lineas> listaLineas = new ArrayList<Lineas>();
private List<Categorias> listaCategorias = new ArrayList<Categorias>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public LineasBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public Lineas getLineas() {
return xdesc;
}
public void setLineas(Lineas xdesc) {
this.xdesc = xdesc;
}
public List<Lineas> getListaLineas() {
return listaLineas;
}
public void setListaLineas(List<Lineas> listaLineas) {
this.listaLineas = listaLineas;
}
public Categorias getCategorias() {
return categorias;
}
public void setCategorias(Categorias categorias) {
this.categorias = categorias;
}
public List<Categorias> getListaCategorias() {
return listaCategorias;
}
public void setListaCategorias(List<Categorias> listaCategorias) {
this.listaCategorias = listaCategorias;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaLineas = new ArrayList<Lineas>();
this.xdesc = new Lineas();
listaCategorias = new ArrayList<Categorias>();
this.categorias = new Categorias();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
this.filtro = "";
listar();
RequestContext.getCurrentInstance().update("formLineas");
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public void nuevo() {
this.xdesc = new Lineas();
}
public List<Lineas> listar() {
//listaLineas = xdescFacade.findAll();
listaLineas = xdescFacade.listarLineasOrdenadoXCategoria();
return listaLineas;
}
public List<Categorias> listarCategorias() {
listaCategorias = categoriasFacade.findAll();
return listaCategorias;
}
public void insertar() {
try {
if (categorias == null ) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención ", "Debe seleccionar una categoría"));
return;
}
xdesc.setXdesc(xdesc.getXdesc().toUpperCase());
xdesc.setFalta(new Date());
xdesc.setCusuario("admin");
xdesc.setCodCATEGORIA(categorias);
xdescFacade.insertarLineas(xdesc);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevLineas').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editar() {
try {
if ("".equals(this.xdesc.getXdesc())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
xdesc.setXdesc(xdesc.getXdesc().toUpperCase());
xdescFacade.edit(xdesc);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditLineas').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void borrar() {
try {
xdescFacade.remove(xdesc);
this.xdesc = new Lineas();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacLineas').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
if ("" != this.xdesc.getXdesc()) {
this.setHabBtnEdit(false);
this.categorias = this.xdesc.getCodCATEGORIA();
} else {
this.setHabBtnEdit(true);
}
}
public void verificarCargaDatos() {
boolean cargado = false;
if (xdesc != null) {
if (xdesc.getXdesc() != null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarLineas').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevLineas').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarLineas').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevLineas').hide();");
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Transportistas.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Hugo
*/
@Entity
@Table(name = "transportistas")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Transportistas.findAll", query = "SELECT t FROM Transportistas t")
, @NamedQuery(name = "Transportistas.findByCodTransp", query = "SELECT t FROM Transportistas t WHERE t.codTransp = :codTransp")
, @NamedQuery(name = "Transportistas.findByXtransp", query = "SELECT t FROM Transportistas t WHERE t.xtransp = :xtransp")
, @NamedQuery(name = "Transportistas.findByCusuario", query = "SELECT t FROM Transportistas t WHERE t.cusuario = :cusuario")
, @NamedQuery(name = "Transportistas.findByFalta", query = "SELECT t FROM Transportistas t WHERE t.falta = :falta")
, @NamedQuery(name = "Transportistas.findByCusuarioModif", query = "SELECT t FROM Transportistas t WHERE t.cusuarioModif = :cusuarioModif")
, @NamedQuery(name = "Transportistas.findByFultimModif", query = "SELECT t FROM Transportistas t WHERE t.fultimModif = :fultimModif")
, @NamedQuery(name = "Transportistas.findByXruc", query = "SELECT t FROM Transportistas t WHERE t.xruc = :xruc")
, @NamedQuery(name = "Transportistas.findByXdomicilio", query = "SELECT t FROM Transportistas t WHERE t.xdomicilio = :xdomicilio")})
public class Transportistas implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
//@NotNull
@Column(name = "cod_transp")
private Short codTransp;
//@Size(max = 50)
@Column(name = "xtransp")
private String xtransp;
//@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
//@Size(max = 30)
@Column(name = "cusuario_modif")
private String cusuarioModif;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
//@Size(max = 30)
@Column(name = "xruc")
private String xruc;
//@Size(max = 50)
@Column(name = "xdomicilio")
private String xdomicilio;
@OneToMany(mappedBy = "codTransp")
private Collection<Depositos> depositosCollection;
public Transportistas() {
}
public Transportistas(Short codTransp) {
this.codTransp = codTransp;
}
public Short getCodTransp() {
return codTransp;
}
public void setCodTransp(Short codTransp) {
this.codTransp = codTransp;
}
public String getXtransp() {
return xtransp;
}
public void setXtransp(String xtransp) {
this.xtransp = xtransp;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuarioModif() {
return cusuarioModif;
}
public void setCusuarioModif(String cusuarioModif) {
this.cusuarioModif = cusuarioModif;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public String getXruc() {
return xruc;
}
public void setXruc(String xruc) {
this.xruc = xruc;
}
public String getXdomicilio() {
return xdomicilio;
}
public void setXdomicilio(String xdomicilio) {
this.xdomicilio = xdomicilio;
}
@XmlTransient
public Collection<Depositos> getDepositosCollection() {
return depositosCollection;
}
public void setDepositosCollection(Collection<Depositos> depositosCollection) {
this.depositosCollection = depositosCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (codTransp != null ? codTransp.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Transportistas)) {
return false;
}
Transportistas other = (Transportistas) object;
if ((this.codTransp == null && other.codTransp != null) || (this.codTransp != null && !this.codTransp.equals(other.codTransp))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Transportistas[ codTransp=" + codTransp + " ]";
}
}
<file_sep>/SisVenLog-war/src/java/bean/PagoProveedoresBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
import dao.ChequesEmitidosFacade;
import dao.CuentasProveedoresFacade;
import dto.ChequeProveedorDto;
import entidad.Bancos;
import entidad.ChequesEmitidos;
import entidad.ChequesEmitidosPK;
import entidad.CuentasProveedores;
import entidad.Proveedores;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import util.ExceptionHandlerView;
/**
*
* @author Edu
*/
@ManagedBean
@SessionScoped
public class PagoProveedoresBean implements Serializable{
@EJB
private ChequesEmitidosFacade chequesEmitidosFacade;
@EJB
private CuentasProveedoresFacade cuentasProveedoresFacade;
private List<ChequeProveedorDto> listadoChequesProvedores;
private short codigoBanco;
private String numeroCheque;
private Long montoCheque;
private Date fechaCobro;
private Date fechaInicio;
private Date fechaFin;
private Short codigoProveedor;
private Bancos bancoSeleccionado;
private ChequesEmitidos chequesEmitidos;
private CuentasProveedores cuentasProveedores;
private Proveedores proveedorSeleccionado;
private ChequeProveedorDto chequeProveedorDto;
private String filtro;
private String contenidoError;
private String tituloError;
@PostConstruct
public void instanciar(){
limpiarVariables();
listadoChequesProvedores = new ArrayList<ChequeProveedorDto>();
chequesEmitidos = new ChequesEmitidos();
chequesEmitidos.setChequesEmitidosPK(new ChequesEmitidosPK());
bancoSeleccionado = new Bancos();
cuentasProveedores = new CuentasProveedores();
chequeProveedorDto = new ChequeProveedorDto();
}
private void limpiarVariables(){
this.codigoBanco = 0;
this.numeroCheque = "";
this.montoCheque = new Long("0");
this.fechaCobro = new Date();
this.fechaInicio = null;
this.fechaFin = null;
this.codigoProveedor = 0;
}
public String limpiarFormulario(){
limpiarVariables();
listadoChequesProvedores = new ArrayList<ChequeProveedorDto>();
chequesEmitidos = new ChequesEmitidos();
chequesEmitidos.setChequesEmitidosPK(new ChequesEmitidosPK());
bancoSeleccionado = new Bancos();
cuentasProveedores = new CuentasProveedores();
chequeProveedorDto = new ChequeProveedorDto();
proveedorSeleccionado = new Proveedores();
return null;
}
public String listarChequesProveedoresNoCobrados(){
try{
codigoBanco = bancoSeleccionado != null ? bancoSeleccionado.getCodBanco() : 0;
codigoProveedor = proveedorSeleccionado != null ? proveedorSeleccionado.getCodProveed() : 0;
listadoChequesProvedores.clear();
listadoChequesProvedores = chequesEmitidosFacade.listadoChequesNoPagadosProveedores( Short.parseShort("2"),
codigoBanco,
numeroCheque,
montoCheque,
fechaInicio,
fechaFin,
codigoProveedor,
fechaCobro);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de cheques.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
return null;
}
public void seleccionarChequeNoCobrado() {
}
public String guardarChequesNoCobradosDeProveedores(){
int contadorChequesSeleccionados = 0;
List<CuentasProveedores> listadoCuentasProveedores = null;
try{
if(!listadoChequesProvedores.isEmpty()){
for(ChequeProveedorDto cp: listadoChequesProvedores){
if(cp.isChequeEmitidoSeleccionado()){
contadorChequesSeleccionados++;
}
}
if(contadorChequesSeleccionados == 0){
//no se selecciono ningun cheque para cobrar
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Seleccione al menos un cheque para cobrar.", null));
return null;
}else{
for(ChequeProveedorDto cp: listadoChequesProvedores){
if(cp.isChequeEmitidoSeleccionado()){
if(cp.getChequeEmitido().getFcobro().before(cp.getChequeEmitido().getFemision()) || cp.getChequeEmitido().getFcobro().before(cp.getChequeEmitido().getFcheque())){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Fecha de cobro debe ser inferior a Fecha de emisión/vencimiento.", null));
return null;
}else{
if(chequesEmitidos != null){
chequesEmitidos.setFcobro(cp.getChequeEmitido().getFcobro());
chequesEmitidos.getChequesEmitidosPK().setNroCheque(cp.getChequeEmitido().getChequesEmitidosPK().getNroCheque());
chequesEmitidos.getChequesEmitidosPK().setCodBanco(cp.getChequeEmitido().getChequesEmitidosPK().getCodBanco());
//listar registros de cuentas proveedores
try{
listadoCuentasProveedores = cuentasProveedoresFacade.listarCuentasProveedoresPorNroChequeBanco(chequesEmitidos.getChequesEmitidosPK().getNroCheque(), chequesEmitidos.getChequesEmitidosPK().getCodBanco());
if(listadoCuentasProveedores == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "No existe recibo/factura asociadas al nro. de cheque: "+chequesEmitidos.getChequesEmitidosPK().getNroCheque(), null));
return null;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de cuentas proveedores.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
//actualizar cheques no cobrados
try{
int resultado = chequesEmitidosFacade.actualizarChequesEmitidosNoCobrados(chequesEmitidos);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la actualización de cheques.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
try{
if(cuentasProveedores != null){
cuentasProveedores.setCtipoDocum("CHP");
cuentasProveedores.setMindice(Short.parseShort("-1"));
cuentasProveedores.setFvenc(cp.getChequeEmitido().getFcheque());
cuentasProveedores.setIpagado(cp.getChequeEmitido().getIcheque());
cuentasProveedores.setTexentas(0);
cuentasProveedores.setCodProveed(cp.getChequeEmitido().getCodProveed());
cuentasProveedores.setFmovim(cp.getChequeEmitido().getFcobro());
cuentasProveedores.setCodEmpr(Short.parseShort("2"));
cuentasProveedores.setNdocumCheq(cp.getChequeEmitido().getChequesEmitidosPK().getNroCheque());
cuentasProveedores.setIretencion(0);
cuentasProveedores.setCodBanco(cp.getChequeEmitido().getBancos());
cuentasProveedores.setIsaldo(0);
cuentasProveedores.setTgravadas(0);
cuentasProveedores.setTimpuestos(0);
cuentasProveedores.setManulado(new Short("1"));
cuentasProveedoresFacade.insertarEnCuentasProveedores(cuentasProveedores);
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error de inserción de movimientos en cuenta proveedor.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}
}
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Datos grabados.", null));
return null;
}
}else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "No existen datos.", null));
return null;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al confirmar la operación.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
public List<ChequeProveedorDto> getListadoChequesProvedores() {
return listadoChequesProvedores;
}
public void setListadoChequesProvedores(List<ChequeProveedorDto> listadoChequesProvedores) {
this.listadoChequesProvedores = listadoChequesProvedores;
}
public short getCodigoBanco() {
return codigoBanco;
}
public void setCodigoBanco(short codigoBanco) {
this.codigoBanco = codigoBanco;
}
public String getNumeroCheque() {
return numeroCheque;
}
public void setNumeroCheque(String numeroCheque) {
this.numeroCheque = numeroCheque;
}
public Long getMontoCheque() {
return montoCheque;
}
public void setMontoCheque(Long montoCheque) {
this.montoCheque = montoCheque;
}
public Date getFechaCobro() {
return fechaCobro;
}
public void setFechaCobro(Date fechaCobro) {
this.fechaCobro = fechaCobro;
}
public Date getFechaInicio() {
return fechaInicio;
}
public void setFechaInicio(Date fechaInicio) {
this.fechaInicio = fechaInicio;
}
public Date getFechaFin() {
return fechaFin;
}
public void setFechaFin(Date fechaFin) {
this.fechaFin = fechaFin;
}
public Short getCodigoProveedor() {
return codigoProveedor;
}
public void setCodigoProveedor(Short codigoProveedor) {
this.codigoProveedor = codigoProveedor;
}
public Bancos getBancoSeleccionado() {
return bancoSeleccionado;
}
public void setBancoSeleccionado(Bancos bancoSeleccionado) {
this.bancoSeleccionado = bancoSeleccionado;
}
public ChequesEmitidos getChequesEmitidos() {
return chequesEmitidos;
}
public void setChequesEmitidos(ChequesEmitidos chequesEmitidos) {
this.chequesEmitidos = chequesEmitidos;
}
public CuentasProveedores getCuentasProveedores() {
return cuentasProveedores;
}
public void setCuentasProveedores(CuentasProveedores cuentasProveedores) {
this.cuentasProveedores = cuentasProveedores;
}
public Proveedores getProveedorSeleccionado() {
return proveedorSeleccionado;
}
public void setProveedorSeleccionado(Proveedores proveedorSeleccionado) {
this.proveedorSeleccionado = proveedorSeleccionado;
}
public ChequeProveedorDto getChequeProveedorDto() {
return chequeProveedorDto;
}
public void setChequeProveedorDto(ChequeProveedorDto chequeProveedorDto) {
this.chequeProveedorDto = chequeProveedorDto;
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public String getContenidoError() {
return contenidoError;
}
public void setContenidoError(String contenidoError) {
this.contenidoError = contenidoError;
}
public String getTituloError() {
return tituloError;
}
public void setTituloError(String tituloError) {
this.tituloError = tituloError;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/ClientesCaracteristicas.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "clientes_caracteristicas")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "ClientesCaracteristicas.findAll", query = "SELECT c FROM ClientesCaracteristicas c")
, @NamedQuery(name = "ClientesCaracteristicas.findByCodCliente", query = "SELECT c FROM ClientesCaracteristicas c WHERE c.clientesCaracteristicasPK.codCliente = :codCliente")
, @NamedQuery(name = "ClientesCaracteristicas.findByCodCaract", query = "SELECT c FROM ClientesCaracteristicas c WHERE c.clientesCaracteristicasPK.codCaract = :codCaract")
, @NamedQuery(name = "ClientesCaracteristicas.findByXvalor", query = "SELECT c FROM ClientesCaracteristicas c WHERE c.xvalor = :xvalor")
, @NamedQuery(name = "ClientesCaracteristicas.findByMtipoDato", query = "SELECT c FROM ClientesCaracteristicas c WHERE c.mtipoDato = :mtipoDato")})
public class ClientesCaracteristicas implements Serializable {
@Size(max = 50)
@Column(name = "xvalor")
private String xvalor;
@Basic(optional = false)
@NotNull
@Column(name = "mtipo_dato")
private Character mtipoDato;
@JoinColumn(name = "cod_caract", referencedColumnName = "cod_caract", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Caracteristicas caracteristicas;
@JoinColumn(name = "cod_cliente", referencedColumnName = "cod_cliente", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Clientes clientes;
private static final long serialVersionUID = 1L;
@EmbeddedId
protected ClientesCaracteristicasPK clientesCaracteristicasPK;
public ClientesCaracteristicas() {
}
public ClientesCaracteristicas(ClientesCaracteristicasPK clientesCaracteristicasPK) {
this.clientesCaracteristicasPK = clientesCaracteristicasPK;
}
public ClientesCaracteristicas(ClientesCaracteristicasPK clientesCaracteristicasPK, Character mtipoDato) {
this.clientesCaracteristicasPK = clientesCaracteristicasPK;
this.mtipoDato = mtipoDato;
}
public ClientesCaracteristicas(int codCliente, short codCaract) {
this.clientesCaracteristicasPK = new ClientesCaracteristicasPK(codCliente, codCaract);
}
public ClientesCaracteristicasPK getClientesCaracteristicasPK() {
return clientesCaracteristicasPK;
}
public void setClientesCaracteristicasPK(ClientesCaracteristicasPK clientesCaracteristicasPK) {
this.clientesCaracteristicasPK = clientesCaracteristicasPK;
}
public Character getMtipoDato() {
return mtipoDato;
}
public void setMtipoDato(Character mtipoDato) {
this.mtipoDato = mtipoDato;
}
@Override
public int hashCode() {
int hash = 0;
hash += (clientesCaracteristicasPK != null ? clientesCaracteristicasPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ClientesCaracteristicas)) {
return false;
}
ClientesCaracteristicas other = (ClientesCaracteristicas) object;
if ((this.clientesCaracteristicasPK == null && other.clientesCaracteristicasPK != null) || (this.clientesCaracteristicasPK != null && !this.clientesCaracteristicasPK.equals(other.clientesCaracteristicasPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.ClientesCaracteristicas[ clientesCaracteristicasPK=" + clientesCaracteristicasPK + " ]";
}
public String getXvalor() {
return xvalor;
}
public void setXvalor(String xvalor) {
this.xvalor = xvalor;
}
public Caracteristicas getCaracteristicas() {
return caracteristicas;
}
public void setCaracteristicas(Caracteristicas caracteristicas) {
this.caracteristicas = caracteristicas;
}
public Clientes getClientes() {
return clientes;
}
public void setClientes(Clientes clientes) {
this.clientes = clientes;
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/genLibroVentas.java
package bean.listados;
import dao.ExcelFacade;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import util.LlamarReportes;
/**
*
* @author Nico
*/
@ManagedBean
@SessionScoped
public class genLibroVentas {
private Date desde;
private Date hasta;
@EJB
private ExcelFacade excelFacade;
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.desde = new Date();
this.hasta = new Date();
}
public void ejecutar(String tipo) {
LlamarReportes rep = new LlamarReportes();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
List<Object[]> lista , lista2, lista3 , lista4 , lista5= new ArrayList<>();
String[] columnas = null;
String sql = "";
columnas = new String[12];
columnas[0] = "ffactur";
columnas[1] = "nrofact";
columnas[2] = "ctipo_docum";
columnas[3] = "mtipo_papel";
columnas[4] = "nro_docum_ini";
columnas[5] = "nro_docum_fin";
columnas[6] = "ttotal";
columnas[7] = "texentas";
columnas[8] = "tgravadas_10";
columnas[9] = "tgravadas_5";
columnas[10] = "timpuestos_10";
columnas[11] = "timpuestos_5";
sql = "(SELECT f.ffactur, f.nrofact,'FAC' AS ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, F.TTOTAL," +
"SUM(d.iexentas) AS texentas, SUM(d.igravadas) AS tgravadas_10, 0 AS tgravadas_5," +
"SUM(ABS(d.impuestos)) AS timpuestos_10, 0 AS timpuestos_5"+
" FROM facturas f "+
" INNER JOIN rangos_documentos r ON f.ctipo_docum = r.ctipo_docum "+
" AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final "+
" INNER JOIN facturas_det d ON f.nrofact = d.nrofact "+
" AND f.ctipo_docum = d.ctipo_docum "+
" AND f.ffactur = d.ffactur "+
" WHERE R.COD_EMPR = 2 AND D.COD_EMPR = 2 AND F.COD_EMPR = 2 "+
" AND (convert(date,f.ffactur) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "+
" AND d.impuestos > 0 AND d.pimpues = 10 AND r.mtipo_papel = 'F' "+
" GROUP BY f.ffactur, f.nrofact, r.mtipo_papel, r.nro_docum_ini,r.nro_docum_fin, f.ttotal) "+
" UNION ALL "+
" (SELECT f.ffactur, f.nrofact,'FAC' AS ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, "+
" SUM(d.iexentas) AS texentas, 0 AS tgravadas_10, SUM(d.igravadas) AS tgravadas_5, 0 AS timpuestos_10,"+
" SUM(ABS(d.impuestos)) AS timpuestos_5 "+
" FROM facturas f "+
" INNER JOIN rangos_documentos r ON f.ctipo_docum = r.ctipo_docum "+
" AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final "+
" INNER JOIN facturas_det d ON f.nrofact = d.nrofact "+
" AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "+
" WHERE R.COD_EMPR = 2 AND D.COD_EMPR = 2 AND F.COD_EMPR = 2 "+
" AND (convert(date,f.ffactur) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "+
" AND d.impuestos > 0 AND d.pimpues = 5 AND r.mtipo_papel = 'F' "+
" GROUP BY f.ffactur, f.nrofact, r.mtipo_papel, r.nro_docum_ini,r.nro_docum_fin, f.ttotal) "+
" UNION ALL "+
" (SELECT f.ffactur, f.nrofact, 'FAC' as ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, f.ttotal,"+
" SUM(d.iexentas) AS texentas, 0 AS tgravadas_10, 0 as tgravadas_5, 0 AS timpuestos_10, 0 AS timpuestos_5 "+
" FROM facturas f "+
" INNER JOIN rangos_documentos r ON f.ctipo_docum = r.ctipo_docum "+
" AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final "+
" INNER JOIN facturas_det d ON f.nrofact = d.nrofact "+
" AND f.ctipo_docum = d.ctipo_docum "+
" AND f.ffactur = d.ffactur "+
" WHERE D.COD_EMPR= 2 AND F.COD_EMPR = 2 AND (convert(date,f.ffactur) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "+
" AND d.impuestos = 0 AND d.pimpues = 0 and r.mtipo_papel = 'F' "+
" GROUP BY f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, f.ttotal) "+
" UNION ALL "+
" (SELECT f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, F.TTOTAL, "+
" SUM(d.iexentas) AS texentas,SUM(d.igravadas) AS tgravadas_10, 0 AS tgravadas_5, "+
" SUM(ABS(d.impuestos)) AS timpuestos_10, 0 AS timpuestos_5 "+
" FROM facturas f "+
" INNER JOIN rangos_documentos r ON f.ctipo_docum = r.ctipo_docum "+
" AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final "+
" INNER JOIN facturas_det d ON f.nrofact = d.nrofact "+
" AND f.ctipo_docum = d.ctipo_docum "+
" AND f.ffactur = d.ffactur "+
" WHERE R.COD_EMPR = 2 AND D.COD_EMPR = 2 AND F.COD_EMPR= 2 AND (convert(date,f.ffactur) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "+
" AND d.impuestos > 0 AND d.pimpues = 10 AND r.mtipo_papel = 'M' "+
" GROUP BY f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, f.ttotal) "+
" UNION ALL "+
" (SELECT f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, "+
" SUM(d.iexentas) AS texentas, 0 AS tgravadas_10, SUM(d.igravadas) AS tgravadas_5, 0 AS timpuestos_10, "+
" SUM(ABS(d.impuestos)) AS timpuestos_5 "+
" FROM facturas f "+
" INNER JOIN rangos_documentos r ON f.ctipo_docum = r.ctipo_docum "+
" AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final "+
" INNER JOIN facturas_det d ON f.nrofact = d.nrofact "+
" AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "+
" WHERE D.COD_EMPR = 2 AND F.COD_EMPR = 2 AND (convert(date,f.ffactur) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "+
" AND d.impuestos > 0 AND d.pimpues = 5 AND r.mtipo_papel = 'M' "+
" GROUP BY f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, f.ttotal) "+
" UNION ALL "+
" (SELECT f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, f.ttotal, "+
" SUM(d.iexentas) AS texentas,0 AS tgravadas_10, 0 as tgravadas_5, 0 AS timpuestos_10, 0 AS timpuestos_5 "+
" FROM facturas f "+
" INNER JOIN rangos_documentos r ON f.ctipo_docum = r.ctipo_docum "+
" AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final "+
" INNER JOIN facturas_det d ON f.nrofact = d.nrofact "+
" AND f.ctipo_docum = d.ctipo_docum "+
" AND f.ffactur = d.ffactur "+
" WHERE R.COD_EMPR = 2 AND F.COD_EMPR = 2 AND d.cod_empr = 2 AND (convert(date,f.ffactur) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "+
" AND d.impuestos = 0 AND d.pimpues = 0 "+
" and r.mtipo_papel = 'M' "+
" GROUP BY f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, f.ttotal )"+
" ORDER BY f.ffactur, r.mtipo_papel, r.nro_docum_ini,r.nro_docum_fin, f.ttotal ";
lista = excelFacade.listarParaExcel(sql);
sql = " (SELECT f.ffactur, f.nrofact,'FAC' AS ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal, " +
" SUM(d.iexentas) AS texentas, SUM(d.igravadas + d.impuestos) AS tgravadas_10, 0 AS tgravadas_5, " +
" SUM(ABS(d.impuestos)) AS timpuestos_10, 0 AS timpuestos_5 "+
" FROM facturas f "+
" INNER JOIN rangos_documentos r ON f.ctipo_docum = r.ctipo_docum "+
" AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final "+
" INNER JOIN facturas_det d ON f.nrofact = d.nrofact "+
" AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "+
" WHERE R.COD_EMPR = 2 AND D.COD_EMPR= 2 AND F.COD_EMPR= 2 "+
" AND (convert(date,f.ffactur) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "+
" AND d.impuestos < 0 AND d.pimpues = 10 AND r.mtipo_papel = 'F' "+
" GROUP BY f.ffactur, f.nrofact, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal) " +
" UNION ALL "+
" (SELECT f.ffactur, f.nrofact,'FAC' AS ctipo_docum, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, " +
" f.ttotal, SUM(d.iexentas) AS texentas, 0 AS tgravadas_10, SUM(d.igravadas + d.impuestos) AS tgravadas_5, "+
" 0 AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "+
" FROM facturas f "+
" INNER JOIN rangos_documentos r ON f.ctipo_docum = r.ctipo_docum "+
" AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final "+
" INNER JOIN facturas_det d ON f.nrofact = d.nrofact "+
" AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur "+
" WHERE R.COD_EMPR = 2 AND F.COD_EMPR= 2 AND D.COD_EMPR= 2 "+
" AND (convert(date,f.ffactur) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) "+
" AND d.impuestos < 0 AND d.pimpues = 5 AND r.mtipo_papel = 'F' "+
" GROUP BY f.ffactur, f.nrofact, r.mtipo_papel, r.nro_docum_ini, r.nro_docum_fin, f.ttotal) "+
" UNION ALL "+
" (SELECT f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, "+
" f.ttotal, SUM(d.iexentas) AS texentas,SUM(d.igravadas + d.impuestos) AS tgravadas_10, "+
" 0 AS tgravadas_5, SUM(ABS(d.impuestos)) AS timpuestos_10, 0 AS timpuestos_5 "+
" FROM facturas f "+
" INNER JOIN rangos_documentos r ON f.ctipo_docum = r.ctipo_docum "+
" AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final "+
" INNER JOIN facturas_det d ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum "+
" AND f.ffactur = d.ffactur "+
" WHERE R.COD_EMPR = 2 AND D.COD_EMPR = 2 AND F.COD_EMPR = 2 "+
" AND (convert(date,f.ffactur) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) " +
" AND d.impuestos < 0 AND d.pimpues = 10 AND r.mtipo_papel = 'M' " +
" GROUP BY f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, f.ttotal) " +
" UNION ALL " +
" (SELECT f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, " +
" f.ttotal, SUM(d.iexentas) AS texentas, 0 AS tgravadas_10, SUM(d.igravadas + d.impuestos) AS tgravadas_5," +
" 0 AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 " +
" FROM facturas f " +
" INNER JOIN rangos_documentos r ON f.ctipo_docum = r.ctipo_docum " +
" AND YEAR(f.ffactur) BETWEEN r.nano_inicial AND r.nano_final " +
" INNER JOIN facturas_det d ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum " +
" AND f.ffactur = d.ffactur " +
" WHERE R.COD_EMPR = 2 AND D.COD_EMPR = 2 AND F.COD_EMPR = 2 AND (convert(date,f.ffactur) BETWEEN '"+fdesde+"' AND '"+fhasta+"') " +
" AND (f.mestado = 'A') AND (f.nrofact BETWEEN r.nro_docum_ini AND r.nro_docum_fin) " +
" AND d.impuestos < 0 AND d.pimpues = 5 AND r.mtipo_papel = 'M' " +
" GROUP BY f.ffactur, f.nrofact, f.ctipo_docum, r.mtipo_papel,r.nro_docum_ini, r.nro_docum_fin, f.ttotal) " +
" ORDER BY f.ffactur, r.mtipo_papel, r.nro_docum_ini,r.nro_docum_fin ";
lista2 = excelFacade.listarParaExcel(sql);
sql = "(SELECT n.fdocum as ffactur, n.ctipo_docum, n.nro_nota,n.cconc, n.ttotal,'F' as mtipo_papel, 0 as nro_docum_ini,"+
" 0 as nro_docum_fin, SUM(d.iexentas) AS texentas,SUM(d.igravadas) AS tgravadas_10, 0 AS tgravadas_5, " +
" SUM(ABS(d.impuestos)) AS timpuestos_10, 0 AS timpuestos_5 " +
" FROM notas_ventas n "+
" INNER JOIN notas_ventas_det d ON N.nro_nota = d.nro_nota AND n.ctipo_docum = d.ctipo_docum "+
" AND n.fdocum = d.fdocum "+
" WHERE N.COD_EMPR = 2 AND D.COD_EMPR = 2 AND (convert(date,n.fdocum) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (n.mestado = 'A') AND d.impuestos < 0 AND d.pimpues = 10 "+
" GROUP BY n.fdocum, n.ctipo_docum, n.cconc, n.nro_nota, n.ttotal) "+
" UNION ALL "+
" (SELECT n.fdocum as ffactur, n.ctipo_docum, n.nro_nota, n.cconc,n.ttotal,'F' as mtipo_papel, 0 AS nro_docum_ini, "+
" 0 as nro_docum_fin, SUM(d.iexentas) AS texentas, 0 AS tgravadas_10, SUM(d.igravadas) AS tgravadas_5, "+
" 0 AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "+
" FROM notas_ventas n "+
" INNER JOIN notas_ventas_det d ON n.nro_nota = d.nro_nota "+
" AND n.ctipo_docum = d.ctipo_docum AND n.fdocum = d.fdocum "+
" WHERE N.COD_EMPR = 2 AND D.COD_EMPR= 2 AND (convert(date,n.fdocum) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (n.mestado = 'A') AND d.impuestos < 0 AND d.pimpues = 5 "+
" GROUP BY n.fdocum, n.ctipo_docum, N.CCONC, n.nro_nota,n.ttotal) "+
" ORDER BY N.fDOCUM, n.nro_nota ";
lista3 = excelFacade.listarParaExcel(sql);
sql = "(SELECT n.fdocum as ffactur, n.ctipo_docum, n.nro_nota, n.cconc,n.ttotal, 'F' as mtipo_papel, "+
" 0 as nro_docum_ini, 0 as nro_docum_fin, SUM(d.iexentas) AS texentas, "+
" SUM(d.igravadas + d.impuestos) AS tgravadas_10, 0 AS tgravadas_5, "+
" SUM(ABS(d.impuestos)) AS timpuestos_10, 0 AS timpuestos_5 "+
" FROM notas_ventas n "+
" INNER JOIN notas_ventas_det d ON N.nro_nota = d.nro_nota "+
" AND n.ctipo_docum = d.ctipo_docum AND n.fdocum = d.fdocum "+
" WHERE N.COD_EMPR = 2 AND D.COD_EMPR = 2 AND (convert(date,n.fdocum) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (n.mestado = 'A') AND d.impuestos < 0 AND d.pimpues = 10 "+
" GROUP BY n.fdocum, n.ctipo_docum, n.cconc, n.nro_nota, n.ttotal) "+
" UNION ALL "+
" (SELECT n.fdocum as ffactur, n.ctipo_docum, n.nro_nota, n.cconc,n.ttotal,'F' as mtipo_papel, "+
" 0 AS nro_docum_ini, 0 as nro_docum_fin, SUM(d.iexentas) AS texentas, 0 AS tgravadas_10, "+
" SUM(d.igravadas + d.impuestos) AS tgravadas_5, 0 AS timpuestos_10, SUM(ABS(d.impuestos)) AS timpuestos_5 "+
" FROM notas_ventas n "+
" INNER JOIN notas_ventas_det d ON n.nro_nota = d.nro_nota "+
" AND n.ctipo_docum = d.ctipo_docum AND n.fdocum = d.fdocum "+
" WHERE N.COD_EMPR = 2 AND D.COD_EMPR= 2 AND (convert(date,n.fdocum) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (n.mestado = 'A') AND d.impuestos < 0 AND d.pimpues = 5 "+
" GROUP BY n.fdocum, n.ctipo_docum, N.CCONC, n.nro_nota, n.ttotal) "+
" UNION ALL "+
" (SELECT n.fdocum as ffactur, n.ctipo_docum, n.nro_nota, n.cconc,n.ttotal,'F' as mtipo_papel, 0 AS nro_docum_ini, "+
" 0 as nro_docum_fin, SUM(d.iexentas) AS texentas, 0 AS tgravadas_10, 0 AS tgravadas_5, "+
" 0 AS timpuestos_10, 0 AS timpuestos_5 "+
" FROM notas_ventas n "+
" INNER JOIN notas_ventas_det d ON n.nro_nota = d.nro_nota "+
" AND n.ctipo_docum = d.ctipo_docum AND n.fdocum = d.fdocum "+
" WHERE N.COD_EMPR= 2 AND D.COD_EMPR = 2 AND (convert(date,n.fdocum) BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
" AND (n.mestado ='A') AND d.impuestos = 0 AND d.pimpues = 0 "+
" GROUP BY n.fdocum, n.ctipo_docum, N.CCONC, n.nro_nota, n.ttotal) "+
" ORDER BY N.fDOCUM, n.nro_nota ";
lista4 = excelFacade.listarParaExcel(sql);
lista5.add(columnas);
lista5.addAll(lista);
lista5.addAll(lista2);
lista5.addAll(lista3);
lista5.addAll(lista4);
rep.exportarCSV(lista5,"librovta");
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/PedidoDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import entidad.Pedidos;
/**
*
* @author Edu
*/
public class PedidoDto {
private Pedidos pedido;
private String nombreCliente;
public Pedidos getPedido() {
return pedido;
}
public void setPedido(Pedidos pedido) {
this.pedido = pedido;
}
public String getNombreCliente() {
return nombreCliente;
}
public void setNombreCliente(String nombreCliente) {
this.nombreCliente = nombreCliente;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/ChequesEmitidos.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Edu
*/
@Entity
@Table(name = "cheques_emitidos")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "ChequesEmitidos.findAll", query = "SELECT c FROM ChequesEmitidos c")
, @NamedQuery(name = "ChequesEmitidos.findByCodEmpr", query = "SELECT c FROM ChequesEmitidos c WHERE c.chequesEmitidosPK.codEmpr = :codEmpr")
, @NamedQuery(name = "ChequesEmitidos.findByCodBanco", query = "SELECT c FROM ChequesEmitidos c WHERE c.chequesEmitidosPK.codBanco = :codBanco")
, @NamedQuery(name = "ChequesEmitidos.findByNroCheque", query = "SELECT c FROM ChequesEmitidos c WHERE c.chequesEmitidosPK.nroCheque = :nroCheque")
, @NamedQuery(name = "ChequesEmitidos.findByXcuentaBco", query = "SELECT c FROM ChequesEmitidos c WHERE c.xcuentaBco = :xcuentaBco")
, @NamedQuery(name = "ChequesEmitidos.findByFcheque", query = "SELECT c FROM ChequesEmitidos c WHERE c.fcheque = :fcheque")
, @NamedQuery(name = "ChequesEmitidos.findByIcheque", query = "SELECT c FROM ChequesEmitidos c WHERE c.icheque = :icheque")
, @NamedQuery(name = "ChequesEmitidos.findByFemision", query = "SELECT c FROM ChequesEmitidos c WHERE c.femision = :femision")
, @NamedQuery(name = "ChequesEmitidos.findByFalta", query = "SELECT c FROM ChequesEmitidos c WHERE c.falta = :falta")
, @NamedQuery(name = "ChequesEmitidos.findByCusuario", query = "SELECT c FROM ChequesEmitidos c WHERE c.cusuario = :cusuario")
, @NamedQuery(name = "ChequesEmitidos.findByFcobro", query = "SELECT c FROM ChequesEmitidos c WHERE c.fcobro = :fcobro")
, @NamedQuery(name = "ChequesEmitidos.findByIretencion", query = "SELECT c FROM ChequesEmitidos c WHERE c.iretencion = :iretencion")})
public class ChequesEmitidos implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected ChequesEmitidosPK chequesEmitidosPK;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 20)
@Column(name = "xcuenta_bco")
private String xcuentaBco;
@Basic(optional = false)
@NotNull
@Column(name = "fcheque")
@Temporal(TemporalType.TIMESTAMP)
private Date fcheque;
@Basic(optional = false)
@NotNull
@Column(name = "icheque")
private long icheque;
@Basic(optional = false)
@NotNull
@Column(name = "femision")
@Temporal(TemporalType.TIMESTAMP)
private Date femision;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "fcobro")
@Temporal(TemporalType.TIMESTAMP)
private Date fcobro;
@Column(name = "iretencion")
private Long iretencion;
@JoinColumn(name = "cod_banco", referencedColumnName = "cod_banco", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Bancos bancos;
@JoinColumn(name = "cod_proveed", referencedColumnName = "cod_proveed")
@ManyToOne(optional = false)
private Proveedores codProveed;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "chequesEmitidos")
private Collection<ChequesEmitidosDet> chequesEmitidosDetCollection;
public ChequesEmitidos() {
}
public ChequesEmitidos(ChequesEmitidosPK chequesEmitidosPK) {
this.chequesEmitidosPK = chequesEmitidosPK;
}
public ChequesEmitidos(ChequesEmitidosPK chequesEmitidosPK, String xcuentaBco, Date fcheque, long icheque, Date femision) {
this.chequesEmitidosPK = chequesEmitidosPK;
this.xcuentaBco = xcuentaBco;
this.fcheque = fcheque;
this.icheque = icheque;
this.femision = femision;
}
public ChequesEmitidos(short codEmpr, short codBanco, String nroCheque) {
this.chequesEmitidosPK = new ChequesEmitidosPK(codEmpr, codBanco, nroCheque);
}
public ChequesEmitidosPK getChequesEmitidosPK() {
return chequesEmitidosPK;
}
public void setChequesEmitidosPK(ChequesEmitidosPK chequesEmitidosPK) {
this.chequesEmitidosPK = chequesEmitidosPK;
}
public String getXcuentaBco() {
return xcuentaBco;
}
public void setXcuentaBco(String xcuentaBco) {
this.xcuentaBco = xcuentaBco;
}
public Date getFcheque() {
return fcheque;
}
public void setFcheque(Date fcheque) {
this.fcheque = fcheque;
}
public long getIcheque() {
return icheque;
}
public void setIcheque(long icheque) {
this.icheque = icheque;
}
public Date getFemision() {
return femision;
}
public void setFemision(Date femision) {
this.femision = femision;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFcobro() {
return fcobro;
}
public void setFcobro(Date fcobro) {
this.fcobro = fcobro;
}
public Long getIretencion() {
return iretencion;
}
public void setIretencion(Long iretencion) {
this.iretencion = iretencion;
}
public Bancos getBancos() {
return bancos;
}
public void setBancos(Bancos bancos) {
this.bancos = bancos;
}
public Proveedores getCodProveed() {
return codProveed;
}
public void setCodProveed(Proveedores codProveed) {
this.codProveed = codProveed;
}
@XmlTransient
public Collection<ChequesEmitidosDet> getChequesEmitidosDetCollection() {
return chequesEmitidosDetCollection;
}
public void setChequesEmitidosDetCollection(Collection<ChequesEmitidosDet> chequesEmitidosDetCollection) {
this.chequesEmitidosDetCollection = chequesEmitidosDetCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (chequesEmitidosPK != null ? chequesEmitidosPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ChequesEmitidos)) {
return false;
}
ChequesEmitidos other = (ChequesEmitidos) object;
if ((this.chequesEmitidosPK == null && other.chequesEmitidosPK != null) || (this.chequesEmitidosPK != null && !this.chequesEmitidosPK.equals(other.chequesEmitidosPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.ChequesEmitidos[ chequesEmitidosPK=" + chequesEmitidosPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Recibos.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author admin
*/
@Entity
@Table(name = "recibos")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Recibos.findAll", query = "SELECT r FROM Recibos r")
, @NamedQuery(name = "Recibos.findByCodEmpr", query = "SELECT r FROM Recibos r WHERE r.recibosPK.codEmpr = :codEmpr")
, @NamedQuery(name = "Recibos.findByNrecibo", query = "SELECT r FROM Recibos r WHERE r.recibosPK.nrecibo = :nrecibo")
, @NamedQuery(name = "Recibos.findByCodCliente", query = "SELECT r FROM Recibos r WHERE r.codCliente = :codCliente")
, @NamedQuery(name = "Recibos.findByFrecibo", query = "SELECT r FROM Recibos r WHERE r.frecibo = :frecibo")
, @NamedQuery(name = "Recibos.findByIrecibo", query = "SELECT r FROM Recibos r WHERE r.irecibo = :irecibo")
, @NamedQuery(name = "Recibos.findByIefectivo", query = "SELECT r FROM Recibos r WHERE r.iefectivo = :iefectivo")
, @NamedQuery(name = "Recibos.findByIretencion", query = "SELECT r FROM Recibos r WHERE r.iretencion = :iretencion")
, @NamedQuery(name = "Recibos.findByIcheques", query = "SELECT r FROM Recibos r WHERE r.icheques = :icheques")
, @NamedQuery(name = "Recibos.findByXobs", query = "SELECT r FROM Recibos r WHERE r.xobs = :xobs")
, @NamedQuery(name = "Recibos.findByMestado", query = "SELECT r FROM Recibos r WHERE r.mestado = :mestado")
, @NamedQuery(name = "Recibos.findByCusuario", query = "SELECT r FROM Recibos r WHERE r.cusuario = :cusuario")
, @NamedQuery(name = "Recibos.findByFalta", query = "SELECT r FROM Recibos r WHERE r.falta = :falta")
, @NamedQuery(name = "Recibos.findByFanul", query = "SELECT r FROM Recibos r WHERE r.fanul = :fanul")})
public class Recibos implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected RecibosPK recibosPK;
@Column(name = "cod_cliente")
private Integer codCliente;
@Basic(optional = false)
@NotNull
@Column(name = "frecibo")
@Temporal(TemporalType.TIMESTAMP)
private Date frecibo;
@Basic(optional = false)
@NotNull
@Column(name = "irecibo")
private long irecibo;
@Basic(optional = false)
@NotNull
@Column(name = "iefectivo")
private long iefectivo;
@Basic(optional = false)
@NotNull
@Column(name = "iretencion")
private long iretencion;
@Basic(optional = false)
@NotNull
@Column(name = "icheques")
private long icheques;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 200)
@Column(name = "xobs")
private String xobs;
@Basic(optional = false)
@NotNull
@Column(name = "mestado")
private Character mestado;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Column(name = "fanul")
@Temporal(TemporalType.TIMESTAMP)
private Date fanul;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "recibos", fetch = FetchType.LAZY)
private Collection<RecibosCheques> recibosChequesCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "recibos", fetch = FetchType.LAZY)
private Collection<RecibosDet> recibosDetCollection;
/*@OneToMany(cascade = CascadeType.ALL, mappedBy = "recibos")
private Collection<MovimientosCobradores> movimientosCobradoresCollection;*/
@Transient
private String nomCliente;
public Recibos() {
}
public Recibos(RecibosPK recibosPK) {
this.recibosPK = recibosPK;
}
public Recibos(RecibosPK recibosPK, Date frecibo, long irecibo, long iefectivo, long iretencion, long icheques, String xobs, Character mestado) {
this.recibosPK = recibosPK;
this.frecibo = frecibo;
this.irecibo = irecibo;
this.iefectivo = iefectivo;
this.iretencion = iretencion;
this.icheques = icheques;
this.xobs = xobs;
this.mestado = mestado;
}
public Recibos(short codEmpr, long nrecibo) {
this.recibosPK = new RecibosPK(codEmpr, nrecibo);
}
public RecibosPK getRecibosPK() {
return recibosPK;
}
public void setRecibosPK(RecibosPK recibosPK) {
this.recibosPK = recibosPK;
}
public Integer getCodCliente() {
return codCliente;
}
public void setCodCliente(Integer codCliente) {
this.codCliente = codCliente;
}
public Date getFrecibo() {
return frecibo;
}
public void setFrecibo(Date frecibo) {
this.frecibo = frecibo;
}
public long getIrecibo() {
return irecibo;
}
public void setIrecibo(long irecibo) {
this.irecibo = irecibo;
}
public long getIefectivo() {
return iefectivo;
}
public void setIefectivo(long iefectivo) {
this.iefectivo = iefectivo;
}
public long getIretencion() {
return iretencion;
}
public void setIretencion(long iretencion) {
this.iretencion = iretencion;
}
public long getIcheques() {
return icheques;
}
public void setIcheques(long icheques) {
this.icheques = icheques;
}
public String getXobs() {
return xobs;
}
public void setXobs(String xobs) {
this.xobs = xobs;
}
public Character getMestado() {
return mestado;
}
public void setMestado(Character mestado) {
this.mestado = mestado;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public Date getFanul() {
return fanul;
}
public void setFanul(Date fanul) {
this.fanul = fanul;
}
@XmlTransient
public Collection<RecibosCheques> getRecibosChequesCollection() {
return recibosChequesCollection;
}
public void setRecibosChequesCollection(Collection<RecibosCheques> recibosChequesCollection) {
this.recibosChequesCollection = recibosChequesCollection;
}
@XmlTransient
public Collection<RecibosDet> getRecibosDetCollection() {
return recibosDetCollection;
}
public void setRecibosDetCollection(Collection<RecibosDet> recibosDetCollection) {
this.recibosDetCollection = recibosDetCollection;
}
/*@XmlTransient
public Collection<MovimientosCobradores> getMovimientosCobradoresCollection() {
return movimientosCobradoresCollection;
}
public void setMovimientosCobradoresCollection(Collection<MovimientosCobradores> movimientosCobradoresCollection) {
this.movimientosCobradoresCollection = movimientosCobradoresCollection;
}*/
@Override
public int hashCode() {
int hash = 0;
hash += (recibosPK != null ? recibosPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Recibos)) {
return false;
}
Recibos other = (Recibos) object;
if ((this.recibosPK == null && other.recibosPK != null) || (this.recibosPK != null && !this.recibosPK.equals(other.recibosPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Recibos[ recibosPK=" + recibosPK + " ]";
}
public String getNomCliente() {
return nomCliente;
}
public void setNomCliente(String nomCliente) {
this.nomCliente = nomCliente;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Remisiones.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author admin
*/
@Entity
@Table(name = "remisiones")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Remisiones.findAll", query = "SELECT r FROM Remisiones r")
, @NamedQuery(name = "Remisiones.findByCodEmpr", query = "SELECT r FROM Remisiones r WHERE r.remisionesPK.codEmpr = :codEmpr")
, @NamedQuery(name = "Remisiones.findByNroRemision", query = "SELECT r FROM Remisiones r WHERE r.remisionesPK.nroRemision = :nroRemision")
, @NamedQuery(name = "Remisiones.findByFremision", query = "SELECT r FROM Remisiones r WHERE r.fremision = :fremision")
, @NamedQuery(name = "Remisiones.findByCodDepo", query = "SELECT r FROM Remisiones r WHERE r.codDepo = :codDepo")
, @NamedQuery(name = "Remisiones.findByCodConductor", query = "SELECT r FROM Remisiones r WHERE r.codConductor = :codConductor")
, @NamedQuery(name = "Remisiones.findByCodTransp", query = "SELECT r FROM Remisiones r WHERE r.codTransp = :codTransp")
, @NamedQuery(name = "Remisiones.findByCodEntregador", query = "SELECT r FROM Remisiones r WHERE r.codEntregador = :codEntregador")
, @NamedQuery(name = "Remisiones.findByMtipo", query = "SELECT r FROM Remisiones r WHERE r.mtipo = :mtipo")
, @NamedQuery(name = "Remisiones.findByMestado", query = "SELECT r FROM Remisiones r WHERE r.mestado = :mestado")
, @NamedQuery(name = "Remisiones.findByFalta", query = "SELECT r FROM Remisiones r WHERE r.falta = :falta")
, @NamedQuery(name = "Remisiones.findByCusuario", query = "SELECT r FROM Remisiones r WHERE r.cusuario = :cusuario")
, @NamedQuery(name = "Remisiones.findByFultimModif", query = "SELECT r FROM Remisiones r WHERE r.fultimModif = :fultimModif")
, @NamedQuery(name = "Remisiones.findByCusuarioModifi", query = "SELECT r FROM Remisiones r WHERE r.cusuarioModifi = :cusuarioModifi")
, @NamedQuery(name = "Remisiones.findByFanul", query = "SELECT r FROM Remisiones r WHERE r.fanul = :fanul")
, @NamedQuery(name = "Remisiones.findByXnroRemision", query = "SELECT r FROM Remisiones r WHERE r.xnroRemision = :xnroRemision")
, @NamedQuery(name = "Remisiones.findByCmotivo", query = "SELECT r FROM Remisiones r WHERE r.cmotivo = :cmotivo")})
public class Remisiones implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected RemisionesPK remisionesPK;
@Column(name = "fremision")
@Temporal(TemporalType.TIMESTAMP)
private Date fremision;
@Column(name = "cod_depo")
private Short codDepo;
@Column(name = "cod_conductor")
private Short codConductor;
@Column(name = "cod_transp")
private Short codTransp;
@Column(name = "cod_entregador")
private Short codEntregador;
@Column(name = "mtipo")
private Character mtipo;
@Column(name = "mestado")
private Character mestado;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "fultim_modif")
@Temporal(TemporalType.TIMESTAMP)
private Date fultimModif;
@Size(max = 30)
@Column(name = "cusuario_modifi")
private String cusuarioModifi;
@Column(name = "fanul")
@Temporal(TemporalType.TIMESTAMP)
private Date fanul;
@Size(max = 15)
@Column(name = "xnro_remision")
private String xnroRemision;
@Column(name = "cmotivo")
private Short cmotivo;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "remisiones")
private Collection<RemisionesDet> remisionesDetCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "remisiones")
private Collection<RemisionesFacturas> remisionesFacturasCollection;
public Remisiones() {
}
public Remisiones(RemisionesPK remisionesPK) {
this.remisionesPK = remisionesPK;
}
public Remisiones(short codEmpr, long nroRemision) {
this.remisionesPK = new RemisionesPK(codEmpr, nroRemision);
}
public RemisionesPK getRemisionesPK() {
return remisionesPK;
}
public void setRemisionesPK(RemisionesPK remisionesPK) {
this.remisionesPK = remisionesPK;
}
public Date getFremision() {
return fremision;
}
public void setFremision(Date fremision) {
this.fremision = fremision;
}
public Short getCodDepo() {
return codDepo;
}
public void setCodDepo(Short codDepo) {
this.codDepo = codDepo;
}
public Short getCodConductor() {
return codConductor;
}
public void setCodConductor(Short codConductor) {
this.codConductor = codConductor;
}
public Short getCodTransp() {
return codTransp;
}
public void setCodTransp(Short codTransp) {
this.codTransp = codTransp;
}
public Short getCodEntregador() {
return codEntregador;
}
public void setCodEntregador(Short codEntregador) {
this.codEntregador = codEntregador;
}
public Character getMtipo() {
return mtipo;
}
public void setMtipo(Character mtipo) {
this.mtipo = mtipo;
}
public Character getMestado() {
return mestado;
}
public void setMestado(Character mestado) {
this.mestado = mestado;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFultimModif() {
return fultimModif;
}
public void setFultimModif(Date fultimModif) {
this.fultimModif = fultimModif;
}
public String getCusuarioModifi() {
return cusuarioModifi;
}
public void setCusuarioModifi(String cusuarioModifi) {
this.cusuarioModifi = cusuarioModifi;
}
public Date getFanul() {
return fanul;
}
public void setFanul(Date fanul) {
this.fanul = fanul;
}
public String getXnroRemision() {
return xnroRemision;
}
public void setXnroRemision(String xnroRemision) {
this.xnroRemision = xnroRemision;
}
public Short getCmotivo() {
return cmotivo;
}
public void setCmotivo(Short cmotivo) {
this.cmotivo = cmotivo;
}
@XmlTransient
public Collection<RemisionesDet> getRemisionesDetCollection() {
return remisionesDetCollection;
}
public void setRemisionesDetCollection(Collection<RemisionesDet> remisionesDetCollection) {
this.remisionesDetCollection = remisionesDetCollection;
}
@XmlTransient
public Collection<RemisionesFacturas> getRemisionesFacturasCollection() {
return remisionesFacturasCollection;
}
public void setRemisionesFacturasCollection(Collection<RemisionesFacturas> remisionesFacturasCollection) {
this.remisionesFacturasCollection = remisionesFacturasCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (remisionesPK != null ? remisionesPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Remisiones)) {
return false;
}
Remisiones other = (Remisiones) object;
if ((this.remisionesPK == null && other.remisionesPK != null) || (this.remisionesPK != null && !this.remisionesPK.equals(other.remisionesPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Remisiones[ remisionesPK=" + remisionesPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/PromocionesDetDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import java.math.BigDecimal;
/**
*
* @author dadob
*/
public class PromocionesDetDto {
private Integer nroPromo;
private String codMerca;
private String xDesc;
private Character mY;
private BigDecimal kKilosIni;
private BigDecimal kKilosFin;
private BigDecimal kCajasIni;
private BigDecimal kCajasFin;
private BigDecimal kUnidIni;
private BigDecimal kUnidFin;
private short porKUnidad;
private short porKCajas;
private BigDecimal kUnidBonif;
private BigDecimal pDesc;
private short kMaxUnidBonif;
private Character cTipoCliente;
private Character mTodos;
private short nRelaPack;
private BigDecimal iDesc;
private short codSublinea;
private short nRelacion;
private Character cTipoVenta;
public Integer getNroPromo() {
return nroPromo;
}
public void setNroPromo(Integer nroPromo) {
this.nroPromo = nroPromo;
}
public String getCodMerca() {
return codMerca;
}
public void setCodMerca(String codMerca) {
this.codMerca = codMerca;
}
public String getxDesc() {
return xDesc;
}
public void setxDesc(String xDesc) {
this.xDesc = xDesc;
}
public Character getmY() {
return mY;
}
public void setmY(Character mY) {
this.mY = mY;
}
public BigDecimal getkKilosIni() {
return kKilosIni;
}
public void setkKilosIni(BigDecimal kKilosIni) {
this.kKilosIni = kKilosIni;
}
public BigDecimal getkKilosFin() {
return kKilosFin;
}
public void setkKilosFin(BigDecimal kKilosFin) {
this.kKilosFin = kKilosFin;
}
public BigDecimal getkCajasIni() {
return kCajasIni;
}
public void setkCajasIni(BigDecimal kCajasIni) {
this.kCajasIni = kCajasIni;
}
public BigDecimal getkCajasFin() {
return kCajasFin;
}
public void setkCajasFin(BigDecimal kCajasFin) {
this.kCajasFin = kCajasFin;
}
public BigDecimal getkUnidIni() {
return kUnidIni;
}
public void setkUnidIni(BigDecimal kUnidIni) {
this.kUnidIni = kUnidIni;
}
public BigDecimal getkUnidFin() {
return kUnidFin;
}
public void setkUnidFin(BigDecimal kUnidFin) {
this.kUnidFin = kUnidFin;
}
public short getPorKUnidad() {
return porKUnidad;
}
public void setPorKUnidad(short porKUnidad) {
this.porKUnidad = porKUnidad;
}
public short getPorKCajas() {
return porKCajas;
}
public void setPorKCajas(short porKCajas) {
this.porKCajas = porKCajas;
}
public BigDecimal getkUnidBonif() {
return kUnidBonif;
}
public void setkUnidBonif(BigDecimal kUnidBonif) {
this.kUnidBonif = kUnidBonif;
}
public BigDecimal getpDesc() {
return pDesc;
}
public void setpDesc(BigDecimal pDesc) {
this.pDesc = pDesc;
}
public short getkMaxUnidBonif() {
return kMaxUnidBonif;
}
public void setkMaxUnidBonif(short kMaxUnidBonif) {
this.kMaxUnidBonif = kMaxUnidBonif;
}
public Character getcTipoCliente() {
return cTipoCliente;
}
public void setcTipoCliente(Character cTipoCliente) {
this.cTipoCliente = cTipoCliente;
}
public Character getmTodos() {
return mTodos;
}
public void setmTodos(Character mTodos) {
this.mTodos = mTodos;
}
public short getnRelaPack() {
return nRelaPack;
}
public void setnRelaPack(short nRelaPack) {
this.nRelaPack = nRelaPack;
}
public BigDecimal getiDesc() {
return iDesc;
}
public void setiDesc(BigDecimal iDesc) {
this.iDesc = iDesc;
}
public short getCodSublinea() {
return codSublinea;
}
public void setCodSublinea(short codSublinea) {
this.codSublinea = codSublinea;
}
public short getnRelacion() {
return nRelacion;
}
public void setnRelacion(short nRelacion) {
this.nRelacion = nRelacion;
}
public Character getcTipoVenta() {
return cTipoVenta;
}
public void setcTipoVenta(Character cTipoVenta) {
this.cTipoVenta = cTipoVenta;
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiExtractoClientesBean.java
package bean.listados;
import dao.CanalesCompraFacade;
import dao.DepositosFacade;
import dao.ClientesFacade;
import dao.ExcelFacade;
import dto.LiMercaSinDto;
import entidad.CanalesCompra;
import entidad.CanalesCompraPK;
import entidad.Depositos;
import entidad.DepositosPK;
import entidad.Clientes;
import entidad.Clientes;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiExtractoClientesBean {
@EJB
private ClientesFacade clientesFacade;
@EJB
private ExcelFacade excelFacade;
private Clientes clientes;
private List<Clientes> listaClientes;
private Date desde;
private Date hasta;
private Boolean todos;
private String clientesSel;
public LiExtractoClientesBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.clientes = new Clientes();
this.listaClientes = new ArrayList<Clientes>();
this.desde = new Date();
this.hasta = new Date();
setTodos(false);
setClientesSel("");
}
public void ejecutar(String tipo) {
LlamarReportes rep = new LlamarReportes();
StringBuilder sql = new StringBuilder();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
Integer clie = 0;
String descclie = "";
String canal = "";
String desccanal = "";
if (this.clientes != null) {
clie = Integer.parseInt(this.clientes.getCodCliente() + "");
descclie = clientesFacade.find(this.clientes.getCodCliente()).getXnombre();
} else {
clie = 0;
descclie = "TODOS";
}
sql.append("SELECT c.cod_cliente,c.ctipo_docum, c.ndocum_cheq, c.fac_ctipo_docum, c.nrofact, \n"
+ " c. fvenc, c.fmovim, t.xnombre, t.nplazo_credito, \n"
+ " (c.texentas+c.tgravadas+c.timpuestos+c.ipagado) as imovim, \n"
+ " mindice \n"
+ " FROM cuentas_corrientes c, clientes t \n"
+ " WHERE fmovim BETWEEN'"+fdesde+"' AND '"+fhasta+"' \n"
+ " AND ( c.fac_ctipo_docum = 'FCR' \n"
+ " OR c.ctipo_docum IN ('CHQ','CHC','PAG','PAC') )\n"
+ " AND fmovim >= '01/09/2005' \n"
+ " AND c.cod_cliente = t.cod_cliente \n");
if (this.clientesSel != "") {
sql.append("AND c.cod_cliente IN ("+this.clientesSel+") \n");
}
sql.append(" ORDER BY c.cod_cliente, fmovim, c.ctipo_docum, c.ndocum_cheq \n");
if (tipo.equals("VIST")) {
rep.reporteLiExtractoCliente(sql.toString(), dateToString2(desde), dateToString2(hasta), "admin", tipo);
} else if (tipo.equals("ARCH")) {
List<Object[]> auxExcel = new ArrayList<Object[]>();
auxExcel = excelFacade.listarParaExcel(sql.toString());
rep.excelLiExtractoCliente(auxExcel);
}
rep.reporteLiExtractoProveedor(clie, descclie, canal, desccanal, dateToString(desde), dateToString2(desde), dateToString(hasta), dateToString2(hasta), "admin", tipo);
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
public void todosLosClientes() {
if (this.todos == true) {
this.clientes = new Clientes();
clientesSel = "";
}
}
public void buscadorClienteTab(AjaxBehaviorEvent event) {
try {
if (this.clientes != null) {
if (!this.clientes.getCodCliente().equals("")) {
this.clientes = this.clientesFacade.buscarPorCodigo(this.clientes.getCodCliente() + "");
if (getClientesSel().equals("")) {
setClientesSel(getClientesSel() + clientes.getCodCliente());
}else{
setClientesSel( getClientesSel() + "," + clientes.getCodCliente());
}
if (this.clientes == null) {
this.clientes = new Clientes();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "No encontrado."));
}
}
} else {
this.clientes = new Clientes();
}
} catch (Exception e) {
this.clientes = new Clientes();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error en la busqueda"));
}
}
//Getters & Setters
public Clientes getClientes() {
return clientes;
}
public void setClientes(Clientes sublineas) {
this.clientes = sublineas;
}
public List<Clientes> getListaClientes() {
return listaClientes;
}
public void setListaClientes(List<Clientes> listaClientes) {
this.listaClientes = listaClientes;
}
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
public Boolean getTodos() {
return todos;
}
public void setTodos(Boolean todos) {
this.todos = todos;
}
public String getClientesSel() {
return clientesSel;
}
public void setClientesSel(String clientesSel) {
this.clientesSel = clientesSel;
}
}
<file_sep>/SisVenLog-war/src/java/bean/CobroPagaresBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
import dao.ClientesFacade;
import dao.CuentasCorrientesFacade;
import dao.PagaresFacade;
import dto.PagareDto;
import entidad.Clientes;
import entidad.CuentasCorrientes;
import entidad.Pagares;
import entidad.PagaresPK;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.SelectEvent;
import util.ExceptionHandlerView;
/**
*
* @author Edu
*/
@ManagedBean
@SessionScoped
public class CobroPagaresBean implements Serializable{
@EJB
private PagaresFacade pagaresFacade;
@EJB
private CuentasCorrientesFacade cuentasCorrientesFacade;
@EJB
private ClientesFacade clientesFacade;
private Pagares pagare;
private PagareDto pagareDto;
private CuentasCorrientes cuentasCorrientes;
private List<PagareDto> listadoPagaresNoCobrados;
private long numeroPagare;
private Long montoPagare;
private Date fechaCobro;
private Date fechaInicio;
private Date fechaFin;
private Integer codigoCliente;
private String nombreCliente;
private String codigoZona;
private String contenidoError;
private String tituloError;
private Clientes clientes;
private List<Clientes> listaClientes;
private String filtro;
public CobroPagaresBean() {
}
@PostConstruct
public void instanciar(){
limpiarVariables();
listadoPagaresNoCobrados = new ArrayList<>();
pagare = new Pagares();
pagare.setPagaresPK(new PagaresPK());
pagareDto = new PagareDto();
pagareDto.setPagare(new Pagares());
cuentasCorrientes = new CuentasCorrientes();
}
private void limpiarVariables(){
this.numeroPagare = 0;
this.montoPagare = new Long("0");
this.fechaCobro = new Date();
this.fechaInicio = null;
this.fechaFin = null;
this.codigoCliente = new Integer("0");
this.nombreCliente = "";
this.codigoZona = "";
}
public void inicializarBuscadorClientes(){
listaClientes = new ArrayList<>();
clientes = new Clientes();
filtro = "";
listarClientesBuscador();
}
public void listarClientesBuscador(){
try{
listaClientes = clientesFacade.buscarPorFiltro(filtro);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de clientes.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public String limpiarFormulario(){
limpiarVariables();
listadoPagaresNoCobrados = new ArrayList<>();
pagare = new Pagares();
pagare.setPagaresPK(new PagaresPK());
pagareDto = new PagareDto();
pagareDto.setPagare(new Pagares());
cuentasCorrientes = new CuentasCorrientes();
return null;
}
public void listarPagaresNoCobrados(){
try{
codigoZona = codigoZona == null ? "" : codigoZona;
if(montoPagare == null){
montoPagare = Long.parseLong("0");
}
if(codigoCliente == null){
codigoCliente = Integer.parseInt("0");
}
listadoPagaresNoCobrados.clear();
listadoPagaresNoCobrados = pagaresFacade.listarPagaresNoCobrados( codigoZona,
numeroPagare,
montoPagare,
fechaInicio,
fechaFin,
codigoCliente,
fechaCobro);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de pagares.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error en la lectura de datos de pagares.", tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public void seleccionarPagareNoCobrado() {
}
public String guardarPagaresNoCobrados(){
int contadorPagaresSeleccionados = 0;
try{
if(!listadoPagaresNoCobrados.isEmpty()){
for(PagareDto pdto: listadoPagaresNoCobrados){
if(pdto.isPagareSeleccionado()){
contadorPagaresSeleccionados++;
}
}
if(contadorPagaresSeleccionados == 0){
//no se selecciono ningun pagaré para cobrar
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Seleccione al menos un pagaré para cobrar.", null));
return null;
}else{
for(PagareDto pdto: listadoPagaresNoCobrados){
if(pdto.isPagareSeleccionado()){
if(pdto.getPagare().getFcobro().before(pdto.getPagare().getFemision())){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Fecha de cobro debe ser mayor/igual a Fecha Emisión ", null));
return null;
}else{
if(pagare != null){
pagare.setFcobro(pdto.getPagare().getFcobro());
pagare.getPagaresPK().setNpagare(pdto.getPagare().getPagaresPK().getNpagare());
try{
//actualizar pagares no cobrados
int resultado = pagaresFacade.actualizarPagaresNoCobrados(pagare);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la actualización de pagarés.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
try{
if(cuentasCorrientes != null){
cuentasCorrientes.setCtipoDocum("PAC");
cuentasCorrientes.setMindice(new Short("-1"));
cuentasCorrientes.setFvenc(pdto.getPagare().getFvenc());
cuentasCorrientes.setIpagado(pdto.getPagare().getIpagare());
cuentasCorrientes.setTexentas(0);
cuentasCorrientes.setCodCliente(pdto.getPagare().getCodCliente());
cuentasCorrientes.setFmovim(pdto.getPagare().getFcobro());
cuentasCorrientes.setCodEmpr(new Short("2"));
cuentasCorrientes.setNdocumCheq(Long.toString(pdto.getPagare().getPagaresPK().getNpagare()));
cuentasCorrientes.setIretencion(0);
cuentasCorrientes.setCodBanco(null);
cuentasCorrientes.setIsaldo(0);
cuentasCorrientes.setTgravadas(0);
cuentasCorrientes.setTimpuestos(0);
cuentasCorrientes.setManulado(new Short("1"));
cuentasCorrientesFacade.insertarCuentas(cuentasCorrientes);
}
}catch(Exception sqle){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(sqle);
tituloError = "Error en la insersión de movimietos en cuentas corrientes.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}
}
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Datos Grabados.", null));
return null;
}
}else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "No existen datos.", null));
return null;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al confirmar la operación.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
public void verificarCliente(){
if(codigoCliente != null){
if(codigoCliente == 0){
//mostrar busqueda de clientes
RequestContext.getCurrentInstance().execute("PF('dlgBusClieCobroPagare').show();");
}else{
try{
Clientes clienteBuscado = clientesFacade.find(codigoCliente);
if(clienteBuscado == null){
//mostrar busqueda de clientes
RequestContext.getCurrentInstance().execute("PF('dlgBusClieCobroPagare').show();");
}else{
this.nombreCliente = clienteBuscado.getXnombre();
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de clientes.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
}
}
public void onRowSelect(SelectEvent event) {
if (getClientes() != null) {
if (getClientes().getXnombre() != null) {
codigoCliente = getClientes().getCodCliente();
nombreCliente = getClientes().getXnombre();
RequestContext.getCurrentInstance().update("panel_buscador_pagares");
RequestContext.getCurrentInstance().execute("PF('dlgBusClieCobroPagare').hide();");
}
}
}
public void onCellEdit(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if(!oldValue.equals(newValue)){
DataTable table = (DataTable) event.getSource();
PagareDto pagareDtoRow = (PagareDto) table.getRowData();
getPagareDto().getPagare().setFcobro(pagareDtoRow.getPagare().getFcobro());
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO,"Fecha de cobro actualizada!", ""));
}
}
public Pagares getPagare() {
return pagare;
}
public void setPagare(Pagares pagare) {
this.pagare = pagare;
}
public PagareDto getPagareDto() {
return pagareDto;
}
public void setPagareDto(PagareDto pagareDto) {
this.pagareDto = pagareDto;
}
public List<PagareDto> getListadoPagaresNoCobrados() {
return listadoPagaresNoCobrados;
}
public void setListadoPagaresNoCobrados(List<PagareDto> listadoPagaresNoCobrados) {
this.listadoPagaresNoCobrados = listadoPagaresNoCobrados;
}
public long getNumeroPagare() {
return numeroPagare;
}
public void setNumeroPagare(long numeroPagare) {
this.numeroPagare = numeroPagare;
}
public Long getMontoPagare() {
return montoPagare;
}
public void setMontoPagare(Long montoPagare) {
this.montoPagare = montoPagare;
}
public Date getFechaCobro() {
return fechaCobro;
}
public void setFechaCobro(Date fechaCobro) {
this.fechaCobro = fechaCobro;
}
public Date getFechaInicio() {
return fechaInicio;
}
public void setFechaInicio(Date fechaInicio) {
this.fechaInicio = fechaInicio;
}
public Date getFechaFin() {
return fechaFin;
}
public void setFechaFin(Date fechaFin) {
this.fechaFin = fechaFin;
}
public Integer getCodigoCliente() {
return codigoCliente;
}
public void setCodigoCliente(Integer codigoCliente) {
this.codigoCliente = codigoCliente;
}
public String getNombreCliente() {
return nombreCliente;
}
public void setNombreCliente(String nombreCliente) {
this.nombreCliente = nombreCliente;
}
public String getCodigoZona() {
return codigoZona;
}
public void setCodigoZona(String codigoZona) {
this.codigoZona = codigoZona;
}
public String getContenidoError() {
return contenidoError;
}
public void setContenidoError(String contenidoError) {
this.contenidoError = contenidoError;
}
public String getTituloError() {
return tituloError;
}
public void setTituloError(String tituloError) {
this.tituloError = tituloError;
}
public Clientes getClientes() {
return clientes;
}
public void setClientes(Clientes clientes) {
this.clientes = clientes;
}
public List<Clientes> getListaClientes() {
return listaClientes;
}
public void setListaClientes(List<Clientes> listaClientes) {
this.listaClientes = listaClientes;
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/RangosDocumentosFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.RangosDocumentos;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author admin
*/
@Stateless
public class RangosDocumentosFacade extends AbstractFacade<RangosDocumentos> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public RangosDocumentosFacade() {
super(RangosDocumentos.class);
}
public List<RangosDocumentos> obtenerRangosDeDocumentos(String lTipoDocum, Long lNroFact){
String sql = "SELECT * FROM rangos_documentos " +
"WHERE cod_empr = 2 and ctipo_docum = '"+lTipoDocum+"' "+
"and mtipo_papel = 'F' " +
"AND "+lNroFact+" BETWEEN nro_docum_ini AND nro_docum_fin";
Query q = em.createNativeQuery(sql, RangosDocumentos.class);
System.out.println(q.toString());
List<RangosDocumentos> resultados = new ArrayList<>();
resultados = q.getResultList();
return resultados;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/Usuarios.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Hugo
*/
@Entity
@Table(name = "usuarios")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Usuarios.findAll", query = "SELECT u FROM Usuarios u")
, @NamedQuery(name = "Usuarios.findByCodUsuario", query = "SELECT u FROM Usuarios u WHERE u.usuariosPK.codUsuario = :codUsuario")
, @NamedQuery(name = "Usuarios.findByXnombre", query = "SELECT u FROM Usuarios u WHERE u.xnombre = :xnombre")
, @NamedQuery(name = "Usuarios.findByCodEmpr", query = "SELECT u FROM Usuarios u WHERE u.usuariosPK.codEmpr = :codEmpr")
, @NamedQuery(name = "Usuarios.findByCusuario", query = "SELECT u FROM Usuarios u WHERE u.cusuario = :cusuario")
, @NamedQuery(name = "Usuarios.findByFalta", query = "SELECT u FROM Usuarios u WHERE u.falta = :falta")})
public class Usuarios implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected UsuariosPK usuariosPK;
//@Size(max = 50)
@Column(name = "xnombre")
private String xnombre;
//@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@JoinColumns({
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
, @JoinColumn(name = "cod_empleado", referencedColumnName = "cod_empleado")})
@ManyToOne(optional = false)
private Empleados empleados;
public Usuarios() {
}
public Usuarios(UsuariosPK usuariosPK) {
this.usuariosPK = usuariosPK;
}
public Usuarios(String codUsuario, short codEmpr) {
this.usuariosPK = new UsuariosPK(codUsuario, codEmpr);
}
public UsuariosPK getUsuariosPK() {
return usuariosPK;
}
public void setUsuariosPK(UsuariosPK usuariosPK) {
this.usuariosPK = usuariosPK;
}
public String getXnombre() {
return xnombre;
}
public void setXnombre(String xnombre) {
this.xnombre = xnombre;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public Empleados getEmpleados() {
return empleados;
}
public void setEmpleados(Empleados empleados) {
this.empleados = empleados;
}
@Override
public int hashCode() {
int hash = 0;
hash += (usuariosPK != null ? usuariosPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Usuarios)) {
return false;
}
Usuarios other = (Usuarios) object;
if ((this.usuariosPK == null && other.usuariosPK != null) || (this.usuariosPK != null && !this.usuariosPK.equals(other.usuariosPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.Usuarios[ usuariosPK=" + usuariosPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/buscadorDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
/**
*
* @author WORK
*/
public class buscadorDto {
private String dato1;
private String dato2;
private String dato3;
public buscadorDto() {
}
public String getDato1() {
return dato1;
}
public void setDato1(String dato1) {
this.dato1 = dato1;
}
public String getDato2() {
return dato2;
}
public void setDato2(String dato2) {
this.dato2 = dato2;
}
public String getDato3() {
return dato3;
}
public void setDato3(String dato3) {
this.dato3 = dato3;
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiDocuResBean.java
package bean.listados;
import dao.DepositosFacade;
import dao.TiposDocumentosFacade;
import entidad.Depositos;
import entidad.DepositosPK;
import entidad.TiposDocumentos;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiDocuResBean {
@EJB
private DepositosFacade depositosFacade;
private Depositos depositos;
private List<Depositos> listaDepositos;
private Date desde;
private Date hasta;
private String operacion;
public LiDocuResBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.depositos = new Depositos(new DepositosPK());
this.listaDepositos = new ArrayList<Depositos>();
this.desde = new Date();
this.hasta = new Date();
}
public List<Depositos> listarDepositos() {
this.listaDepositos = depositosFacade.listarDepositosActivos();
return this.listaDepositos;
}
public void ejecutar(String tipo) {
LlamarReportes rep = new LlamarReportes();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
Integer deposito = 0;
if (this.depositos == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Debe seleccionar un deposito"));
return;
} else {
deposito = Integer.parseInt(this.depositos.getDepositosPK().getCodDepo()+"");
}
rep.reporteLiDocuRes(deposito, depositosFacade.find(depositos.getDepositosPK()).getXdesc(),dateToString(desde), dateToString2(desde), dateToString(hasta), dateToString2(hasta), "admin", tipo);
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
//Getters & Setters
public Depositos getDepositos() {
return depositos;
}
public void setDepositos(Depositos depositos) {
this.depositos = depositos;
}
public List<Depositos> getListaDepositos() {
return listaDepositos;
}
public void setListaDepositos(List<Depositos> listaDepositos) {
this.listaDepositos = listaDepositos;
}
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
public String getOperacion() {
return operacion;
}
public void setOperacion(String operacion) {
this.operacion = operacion;
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiFacBonifBean.java
package bean.listados;
import dao.ExcelFacade;
import dao.PromocionesFacade;
import dao.TiposDocumentosFacade;
import entidad.Promociones;
import entidad.PromocionesPK;
import entidad.TiposDocumentos;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiFacBonifBean {
@EJB
private TiposDocumentosFacade tiposDocumentosFacade;
@EJB
private ExcelFacade excelFacade;
private TiposDocumentos tiposDocumentos;
private List<TiposDocumentos> listaTiposDocumentos;
@EJB
private PromocionesFacade promocionesFacade;
private Promociones promociones;
private List<Promociones> listaPromociones;
private Date desde;
private Date hasta;
private String operacion;
public LiFacBonifBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.tiposDocumentos = new TiposDocumentos();
this.listaTiposDocumentos = new ArrayList<TiposDocumentos>();
this.promociones = new Promociones(new PromocionesPK());
this.listaPromociones = new ArrayList<Promociones>();
this.desde = new Date();
this.hasta = new Date();
setOperacion("A");
}
public List<TiposDocumentos> listarTipoDocumentoLiFacBonif() {
this.listaTiposDocumentos = tiposDocumentosFacade.listarTipoDocumentoLiFacBonif();
return this.listaTiposDocumentos;
}
public void listarPromociones() {
this.listaPromociones = promocionesFacade.listarPromocionesLiFacBonif(dateToString(desde), dateToString(hasta));
}
public void ejecutar(String tipo) {
LlamarReportes rep = new LlamarReportes();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
String tipoDoc = "";
String promoDesc = "";
Integer tipoDocumento = 0;
Integer nroPromo = 0;
if (this.tiposDocumentos == null) {
tipoDoc = "TODOS";
} else {
tipoDoc = this.tiposDocumentos.getCtipoDocum();
}
if (this.promociones == null) {
nroPromo = 0;
promoDesc = "TODOS";
} else {
nroPromo = Integer.parseInt(this.promociones.getPromocionesPK().getNroPromo() + "");
promoDesc = this.promociones.getXdesc();
}
if (tipo.equals("VIST")) {
rep.reporteLiFacBonif(nroPromo, tipoDoc, fdesde, fhasta, dateToString2(desde),
dateToString2(hasta), tipoDoc, promoDesc, "admin", tipo);
} else {
List<Object[]> lista = new ArrayList<Object[]>();
String[] columnas = new String[13];
columnas[0] = "nrofact";
columnas[1] = "ffactur";
columnas[2] = "ctipo_docum";
columnas[3] = "cod_cliente";
columnas[4] = "xrazon_social";
columnas[5] = "cod_vendedor";
columnas[6] = "cod_merca";
columnas[7] = "xdesc";
columnas[8] = "cajas_bonif";
columnas[9] = "unid_bonif";
columnas[10] = "xnombre";
columnas[11] = "nro_promo";
columnas[12] = "xpromo";
String sql = "SELECT f.nrofact, f.ffactur, f.ctipo_docum, f.cod_cliente, f.xrazon_social, f.cod_vendedor,\n"
+ " d.cod_merca, m.xdesc, d.cajas_bonif, d.unid_bonif, v.xnombre, d.nro_promo, p.xdesc as xpromo\n"
+ " FROM facturas f, facturas_det d, mercaderias m, tmp_mercaderias t, empleados v, promociones p\n"
+ " WHERE (f.cod_empr = 2)\n"
+ " AND v.cod_empleado = f.cod_vendedor\n"
+ " AND (f.mestado = 'A')\n"
+ " AND f.cod_empr = 2\n"
+ " AND p.nro_promo= d.nro_promo\n"
+ " AND d.cod_empr = 2\n"
+ " AND (f.ffactur BETWEEN '"+fdesde+"' AND '"+fhasta+"')\n"
+ " AND f.nrofact = d.nrofact\n"
+ " AND f.ffactur = d.ffactur\n"
+ " AND d.cod_merca = t.cod_merca\n"
+ " AND (d.cajas_bonif > 0 OR d.unid_bonif > 0)\n"
+ " AND f.ctipo_docum = d.ctipo_docum\n"
+ " AND f.cod_empr = d.cod_empr\n"
+ " AND d.cod_merca = m.cod_merca\n"
+ "AND (d.nro_promo = "+nroPromo+" or "+nroPromo+" =0)\n"
+ "AND (f.ctipo_docum = '"+tipoDoc+"' OR '"+tipoDoc+"' = 'TODOS')\n"
+ "ORDER BY d.nro_promo, f.cod_vendedor, f.nrofact";
lista = excelFacade.listarParaExcel(sql);
rep.exportarExcel(columnas, lista, "lifactbonif");
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
//Getters & Setters
public TiposDocumentos getTiposDocumentos() {
return tiposDocumentos;
}
public void setTiposDocumentos(TiposDocumentos tiposDocumentos) {
this.tiposDocumentos = tiposDocumentos;
}
public List<TiposDocumentos> getListaTiposDocumentos() {
return listaTiposDocumentos;
}
public void setListaTiposDocumentos(List<TiposDocumentos> listaTiposDocumentos) {
this.listaTiposDocumentos = listaTiposDocumentos;
}
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
public String getOperacion() {
return operacion;
}
public void setOperacion(String operacion) {
this.operacion = operacion;
}
public Promociones getPromociones() {
return promociones;
}
public void setPromociones(Promociones promociones) {
this.promociones = promociones;
}
public List<Promociones> getListaPromociones() {
return listaPromociones;
}
public void setListaPromociones(List<Promociones> listaPromociones) {
this.listaPromociones = listaPromociones;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/HpedidosDet.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author admin
*/
@Entity
@Table(name = "hpedidos_det")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "HpedidosDet.findAll", query = "SELECT h FROM HpedidosDet h")
, @NamedQuery(name = "HpedidosDet.findByCodEmpr", query = "SELECT h FROM HpedidosDet h WHERE h.hpedidosDetPK.codEmpr = :codEmpr")
, @NamedQuery(name = "HpedidosDet.findByNroPedido", query = "SELECT h FROM HpedidosDet h WHERE h.hpedidosDetPK.nroPedido = :nroPedido")
, @NamedQuery(name = "HpedidosDet.findByCodMerca", query = "SELECT h FROM HpedidosDet h WHERE h.hpedidosDetPK.codMerca = :codMerca")
, @NamedQuery(name = "HpedidosDet.findByNroEnvio", query = "SELECT h FROM HpedidosDet h WHERE h.nroEnvio = :nroEnvio")
, @NamedQuery(name = "HpedidosDet.findByCantCajas", query = "SELECT h FROM HpedidosDet h WHERE h.cantCajas = :cantCajas")
, @NamedQuery(name = "HpedidosDet.findByCantUnid", query = "SELECT h FROM HpedidosDet h WHERE h.cantUnid = :cantUnid")
, @NamedQuery(name = "HpedidosDet.findByPrecioCaja", query = "SELECT h FROM HpedidosDet h WHERE h.precioCaja = :precioCaja")
, @NamedQuery(name = "HpedidosDet.findByPrecioUnidad", query = "SELECT h FROM HpedidosDet h WHERE h.precioUnidad = :precioUnidad")
, @NamedQuery(name = "HpedidosDet.findByIexentas", query = "SELECT h FROM HpedidosDet h WHERE h.iexentas = :iexentas")
, @NamedQuery(name = "HpedidosDet.findByIgravadas", query = "SELECT h FROM HpedidosDet h WHERE h.igravadas = :igravadas")
, @NamedQuery(name = "HpedidosDet.findByImpuestos", query = "SELECT h FROM HpedidosDet h WHERE h.impuestos = :impuestos")})
public class HpedidosDet implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected HpedidosDetPK hpedidosDetPK;
@Column(name = "nro_envio")
private Long nroEnvio;
@Column(name = "cant_cajas")
private Integer cantCajas;
@Column(name = "cant_unid")
private Integer cantUnid;
@Column(name = "precio_caja")
private Long precioCaja;
@Column(name = "precio_unidad")
private Long precioUnidad;
@Column(name = "iexentas")
private Long iexentas;
@Column(name = "igravadas")
private Long igravadas;
@Column(name = "impuestos")
private Long impuestos;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "hpedidosDet")
private Collection<PedPromoDet> pedPromoDetCollection;
public HpedidosDet() {
}
public HpedidosDet(HpedidosDetPK hpedidosDetPK) {
this.hpedidosDetPK = hpedidosDetPK;
}
public HpedidosDet(short codEmpr, long nroPedido, String codMerca) {
this.hpedidosDetPK = new HpedidosDetPK(codEmpr, nroPedido, codMerca);
}
public HpedidosDetPK getHpedidosDetPK() {
return hpedidosDetPK;
}
public void setHpedidosDetPK(HpedidosDetPK hpedidosDetPK) {
this.hpedidosDetPK = hpedidosDetPK;
}
public Long getNroEnvio() {
return nroEnvio;
}
public void setNroEnvio(Long nroEnvio) {
this.nroEnvio = nroEnvio;
}
public Integer getCantCajas() {
return cantCajas;
}
public void setCantCajas(Integer cantCajas) {
this.cantCajas = cantCajas;
}
public Integer getCantUnid() {
return cantUnid;
}
public void setCantUnid(Integer cantUnid) {
this.cantUnid = cantUnid;
}
public Long getPrecioCaja() {
return precioCaja;
}
public void setPrecioCaja(Long precioCaja) {
this.precioCaja = precioCaja;
}
public Long getPrecioUnidad() {
return precioUnidad;
}
public void setPrecioUnidad(Long precioUnidad) {
this.precioUnidad = precioUnidad;
}
public Long getIexentas() {
return iexentas;
}
public void setIexentas(Long iexentas) {
this.iexentas = iexentas;
}
public Long getIgravadas() {
return igravadas;
}
public void setIgravadas(Long igravadas) {
this.igravadas = igravadas;
}
public Long getImpuestos() {
return impuestos;
}
public void setImpuestos(Long impuestos) {
this.impuestos = impuestos;
}
@XmlTransient
public Collection<PedPromoDet> getPedPromoDetCollection() {
return pedPromoDetCollection;
}
public void setPedPromoDetCollection(Collection<PedPromoDet> pedPromoDetCollection) {
this.pedPromoDetCollection = pedPromoDetCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (hpedidosDetPK != null ? hpedidosDetPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof HpedidosDet)) {
return false;
}
HpedidosDet other = (HpedidosDet) object;
if ((this.hpedidosDetPK == null && other.hpedidosDetPK != null) || (this.hpedidosDetPK != null && !this.hpedidosDetPK.equals(other.hpedidosDetPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.HpedidosDet[ hpedidosDetPK=" + hpedidosDetPK + " ]";
}
}
<file_sep>/SisVenLog-war/src/java/bean/buscadores/BuscadorConductoresBean.java
package bean.buscadores;
import bean.DepositosBean;
import dao.ConductoresFacade;
import entidad.Conductores;
import entidad.Conductores;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class BuscadorConductoresBean {
@EJB
private ConductoresFacade conductoresFacade;
private Conductores conductores;
private List<Conductores> listaConductores;
private String filtro = "";
@ManagedProperty("#{depositosBean}")
private DepositosBean depositosBean;
public BuscadorConductoresBean() throws IOException {
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public Conductores getConductores() {
return conductores;
}
public void setConductores(Conductores conductores) {
this.conductores = conductores;
}
public List<Conductores> getListaConductores() {
return listaConductores;
}
public void setListaConductores(List<Conductores> listaConductores) {
this.listaConductores = listaConductores;
}
public DepositosBean getDepositosBean() {
return depositosBean;
}
public void setDepositosBean(DepositosBean depositosBean) {
this.depositosBean = depositosBean;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaConductores = new ArrayList<Conductores>();
this.conductores = new Conductores();
listarConductoresBuscador();
}
public void nuevo() {
this.conductores = new Conductores();
}
public void listarConductoresBuscador() {
listaConductores = conductoresFacade.buscarPorFiltro(filtro);
}
public void onRowSelect(SelectEvent event) {
if (this.conductores != null) {
if (this.conductores.getXconductor() != null) {
depositosBean.setConductores(this.conductores);
RequestContext.getCurrentInstance().update("agreDepoPnlCond");
RequestContext.getCurrentInstance().update("editDepoPnlCond");
RequestContext.getCurrentInstance().execute("PF('dlgBusCond').hide();");
}
}
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiTotRetenBean.java
package bean.listados;
import dao.EmpleadosFacade;
import dao.ExcelFacade;
import entidad.Empleados;
import entidad.EmpleadosPK;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiTotRetenBean {
private Date desde;
private Date hasta;
@EJB
private ExcelFacade excelFacade;
public LiTotRetenBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.desde = new Date();
this.hasta = new Date();
}
public void ejecutar(String tipo) {
LlamarReportes rep = new LlamarReportes();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
if (tipo.equals("VIST")) {
rep.reporteTotReten(dateToString(desde), dateToString(hasta), dateToString2(desde), dateToString2(hasta), "admin", tipo);
} else {
List<Object[]> lista = new ArrayList<Object[]>();
String[] columnas = new String[7];
columnas[0] = "nrecibo";
columnas[1] = "cod_cliente";
columnas[2] = "xnombre";
columnas[3] = "irecibo";
columnas[4] = "frecibo";
columnas[5] = "iretencion";
columnas[6] = "mtipo";
String sql = "SELECT r.nrecibo, r.cod_cliente, c.xnombre, r.irecibo, r.frecibo, r.iretencion, 'V' as mtipo\n"
+ " FROM recibos r, clientes c\n"
+ " WHERE r.cod_empr = 2\n"
+ " AND r.cod_cliente = c.cod_cliente\n"
+ " AND r.iretencion > 0\n"
+ " AND r.mestado = 'A'\n"
+ " AND r.frecibo BETWEEN '" + fdesde + "' AND '" + fhasta + "'\n"
+ " UNION ALL\n"
+ "SELECT r2.nrecibo, r2.cod_proveed as cod_cliente, p.xnombre, r2.irecibo, r2.frecibo, r2.iretencion, 'C' as mtipo\n"
+ " FROM recibos_prov r2, proveedores p\n"
+ " WHERE r2.cod_empr = 2\n"
+ " AND r2.cod_proveed = p.cod_proveed\n"
+ " AND r2.iretencion > 0\n"
+ " AND r2.frecibo BETWEEN '" + fdesde + "' AND '" + fhasta + "'\n"
+ " AND r2.mestado = 'A'\n"
+ "ORDER BY 7, 1";
lista = excelFacade.listarParaExcel(sql);
rep.exportarExcel(columnas, lista, "litotreten");
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
//Getters & Setters
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
}
<file_sep>/SisVenLog-war/src/java/bean/ToleranciaBean.java
package bean;
import dao.DepositosFacade;
import dao.MercaTolerarFacade;
import dao.MercaderiasFacade;
import dao.ProveedoresFacade;
import entidad.Depositos;
import entidad.MercaTolerar;
import entidad.Mercaderias;
import entidad.Proveedores;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class ToleranciaBean implements Serializable {
@EJB
private ProveedoresFacade proveedoresFacade;
private Proveedores proveedores = new Proveedores();
private List<Proveedores> listaProveedores = new ArrayList<Proveedores>();
private MercaderiasFacade mercaderiasFacade;
private Mercaderias mercaderias = new Mercaderias();
private List<Mercaderias> listaMercaderias = new ArrayList<Mercaderias>();
private DepositosFacade depositosFacade;
private Depositos depositos = new Depositos();
private List<Depositos> listaDepositos = new ArrayList<Depositos>();
private MercaTolerarFacade mercaTolerarFacade;
private MercaTolerar mercaTolerar = new MercaTolerar();
private List<MercaTolerar> listaMercaTolerar = new ArrayList<MercaTolerar>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public ToleranciaBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public Proveedores getProveedores() {
return proveedores;
}
public void setProveedores(Proveedores proveedores) {
this.proveedores = proveedores;
}
public List<Proveedores> getListaProveedores() {
return listaProveedores;
}
public void setListaProveedores(List<Proveedores> listaProveedores) {
this.listaProveedores = listaProveedores;
}
public MercaderiasFacade getMercaderiasFacade() {
return mercaderiasFacade;
}
public void setMercaderiasFacade(MercaderiasFacade mercaderiasFacade) {
this.mercaderiasFacade = mercaderiasFacade;
}
public Mercaderias getMercaderias() {
return mercaderias;
}
public void setMercaderias(Mercaderias mercaderias) {
this.mercaderias = mercaderias;
}
public List<Mercaderias> getListaMercaderias() {
return listaMercaderias;
}
public void setListaMercaderias(List<Mercaderias> listaMercaderias) {
this.listaMercaderias = listaMercaderias;
}
public ProveedoresFacade getProveedoresFacade() {
return proveedoresFacade;
}
public void setProveedoresFacade(ProveedoresFacade proveedoresFacade) {
this.proveedoresFacade = proveedoresFacade;
}
public DepositosFacade getDepositosFacade() {
return depositosFacade;
}
public void setDepositosFacade(DepositosFacade depositosFacade) {
this.depositosFacade = depositosFacade;
}
public Depositos getDepositos() {
return depositos;
}
public void setDepositos(Depositos depositos) {
this.depositos = depositos;
}
public List<Depositos> getListaDepositos() {
return listaDepositos;
}
public void setListaDepositos(List<Depositos> listaDepositos) {
this.listaDepositos = listaDepositos;
}
public MercaTolerarFacade getMercaTolerarFacade() {
return mercaTolerarFacade;
}
public void setMercaTolerarFacade(MercaTolerarFacade mercaTolerarFacade) {
this.mercaTolerarFacade = mercaTolerarFacade;
}
public MercaTolerar getMercaTolerar() {
return mercaTolerar;
}
public void setMercaTolerar(MercaTolerar mercaTolerar) {
this.mercaTolerar = mercaTolerar;
}
public List<MercaTolerar> getListaMercaTolerar() {
return listaMercaTolerar;
}
public void setListaMercaTolerar(List<MercaTolerar> listaMercaTolerar) {
this.listaMercaTolerar = listaMercaTolerar;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaProveedores = new ArrayList<Proveedores>();
this.proveedores = new Proveedores();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
listar();
//RequestContext.getCurrentInstance().update("formPersonas");
}
public void nuevo() {
this.proveedores = new Proveedores();
listaProveedores = new ArrayList<Proveedores>();
}
public List<Proveedores> listar() {
listaProveedores = proveedoresFacade.findAll();
return listaProveedores;
}
/*public Boolean validarDeposito() {
boolean valido = true;
try {
List<Proveedores> aux = new ArrayList<Proveedores>();
if ("".equals(this.proveedores.getXdesc())) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
} else {
// aux = proveedoresFacade.buscarPorDescripcion(proveedores.getXdesc());
/*if (aux.size() > 0) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Ya existe."));
}
}
} catch (Exception e) {
valido = false;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al validar los datos."));
}
return valido;
}
*/
public void insertar() {
try {
proveedores.setXnombre(proveedores.getXnombre().toUpperCase());
proveedores.setFalta(new Date());
proveedores.setCusuario("admin");
proveedoresFacade.insertarProveedores(proveedores);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevProv').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editar() {
try {
if ("".equals(this.proveedores.getXnombre())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
proveedores.setXnombre(proveedores.getXnombre().toUpperCase());
proveedoresFacade.edit(proveedores);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditProv').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void borrar() {
try {
proveedoresFacade.remove(proveedores);
this.proveedores = new Proveedores();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacProv').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
if ("" != this.proveedores.getXnombre()) {
this.setHabBtnEdit(false);
} else {
this.setHabBtnEdit(true);
}
}
public void verificarCargaDatos() {
boolean cargado = false;
if (proveedores != null) {
if (proveedores.getXnombre()!= null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarProv').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevProv').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarProv').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevProv').hide();");
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/EnviosPK.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
/**
*
* @author admin
*/
@Embeddable
public class EnviosPK implements Serializable {
@Basic(optional = false)
@NotNull(message="Se debe especificar el codigo empresa.")
@Column(name = "cod_empr")
private short codEmpr;
@Basic(optional = false)
@NotNull(message="Se debe especificar el nro de envio.")
@Column(name = "nro_envio")
private long nroEnvio;
public EnviosPK() {
}
public EnviosPK(short codEmpr, long nroEnvio) {
this.codEmpr = codEmpr;
this.nroEnvio = nroEnvio;
}
public short getCodEmpr() {
return codEmpr;
}
public void setCodEmpr(short codEmpr) {
this.codEmpr = codEmpr;
}
public long getNroEnvio() {
return nroEnvio;
}
public void setNroEnvio(long nroEnvio) {
this.nroEnvio = nroEnvio;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) codEmpr;
hash += (int) nroEnvio;
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof EnviosPK)) {
return false;
}
EnviosPK other = (EnviosPK) object;
if (this.codEmpr != other.codEmpr) {
return false;
}
if (this.nroEnvio != other.nroEnvio) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.EnviosPK[ codEmpr=" + codEmpr + ", nroEnvio=" + nroEnvio + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/NotasVentasFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import dto.NotaVentaDto;
import entidad.NotasVentas;
import entidad.NotasVentasPK;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author admin
*/
@Stateless
public class NotasVentasFacade extends AbstractFacade<NotasVentas> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public NotasVentasFacade() {
super(NotasVentas.class);
}
public List<NotaVentaDto> listadoDeNotasDeVentas( Date fechaInicio,
Date fechaFin,
Character estado,
long nroDocumento,
String tipoDocumento,
Integer codigoCliente){
String sql = "SELECT p.ctipo_docum, p.fdocum, p.nro_nota, p.cconc, p.fac_ctipo_docum, p.nrofact, p.texentas, c.xnombre, p.mestado " +
"FROM notas_ventas p, clientes c " +
"WHERE p.cod_cliente = c.cod_cliente " +
"AND p.cod_empr = 2";
if(fechaInicio != null){
sql += " AND p.fdocum >= ?";
}
if(fechaFin != null){
sql += " AND p.fdocum <= ?";
}
if(estado == 'A'){
sql += " AND p.mestado != 'X'";
}else{
sql += " AND p.mestado = 'X'";
}
if(nroDocumento != 0){
sql += " AND p.nro_nota = ?";
}
if(!tipoDocumento.equals("") || !tipoDocumento.isEmpty()){
sql += " AND p.ctipo_docum = ?";
}
if(codigoCliente != null){
if(codigoCliente > 0){
sql += " AND p.cod_cliente = ?";
}
}
Query q = em.createNativeQuery(sql);
int i = 1;
if(fechaInicio != null){
i++;
q.setParameter(i, fechaInicio);
}
if(fechaFin != null){
i++;
q.setParameter(i, fechaFin);
}
i++;
q.setParameter(i, estado);
if(nroDocumento != 0){
i++;
q.setParameter(i, nroDocumento);
}
if(!tipoDocumento.equals("") || !tipoDocumento.isEmpty()){
i++;
q.setParameter(i, tipoDocumento);
}
if(codigoCliente != null){
if(codigoCliente > 0){
i++;
q.setParameter(i, codigoCliente);
}
}
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
List<NotaVentaDto> listadoNotaVenta = new ArrayList<NotaVentaDto>();
for(Object[] resultado: resultados){
//clave primaria nota de venta
NotasVentasPK notaVentaPk = new NotasVentasPK();
notaVentaPk.setCodEmpr(Short.parseShort("2"));
notaVentaPk.setCtipoDocum(resultado[0].toString());
if(resultado[1] != null){
Timestamp timeStamp_1 = (Timestamp) resultado[1];
java.util.Date dateResult_1 = new Date(timeStamp_1.getTime());
notaVentaPk.setFdocum(dateResult_1);
}else{
notaVentaPk.setFdocum(null);
}
notaVentaPk.setNroNota(Long.parseLong(resultado[2].toString()));
//nota de venta
NotasVentas notaVenta = new NotasVentas();
notaVenta.setNotasVentasPK(notaVentaPk);
notaVenta.getConceptosDocumentos().getConceptosDocumentosPK().setCconc(resultado[3].toString());
notaVenta.setFacCtipoDocum(resultado[4].toString());
notaVenta.setNrofact(resultado[5] == null ? null : Long.parseLong(resultado[5].toString()));
notaVenta.setTexentas(resultado[6] == null ? null : Long.parseLong(resultado[6].toString()));
//nombre cliente
String nombreCliente = null;
if(resultado[7] != null){
nombreCliente = resultado[7].toString();
}
notaVenta.setMestado((Character)resultado[8]);
NotaVentaDto nvdto = new NotaVentaDto();
nvdto.setNotaVenta(notaVenta);
nvdto.setNombreCliente(nombreCliente);
listadoNotaVenta.add(nvdto);
}
return listadoNotaVenta;
}
public List<NotasVentas> listadoDeNotasDeVentasPorNroFactura(Long lNroFact){
String sql = "SELECT * " +
"FROM notas_ventas " +
"WHERE cod_empr = 2 " +
"AND nrofact = "+lNroFact +
"AND isaldo > 0";
Query q = em.createQuery(sql, NotasVentas.class);
System.out.println(q.toString());
List<NotasVentas> resultados = q.getResultList();
return resultados;
}
public void disminuirSaldoNotasVentas(long lNroNota, long importeARestar){
String sql = "UPDATE notas_ventas " +
"SET isaldo = isaldo - "+importeARestar+
"WHERE cod_empr = 2 " +
"AND nro_nota = "+lNroNota;
Query q = em.createQuery(sql);
System.out.println(q.toString());
q.executeUpdate();
}
public void aumentarSaldoNotasVentas(long lNroNota, long importeASumar){
String sql = "UPDATE notas_ventas " +
"SET isaldo = isaldo - "+importeASumar+
"WHERE cod_empr = 2 " +
"AND nro_nota = "+lNroNota;
Query q = em.createQuery(sql);
System.out.println(q.toString());
q.executeUpdate();
}
public long obtenerSaldoNotasVentasMayorACero(long lNroNota){
String sql = "SELECT * " +
"FROM notas_ventas " +
"WHERE cod_empr = 2 " +
"AND nro_nota = "+lNroNota+
"AND isaldo > 0";
Query q = em.createNativeQuery(sql, NotasVentas.class);
System.out.println(q.toString());
List<NotasVentas> resultados = q.getResultList();
long saldo = 0;
for(NotasVentas nv: resultados){
saldo = nv.getIsaldo();
}
return saldo;
}
public long obtenerSaldoNotasVentas(long lNroNota){
String sql = "SELECT * " +
"FROM notas_ventas " +
"WHERE cod_empr = 2 " +
"AND nro_nota = "+lNroNota;
Query q = em.createNativeQuery(sql, NotasVentas.class);
System.out.println(q.toString());
List<NotasVentas> resultados = q.getResultList();
long saldo = 0;
for(NotasVentas nv: resultados){
saldo = nv.getIsaldo();
}
return saldo;
}
public List<NotaVentaDto> listadoDeNotasDeVentasPorNroNota(long lNroNota){
String sql = "SELECT cod_cliente, ISNULL(nrofact,0) as nro_factura, fac_ctipo_docum, " +
"fdocum as ffactur, ttotal, isaldo " +
"FROM notas_ventas WHERE cod_empr = 2 " +
"AND mestado = 'A' AND nro_nota = "+lNroNota;
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
List<NotaVentaDto> listadoNotaVenta = new ArrayList<NotaVentaDto>();
for(Object[] resultado: resultados){
NotasVentasPK nvPK = new NotasVentasPK();
NotasVentas nv = new NotasVentas();
nv.setCodCliente(resultado[0] == null ? null : Integer.parseInt(resultado[0].toString()));
nv.setNrofact(resultado[1] == null ? null : Long.parseLong(resultado[1].toString()));
nv.setFacCtipoDocum(resultado[2] == null ? null : resultado[2].toString());
if(resultado[3] != null){
Timestamp timeStamp_3 = (Timestamp) resultado[1];
java.util.Date dateResult_3 = new Date(timeStamp_3.getTime());
nvPK.setFdocum(dateResult_3);
}else{
nvPK.setFdocum(null);
}
nv.setTtotal(resultado[4] == null ? 0 : Long.parseLong(resultado[4].toString()));
nv.setIsaldo(resultado[5] == null ? 0 : Long.parseLong(resultado[5].toString()));
NotaVentaDto nvdto = new NotaVentaDto();
nvdto.setNotaVenta(nv);
listadoNotaVenta.add(nvdto);
}
return listadoNotaVenta;
}
public List<NotaVentaDto> listadoDeNotasDeVentasPorFechaNroNota(String lFDocum, long lNroNota){
String sql = "SELECT cod_cliente, ISNULL(nrofact,0) as nro_factura, fac_ctipo_docum, " +
"fdocum as ffactur, ttotal, isaldo " +
"FROM notas_ventas WHERE cod_empr = 2 " +
"AND fdocum = '"+lFDocum+"' "+
"AND mestado = 'A' AND nro_nota = "+lNroNota;
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
List<NotaVentaDto> listadoNotaVenta = new ArrayList<NotaVentaDto>();
for(Object[] resultado: resultados){
NotasVentasPK nvPK = new NotasVentasPK();
NotasVentas nv = new NotasVentas();
nv.setCodCliente(resultado[0] == null ? null : Integer.parseInt(resultado[0].toString()));
nv.setNrofact(resultado[1] == null ? null : Long.parseLong(resultado[1].toString()));
nv.setFacCtipoDocum(resultado[2] == null ? null : resultado[2].toString());
if(resultado[3] != null){
Timestamp timeStamp_3 = (Timestamp) resultado[3];
java.util.Date dateResult_3 = new Date(timeStamp_3.getTime());
nvPK.setFdocum(dateResult_3);
}else{
nvPK.setFdocum(null);
}
nv.setNotasVentasPK(nvPK);
nv.setTtotal(resultado[4] == null ? 0 : Long.parseLong(resultado[4].toString()));
nv.setIsaldo(resultado[5] == null ? 0 : Long.parseLong(resultado[5].toString()));
NotaVentaDto nvdto = new NotaVentaDto();
nvdto.setNotaVenta(nv);
listadoNotaVenta.add(nvdto);
}
return listadoNotaVenta;
}
public List<NotaVentaDto> listadoDeNotasDeVentasConMaximaFechaPorNroNota(long lNroNota){
String sql = "SELECT cod_cliente, ISNULL(nrofact,0) as nro_factura, fac_ctipo_docum, " +
"fdocum as ffactur, ttotal, isaldo " +
"FROM notas_ventas WHERE cod_empr = 2 " +
"AND mestado = 'A' AND nro_nota = "+lNroNota+" "+
"AND fdocum = (SELECT MAX(fdocum) FROM notas_ventas " +
"WHERE cod_empr = 2 "+
"AND mestado = 'A' "+
"AND nro_nota = "+lNroNota+")";
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
List<NotaVentaDto> listadoNotaVenta = new ArrayList<NotaVentaDto>();
for(Object[] resultado: resultados){
NotasVentasPK nvPK = new NotasVentasPK();
NotasVentas nv = new NotasVentas();
nv.setCodCliente(resultado[0] == null ? null : Integer.parseInt(resultado[0].toString()));
nv.setNrofact(resultado[1] == null ? null : Long.parseLong(resultado[1].toString()));
nv.setFacCtipoDocum(resultado[2] == null ? null : resultado[2].toString());
if(resultado[3] != null){
Timestamp timeStamp_3 = (Timestamp) resultado[3];
java.util.Date dateResult_3 = new Date(timeStamp_3.getTime());
nvPK.setFdocum(dateResult_3);
}else{
nvPK.setFdocum(null);
}
nv.setNotasVentasPK(nvPK);
nv.setTtotal(resultado[4] == null ? 0 : Long.parseLong(resultado[4].toString()));
nv.setIsaldo(resultado[5] == null ? 0 : Long.parseLong(resultado[5].toString()));
NotaVentaDto nvdto = new NotaVentaDto();
nvdto.setNotaVenta(nv);
listadoNotaVenta.add(nvdto);
}
return listadoNotaVenta;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/EnviosFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import dto.EnvioDto;
import entidad.Envios;
import entidad.EnviosPK;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
/**
*
* @author admin
*/
@Stateless
public class EnviosFacade extends AbstractFacade<Envios> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public EnviosFacade() {
super(Envios.class);
}
public void insertarEnvios(Envios envios) {
em.persist(envios);
}
public BigDecimal getMaxNroEnvio() {
Query q = getEntityManager().createNativeQuery("select MAX(nro_envio)+1 as maximo\n"
+ "from envios");
System.out.println(q.toString());
BigDecimal respuesta = (BigDecimal) q.getSingleResult();
return respuesta;
}
public void insertarEnvios2(Envios envios) {
StoredProcedureQuery q = getEntityManager().createStoredProcedureQuery("InsertarEnvios");
q.registerStoredProcedureParameter("cod_entregador", Short.class, ParameterMode.IN);
q.registerStoredProcedureParameter("nro_envio", Long.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cod_canal", Character.class, ParameterMode.IN);
q.registerStoredProcedureParameter("depo_origen", Short.class, ParameterMode.IN);
q.registerStoredProcedureParameter("depo_destino", Short.class, ParameterMode.IN);
q.registerStoredProcedureParameter("fenvio", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("fanul", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("tot_peso", Double.class, ParameterMode.IN);
q.registerStoredProcedureParameter("ffactur", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("mestado", Character.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xobs", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("mtipo", Character.class, ParameterMode.IN);
q.registerStoredProcedureParameter("falta", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cusuario", String.class, ParameterMode.IN);
q.setParameter("cod_entregador", envios.getCodEntregador());
q.setParameter("nro_envio", envios.getEnviosPK().getNroEnvio());
q.setParameter("cod_canal", envios.getCodCanal());
q.setParameter("depo_origen", envios.getDepoOrigen());
q.setParameter("depo_destino", envios.getDepoDestino());
q.setParameter("fenvio", envios.getFenvio());
q.setParameter("fanul", envios.getFanul());
q.setParameter("tot_peso", envios.getTotPeso());
q.setParameter("ffactur", envios.getFfactur());
q.setParameter("mestado", envios.getMestado());
q.setParameter("xobs", envios.getXobs());
q.setParameter("mtipo", envios.getMtipo());
q.setParameter("falta", envios.getFalta());
q.setParameter("cusuario", envios.getCusuario());
q.execute();
}
public List<EnvioDto> listadoDeEnviosPorNroPedido(long nroPedido) {
String sql = "SELECT e.nro_envio, e.cod_entregador, e.cod_canal, e.depo_origen, e.depo_destino, e.fenvio, e.fanul, e.ffactur, e.tot_peso, "
+ "e.mtipo, v.xdesc as xcanal, m.xnombre, o.xdesc as xorigen, d.xdesc as xdestino "
+ "FROM pedidos_envios p, envios e, canales_venta v, empleados m, depositos d, depositos o "
+ "WHERE p.cod_empr = 2 "
+ "AND p.cod_empr = e.cod_empr "
+ "AND e.cod_empr = m.cod_empr "
+ "AND p.nro_envio = e.nro_envio "
+ "AND e.cod_entregador = m.cod_empleado "
+ "AND e.depo_origen = o.cod_depo "
+ "AND e.cod_empr = o.cod_empr "
+ "AND e.cod_canal = v.cod_canal "
+ "AND e.cod_empr = d.cod_empr "
+ "AND e.depo_destino = d.cod_depo";
if (nroPedido != 0) {
sql += " AND e.nro_pedido = ?";
}
Query q = em.createNativeQuery(sql);
int i = 1;
if (nroPedido != 0) {
i++;
q.setParameter(i, nroPedido);
}
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
List<EnvioDto> listadoEnvios = new ArrayList<EnvioDto>();
for (Object[] resultado : resultados) {
//clave primaria de envios
EnviosPK enviosPk = new EnviosPK();
enviosPk.setCodEmpr(Short.parseShort("2"));
enviosPk.setNroEnvio(Long.parseLong(resultado[0].toString()));
//envios
Envios e = new Envios();
e.setEnviosPK(enviosPk);
e.setCodEntregador(resultado[1] == null ? null : Short.parseShort(resultado[1].toString()));
e.setCodCanal(resultado[2].toString());
e.setDepoOrigen(Short.parseShort(resultado[3].toString()));
e.setDepoDestino(Short.parseShort(resultado[4].toString()));
if (resultado[5] != null) {
Timestamp timeStamp_5 = (Timestamp) resultado[5];
java.util.Date dateResult_5 = new Date(timeStamp_5.getTime());
e.setFenvio(dateResult_5);
} else {
e.setFenvio(null);
}
if (resultado[6] != null) {
Timestamp timeStamp_6 = (Timestamp) resultado[6];
java.util.Date dateResult_6 = new Date(timeStamp_6.getTime());
e.setFanul(dateResult_6);
} else {
e.setFanul(null);
}
if (resultado[7] != null) {
Timestamp timeStamp_7 = (Timestamp) resultado[7];
java.util.Date dateResult_7 = new Date(timeStamp_7.getTime());
e.setFfactur(dateResult_7);
} else {
e.setFfactur(null);
}
e.setTotPeso(resultado[8] == null ? null : BigDecimal.valueOf(Long.parseLong(resultado[8].toString())));
e.setMtipo((Character) resultado[9]);
//nombre canal
String nombreCanal = null;
if (resultado[10] != null) {
nombreCanal = resultado[10].toString();
}
//nombre empleado
String nombreEmpleado = null;
if (resultado[11] != null) {
nombreEmpleado = resultado[11].toString();
}
//deposito origen
String depositoOrigen = null;
if (resultado[12] != null) {
depositoOrigen = resultado[12].toString();
}
//deposito destino
String depositoDestino = null;
if (resultado[13] != null) {
depositoDestino = resultado[13].toString();
}
EnvioDto edto = new EnvioDto();
edto.setEnvio(e);
edto.setDescripcionCanal(nombreCanal);
edto.setNombreEmpleado(nombreEmpleado);
edto.setDepositoOrigen(depositoOrigen);
edto.setDepositoDestino(depositoDestino);
listadoEnvios.add(edto);
}
return listadoEnvios;
}
public List<Envios> buscarEnviosPorNroEnvioFecha(String nroEnvio, int[] range) {
try {
Query q = getEntityManager().createNativeQuery("select *from envios where nro_envio = " + nroEnvio + "\n",
Envios.class);
q.setMaxResults(range[1]);
q.setFirstResult(range[0]);
System.out.println(q.toString());
List<Envios> respuesta = q.getResultList();
return respuesta;
} catch (Exception e) {
return null;
}
}
public int CountBuscarEnviosPorNroEnvioFecha(String nroEnvio) {
try {
Query q = getEntityManager().createNativeQuery("select *from envios where nro_envio = " + nroEnvio + "\n",
Envios.class);
System.out.println(q.toString());
int respuesta = q.getResultList().size();
return respuesta;
} catch (Exception e) {
return 0;
}
}
public List<Envios> findRangeSort(int[] range) {
Query q = getEntityManager().createNativeQuery("select *from envios order by nro_envio desc ",
Envios.class);
q.setMaxResults(range[1]);
q.setFirstResult(range[0]);
return q.getResultList();
}
public Integer buscarFacturasActivas(Long nroEnvio) {
/*Select count(*) as krows "+;
" FROM pedidos_envios p, facturas f "+;
" WHERE p.nro_envio = ?l_nro_envio "+;
" AND p.nro_pedido = f.nro_pedido "+;
" AND f.cod_empr = 2 "+;
" AND p.cod_empr = 2 "+;
" AND f.mestado = 'A' "*/
try {
Query q = getEntityManager().createNativeQuery("select count(*) as krows\n"
+ "FROM pedidos_envios p, facturas f\n"
+ "WHERE p.nro_pedido = f.nro_pedido\n"
+ "AND f.cod_empr = 2\n"
+ "AND p.cod_empr = 2\n"
+ "AND f.mestado = 'A'\n"
+ "AND p.nro_envio = " + nroEnvio + "\n");
System.out.println(q.toString());
Integer respuesta = (Integer) q.getSingleResult();
return respuesta;
} catch (Exception e) {
return -1;
}
}
public Integer updatePedidosPorNroEnvio(Long nroEnvio) {
/*UPDATE pedidos SET mestado = 'N' "+;
" WHERE cod_empr = 2 "+;
" AND nro_pedido IN (SELECT DISTINCT nro_pedido "+;
" FROM pedidos_envios "+;
" WHERE nro_envio = ?l_nro_envio "+;
" AND cod_empr = 2 ) ") */
try {
Query q = getEntityManager().createNativeQuery("UPDATE pedidos SET mestado = 'N'\n"
+ "WHERE cod_empr = 2\n"
+ "AND nro_pedido IN (SELECT DISTINCT nro_pedido FROM pedidos_envios\n"
+ "WHERE cod_empr = 2 AND nro_envio = " + nroEnvio + ")\n");
System.out.println(q.toString());
Integer respuesta = q.executeUpdate();
return respuesta;
} catch (Exception e) {
return -1;
}
}
}
<file_sep>/SisVenLog-war/src/java/bean/TipoDocumentoBean.java
package bean;
import dao.TiposDocumentosFacade;
import entidad.TiposDocumentos;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class TipoDocumentoBean implements Serializable {
@EJB
private TiposDocumentosFacade tipoDocumentoFacade;
private String filtro = "";
private TiposDocumentos tipoDocumento = new TiposDocumentos();
private List<TiposDocumentos> listaTipoDocumento = new ArrayList<TiposDocumentos>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public TipoDocumentoBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public TiposDocumentos getTipoDocumento() {
return tipoDocumento;
}
public void setTipoDocumento(TiposDocumentos tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
public List<TiposDocumentos> getListaTipoDocumento() {
return listaTipoDocumento;
}
public void setListaTipoDocumento(List<TiposDocumentos> listaTipoDocumento) {
this.listaTipoDocumento = listaTipoDocumento;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaTipoDocumento = new ArrayList<TiposDocumentos>();
this.tipoDocumento = new TiposDocumentos();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
this.filtro = "";
tipoDocumento.setMdebCred('D');
tipoDocumento.setMafectaCtacte('N');
tipoDocumento.setMincluIva('N');
tipoDocumento.setMfijoSis('N');
tipoDocumento.setMafectaStockRes('S');
listar();
RequestContext.getCurrentInstance().update("formTipoDocumento");
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public void nuevo() {
this.tipoDocumento = new TiposDocumentos();
}
public List<TiposDocumentos> listar() {
listaTipoDocumento = tipoDocumentoFacade.findAll();
return listaTipoDocumento;
}
public List<TiposDocumentos> listarTiposDocumentosLiNotasComp2() {
listaTipoDocumento = tipoDocumentoFacade.listarTipoDocumentoListadoNotaCompras();
return listaTipoDocumento;
}
public void insertar() {
try {
if (tipoDocumento.getMdebCred()!= null &&
tipoDocumento.getMdebCred().equals("D")) {
tipoDocumento.setMindice(new Float(1));
}else{
tipoDocumento.setMindice(new Float(-1));
}
tipoDocumento.setXdesc(tipoDocumento.getXdesc().toUpperCase());
tipoDocumento.setFalta(new Date());
tipoDocumento.setCusuario("admin");
tipoDocumentoFacade.create(tipoDocumento);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevTipoDocumento').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editar() {
try {
if ("".equals(this.tipoDocumento.getXdesc())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
tipoDocumento.setXdesc(tipoDocumento.getXdesc().toUpperCase());
tipoDocumentoFacade.edit(tipoDocumento);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditTipoDocumento').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void borrar() {
try {
tipoDocumentoFacade.remove(tipoDocumento);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacTipoDocumento').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
if ("" != this.tipoDocumento.getXdesc()) {
this.setHabBtnEdit(false);
} else {
this.setHabBtnEdit(true);
}
}
public String tipoDocumentoDC(Float indice) {
String retorno = "";
Float aux = indice;
if (aux < 0) {
retorno = "CREDITO";
}
if (aux >= 0) {
retorno = "DEBITO";
}
return retorno;
}
public void verificarCargaDatos() {
boolean cargado = false;
if (tipoDocumento != null) {
if (tipoDocumento.getXdesc() != null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarTipoDocumento').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevTipoDocumento').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarTipoDocumento').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevTipoDocumento').hide();");
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/VencimientoMerca.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author admin
*/
@Entity
@Table(name = "vencimiento_merca")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "VencimientoMerca.findAll", query = "SELECT v FROM VencimientoMerca v")
, @NamedQuery(name = "VencimientoMerca.findByCodEmpr", query = "SELECT v FROM VencimientoMerca v WHERE v.vencimientoMercaPK.codEmpr = :codEmpr")
, @NamedQuery(name = "VencimientoMerca.findByCtipoDocum", query = "SELECT v FROM VencimientoMerca v WHERE v.vencimientoMercaPK.ctipoDocum = :ctipoDocum")
, @NamedQuery(name = "VencimientoMerca.findByNrofact", query = "SELECT v FROM VencimientoMerca v WHERE v.vencimientoMercaPK.nrofact = :nrofact")
, @NamedQuery(name = "VencimientoMerca.findByCodProveed", query = "SELECT v FROM VencimientoMerca v WHERE v.vencimientoMercaPK.codProveed = :codProveed")
, @NamedQuery(name = "VencimientoMerca.findByCodMerca", query = "SELECT v FROM VencimientoMerca v WHERE v.vencimientoMercaPK.codMerca = :codMerca")
, @NamedQuery(name = "VencimientoMerca.findByAitem", query = "SELECT v FROM VencimientoMerca v WHERE v.vencimientoMercaPK.aitem = :aitem")
, @NamedQuery(name = "VencimientoMerca.findByCantCajas", query = "SELECT v FROM VencimientoMerca v WHERE v.cantCajas = :cantCajas")
, @NamedQuery(name = "VencimientoMerca.findByCantUnid", query = "SELECT v FROM VencimientoMerca v WHERE v.cantUnid = :cantUnid")
, @NamedQuery(name = "VencimientoMerca.findByFvenc", query = "SELECT v FROM VencimientoMerca v WHERE v.fvenc = :fvenc")
, @NamedQuery(name = "VencimientoMerca.findByFfactur", query = "SELECT v FROM VencimientoMerca v WHERE v.ffactur = :ffactur")})
public class VencimientoMerca implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected VencimientoMercaPK vencimientoMercaPK;
@Basic(optional = false)
@NotNull
@Column(name = "cant_cajas")
private short cantCajas;
@Basic(optional = false)
@NotNull
@Column(name = "cant_unid")
private short cantUnid;
@Basic(optional = false)
@NotNull
@Column(name = "fvenc")
@Temporal(TemporalType.TIMESTAMP)
private Date fvenc;
@Basic(optional = false)
@NotNull
@Column(name = "ffactur")
@Temporal(TemporalType.TIMESTAMP)
private Date ffactur;
public VencimientoMerca() {
}
public VencimientoMerca(VencimientoMercaPK vencimientoMercaPK) {
this.vencimientoMercaPK = vencimientoMercaPK;
}
public VencimientoMerca(VencimientoMercaPK vencimientoMercaPK, short cantCajas, short cantUnid, Date fvenc, Date ffactur) {
this.vencimientoMercaPK = vencimientoMercaPK;
this.cantCajas = cantCajas;
this.cantUnid = cantUnid;
this.fvenc = fvenc;
this.ffactur = ffactur;
}
public VencimientoMerca(short codEmpr, String ctipoDocum, long nrofact, long codProveed, String codMerca, short aitem) {
this.vencimientoMercaPK = new VencimientoMercaPK(codEmpr, ctipoDocum, nrofact, codProveed, codMerca, aitem);
}
public VencimientoMercaPK getVencimientoMercaPK() {
return vencimientoMercaPK;
}
public void setVencimientoMercaPK(VencimientoMercaPK vencimientoMercaPK) {
this.vencimientoMercaPK = vencimientoMercaPK;
}
public short getCantCajas() {
return cantCajas;
}
public void setCantCajas(short cantCajas) {
this.cantCajas = cantCajas;
}
public short getCantUnid() {
return cantUnid;
}
public void setCantUnid(short cantUnid) {
this.cantUnid = cantUnid;
}
public Date getFvenc() {
return fvenc;
}
public void setFvenc(Date fvenc) {
this.fvenc = fvenc;
}
public Date getFfactur() {
return ffactur;
}
public void setFfactur(Date ffactur) {
this.ffactur = ffactur;
}
@Override
public int hashCode() {
int hash = 0;
hash += (vencimientoMercaPK != null ? vencimientoMercaPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof VencimientoMerca)) {
return false;
}
VencimientoMerca other = (VencimientoMerca) object;
if ((this.vencimientoMercaPK == null && other.vencimientoMercaPK != null) || (this.vencimientoMercaPK != null && !this.vencimientoMercaPK.equals(other.vencimientoMercaPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.VencimientoMerca[ vencimientoMercaPK=" + vencimientoMercaPK + " ]";
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiConCliBean.java
package bean.listados;
import dao.EmpleadosFacade;
import dao.ExcelFacade;
import dao.ZonasFacade;
import entidad.Empleados;
import entidad.EmpleadosPK;
import entidad.Zonas;
import entidad.ZonasPK;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import util.LlamarReportes;
/**
*
* @author Nico
*/
@ManagedBean
@SessionScoped
public class LiConCliBean {
private Date desde;
private Date hasta;
private Zonas zonas;
private Empleados vendedor;
@EJB
private ZonasFacade zonasFacade;
@EJB
private EmpleadosFacade vendedoresFacade;
@EJB
private ExcelFacade excelFacade;
private String seleccion,nuevos;
private Boolean nuevo;
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.seleccion = new String();
this.vendedor = new Empleados(new EmpleadosPK());
this.zonas = new Zonas(new ZonasPK());
this.nuevo = false;
this.desde = new Date();
this.hasta = new Date();
}
public void ejecutar(String tipo) {
LlamarReportes rep = new LlamarReportes();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
String extras = "" , extras2 = "";
if (this.zonas != null){
extras += " AND f.cod_zona = '"+this.zonas.getZonasPK().getCodZona()+"' ";
extras2 += " AND f.cod_zona = '"+this.zonas.getZonasPK().getCodZona()+"' ";
}
if (this.vendedor != null){
extras += " AND f.cod_vendedor = "+this.vendedor.getEmpleadosPK().getCodEmpleado()+" ";
}
if ( this.nuevo ) {
String ldesde = fdesde + "00:00:00";
String lhasta = fhasta + "23:59:00";
extras += " AND m.falta between '"+ldesde+"' AND '"+lhasta+"' ";
}
List<Object[]> lista = new ArrayList<Object[]>();
String[] columnas = null;
String sql = "";
switch ( this.seleccion ) {
case "1":
columnas = new String[6];
columnas[0] = "cod_vendedor";
columnas[1] = "xnombre";
columnas[2] = "cod_merca";
columnas[3] = "xdesc";
columnas[4] = "fch_alta";
columnas[5] = "cant_clientes";
sql = "select f.cod_vendedor, e.xnombre,m.cod_merca, m.xdesc," +
"m.falta as fch_alta, count(distinct cod_cliente) as cant_clientes" +
" from facturas f, facturas_det d, empleados e, mercaderias m " +
"where f.ffactur between '"+fdesde+"' AND '"+fhasta+
"' and f.mestado ='A' AND f.ctipo_vta != 'X' " +
"AND f.nrofact = d.nrofact and f.ctipo_docum = d.ctipo_docum " +
"AND f.ffactur = d.ffactur AND f.cod_empr = d.cod_empr " +
"and d.cod_empr = m.cod_empr and f.cod_vendedor = e.cod_empleado " +
"AND f.cod_empr = e.cod_empr and d.cod_merca = m.cod_merca " +
"AND f.cod_empr = 2 AND d.cod_empr = 2 " +
"AND e.cod_empr = 2 AND m.cod_empr = 2 "+
extras +
" group by f.cod_vendedor, e.xnombre, m.cod_merca, m.xdesc, m.falta ";
break;
case "2":
columnas = new String[7];
columnas[0] = "cod_vendedor";
columnas[1] = "xnombre";
columnas[2] = "cod_sublinea";
columnas[3] = "xdesc";
columnas[4] = "ctipo_vta";
columnas[5] = "ctipo_cliente";
columnas[6] = "cant_clientes";
sql = "select f.cod_vendedor, e.xnombre, m.cod_sublinea, s.xdesc," +
"f.ctipo_vta, c.ctipo_cliente, count(distinct c.cod_cliente) as cant_clientes " +
"from facturas f, facturas_det d, empleados e, sublineas s,mercaderias m, clientes c " +
"where f.ffactur between '"+fdesde+"' AND '" +fhasta+
"' AND f.cod_cliente = c.cod_cliente and f.mestado ='A' " +
"and f.ctipo_vta !='X' and m.cod_sublinea = s.cod_sublinea " +
" AND f.nrofact = d.nrofact and f.ctipo_docum = d.ctipo_docum " +
" AND f.ffactur = d.ffactur AND f.cod_empr = d.cod_empr " +
" and d.cod_empr = m.cod_empr and f.cod_vendedor = e.cod_empleado " +
" AND f.cod_empr = e.cod_empr and d.cod_merca = m.cod_merca " +
" AND f.cod_empr = 2 AND d.cod_empr = 2 " +
" AND e.cod_empr = 2 AND m.cod_empr = 2"+
extras +
" group by f.cod_vendedor, e.xnombre, m.cod_sublinea, s.xdesc, f.ctipo_vta, c.ctipo_cliente ";
break;
case "3":
columnas = new String[12];
columnas[0] = "finicial";
columnas[1] = "ffinal";
columnas[2] = "cod_zona";
columnas[3] = "cod_vendedor";
columnas[4] = "xnombre";
columnas[5] = "xdes_sublinea";
columnas[6] = "ctipo_vta";
columnas[7] = "ctipo_cliente";
columnas[8] = "itotal";
columnas[9] = "cant_cajas";
columnas[10] = "cant_unid";
columnas[11] = "cant_clientes";
sql = "SELECT cast('"+fdesde+"' as char) as finicial," +
"cast('"+fhasta+"' as char) as ffinal, f.cod_zona, f.cod_vendedor," +
"v.xnombre,d.cod_merca, m.xdesc as xdesc_merca, m.cod_sublinea," +
"s.xdesc AS xdesc_sublinea, f.ctipo_vta, c.ctipo_cliente," +
"SUM(d.itotal) as itotal, SUM(d.cant_cajas) as cant_cajas ," +
"SUM(d.cant_unid) AS cant_unid, COUNT(DISTINCT f.cod_cliente) AS cant_clientes " +
"FROM facturas f INNER JOIN facturas_det d ON f.nrofact = d.nrofact " +
"AND f.ctipo_docum = d.ctipo_docum and F.FFACTUR = D.FFACTUR " +
"INNER JOIN empleados v ON f.cod_vendedor = v.cod_empleado " +
"INNER JOIN mercaderias m ON d.cod_merca = m.cod_merca" +
"INNER JOIN sublineas s ON m.cod_sublinea = s.cod_sublinea" +
"INNER JOIN clientes c ON f.cod_cliente = c.cod_cliente" +
"WHERE f.ctipo_vta !='X' AND F.MESTADO ='A' AND (f.cod_empr = 2) " +
"and f.cod_empr = d.cod_empr AND (f.ffactur BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
extras +
" GROUP BY f.cod_zona, f.cod_vendedor, v.xnombre, d.cod_merca, m.xdesc, m.cod_sublinea, s.xdesc, f.ctipo_vta, c.ctipo_cliente ";
break;
case "4":
columnas = new String[6];
columnas[0] = "finicial";
columnas[1] = "ffinal";
columnas[2] = "cod_vendedor";
columnas[3] = "xnombre";
columnas[4] = "cant_clientes";
columnas[5] = "ttotal";
sql = "SELECT cast('"+fdesde+"' as char) as finicial, cast('"+fhasta+"' as char) as ffinal," +
"f.cod_vendedor, v.xnombre, COUNT(DISTINCT f.cod_cliente) AS cant_clientes," +
"SUM(f.ttotal - f.tnotas) AS ttotal " +
"FROM facturas f " +
"INNER JOIN facturas_det d ON f.nrofact = d.nrofact " +
" AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur " +
" INNER JOIN empleados v ON f.cod_vendedor = v.cod_empleado " +
" INNER JOIN mercaderias m ON d.cod_merca = m.cod_merca " +
" INNER JOIN sublineas s ON m.cod_sublinea = s.cod_sublinea " +
" INNER JOIN clientes c ON f.cod_cliente = c.cod_cliente " +
" where F.CTIPO_VTA !='X' AND F.MESTADO ='A' " +
" AND (f.cod_empr = 2) and f.cod_empr = d.cod_empr " +
" AND (f.ffactur BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
extras +
" GROUP BY f.cod_vendedor, v.xnombre ";
break;
case "5":
columnas = new String[7];
columnas[0] = "cod_vendedor";
columnas[1] = "xnombre";
columnas[2] = "cod_linea";
columnas[3] = "xdesc";
columnas[4] = "ctipo_vta";
columnas[5] = "ctipo_cliente";
columnas[6] = "cant_clientes";
sql = "select f.cod_vendedor, e.xnombre, L.cod_linea, l.xdesc, f.ctipo_vta," +
"c.ctipo_cliente, count(distinct c.cod_cliente) as cant_clientes " +
"from facturas f, facturas_det d, empleados e, sublineas s, mercaderias m, lineas l, clientes c " +
"where f.ffactur between '"+fdesde+"' AND '"+fhasta+
"' and f.mestado ='A' and f.ctipo_vta !='X' " +
"AND f.cod_cliente = c.cod_cliente AND s.cod_linea = l.cod_linea " +
"and m.cod_sublinea = s.cod_sublinea AND f.nrofact = d.nrofact " +
" and f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur " +
" AND f.cod_empr = d.cod_empr and d.cod_empr = m.cod_empr " +
" and f.cod_vendedor = e.cod_empleado AND f.cod_empr = e.cod_empr " +
" and d.cod_merca = m.cod_merca AND f.cod_empr = 2 " +
" AND d.cod_empr = 2 AND e.cod_empr = 2 " +
" AND m.cod_empr = 2 "+
extras +
" group by f.cod_vendedor, e.xnombre, l.cod_linea, l.xdesc, f.ctipo_vta, c.ctipo_cliente ";
break;
case "6":
columnas = new String[5];
columnas[0] = "cod_zona";
columnas[1] = "cod_sublinea";
columnas[2] = "xdesc";
columnas[3] = "cant_clientes";
columnas[4] = "tot_clien";
sql = "SELECT v.*, c.tot_clien " +
" from ( select f.cod_zona, m.cod_sublinea, s.xdesc, count(distinct f.cod_cliente) as cant_clientes " +
" from facturas f, facturas_det d, sublineas s, mercaderias m " +
" where f.ffactur between '"+fdesde+"' AND '"+fhasta+
"' and f.mestado ='A' and f.ctipo_vta !='X' " +
" and m.cod_sublinea = s.cod_sublinea AND f.nrofact = d.nrofact " +
" and f.ctipo_docum = d.ctipo_docum ANd f.ffactur = d.ffactur " +
" AND f.cod_empr = d.cod_empr and d.cod_empr = m.cod_empr " +
" and d.cod_merca = m.cod_merca AND f.cod_empr = 2 " +
" AND d.cod_empr = 2 AND m.cod_empr = 2 " +
extras +
" group by F.COD_ZONA, m.cod_sublinea, s.xdesc ) as v ," +
"( SELECT r.cod_zona,COUNT(*) as tot_clien " +
" FROM clientes c, rutas r " +
" WHERE c.cod_estado = 'A' AND c.cod_ruta = r.cod_ruta " +
extras2+
" GROUP BY r.cod_zona ) as c "+
" WHERE v.cod_zona = c.cod_zona ";
break;
case "7":
columnas = new String[5];
columnas[0] = "cod_zona";
columnas[1] = "cod_sublinea";
columnas[2] = "xdesc";
columnas[3] = "cant_clientes";
columnas[4] = "tot_clien";
sql = "SELECT v.*, c.tot_clien " +
"from ( select f.cod_zona, m.cod_sublinea, s.xdesc, c.ctipo_cliente as tipo_neg, count(distinctc.cod_cliente) as cant_clientes " +
"from facturas f, facturas_det d, sublineas s, mercaderias m,clientes c " +
"where f.ffactur between '"+fdesde+"' AND '"+fhasta+
"' AND f.cod_cliente = c.cod_cliente and f.mestado ='A' " +
" and f.ctipo_vta !='X' and m.cod_sublinea = s.cod_subline " +
" AND f.nrofact = d.nrofact and f.ctipo_docum = d.ctipo_docum " +
" AND f.ffactur = d.ffactur AND f.cod_empr = d.cod_empr " +
" and d.cod_empr = m.cod_empr and d.cod_merca = m.cod_merca " +
" AND f.cod_empr = 2 AND d.cod_empr = 2 AND m.cod_empr = 2 " +
extras +
" group by F.COD_ZONA,m.cod_sublinea, s.xdesc, c.ctipo_cliente ) as v , " +
" ( SELECT r.cod_zona, c.ctipo_cliente, COUNT(*) as tot_clien " +
" FROM clientes c, rutas r " +
" WHERE c.cod_estado = 'A' AND c.cod_ruta = r.cod_ruta " +
extras2+
" GROUP BY r.cod_zona, c.ctipo_cliente ) as c " +
" WHERE v.cod_zona = c.cod_zona " +
" AND v.tipo_neg = c.ctipo_cliente ";
break;
case "8":
columnas = new String[8];
columnas[0] = "finicial";
columnas[1] = "ffinal";
columnas[2] = "cod_vendedor";
columnas[3] = "cod_sublinea";
columnas[4] = "xdesc";
columnas[5] = "xnombre";
columnas[6] = "cant_clientes";
columnas[7] = "ttotal";
sql = "SELECT cast('"+fdesde+"' as char) as finicial, cast('"+fhasta+"' as char) as ffinal, f.cod_vendedor, s.cod_sublinea," +
"s.xdesc, v.xnombre, COUNT(DISTINCT f.cod_cliente) AS cant_clientes, SUM(f.ttotal - f.tnotas) AS ttotal " +
"FROM facturas f INNER JOIN facturas_det d ON f.nrofact = d.nrofact AND f.ctipo_docum = d.ctipo_docum AND f.ffactur = d.ffactur " +
" INNER JOIN empleados v ON f.cod_vendedor = v.cod_empleado " +
" INNER JOIN mercaderias m ON d.cod_merca = m.cod_merca " +
" INNER JOIN sublineas s ON m.cod_sublinea = s.cod_sublinea " +
" INNER JOIN clientes c ON f.cod_cliente = c.cod_cliente " +
" WHERE F.CTIPO_VTA != 'X' AND F.MESTADO ='A' AND (f.cod_empr = 2) " +
" and f.cod_empr = d.cod_empr AND (f.ffactur BETWEEN '"+fdesde+"' AND '"+fhasta+"') "+
extras +
" GROUP BY f.cod_vendedor, v.xnombre, s.cod_sublinea, s.xdesc ";
break;
}
lista = excelFacade.listarParaExcel(sql);
rep.exportarExcel(columnas, lista, "KCLIDOS");
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
public List<Zonas> getListZonas(){
return zonasFacade.findAll();
}
public List<Empleados> getListVendedores(){
return vendedoresFacade.getEmpleadosVendedoresActivosPorCodEmp(2);
}
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
public Zonas getZonas() {
return zonas;
}
public void setZonas(Zonas zonas) {
this.zonas = zonas;
}
public Empleados getVendedor() {
return vendedor;
}
public void setVendedor(Empleados vendedor) {
this.vendedor = vendedor;
}
public String getSeleccion() {
return seleccion;
}
public void setSeleccion(String seleccion) {
this.seleccion = seleccion;
}
public String getNuevos() {
return nuevos;
}
public void setNuevos(String nuevos) {
this.nuevos = nuevos;
}
public Boolean getNuevo() {
return nuevo;
}
public void setNuevo(Boolean nuevo) {
this.nuevo = nuevo;
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/ChequeDetalleDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import entidad.Cheques;
import java.util.Date;
/**
*
* @author dadob
*/
public class ChequeDetalleDto {
private String tipoDocumento;
private String nroCheque;
private String nombreBanco;
private Date fechaVencimiento;
private long importePagado;
private Date fechaEmision;
private Cheques cheque;
public String getTipoDocumento() {
return tipoDocumento;
}
public void setTipoDocumento(String tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
public String getNroCheque() {
return nroCheque;
}
public void setNroCheque(String nroCheque) {
this.nroCheque = nroCheque;
}
public Date getFechaVencimiento() {
return fechaVencimiento;
}
public void setFechaVencimiento(Date fechaVencimiento) {
this.fechaVencimiento = fechaVencimiento;
}
public long getImportePagado() {
return importePagado;
}
public void setImportePagado(long importePagado) {
this.importePagado = importePagado;
}
public Date getFechaEmision() {
return fechaEmision;
}
public void setFechaEmision(Date fechaEmision) {
this.fechaEmision = fechaEmision;
}
public String getNombreBanco() {
return nombreBanco;
}
public void setNombreBanco(String nombreBanco) {
this.nombreBanco = nombreBanco;
}
public Cheques getCheque() {
return cheque;
}
public void setCheque(Cheques cheque) {
this.cheque = cheque;
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/PlanillaCobradores.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author admin
*/
@Entity
@Table(name = "planilla_cobradores")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "PlanillaCobradores.findAll", query = "SELECT p FROM PlanillaCobradores p")
, @NamedQuery(name = "PlanillaCobradores.findByCodEmpr", query = "SELECT p FROM PlanillaCobradores p WHERE p.planillaCobradoresPK.codEmpr = :codEmpr")
, @NamedQuery(name = "PlanillaCobradores.findByNplanilla", query = "SELECT p FROM PlanillaCobradores p WHERE p.planillaCobradoresPK.nplanilla = :nplanilla")
, @NamedQuery(name = "PlanillaCobradores.findByCodEmpleado", query = "SELECT p FROM PlanillaCobradores p WHERE p.codEmpleado = :codEmpleado")
, @NamedQuery(name = "PlanillaCobradores.findByFdocum", query = "SELECT p FROM PlanillaCobradores p WHERE p.fdocum = :fdocum")
, @NamedQuery(name = "PlanillaCobradores.findByTtotal", query = "SELECT p FROM PlanillaCobradores p WHERE p.ttotal = :ttotal")
, @NamedQuery(name = "PlanillaCobradores.findByFalta", query = "SELECT p FROM PlanillaCobradores p WHERE p.falta = :falta")
, @NamedQuery(name = "PlanillaCobradores.findByCusuario", query = "SELECT p FROM PlanillaCobradores p WHERE p.cusuario = :cusuario")
, @NamedQuery(name = "PlanillaCobradores.findByMestado", query = "SELECT p FROM PlanillaCobradores p WHERE p.mestado = :mestado")})
public class PlanillaCobradores implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected PlanillaCobradoresPK planillaCobradoresPK;
@Column(name = "cod_empleado")
private Short codEmpleado;
@Column(name = "fdocum")
@Temporal(TemporalType.TIMESTAMP)
private Date fdocum;
@Basic(optional = false)
@NotNull
@Column(name = "ttotal")
private long ttotal;
@Column(name = "falta")
@Temporal(TemporalType.TIMESTAMP)
private Date falta;
@Size(max = 30)
@Column(name = "cusuario")
private String cusuario;
@Basic(optional = false)
@NotNull
@Column(name = "mestado")
private Character mestado;
@JoinColumn(name = "cod_empr", referencedColumnName = "cod_empr", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Empresas empresas;
@JoinColumn(name = "cod_estado", referencedColumnName = "cod_estado")
@ManyToOne
private EstadosCobranzas codEstado;
/*@OneToMany(cascade = CascadeType.ALL, mappedBy = "planillaCobradores")
private Collection<MovimientosCobradores> movimientosCobradoresCollection;*/
public PlanillaCobradores() {
}
public PlanillaCobradores(PlanillaCobradoresPK planillaCobradoresPK) {
this.planillaCobradoresPK = planillaCobradoresPK;
}
public PlanillaCobradores(PlanillaCobradoresPK planillaCobradoresPK, long ttotal, Character mestado) {
this.planillaCobradoresPK = planillaCobradoresPK;
this.ttotal = ttotal;
this.mestado = mestado;
}
public PlanillaCobradores(short codEmpr, short nplanilla) {
this.planillaCobradoresPK = new PlanillaCobradoresPK(codEmpr, nplanilla);
}
public PlanillaCobradoresPK getPlanillaCobradoresPK() {
return planillaCobradoresPK;
}
public void setPlanillaCobradoresPK(PlanillaCobradoresPK planillaCobradoresPK) {
this.planillaCobradoresPK = planillaCobradoresPK;
}
public Short getCodEmpleado() {
return codEmpleado;
}
public void setCodEmpleado(Short codEmpleado) {
this.codEmpleado = codEmpleado;
}
public Date getFdocum() {
return fdocum;
}
public void setFdocum(Date fdocum) {
this.fdocum = fdocum;
}
public long getTtotal() {
return ttotal;
}
public void setTtotal(long ttotal) {
this.ttotal = ttotal;
}
public Date getFalta() {
return falta;
}
public void setFalta(Date falta) {
this.falta = falta;
}
public String getCusuario() {
return cusuario;
}
public void setCusuario(String cusuario) {
this.cusuario = cusuario;
}
public Character getMestado() {
return mestado;
}
public void setMestado(Character mestado) {
this.mestado = mestado;
}
public Empresas getEmpresas() {
return empresas;
}
public void setEmpresas(Empresas empresas) {
this.empresas = empresas;
}
public EstadosCobranzas getCodEstado() {
return codEstado;
}
public void setCodEstado(EstadosCobranzas codEstado) {
this.codEstado = codEstado;
}
/*@XmlTransient
public Collection<MovimientosCobradores> getMovimientosCobradoresCollection() {
return movimientosCobradoresCollection;
}
public void setMovimientosCobradoresCollection(Collection<MovimientosCobradores> movimientosCobradoresCollection) {
this.movimientosCobradoresCollection = movimientosCobradoresCollection;
}*/
@Override
public int hashCode() {
int hash = 0;
hash += (planillaCobradoresPK != null ? planillaCobradoresPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PlanillaCobradores)) {
return false;
}
PlanillaCobradores other = (PlanillaCobradores) object;
if ((this.planillaCobradoresPK == null && other.planillaCobradoresPK != null) || (this.planillaCobradoresPK != null && !this.planillaCobradoresPK.equals(other.planillaCobradoresPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.PlanillaCobradores[ planillaCobradoresPK=" + planillaCobradoresPK + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/ChequesEmitidosFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import dto.ChequeProveedorDto;
import entidad.ChequesEmitidos;
import entidad.ChequesEmitidosPK;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author Edu
*/
@Stateless
public class ChequesEmitidosFacade extends AbstractFacade<ChequesEmitidos>{
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@EJB
private ProveedoresFacade proveedoresFacade;
@EJB
private BancosFacade bancosFacade;
public ChequesEmitidosFacade() {
super(ChequesEmitidos.class);
}
@Override
protected EntityManager getEntityManager() {
return em;
}
public List<ChequeProveedorDto> listadoChequesNoPagadosProveedores( short codigoEmpresa,
short codigoBanco,
String numeroCheque,
Long montoCheque,
Date fechaInicio,
Date fechaFin,
Short codigoProveedor,
Date fechaCobro){
String sql = " SELECT h.cod_empr, h.cod_banco, h.nro_cheque, h.xcuenta_bco, h.fcheque, h.icheque, h.cod_proveed, h.fcobro, h.femision, h.iretencion, b.xdesc, c.xnombre"+
" FROM cheques_emitidos h, bancos b, proveedores c "+
" WHERE h.cod_empr = ?"+
" AND h.cod_proveed = c.cod_proveed"+
" AND (h.fcobro is null or h.fcobro = '')"+
" AND h.cod_banco = b.cod_banco"+
" AND h.fcheque >= '01/12/2008'";
if(codigoBanco != 0){
sql += " AND h.cod_banco = ?";
}
if(!numeroCheque.equals("") || !numeroCheque.isEmpty()){
sql += " AND h.nro_cheque = ?";
}
if(montoCheque != 0){
sql += " AND h.icheque = ?";
}
if(fechaInicio != null){
sql += " AND h.fcheque >= ?";
}
if(fechaFin != null){
sql += " AND h.fcheque <= ?";
}
if(codigoProveedor != 0){
sql += " AND h.cod_proveed = ?";
}
sql += " ORDER BY h.fcheque, h.cod_banco";
Query q = em.createNativeQuery(sql);
int i = 1;
q.setParameter(i, codigoEmpresa);
if(codigoBanco != 0){
i++;
q.setParameter(i, codigoBanco);
}
if(!numeroCheque.equals("") || !numeroCheque.isEmpty()){
i++;
q.setParameter(i, numeroCheque);
}
if(montoCheque != 0){
i++;
q.setParameter(i, montoCheque);
}
if(fechaInicio != null){
i++;
q.setParameter(i, fechaInicio);
}
if(fechaFin != null){
i++;
q.setParameter(i, fechaFin);
}
if(codigoProveedor != null){
i++;
q.setParameter(i, codigoProveedor);
}
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
List<ChequeProveedorDto> listaChequesProveedores = new ArrayList<ChequeProveedorDto>();
for(Object[] resultado: resultados){
//clave primaria de cheques emitidos
ChequesEmitidosPK chequeEmitidoPK = new ChequesEmitidosPK();
chequeEmitidoPK.setCodEmpr(Short.parseShort(resultado[0].toString()));
chequeEmitidoPK.setCodBanco(Short.parseShort(resultado[1].toString()));
chequeEmitidoPK.setNroCheque(resultado[2].toString());
//cheques emitidos
ChequesEmitidos chequeEmitido = new ChequesEmitidos();
chequeEmitido.setChequesEmitidosPK(chequeEmitidoPK);
chequeEmitido.setXcuentaBco(resultado[3] == null || resultado[3].equals("") ? null: resultado[3].toString());
if(resultado[4] != null){
Timestamp timeStamp_4 = (Timestamp) resultado[4];
java.util.Date dateResult_4 = new Date(timeStamp_4.getTime());
chequeEmitido.setFcheque(dateResult_4);
}else{
chequeEmitido.setFcheque(null);
}
chequeEmitido.setIcheque(resultado[5] == null ? null: Long.parseLong(resultado[5].toString()));
chequeEmitido.setCodProveed(resultado[6] == null ? null : proveedoresFacade.find(Short.parseShort(resultado[6].toString())));
chequeEmitido.setBancos(resultado[1] == null ? null : bancosFacade.find(Short.parseShort(resultado[1].toString())));
chequeEmitido.setFcobro(fechaCobro); //fecha de cobro recibido por parametro desde la vista
if(resultado[8] != null){
Timestamp timeStamp_8 = (Timestamp) resultado[8];
java.util.Date dateResult_8 = new Date(timeStamp_8.getTime());
chequeEmitido.setFemision(dateResult_8);
}else{
chequeEmitido.setFemision(null);
}
chequeEmitido.setIretencion(resultado[9] == null ? null : Long.parseLong(resultado[9].toString()));
//nombre banco
String nombreBanco = null;
if(resultado[10] != null){
nombreBanco = resultado[10].toString();
}
//nombre proveedor
String nombreProveedor = null;
if(resultado[11] != null){
nombreProveedor = resultado[11].toString();
}
ChequeProveedorDto chequeProveedorDto = new ChequeProveedorDto();
chequeProveedorDto.setChequeEmitido(chequeEmitido);
chequeProveedorDto.setNombreBanco(nombreBanco);
chequeProveedorDto.setNombreProveedor(nombreProveedor);
chequeProveedorDto.setChequeEmitidoSeleccionado(false);
listaChequesProveedores.add(chequeProveedorDto);
}
return listaChequesProveedores;
}
public int actualizarChequesEmitidosNoCobrados(ChequesEmitidos chequeEmitido){
String sql = "UPDATE cheques_emitidos SET fcobro = ? WHERE cod_empr = 2 AND nro_cheque = ? AND cod_banco = ?";
Query q = em.createNativeQuery(sql);
q.setParameter(1, chequeEmitido.getFcobro());
q.setParameter(2, chequeEmitido.getChequesEmitidosPK().getNroCheque());
q.setParameter(3, chequeEmitido.getChequesEmitidosPK().getCodBanco());
return q.executeUpdate();
}
public void insertarChequeEmitido( short gCodEmpresa,
short lCodBanco,
String lNroCheque,
String lXCuentaBco,
String lFCheque,
String lFemision,
long lICheque,
Short lCodProveed){
String sql = "INSERT INTO cheques_emitidos (cod_empr, cod_banco, " +
"nro_cheque, xcuenta_bco, fcheque, femision, icheque, cod_proveed) " +
"VALUES ("+gCodEmpresa+", "+lCodBanco+", '"+lNroCheque+"', " +
"'"+lXCuentaBco+"', '"+lFCheque+"', '"+lFemision+"', "+lICheque+", "+lCodProveed+")";
System.out.println(sql);
Query q = getEntityManager().createNativeQuery(sql);
q.executeUpdate();
}
}
<file_sep>/SisVenLog-ejb/src/java/entidad/RecaudacionPK.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entidad;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
/**
*
* @author admin
*/
@Embeddable
public class RecaudacionPK implements Serializable {
@Basic(optional = false)
@NotNull
@Column(name = "cod_empr")
private short codEmpr;
@Basic(optional = false)
@NotNull
@Column(name = "nro_planilla")
private long nroPlanilla;
public RecaudacionPK() {
}
public RecaudacionPK(short codEmpr, long nroPlanilla) {
this.codEmpr = codEmpr;
this.nroPlanilla = nroPlanilla;
}
public short getCodEmpr() {
return codEmpr;
}
public void setCodEmpr(short codEmpr) {
this.codEmpr = codEmpr;
}
public long getNroPlanilla() {
return nroPlanilla;
}
public void setNroPlanilla(long nroPlanilla) {
this.nroPlanilla = nroPlanilla;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) codEmpr;
hash += (int) nroPlanilla;
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof RecaudacionPK)) {
return false;
}
RecaudacionPK other = (RecaudacionPK) object;
if (this.codEmpr != other.codEmpr) {
return false;
}
if (this.nroPlanilla != other.nroPlanilla) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidad.RecaudacionPK[ codEmpr=" + codEmpr + ", nroPlanilla=" + nroPlanilla + " ]";
}
}
<file_sep>/SisVenLog-ejb/src/java/util/StringUtil.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package util;
import java.util.List;
import entidad.Clientes;
/**
*
* @author jvera
*/
public class StringUtil {
public static String convertirListaAString(List<Clientes> lista){
String listaString = "";
if (!lista.isEmpty()) {
for (int i = 0; i < lista.size(); i++) {
if (i == (lista.size()-1)) {
listaString += lista.get(i).getCodCliente();
}else{
listaString += lista.get(i).getCodCliente()+ ", ";
}
}
}
return listaString;
}
}
<file_sep>/SisVenLog-war/src/java/bean/buscadores/BuscadorBean.java
package bean.buscadores;
import bean.CanalesBean;
import dao.BuscadorFacade;
import dto.buscadorDto;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class BuscadorBean {
@EJB
private BuscadorFacade buscadorFacade;
private List<buscadorDto> listaResultado;
private List<String> columnas;
private List<String> filtros;
private buscadorDto Resultado;
private String filtro;
private String titulo;
private String sql;
private String sqlOrderGroup;
private String ventana;
/*@ManagedProperty("#{canalesBean}")*/
private CanalesBean canalesBean = new CanalesBean();
public BuscadorBean() throws IOException {
}
public void instanciar() {
listaResultado = new ArrayList<buscadorDto>();
columnas = new ArrayList<String>();
filtros = new ArrayList<String>();
Resultado = new buscadorDto();
filtro = "";
titulo = "";
sql = "";
sqlOrderGroup = "";
ventana = "";
}
public void buscar() {
try {
StringBuilder sqlFinal = new StringBuilder();
sqlFinal.append(sql + "\n");
sqlFinal.append("and ( \n");
for (int i = 0; i < filtros.size(); i++) {
if (i == 0) {
sqlFinal.append(" upper(" + filtros.get(i) + ") like upper('%"+filtro+"%') \n");
}else{
sqlFinal.append(" or upper(" + filtros.get(i) + ") like upper('%"+filtro+"%') \n");
}
}
sqlFinal.append(" ) \n");
/*String sql = "(UPPER(xnombre) like UPPER('%"+filtro+"%') or xruc like '%"+filtro+"%')";*/
this.listaResultado = buscadorFacade.buscar(sqlFinal.toString());
if (this.listaResultado.size() <= 0) {
FacesContext.getCurrentInstance()
.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Atencion", "Datos no encontrados."));
}else{
return;
}
} catch (Exception e) {
FacesContext.getCurrentInstance()
.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Atencion", "Error durante la busqueda de datos."));
}
}
public void onRowSelect(SelectEvent event) {
if (this.Resultado != null) {
if (this.Resultado.getDato1() != null) {
if (this.ventana.equals("maCanales")) {
canalesBean.setResultadoProveedor(Resultado);
RequestContext.getCurrentInstance().update("agreCanalPnlProv");
}
RequestContext.getCurrentInstance().execute("PF('dlgBuscador').hide();");
}
}
}
//Getters & Setters
public List<buscadorDto> getListaResultado() {
return listaResultado;
}
public void setListaResultado(List<buscadorDto> listaResultado) {
this.listaResultado = listaResultado;
}
public buscadorDto getResultado() {
return Resultado;
}
public void setResultado(buscadorDto Resultado) {
this.Resultado = Resultado;
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public List<String> getColumnas() {
return columnas;
}
public void setColumnas(List<String> columnas) {
this.columnas = columnas;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public List<String> getFiltros() {
return filtros;
}
public void setFiltros(List<String> filtros) {
this.filtros = filtros;
}
public String getSqlOrderGroup() {
return sqlOrderGroup;
}
public void setSqlOrderGroup(String sqlOrderGroup) {
this.sqlOrderGroup = sqlOrderGroup;
}
public String getVentana() {
return ventana;
}
public void setVentana(String ventana) {
this.ventana = ventana;
}
/*public CanalesBean getCanalesBean() {
return canalesBean;
}
public void setCanalesBean(CanalesBean canalesBean) {
this.canalesBean = canalesBean;
}*/
}
<file_sep>/SisVenLog-ejb/src/java/dao/CuentasCorrientesFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import dto.CuentaCorrienteDto;
import entidad.CuentasCorrientes;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
/**
*
* @author Edu
*/
@Stateless
public class CuentasCorrientesFacade extends AbstractFacade<CuentasCorrientes>{
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
public CuentasCorrientesFacade() {
super(CuentasCorrientes.class);
}
@Override
protected EntityManager getEntityManager() {
return em;
}
public void insertarCuentasCorrientes(CuentasCorrientes cuentaCorriente) throws SQLException{
StoredProcedureQuery q = getEntityManager().createStoredProcedureQuery("InsertarCuentasCorrientes");
q.registerStoredProcedureParameter("fmovim", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("ctipo_docum", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cod_banco", Short.class, ParameterMode.IN);
q.registerStoredProcedureParameter("ndocum_cheq", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cod_empr", Short.class, ParameterMode.IN);
q.registerStoredProcedureParameter("nrofact", Long.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cod_cliente", Integer.class, ParameterMode.IN);
q.registerStoredProcedureParameter("fac_ctipo_docum", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("texentas", Long.class, ParameterMode.IN);
q.registerStoredProcedureParameter("ipagado", Long.class, ParameterMode.IN);
q.registerStoredProcedureParameter("iretencion", Long.class, ParameterMode.IN);
q.registerStoredProcedureParameter("isaldo", Long.class, ParameterMode.IN);
q.registerStoredProcedureParameter("falta", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("manulado", Short.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cusuario", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("tgravadas", Long.class, ParameterMode.IN);
q.registerStoredProcedureParameter("timpuestos", Long.class, ParameterMode.IN);
q.registerStoredProcedureParameter("mindice", Short.class, ParameterMode.IN);
q.registerStoredProcedureParameter("fvenc", Date.class, ParameterMode.IN);
q.registerStoredProcedureParameter("xcuenta_bco", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("ffactur", Date.class, ParameterMode.IN);
q.setParameter("fmovim", cuentaCorriente.getFmovim());
q.setParameter("ctipo_docum", cuentaCorriente.getCtipoDocum());
q.setParameter("cod_banco", cuentaCorriente.getCodBanco().getCodBanco());
q.setParameter("ndocum_cheq", cuentaCorriente.getNdocumCheq());
q.setParameter("cod_empr", cuentaCorriente.getCodEmpr());
q.setParameter("nrofact", cuentaCorriente.getNrofact());
q.setParameter("cod_cliente", cuentaCorriente.getCodCliente().getCodCliente());
q.setParameter("fac_ctipo_docum", cuentaCorriente.getFacCtipoDocum());
q.setParameter("texentas", cuentaCorriente.getTexentas());
q.setParameter("ipagado", cuentaCorriente.getIpagado());
q.setParameter("iretencion", cuentaCorriente.getIretencion());
q.setParameter("isaldo", cuentaCorriente.getIsaldo());
q.setParameter("falta", cuentaCorriente.getFalta());
q.setParameter("manulado", cuentaCorriente.getManulado());
q.setParameter("cusuario", cuentaCorriente.getCusuario());
q.setParameter("tgravadas", cuentaCorriente.getTgravadas());
q.setParameter("timpuestos", cuentaCorriente.getTimpuestos());
q.setParameter("mindice", cuentaCorriente.getMindice());
q.setParameter("fvenc", cuentaCorriente.getFvenc());
q.setParameter("xcuenta_bco", cuentaCorriente.getXcuentaBco());
q.setParameter("ffactur", cuentaCorriente.getFfactur());
System.out.println(q.toString());
q.execute();
}
public void insertarCuentas(CuentasCorrientes cuentaCorriente){
String sql = "INSERT INTO cuentas_corrientes(cod_empr, ctipo_docum, fvenc, fmovim, ndocum_cheq, ipagado, iretencion, cod_banco, cod_cliente, isaldo, mindice, manulado, texentas, tgravadas, timpuestos) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
Query q = em.createNativeQuery(sql);
q.setParameter(1, cuentaCorriente.getCodEmpr());
q.setParameter(2, cuentaCorriente.getCtipoDocum());
q.setParameter(3, cuentaCorriente.getFvenc());
q.setParameter(4, cuentaCorriente.getFmovim());
q.setParameter(5, cuentaCorriente.getNdocumCheq());
q.setParameter(6, cuentaCorriente.getIpagado());
q.setParameter(7, cuentaCorriente.getIretencion());
q.setParameter(8, cuentaCorriente.getCodBanco() == null ? null : cuentaCorriente.getCodBanco().getCodBanco());
q.setParameter(9, cuentaCorriente.getCodCliente() == null ? null : cuentaCorriente.getCodCliente().getCodCliente());
q.setParameter(10, cuentaCorriente.getIsaldo());
q.setParameter(11, cuentaCorriente.getMindice());
q.setParameter(12, cuentaCorriente.getManulado());
q.setParameter(13, cuentaCorriente.getTexentas());
q.setParameter(14, cuentaCorriente.getTgravadas());
q.setParameter(15, cuentaCorriente.getTimpuestos());
q.executeUpdate();
}
public List<CuentaCorrienteDto> listadoDeFacturasCuentasCorrientesPorNrofacturaYFecha(Long numeroFactura, Date fechaFactura){
String sql = "SELECT c.ctipo_docum, c.ndocum_cheq, " +
"c.fmovim, (c.texentas * mindice) as texentas, " +
"(c.tgravadas * mindice) as tgravadas, " +
"(c.timpuestos * mindice) as timpuestos, " +
"t.cconc, c.fvenc, c.ipagado " +
"FROM cuentas_corrientes c LEFT JOIN notas_ventas t " +
"ON c.ndocum_cheq = t.nro_nota " +
"AND c.ctipo_docum = t.ctipo_docum " +
"WHERE c.cod_empr = 2";
if(numeroFactura != null){
if(numeroFactura > 0){
sql += " AND c.nrofact = ?";
}
}
if(fechaFactura != null){
sql += " AND c.ffactur = ?";
}
Query q = em.createNativeQuery(sql);
int i = 1;
if(numeroFactura != null){
if(numeroFactura > 0){
i++;
q.setParameter(i, numeroFactura);
}
}
if(fechaFactura != null){
i++;
q.setParameter(i, fechaFactura);
}
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
List<CuentaCorrienteDto> listadoCuentasCorrientes = new ArrayList<CuentaCorrienteDto>();
for(Object[] resultado: resultados){
CuentaCorrienteDto ccdto = new CuentaCorrienteDto();
ccdto.setTipoDocumento(resultado[0] == null ? null : resultado[0].toString());
ccdto.setNumeroDocumentoCheque(resultado[1] == null ? null : resultado[1].toString());
if(resultado[2] != null){
Timestamp timeStamp_2 = (Timestamp) resultado[2];
java.util.Date dateResult_2 = new Date(timeStamp_2.getTime());
ccdto.setFechaMovimiento(dateResult_2);
}else{
ccdto.setFechaMovimiento(null);
}
ccdto.setExentas(Long.parseLong(resultado[3].toString()));
ccdto.setGravadas(Long.parseLong(resultado[4].toString()));
ccdto.setImpuestos(Long.parseLong(resultado[5].toString()));
ccdto.setConcepto(resultado[6] == null ? null : resultado[6].toString());
if(resultado[7] != null){
Timestamp timeStamp_7 = (Timestamp) resultado[7];
java.util.Date dateResult_7 = new Date(timeStamp_7.getTime());
ccdto.setFechaVencimiento(dateResult_7);
}else{
ccdto.setFechaVencimiento(null);
}
ccdto.setImportePagado(Long.parseLong(resultado[8].toString()));
listadoCuentasCorrientes.add(ccdto);
}
return listadoCuentasCorrientes;
}
public long obtenerTotalCtaCtePorClienteEnRangoDeFechas(Integer lCodCliente, String lFMovimDesde, String lFMovimHasta) {
String sql = "SELECT ISNULL(SUM((texentas+tgravadas+timpuestos)*mindice),0) + ISNULL(SUM(ipagado * MINDICE),0) as tmovim "
+ "FROM cuentas_corrientes "
+ "WHERE cod_cliente = "+lCodCliente+" "
+ "AND cod_empr = 2 "
+ "AND (fac_ctipo_docum IS NULL OR fac_ctipo_docum != 'FCO') "
+ "AND fmovim > '" + lFMovimDesde + "' "
+ "AND fmovim < '" + lFMovimHasta + "' ";
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
long total = 0;
for(Object[] resultado: resultados){
total = resultado[0] == null ? Long.parseLong("0") : Long.parseLong(resultado[0].toString());
}
return total;
}
}
<file_sep>/SisVenLog-war/src/java/bean/ZonasBean.java
package bean;
import dao.ZonasFacade;
import entidad.Zonas;
import entidad.ZonasPK;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class ZonasBean implements Serializable {
@EJB
private ZonasFacade zonasFacade;
private String filtro = "";
private Zonas zonas = new Zonas(new ZonasPK());
private List<Zonas> listaZonas = new ArrayList<Zonas>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public ZonasBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public Zonas getZonas() {
return zonas;
}
public void setZonas(Zonas zonas) {
this.zonas = zonas;
}
public List<Zonas> getListaZonas() {
return listaZonas;
}
public void setListaZonas(List<Zonas> listaZonas) {
this.listaZonas = listaZonas;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaZonas = new ArrayList<Zonas>();
this.zonas = new Zonas(new ZonasPK());
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
this.filtro = "";
listar();
//RequestContext.getCurrentInstance().update("formBtnZonas");
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public void nuevo() {
this.zonas = new Zonas(new ZonasPK());
}
public List<Zonas> listar() {
listaZonas = zonasFacade.findAll();
return listaZonas;
}
public void insertar() {
try {
zonas.getZonasPK().setCodEmpr(new Short("1"));
zonas.setXdesc(zonas.getXdesc().toUpperCase());
zonas.setFalta(new Date());
zonas.setCusuario("admin");
zonasFacade.create(zonas);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevZon').hide();");
instanciar();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void editar() {
try {
if ("".equals(this.zonas.getXdesc())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
zonas.setXdesc(zonas.getXdesc().toUpperCase());
zonasFacade.edit(zonas);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditZon').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void borrar() {
try {
zonasFacade.remove(zonas);
this.zonas = new Zonas(new ZonasPK());
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacZon').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", e.getMessage()));
}
}
public void onRowSelect(SelectEvent event) {
if ("" != this.zonas.getXdesc()) {
this.setHabBtnEdit(false);
} else {
this.setHabBtnEdit(true);
}
}
public void verificarCargaDatos() {
boolean cargado = false;
if (zonas != null) {
if (zonas.getXdesc() != null) {
cargado = true;
}
}
if (cargado) {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarZon').show();");
} else {
RequestContext.getCurrentInstance().execute("PF('dlgNuevZon').hide();");
}
}
public void cerrarDialogosAgregar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarZon').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevZon').hide();");
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiVtaRetornoBean.java
package bean.listados;
import dao.ExcelFacade;
import dao.LineasFacade;
import dao.SublineasFacade;
import dto.LiMercaSinDto;
import entidad.Lineas;
import entidad.Mercaderias;
import entidad.MercaderiasPK;
import entidad.Sublineas;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import org.primefaces.model.DualListModel;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiVtaRetornoBean {
@EJB
private LineasFacade lineasFacade;
@EJB
private SublineasFacade sublineasFacade;
@EJB
private ExcelFacade excelFacade;
private Lineas lineas;
private List<Lineas> listaLineas;
private DualListModel<Mercaderias> mercaderias;
private Sublineas sublineas;
private List<Sublineas> listaSublineas;
private Date desde;
private Date hasta;
public LiVtaRetornoBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.lineas = new Lineas();
this.listaLineas = new ArrayList<Lineas>();
this.sublineas = new Sublineas();
this.listaSublineas = new ArrayList<Sublineas>();
this.desde = new Date();
this.hasta = new Date();
}
public void ejecutar(String tipo) {
try {
LlamarReportes rep = new LlamarReportes();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
//String tipoDoc = "";
Short linea = new Short("0");
Short sublinea = new Short("0");
String descLinea = "";
String descSublinea = "";
StringBuilder sql = new StringBuilder();
if (this.lineas == null) {
linea = new Short("0");
descLinea = "TODOS";
} else {
linea = this.lineas.getCodLinea();
descLinea = lineasFacade.find(this.lineas.getCodLinea()).getXdesc();
}
if (this.sublineas == null) {
sublinea = new Short("0");
descSublinea = "TODOS";
} else {
sublinea = this.sublineas.getCodSublinea();
descSublinea = sublineasFacade.find(this.sublineas.getCodSublinea()).getXdesc();
}
sql.append(" SELECT d.cod_merca, m.xdesc as xdesc_merca, s.cod_sublinea, s.xdesc as xdesc_sublinea, m.nrelacion, f.ctipo_vta, \n"
+ " SUM(d.cant_cajas) * -1 as cant_cajas, SUM(d.cant_unid) * -1 as cant_unid, \n"
+ " l.cod_linea, l.xdesc as xdesc_linea , r.idevol_caja, r.idevol_unidad, r.iretorno_caja, r.iretorno_unidad, \n"
+ " r.frige_desde, r.frige_hasta \n"
+ " FROM movimientos_merca d, sublineas s, mercaderias m, lineas l, facturas f, retornos_precios r \n"
+ " WHERE d.cod_empr = 2 \n"
+ " AND s.cod_linea = l.cod_linea \n"
+ " AND d.cod_empr = m.cod_empr \n"
+ " AND d.cod_merca = m.cod_merca \n"
+ " AND d.cod_merca = r.cod_merca \n"
+ " AND f.ctipo_vta = r.ctipo_vta \n"
+ " AND d.fmovim BETWEEN r.frige_desde AND r.frige_hasta \n"
+ " AND m.cod_sublinea = s.cod_sublinea \n"
+ " AND d.fac_ctipo_docum = f.ctipo_docum \n"
+ " AND d.nrofact = f.nrofact \n"
+ " AND f.ffactur >= '01/01/2015' \n"
+ " AND d.ctipo_docum IN ('FCO','FCR','CPV','NCV','NDV') \n"
+ " AND d.fmovim BETWEEN '" + fdesde + "' AND '" + fhasta + "' \n"
+ " AND (m.cod_sublinea = " + sublinea + " or " + sublinea + " = 0) \n"
+ " AND (s.cod_linea = " + linea + " or " + linea + " = 0) \n"
+ " GROUP BY s.cod_sublinea, s.xdesc, d.cod_merca, m.xdesc,M.NRELACION, l.cod_linea, l.xdesc, \n"
+ " f.ctipo_vta, r.idevol_caja, r.idevol_unidad, r.iretorno_caja, r.iretorno_unidad, r.frige_desde, r.frige_hasta \n"
+ " ORDER BY l.cod_linea, s.cod_sublinea, d.cod_merca ");
System.out.println("======> SQL: " + sql.toString());
if (tipo.equals("VIST")) {
rep.reporteLiVtaRetorno(sql.toString(), dateToString2(desde), dateToString2(hasta), descLinea, "admin", descSublinea, tipo);
} else if (tipo.equals("ARCH")) {
List<Object[]> lista = new ArrayList<Object[]>();
String[] columnas = new String[6];
columnas[0] = " ";
columnas[1] = " ";
columnas[2] = " ";
columnas[3] = " ";
columnas[4] = " ";
columnas[5] = " ";
lista = excelFacade.listarParaExcel(sql.toString());
rep.exportarExcel(columnas, lista, "liaplica");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Error", e.getMessage()));
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
//Getters & Setters
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
public Sublineas getSublineas() {
return sublineas;
}
public void setSublineas(Sublineas sublineas) {
this.sublineas = sublineas;
}
public List<Sublineas> getListaSublineas() {
return listaSublineas;
}
public void setListaSublineas(List<Sublineas> listaSublineas) {
this.listaSublineas = listaSublineas;
}
public DualListModel<Mercaderias> getMercaderias() {
return mercaderias;
}
public void setMercaderias(DualListModel<Mercaderias> mercaderias) {
this.mercaderias = mercaderias;
}
public Lineas getLineas() {
return lineas;
}
public void setLineas(Lineas lineas) {
this.lineas = lineas;
}
public List<Lineas> getListaLineas() {
return listaLineas;
}
public void setListaLineas(List<Lineas> listaLineas) {
this.listaLineas = listaLineas;
}
}
<file_sep>/SisVenLog-ejb/src/java/dto/ChequeProveedorDto.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import entidad.ChequesEmitidos;
/**
*
* @author Edu
*/
public class ChequeProveedorDto {
private ChequesEmitidos chequeEmitido;
private String nombreBanco;
private String nombreProveedor;
private boolean chequeEmitidoSeleccionado;
private long importeAPagar;
public ChequeProveedorDto() {
}
public ChequesEmitidos getChequeEmitido() {
return chequeEmitido;
}
public void setChequeEmitido(ChequesEmitidos chequeEmitido) {
this.chequeEmitido = chequeEmitido;
}
public String getNombreBanco() {
return nombreBanco;
}
public void setNombreBanco(String nombreBanco) {
this.nombreBanco = nombreBanco;
}
public String getNombreProveedor() {
return nombreProveedor;
}
public void setNombreProveedor(String nombreProveedor) {
this.nombreProveedor = nombreProveedor;
}
public boolean isChequeEmitidoSeleccionado() {
return chequeEmitidoSeleccionado;
}
public void setChequeEmitidoSeleccionado(boolean chequeEmitidoSeleccionado) {
this.chequeEmitidoSeleccionado = chequeEmitidoSeleccionado;
}
public long getImporteAPagar() {
return importeAPagar;
}
public void setImporteAPagar(long importeAPagar) {
this.importeAPagar = importeAPagar;
}
}
<file_sep>/SisVenLog-war/src/java/Converter/MercaderiasConverter2.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Converter;
import dao.MercaderiasFacade;
import entidad.Mercaderias;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ApplicationScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UISelectItem;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.inject.Inject;
import javax.inject.Named;
/**
*
* @author Norio
*/
@Named(value = "mercaderiasConverter2")
@ApplicationScoped
public class MercaderiasConverter2 implements Converter, Serializable{
@Inject
private MercaderiasFacade ejbFacade;
private static final String SEPARATOR = "#";
private static final String SEPARATOR_ESCAPED = "\\#";
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0 || isDummySelectItem(component, value)) {
return null;
}
return ejbFacade.find(getKey(value));
}
entidad.MercaderiasPK getKey(String value) {
entidad.MercaderiasPK key;
String values[] = value.split(SEPARATOR_ESCAPED);
key = new entidad.MercaderiasPK();
key.setCodEmpr(Short.parseShort(values[0]));
key.setCodMerca(values[1]);
return key;
}
String getStringKey(entidad.MercaderiasPK value) {
StringBuffer sb = new StringBuffer();
sb.append(value.getCodEmpr());
sb.append(SEPARATOR);
sb.append(value.getCodMerca());
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null
|| (object instanceof String && ((String) object).length() == 0)) {
return null;
}
if (object instanceof Mercaderias) {
Mercaderias o = (Mercaderias) object;
return getStringKey(o.getMercaderiasPK());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Mercaderias.class.getName()});
return null;
}
}
public boolean isDummySelectItem(UIComponent component, String value) {
for (UIComponent children : component.getChildren()) {
if (children instanceof UISelectItem) {
UISelectItem item = (UISelectItem) children;
if (item.getItemValue() == null && item.getItemLabel().equals(value)) {
return true;
}
break;
}
}
return false;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/RecibosChequesFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import dto.ChequeDetalleDto;
import entidad.RecibosCheques;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author admin
*/
@Stateless
public class RecibosChequesFacade extends AbstractFacade<RecibosCheques> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public RecibosChequesFacade() {
super(RecibosCheques.class);
}
public List<ChequeDetalleDto> listadoDeRecibosPorNroFacturaYFecha(Long numeroFactura, String fechaFactura){
String sql = "select 'REC' as ctipo_docum, a.nro_cheque, b.fvenc as fvenc, a.ipagado, b.fmovim as fmovim, c.xdesc "+
"from recibos_cheques a, cuentas_corrientes b, bancos c " +
"where b.fac_ctipo_docum = 'FCR' " +
"and b.ffactur = '"+fechaFactura+"' "+
"and b.ctipo_docum = 'REC' " +
"AND b.ndocum_cheq = a.nrecibo "+
"AND a.cod_banco = c.cod_banco";
if(numeroFactura != null){
if(numeroFactura > 0){
sql += " AND b.nrofact = ?";
}
}
Query q = em.createNativeQuery(sql);
int i = 0;
if(numeroFactura != null){
if(numeroFactura > 0){
i++;
q.setParameter(i, numeroFactura);
}
}
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
List<ChequeDetalleDto> listadoCheques = new ArrayList<ChequeDetalleDto>();
for(Object[] resultado: resultados){
ChequeDetalleDto cddto = new ChequeDetalleDto();
cddto.setTipoDocumento(resultado[0].toString());
cddto.setNroCheque(resultado[1].toString());
if(resultado[2] != null){
Timestamp timeStamp_2 = (Timestamp) resultado[2];
java.util.Date dateResult_2 = new Date(timeStamp_2.getTime());
cddto.setFechaVencimiento(dateResult_2);
}else{
cddto.setFechaVencimiento(null);
}
cddto.setImportePagado(Long.parseLong(resultado[3].toString()));
if(resultado[4] != null){
Timestamp timeStamp_4 = (Timestamp) resultado[4];
java.util.Date dateResult_4 = new Date(timeStamp_4.getTime());
cddto.setFechaEmision(dateResult_4);
}else{
cddto.setFechaEmision(null);
}
cddto.setNombreBanco(resultado[5] == null ? null : resultado[5].toString());
listadoCheques.add(cddto);
}
return listadoCheques;
}
public long obtenerImportePagadoRecibosCheques(String lNroCheque, short lCodBanco){
String sql = "SELECT sum(r.ipagado) " +
"from recibos_cheques r, recibos e " +
"WHERE r.nro_cheque = '" + lNroCheque + "' "+
"and r.nrecibo = e.nrecibo "+
"AND e.mestado = 'A' "+
"AND r.cod_banco = "+lCodBanco;
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
long importePagado = 0;
for(Object[] resultado: resultados){
importePagado = resultado == null ? 0 : Long.parseLong(resultado[0].toString());
}
return importePagado;
}
public void insertarReciboCheque( long lNroRecibo,
Short lCodBanco,
String lNroCheque,
long lIPagado){
String sql = "INSERT INTO recibos_cheques(cod_empr, nrecibo, " +
"cod_banco, nro_cheque, ipagado) " +
"values(2, "+lNroRecibo+", " +
""+lCodBanco+", '"+lNroCheque+"', "+lIPagado+")";
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
q.executeUpdate();
}
}
<file_sep>/SisVenLog-ejb/src/java/util/DateUtil.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
*
* @author Edu
*/
public class DateUtil {
private DateUtil(){}
public static String getFechaActual() throws ParseException{
Date ahora = new Date();
SimpleDateFormat formateador = new SimpleDateFormat("dd-MM-yyyy");
return formateador.format(ahora);
}
public static String formaterDateToString(Date fecha){
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
String date = DATE_FORMAT.format(fecha);
return date;
}
public static String obtenerDiaSemana(Date fecha) {
String[] dias = {"domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"};
Calendar cal = Calendar.getInstance();
cal.setTime(fecha);
int numeroDia = cal.get(Calendar.DAY_OF_WEEK);
return dias[numeroDia - 1];
}
public static String getHoraActual() {
Date ahora = new Date();
SimpleDateFormat formateador = new SimpleDateFormat("HH:mm");
return formateador.format(ahora);
}
public static String formaterDateTimeToString(Date fecha){
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss");
String date = DATE_FORMAT.format(fecha);
return date;
}
public static String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return resultado;
}
// Suma los días recibidos a la fecha
public static Date sumarRestarDiasFecha(Date fecha, int dias) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(fecha); // Configuramos la fecha que se recibe
calendar.add(Calendar.DAY_OF_YEAR, dias); // numero de días a añadir, o restar en caso de días<0
return calendar.getTime(); // Devuelve el objeto Date con los nuevos días añadidos
}
}
<file_sep>/SisVenLog-war/src/java/bean/listados/LiMovMercaBean.java
package bean.listados;
import dao.ExcelFacade;
import dao.MercaderiasFacade;
import dao.PersonalizedFacade;
import dao.TiposDocumentosFacade;
import dto.LiMercaSinDto;
import entidad.Mercaderias;
import entidad.MercaderiasPK;
import entidad.Zonas;
import entidad.ZonasPK;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import org.primefaces.model.DualListModel;
import util.LlamarReportes;
@ManagedBean
@SessionScoped
public class LiMovMercaBean {
@EJB
private MercaderiasFacade mercaderiasFacade;
@EJB
private PersonalizedFacade personalizedFacade;
@EJB
private ExcelFacade excelFacade;
private Mercaderias mercaderias;
private Zonas zonas;
private List<Zonas> listaZonas;
private Date desde;
private Date hasta;
public LiMovMercaBean() throws IOException {
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
this.zonas = new Zonas(new ZonasPK());
this.mercaderias = new Mercaderias(new MercaderiasPK());
this.listaZonas = new ArrayList<Zonas>();
this.desde = new Date();
this.hasta = new Date();
}
public void ejecutar(String tipo) {
LlamarReportes rep = new LlamarReportes();
String fdesde = dateToString(desde);
String fhasta = dateToString(hasta);
//String tipoDoc = "";
String zona = "";
StringBuilder sql = new StringBuilder();
if (this.zonas == null) {
zona = "TODOS";
} else {
zona = this.zonas.getZonasPK().getCodZona();
}
System.out.println("SQL limovimerca: " + sql.toString());
if (tipo.equals("VIST")) {
//rep.reporteLiMercaSin(sql.toString(), dateToString2(desde), dateToString2(hasta), tipoDocumento, "admin", zona, tipo);
} else if (tipo.equals("ARCH")) {
List<LiMercaSinDto> auxExcel = new ArrayList<LiMercaSinDto>();
auxExcel = excelFacade.listarLiMercaSin(sql.toString());
rep.excelLiMercaSin(auxExcel);
}
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
private String dateToString2(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
//Getters & Setters
public Date getDesde() {
return desde;
}
public void setDesde(Date desde) {
this.desde = desde;
}
public Date getHasta() {
return hasta;
}
public void setHasta(Date hasta) {
this.hasta = hasta;
}
public Zonas getZonas() {
return zonas;
}
public void setZonas(Zonas zonas) {
this.zonas = zonas;
}
public List<Zonas> getListaZonas() {
return listaZonas;
}
public void setListaZonas(List<Zonas> listaZonas) {
this.listaZonas = listaZonas;
}
public Mercaderias getMercaderias() {
return mercaderias;
}
public void setMercaderias(Mercaderias mercaderias) {
this.mercaderias = mercaderias;
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/PersonalizedFacade.java
package dao;
import dto.AuxiliarImpresionMasivaDto;
import dto.AuxiliarImpresionRemisionDto;
import dto.AuxiliarImpresionServiciosDto;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.*;
@Stateless
public class PersonalizedFacade {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public PersonalizedFacade() {
}
public List<AuxiliarImpresionMasivaDto> listarSecuenciasFacturas(Integer desde, Integer hasta) {
List<AuxiliarImpresionMasivaDto> respuesta = new ArrayList<AuxiliarImpresionMasivaDto>();
try {
Query q = getEntityManager().createNativeQuery("SELECT distinct(f.nrofact), f.xfactura, f.mestado\n"
+ "FROM facturas f, facturas_det d, empleados e, mercaderias m , zonas z, depositos p left outer join conductores c\n"
+ " ON p.cod_conductor = c.cod_conductor LEFT OUTER JOIN transportistas t\n"
+ " ON p.cod_transp = t.cod_transp\n"
+ " WHERE f.cod_empr = 2\n"
+ " AND d.cod_empr = 2\n"
+ " AND f.ffactur = d.ffactur\n"
+ " AND f.cod_empr = d.cod_empr\n"
+ " AND f.nrofact = d.nrofact\n"
+ " AND d.cod_merca = m.cod_merca\n"
+ " AND m.cod_empr = d.cod_empr\n"
+ " AND f.cod_depo = p.cod_depo\n"
+ " AND f.cod_zona = z.cod_zona\n"
+ " AND f.cod_empr = p.cod_empr\n"
+ " AND f.cod_vendedor = e.cod_empleado\n"
+ " AND f.ctipo_docum = d.ctipo_docum\n"
+ " AND f.cod_empr = e.cod_empr\n"
+ " and f.ctipo_docum in ('FCO','FCR')\n"
+ " AND f.nrofact between " + desde + " and " + hasta + "\n"
//+ " AND f.mestado = 'A'\n"
+ " ORDER BY f.nrofact");
System.out.println(q.toString());
List<Object[]> resultList = q.getResultList();
if (resultList.size() <= 0) {
respuesta = new ArrayList<AuxiliarImpresionMasivaDto>();
return respuesta;
} else {
for (Object[] obj : resultList) {
AuxiliarImpresionMasivaDto aux = new AuxiliarImpresionMasivaDto();
aux.setSecuencia(new Integer(obj[0].toString()));
aux.setFactura(obj[1].toString());
aux.setEstado(obj[2].toString());
respuesta.add(aux);
}
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al listar secuencias."));
}
return respuesta;
}
public List<AuxiliarImpresionServiciosDto> listarSecuenciasFacturasServicios(Integer desde, Integer hasta) {
List<AuxiliarImpresionServiciosDto> respuesta = new ArrayList<AuxiliarImpresionServiciosDto>();
try {
Query q = getEntityManager().createNativeQuery("SELECT distinct(f.nrofact), f.xfactura\n"
+ "FROM facturas f, facturas_ser d, servicios s\n"
+ " WHERE f.cod_empr = 2\n"
+ " AND d.cod_empr = 2\n"
+ " AND d.ctipo_docum = f.ctipo_docum\n"
+ " AND f.ffactur = d.ffactur\n"
+ " AND f.cod_empr = d.cod_empr\n"
+ " AND f.nrofact = d.nrofact\n"
+ " AND d.cod_servicio = s.cod_servicio\n"
+ " AND f.ctipo_docum IN ('FCS','FCP')\n"
+ " AND f.nrofact between " + desde + " and " + hasta + "\n"
+ " AND f.mestado = 'A'\n"
+ " order by f.nrofact asc");
System.out.println(q.toString());
List<Object[]> resultList = q.getResultList();
if (resultList.size() <= 0) {
respuesta = new ArrayList<AuxiliarImpresionServiciosDto>();
return respuesta;
} else {
for (Object[] obj : resultList) {
AuxiliarImpresionServiciosDto aux = new AuxiliarImpresionServiciosDto();
aux.setSecuencia(new Integer(obj[0].toString()));
aux.setFactura(obj[1].toString());
respuesta.add(aux);
}
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al listar secuencias."));
}
return respuesta;
}
public List<AuxiliarImpresionRemisionDto> listarSecuenciasRemision(Integer desde, Integer hasta) {
List<AuxiliarImpresionRemisionDto> respuesta = new ArrayList<AuxiliarImpresionRemisionDto>();
try {
Query q = getEntityManager().createNativeQuery("SELECT distinct(e.nro_remision), e.xnro_remision \n"
+ "FROM remisiones e INNER JOIN\n"
+ " remisiones_det d ON e.nro_remision = d.nro_remision AND e.cod_empr = d.cod_empr LEFT OUTER JOIN\n"
+ " vw_fact_remisiones v2 ON e.nro_remision = v2.nro_remision AND v2.ctipo_docum = 'FCR' AND e.cod_empr = v2.cod_empr LEFT OUTER JOIN\n"
+ " vw_fact_remisiones v ON e.nro_remision = v.nro_remision AND v.ctipo_docum in ('CPV','FCO') AND e.cod_empr = v.cod_empr INNER JOIN\n"
+ " depositos d3 ON e.cod_depo = d3.cod_depo AND e.cod_empr = d3.cod_empr INNER JOIN\n"
+ " empleados p ON e.cod_entregador = p.cod_empleado AND e.cod_empr = p.cod_empr INNER JOIN\n"
+ " conductores c ON e.cod_conductor = c.cod_conductor INNER JOIN\n"
+ " transportistas t ON e.cod_transp = t.cod_transp INNER JOIN\n"
+ " mercaderias m ON d.cod_merca = m.cod_merca INNER JOIN\n"
+ " empresas e2 ON e2.cod_empr = e.cod_empr\n"
+ " WHERE e.cod_empr = 2\n"
+ " AND e.cod_empr = 2\n"
+ " AND e.nro_remision >= "+desde+"\n"
+ " AND e.nro_remision <= "+hasta+"\n"
+ " and e.mestado ='A'\n"
+ " ORDER BY e.nro_remision");
System.out.println(q.toString());
List<Object[]> resultList = q.getResultList();
if (resultList.size() <= 0) {
respuesta = new ArrayList<AuxiliarImpresionRemisionDto>();
return respuesta;
} else {
for (Object[] obj : resultList) {
AuxiliarImpresionRemisionDto aux = new AuxiliarImpresionRemisionDto();
aux.setSecuencia(new Integer(obj[0].toString()));
aux.setFactura(obj[1].toString());
respuesta.add(aux);
}
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al listar secuencias."));
}
return respuesta;
}
public Integer ejecutarSentenciaSQL(String sql){
int respuesta = 0;
System.out.println(sql);
Query q = getEntityManager().createNativeQuery(sql);
respuesta = q.executeUpdate();
return respuesta;
}
public Integer ejecutarConsultaRetornaInt(String consulta) {
Integer respuesta = 0;
try {
Query q = getEntityManager().createNativeQuery(consulta);
System.out.println(q.toString());
Integer resultList = (Integer) q.getSingleResult();
return resultList;
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al ejecutar consulta."));
}
return respuesta;
}
}
<file_sep>/SisVenLog-war/src/java/bean/AplicaRolBean.java
package bean;
import dao.GruposCargaFacade;
import dao.RolesAplicacionesFacade;
import entidad.GruposCarga;
import entidad.RolesAplicaciones;
import entidad.RolesAplicacionesPK;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
@ManagedBean
@SessionScoped
public class AplicaRolBean implements Serializable {
@EJB
private RolesAplicacionesFacade rolesAplicacionesFacade;
@EJB
private GruposCargaFacade gruposCargaFacade;
private String filtro = "";
private RolesAplicaciones rolesAplicaciones = new RolesAplicaciones();
private List<RolesAplicaciones> listaRolesAplicaciones = new ArrayList<RolesAplicaciones>();
private GruposCarga gruposCarga = new GruposCarga();
private List<GruposCarga> listaGruposCarga = new ArrayList<GruposCarga>();
private boolean habBtnEdit;
private boolean habBtnAct;
private boolean habBtnInac;
public AplicaRolBean() {
//instanciar();
}
public boolean isHabBtnEdit() {
return habBtnEdit;
}
public void setHabBtnEdit(boolean habBtnEdit) {
this.habBtnEdit = habBtnEdit;
}
public boolean isHabBtnAct() {
return habBtnAct;
}
public void setHabBtnAct(boolean habBtnAct) {
this.habBtnAct = habBtnAct;
}
public boolean isHabBtnInac() {
return habBtnInac;
}
public void setHabBtnInac(boolean habBtnInac) {
this.habBtnInac = habBtnInac;
}
public RolesAplicaciones getRolesAplicaciones() {
return rolesAplicaciones;
}
public void setRolesAplicaciones(RolesAplicaciones rolesAplicaciones) {
this.rolesAplicaciones = rolesAplicaciones;
}
public List<RolesAplicaciones> getListaRolesAplicaciones() {
return listaRolesAplicaciones;
}
public void setListaRolesAplicaciones(List<RolesAplicaciones> listaRolesAplicaciones) {
this.listaRolesAplicaciones = listaRolesAplicaciones;
}
public GruposCarga getGruposCarga() {
return gruposCarga;
}
public void setGruposCarga(GruposCarga gruposCarga) {
this.gruposCarga = gruposCarga;
}
public List<GruposCarga> getListaGruposCarga() {
return listaGruposCarga;
}
public void setListaGruposCarga(List<GruposCarga> listaGruposCarga) {
this.listaGruposCarga = listaGruposCarga;
}
public RolesAplicacionesFacade getRolesAplicacionesFacade() {
return rolesAplicacionesFacade;
}
public void setRolesAplicacionesFacade(RolesAplicacionesFacade rolesAplicacionesFacade) {
this.rolesAplicacionesFacade = rolesAplicacionesFacade;
}
public GruposCargaFacade getGruposCargaFacade() {
return gruposCargaFacade;
}
public void setGruposCargaFacade(GruposCargaFacade gruposCargaFacade) {
this.gruposCargaFacade = gruposCargaFacade;
}
//Operaciones
//Instanciar objetos
@PostConstruct
public void instanciar() {
listaRolesAplicaciones = new ArrayList<RolesAplicaciones>();
this.rolesAplicaciones = new RolesAplicaciones();
this.rolesAplicaciones.setRolesAplicacionesPK(new RolesAplicacionesPK());
listaGruposCarga = new ArrayList<GruposCarga>();
this.gruposCarga = new GruposCarga();
this.setHabBtnEdit(true);
this.setHabBtnAct(true);
this.setHabBtnInac(true);
this.filtro = "";
listar();
//RequestContext.getCurrentInstance().update("formPersonas");
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public void nuevo() {
this.rolesAplicaciones = new RolesAplicaciones();
}
public List<RolesAplicaciones> listar() {
listaRolesAplicaciones = rolesAplicacionesFacade.findAll();
return listaRolesAplicaciones;
}
public List<GruposCarga> listarGruposCarga() {
listaGruposCarga = gruposCargaFacade.findAll();
return listaGruposCarga;
}
public void insertar() {
try {
{
/*if (this.rolesAplicaciones.getPersEmail() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Debe cargar e-mail."));
return;
}
if (this.Persona.getPersTelefono() == null && this.Persona.getPersCelular() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Debe cargar telefono o celular."));
return;
}
if (this.Persona.getPersSexo() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion", "Debe cargar el genero."));
return;
}*/
//String usu = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("usuario").toString();
RolesAplicacionesPK pk = null;
rolesAplicaciones.setRolesAplicacionesPK(pk);
rolesAplicaciones.setFalta(new Date());
rolesAplicaciones.setCusuario("admin");
rolesAplicacionesFacade.insertarRolesAplicaciones(rolesAplicaciones);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "El registro fue creado con exito."));
RequestContext.getCurrentInstance().execute("PF('dlgNuevRolesAplicaciones').hide();");
instanciar();
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Ocurrió un error."));
}
}
public void editar() {
try {
if ("".equals(this.rolesAplicaciones.getRolesAplicacionesPK())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Campo requerido", "Debe ingresar una descripcion."));
return;
} else {
rolesAplicacionesFacade.edit(rolesAplicaciones);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Guardado con exito."));
instanciar();
listar();
RequestContext.getCurrentInstance().execute("PF('dlgEditRolesAplicaciones').hide();");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Ocurrió un error."));
}
}
public void borrar() {
try {
rolesAplicacionesFacade.remove(rolesAplicaciones);
this.rolesAplicaciones = new RolesAplicaciones();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Borrado con éxito."));
instanciar();
RequestContext.getCurrentInstance().execute("PF('dlgInacRolesAplicaciones').hide();");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Ocurrió un error."));
}
}
public void onRowSelect(SelectEvent event) {
if (null != this.rolesAplicaciones.getRolesAplicacionesPK()) {
this.setHabBtnEdit(false);
this.gruposCarga = this.getGruposCarga();
} else {
this.setHabBtnEdit(true);
}
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/RecibosProvDetFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.RecibosProvDet;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author admin
*/
@Stateless
public class RecibosProvDetFacade extends AbstractFacade<RecibosProvDet> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public RecibosProvDetFacade() {
super(RecibosProvDet.class);
}
public void insertarReciboProveedorDetalle( short gCodEmpresa,
Short lCodProveed,
long lNroRecibo,
long lNroFact,
String ctipoDocum,
long lIDeuda,
String lFFactura,
long lInteres,
long lTTotal,
long lISaldo,
String lFRecibo){
//lITotal es igual a l_ideuda
String sql = "INSERT INTO recibos_prov_det(cod_empr, cod_proveed, nrecibo, " +
"nrofact, ctipo_docum, itotal, ffactur, interes, ttotal, isaldo, frecibo) " +
"values ("+gCodEmpresa+", "+lCodProveed+", "+lNroRecibo+", " +
""+lNroFact+", '"+ctipoDocum+"', "+lIDeuda+", '"+lFFactura+"', "+lInteres+", "+lTTotal+", "+lISaldo+", '"+lFRecibo+"')";
System.out.println(sql);
Query q = getEntityManager().createNativeQuery(sql);
q.executeUpdate();
}
}
<file_sep>/SisVenLog-ejb/src/java/dao/TiposClientesFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entidad.Depositos;
import entidad.Lineas;
import entidad.TiposClientes;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
/**
*
* @author admin
*/
@Stateless
public class TiposClientesFacade extends AbstractFacade<TiposClientes> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public TiposClientesFacade() {
super(TiposClientes.class);
}
public void insertarTipoCliDeposito(TiposClientes tipoCli, Depositos depositos) {
StoredProcedureQuery q = getEntityManager().createStoredProcedureQuery("InsertarTipoCli");
q.registerStoredProcedureParameter("ctipo_cliente", String.class, ParameterMode.IN);
q.registerStoredProcedureParameter("cod_depo", Short.class, ParameterMode.IN);
q.setParameter("ctipo_cliente", tipoCli.getCtipoCliente());
q.setParameter("cod_depo", depositos.getDepositosPK().getCodDepo());
q.execute();
}
public List<TiposClientes> listarTiposClientes() {
Query q = getEntityManager().createNativeQuery("SELECT * FROM tipos_clientes", TiposClientes.class);
System.out.println(q.toString());
List<TiposClientes> respuesta = new ArrayList<TiposClientes>();
respuesta = q.getResultList();
return respuesta;
}
//JLVC 15-04-2020
public TiposClientes buscarPorCodigo(String filtro) {
Query q = getEntityManager().createNativeQuery("select * from tipos_clientes where ctipo_cliente = upper('" + filtro + "') ", TiposClientes.class);
//System.out.println(q.toString());
TiposClientes respuesta = new TiposClientes();
if (q.getResultList().size() <= 0) {
respuesta = null;
} else {
respuesta = (TiposClientes) q.getSingleResult();
}
return respuesta;
}
}<file_sep>/SisVenLog-ejb/src/java/dao/PedidosFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import dto.PedidoDto;
import entidad.Pedidos;
import entidad.PedidosPK;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author admin
*/
@Stateless
public class PedidosFacade extends AbstractFacade<Pedidos> {
@PersistenceContext(unitName = "SisVenLog-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public PedidosFacade() {
super(Pedidos.class);
}
public List<PedidoDto> listadoDePedidos(Date fechaInicio,
Date fechaFin,
Character estado,
Integer codigoCliente,
long nroDocumento){
String sql = "SELECT p.ctipo_docum, p.nro_pedido, p.cod_cliente, "+
"c.xnombre, p.cod_canal, p.cod_depo, p.npeso_acum, p.mestado "+
"FROM pedidos p, clientes c "+
"WHERE p.cod_cliente = c.cod_cliente "+
"AND p.cod_empr = 2";
if(fechaInicio != null){
sql += " AND p.fpedido >= ?";
}
if(fechaFin != null){
sql += " AND p.fpedido <= ?";
}
if(estado == 'A'){
sql += " AND p.mestado != 'X'";
}else{
sql += " AND p.mestado = 'X'";
}
if(codigoCliente != null){
if(codigoCliente > 0){
sql += " AND p.cod_cliente = ?";
}
}
if(nroDocumento != 0){
sql += " AND p.nro_pedido = ?";
}
Query q = em.createNativeQuery(sql);
int i = 1;
if(fechaInicio != null){
i++;
q.setParameter(i, fechaInicio);
}
if(fechaFin != null){
i++;
q.setParameter(i, fechaFin);
}
i++;
q.setParameter(i, estado);
if(codigoCliente != null){
if(codigoCliente > 0){
i++;
q.setParameter(i, codigoCliente);
}
}
if(nroDocumento != 0){
i++;
q.setParameter(i, nroDocumento);
}
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
List<PedidoDto> listadoPedidos = new ArrayList<PedidoDto>();
for(Object[] resultado: resultados){
//clave primaria de pedidos
PedidosPK pedidosPk = new PedidosPK();
pedidosPk.setCodEmpr(Short.parseShort("2"));
pedidosPk.setNroPedido(Long.parseLong(resultado[1].toString()));
//pedidos
Pedidos pedido = new Pedidos();
pedido.setPedidosPK(pedidosPk);
pedido.setCtipoDocum(resultado[0].toString());
pedido.setCodCliente(resultado[2] == null ? null : Integer.parseInt(resultado[2].toString()));
pedido.setCodCanal(resultado[4].toString());
pedido.setCodDepo(resultado[5] == null ? null : Short.parseShort(resultado[5].toString()));
pedido.setNpesoAcum(resultado[6] == null ? null : BigDecimal.valueOf(Long.parseLong(resultado[6].toString())));
pedido.setMestado((Character)resultado[7]);
//nombre cliente
String nombreCliente = null;
if(resultado[3] != null){
nombreCliente = resultado[3].toString();
}
PedidoDto pdto = new PedidoDto();
pdto.setPedido(pedido);
pdto.setNombreCliente(nombreCliente);
listadoPedidos.add(pdto);
}
return listadoPedidos;
}
public long obtenerTotalPedidosPorClienteFecha(Integer lCodCliente, String lFechaPedido){
String sql = "SELECT ISNULL(SUM(ttotal),0) as tot_ped " +
"FROM pedidos " +
"WHERE cod_cliente = "+lCodCliente+" "+
"AND cod_empr = 2 " +
"AND fpedido >= '"+lFechaPedido+"' "+
"AND mestado IN ('N','E')";
Query q = em.createNativeQuery(sql);
System.out.println(q.toString());
List<Object[]> resultados = q.getResultList();
Long total = Long.parseLong("0");
for(Object[] resultado: resultados){
total = resultado[0] == null ? Long.parseLong("0") : Long.parseLong(resultado[0].toString());
}
return total;
}
public void actualizarPedidosPorNro(long lNroPedido){
String sql = "UPDATE pedidos SET mestado = 'E' "+
"WHERE nro_pedido = "+lNroPedido+" "+
"AND cod_empr = 2";
Query q = em.createNativeQuery(sql);
q.executeUpdate();
}
}
<file_sep>/SisVenLog-war/src/java/bean/FacturasBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
import dao.CanalesVendedoresFacade;
import dao.ClientesFacade;
import dao.CuentasCorrientesFacade;
import dao.DepositosFacade;
import dao.EmpleadosFacade;
import dao.EmpleadosZonasFacade;
import dao.ExistenciasFacade;
import dao.FacturasDetFacade;
import dao.FacturasFacade;
import dao.MercaImpuestosFacade;
import dao.MercaderiasFacade;
import dao.MotivosFacade;
import dao.MovimientosMercaFacade;
import dao.PedidosFacade;
import dao.PreciosFacade;
import dao.PromocionesFacade;
import dao.RangosDocumentosFacade;
import dao.RetornosPreciosFacade;
import dao.SaldosClientesFacade;
import dao.TiposDocumentosFacade;
import dao.TiposVentasFacade;
import dto.FacturaDetDto;
import dto.MovimientoMercaDto;
import dto.PromocionDto;
import dto.PromocionesDetDto;
import entidad.CanalesVendedores;
import entidad.Clientes;
import entidad.CuentasCorrientes;
import entidad.Depositos;
import entidad.DepositosPK;
import entidad.Empleados;
import entidad.EmpleadosZonas;
import entidad.Existencias;
import entidad.Facturas;
import entidad.FacturasDet;
import entidad.FacturasDetPK;
import entidad.FacturasPK;
import entidad.Impuestos;
import entidad.Mercaderias;
import entidad.Motivos;
import entidad.MovimientosMerca;
import entidad.Precios;
import entidad.Promociones;
import entidad.PromocionesPK;
import entidad.RangosDocumentos;
import entidad.RetornosPrecios;
import entidad.SaldosClientes;
import entidad.TiposDocumentos;
import entidad.TiposVentas;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import util.DateUtil;
import util.ExceptionHandlerView;
/**
*
* @author dadob
*/
@ManagedBean
@SessionScoped
public class FacturasBean implements Serializable{
@EJB
private ClientesFacade clientesFacade;
@EJB
private TiposVentasFacade tiposVentasFacade;
@EJB
private DepositosFacade depositosFacade;
@EJB
private PedidosFacade pedidosFacade;
@EJB
private SaldosClientesFacade saldosClientesFacade;
@EJB
private CuentasCorrientesFacade cuentasCorrientesFacade;
@EJB
private FacturasFacade facturasFacade;
@EJB
private RangosDocumentosFacade rangosDocumentosFacade;
@EJB
private ExistenciasFacade existenciasFacade;
@EJB
private MercaderiasFacade mercaderiasFacade;
@EJB
private FacturasDetFacade facturasDetFacade;
@EJB
private PromocionesFacade promocionesFacade;
@EJB
private MovimientosMercaFacade movimientosMercaFacade;
@EJB
private TiposDocumentosFacade tiposDocumentosFacade;
@EJB
private PreciosFacade preciosFacade;
@EJB
private EmpleadosZonasFacade empleadosZonasFacade;
@EJB
private CanalesVendedoresFacade canalesVendedoresFacade;
@EJB
private EmpleadosFacade empleadosFacade;
@EJB
private MercaImpuestosFacade mercaImpuestosFacade;
@EJB
private RetornosPreciosFacade retornosPreciosFacade;
@EJB
private MotivosFacade motivosFacade;
private Date fechaFactLbl;
private Integer codClienteLbl;
private String nombreClienteLbl;
private Short nPuntoEstabLbl;
private Short nPuntoExpedLbl;
private long nroFactLbl;
private short codDepositoLbl;
private long nroPedidoLbl;
private Character ctipoVtaLbl;
private Date fechaVencLbl;
private Date fechaVencImpresLbl;
private int cantDiasChequesLbl;
private int cantDiasImpresionChequesLbl;
private short plazosChequesLbl;
private short codVendedorLbl;
private String codCanalVentaLbl;
private TiposDocumentos tipoDocumentoSeleccionadoLbl;
private String contenidoError;
private String tituloError;
private List<TiposVentas> listadoTiposVentas;
private List<Depositos> listadoDepositos;
private Clientes clienteBuscado;
private boolean mostrarCantDiasChequesLbl;
private boolean mostrarCantDiasImpresionChequesLbl;
private boolean mostrarPlazosChequesLbl;
private boolean mostrarTotalIva;
private boolean mostrarFechaVencimiento;
private boolean mostrarFechaVencimientoImpresion;
private long totalFinal;
private long totalIva;
private long totalExentas;
private long totalGravadas;
private long totalDescuentos;
private Depositos depositoSeleccionado;
private String codZonaLbl;
private String observacionLbl;
private short codEntregadorLbl;
private String direccionLbl;
private String razonSocialLbl;
private String telefonoLbl;
private String ciudadLbl;
private short codRutaLbl;
private Facturas facturaSeleccionada;
private List<Facturas> listadoFacturas;
private Short cMotivoLbl;
private Date fechaAnulacionLbl;
//variables del detalle
private String codMercaDet;
private int cantCajasDet;
private int cantUnidDet;
private int cantCajasBonifDet;
private int cantUnidBonifDet;
private Mercaderias mercaderiaDet;
private List<FacturaDetDto> listadoDetalle;
private List<FacturasDet> listadoFacturasDet;
private String descMercaDet;
private long precioCajaDet;
private long precioUnidDet;
private long gravadasDet;
private long exentasDet;
private long impuestosDet;
private long descuentosDet;
private long totalDet;
private Integer nroPromoDet;
private String descPromoDet;
private BigDecimal pdescDet;
private BigDecimal pimpuesDet;
private Short nRelacionDet;
private Character mPromoPackDet;
private Short codSublineaDet;
private BigDecimal nPesoCajaDet;
private BigDecimal nPesoUnidadDet;
private boolean habilitaBotonEliminar;
private List<TiposDocumentos> listadoTiposDocumentos;
private List<EmpleadosZonas> listadoVendedores;
private List<CanalesVendedores> listadoCanales;
private List<Empleados> listadoEntregadores;
private String filtro;
private FacturaDetDto facturaDetDtoSeleccionada;
private Character mGravExeDet;
private long precioCajaSimDet;
private long precioUnidadSimDet;
private long gravadas2Det;
private Clientes clientes;
private List<Clientes> listaClientes;
private List<Existencias> listaExistencias;
private Existencias existencias;
private LazyDataModel<Existencias> model;
private boolean habilitaBotonVisualizar;
HashMap<String, TiposDocumentos> tipoDocumentoEnMemoria;
HashMap<String, Depositos> depositoEnMemoria;
private List<Motivos> listadoMotivos;
@PostConstruct
public void init(){
limpiarFormulario();
}
public void cambiaDeposito(){
try{
if(codDepositoLbl != 0){
DepositosPK dPK = new DepositosPK();
dPK.setCodEmpr(Short.parseShort("2"));
dPK.setCodDepo(codDepositoLbl);
depositoSeleccionado = depositosFacade.find(dPK);
depositoEnMemoria.put("deposito", depositoSeleccionado);
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al cambiar depósito.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public void cambiaPlazoCheque() {
try {
if (clienteBuscado != null) {
if (plazosChequesLbl > clienteBuscado.getNplazoCredito()) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención", "Plazo máximo del cliente es: " + clienteBuscado.getNplazoCredito() + " días."));
}
}
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al cambiar plazo cheque.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public void cambiaTipoDocumento() {
try {
if(tipoDocumentoSeleccionadoLbl != null){
tipoDocumentoSeleccionadoLbl = tiposDocumentosFacade.find(this.tipoDocumentoSeleccionadoLbl.getCtipoDocum());
tipoDocumentoEnMemoria.put("tipo_documento", tipoDocumentoSeleccionadoLbl);
mostrarTotalIva = this.tipoDocumentoSeleccionadoLbl.getMincluIva() == 'S';
if (tipoDocumentoSeleccionadoLbl.getCtipoDocum().equals("FCR")) {
mostrarFechaVencimiento = false;
mostrarFechaVencimientoImpresion = false;
} else {
mostrarFechaVencimiento = true;
mostrarFechaVencimientoImpresion = true;
}
}
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al cambiar tipos de documentos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public void cambiaVendedor() {
listadoCanales = new ArrayList<>();
if (codVendedorLbl != 0) {
try {
listadoCanales = canalesVendedoresFacade.obtenerCanalesVendedores(codVendedorLbl);
//obtener codZonaLbl
for(EmpleadosZonas ez: listadoVendedores){
if(ez.getEmpleados().getEmpleadosPK().getCodEmpleado() == codVendedorLbl){
codZonaLbl = ez.getZonas().getZonasPK().getCodZona();
break; //salimos del for.
}
}
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de canales_vendedores.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
}
public void limpiarFormulario(){
listadoTiposVentas = new ArrayList<>();
listadoDepositos = new ArrayList<>();
clienteBuscado = new Clientes();
mostrarCantDiasChequesLbl = false;
mostrarCantDiasImpresionChequesLbl = false;
mostrarPlazosChequesLbl = false;
mostrarTotalIva = false;
depositoSeleccionado = new Depositos();
mercaderiaDet = new Mercaderias();
listadoDetalle = new ArrayList<>();
facturaSeleccionada = new Facturas();
listadoFacturas = new ArrayList<>();
listadoFacturasDet = new ArrayList<>();
//variables factura
fechaFactLbl = new Date();
codClienteLbl = null;
nombreClienteLbl = null;
nPuntoEstabLbl = 0;
nPuntoExpedLbl = 0;
nroFactLbl = 0;
codDepositoLbl = 0;
nroPedidoLbl = 0;
ctipoVtaLbl = 0;
fechaVencLbl = null;
fechaVencImpresLbl = null;
cantDiasChequesLbl = 0;
cantDiasImpresionChequesLbl = 0;
plazosChequesLbl = 0;
codVendedorLbl = 0;
codCanalVentaLbl = null;
tipoDocumentoSeleccionadoLbl = null;
contenidoError = null;
tituloError = null;
mostrarCantDiasChequesLbl = true;
mostrarCantDiasImpresionChequesLbl = true;
mostrarPlazosChequesLbl = true;
totalFinal = 0;
totalIva = 0;
totalExentas = 0;
totalGravadas = 0;
totalDescuentos = 0;
codZonaLbl = null;
observacionLbl = null;
codEntregadorLbl = 0;
direccionLbl = null;
razonSocialLbl = null;
telefonoLbl = null;
ciudadLbl = null;
codRutaLbl = 0;
cMotivoLbl = 0;
fechaAnulacionLbl = null;
//variables del detalle
codMercaDet = null;
cantCajasDet = 0;
cantUnidDet = 0;
cantCajasBonifDet = 0;
cantUnidBonifDet = 0;
mercaderiaDet = new Mercaderias();
descMercaDet = null;
precioCajaDet = 0;
precioUnidDet = 0;
gravadasDet = 0;
exentasDet = 0;
impuestosDet = 0;
descuentosDet = 0;
nroPromoDet = 0;
descPromoDet = null;
pdescDet = BigDecimal.ZERO;
pimpuesDet = BigDecimal.ZERO;
nRelacionDet = 0;
mPromoPackDet = 0;
codSublineaDet = 0;
nPesoUnidadDet = null;
nPesoCajaDet = null;
habilitaBotonEliminar = true;
habilitaBotonVisualizar = true;
listadoTiposDocumentos = new ArrayList<>();
listadoVendedores = new ArrayList<>();
listadoCanales = new ArrayList<>();
listadoEntregadores = new ArrayList<>();
filtro = null;
totalDet = 0;
facturaDetDtoSeleccionada = new FacturaDetDto();
mostrarFechaVencimiento = false;
mostrarFechaVencimientoImpresion = false;
mGravExeDet = 0;
precioCajaSimDet = 0;
precioUnidadSimDet = 0;
gravadas2Det = 0;
clientes = new Clientes();
listaClientes = new ArrayList<>();
listaExistencias = new ArrayList<>();
existencias = new Existencias();
tipoDocumentoEnMemoria = new HashMap<>();
depositoEnMemoria = new HashMap<>();
listadoMotivos = new ArrayList<>();
listarFacturas();
}
public List<Motivos> listarMotivos(){
listadoMotivos = new ArrayList<>();
try{
listadoMotivos = motivosFacade.findAll();
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de motivos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
return listadoMotivos;
}
public List<Empleados> listarEntregadores(){
listadoEntregadores = new ArrayList<>();
try{
listadoEntregadores = empleadosFacade.listarEntregador();
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de empleados.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
return listadoEntregadores;
}
public List<CanalesVendedores> listarCanales(){
listadoCanales = new ArrayList<>();
try{
listadoCanales = canalesVendedoresFacade.obtenerCanalesVendedores(codVendedorLbl);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de canales_vendedores.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
return listadoCanales;
}
public List<EmpleadosZonas> listarVendedoresZonas(){
listadoVendedores = new ArrayList<>();
try{
listadoVendedores = empleadosZonasFacade.obtenerEmpleadosZonas();
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de empleados_zonas.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
return listadoVendedores;
}
public List<TiposDocumentos> listarTiposDocumentos(){
listadoTiposDocumentos = new ArrayList<>();
try{
listadoTiposDocumentos = tiposDocumentosFacade.listarTipoDocumentoFactura();
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de tipos de documentos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
return listadoTiposDocumentos;
}
public void listarFacturas(){
try{
listadoFacturas = facturasFacade.listadoDeFacturas();
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de facturas.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public String comprobarNroPromo(){
descPromoDet = null;
if(pdescDet.compareTo(BigDecimal.ZERO) != 0){
//si hay descuento, es obligatorio el nro. de promocion.
if(nroPromoDet == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Debe ingresar el nro. de promoción."));
return null;
}else{
try{
String lFFactura = dateToString(fechaFactLbl);
List<Promociones> listadoPromo = promocionesFacade.findByNroPromoYFechaFactura(nroPromoDet, lFFactura);
if (listadoPromo.isEmpty()) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "No existe promoción"));
return null;
}
if (cantCajasDet > 0 || cantUnidDet > 0) {
//validar promocion
if (mPromoPackDet == 'N') {
if (validarPromocion(nroPromoDet,
codZonaLbl,
codMercaDet,
cantCajasDet,
cantUnidDet,
cantUnidBonifDet,
clienteBuscado.getCtipoCliente(),
pdescDet,
codSublineaDet,
ctipoVtaLbl,
"",
nRelacionDet,
obtenerNroFacturaCompleto())){
for(Promociones p: listadoPromo){
descPromoDet = p.getXdesc();
}
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Ingrese cajas/unidades facturadas."));
return null;
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de promociones.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}
return null;
}
public String comprobarCodMerca(){
if(codMercaDet.equals("") || codMercaDet == null){
//mostrar busqueda de mercaderías
RequestContext.getCurrentInstance().execute("PF('dlgBusMercaFact').show();");
}else{
try{
if(codDepositoLbl == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Debe seleccionar el depósito."));
return null;
}
if(codCanalVentaLbl.equals("") || codCanalVentaLbl == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Debe seleccionar el canal de venta."));
return null;
}
listaExistencias = existenciasFacade.buscarPorCodigoDepositoOrigenMerca(codMercaDet, codDepositoLbl, codCanalVentaLbl);
if(!listaExistencias.isEmpty()){
for(Existencias e: listaExistencias){
descMercaDet = e.getMercaderias().getXdesc();
mPromoPackDet = e.getMercaderias().getMpromoPack();
codSublineaDet = e.getMercaderias().getCodSublinea().getCodSublinea();
nRelacionDet = e.getMercaderias().getNrelacion() == null ? 0 : e.getMercaderias().getNrelacion().shortValue();
}
}else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Mercadería no existe."));
return null;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de mercaderías.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
return null;
}
public void inicializarBuscadorClientes(){
listaClientes = new ArrayList<>();
clientes = new Clientes();
filtro = "";
listarClientesBuscador();
}
public void listarClientesBuscador(){
try{
listaClientes = clientesFacade.buscarPorFiltro(filtro);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de clientes.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public void inicializarBuscadorMercaderia(){
listaExistencias = new ArrayList<>();
existencias = new Existencias();
filtro = "";
if(codDepositoLbl == 0){
RequestContext.getCurrentInstance().execute("PF('dlgBusMercaFact').hide();");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Debe seleccionar el depósito."));
return;
}
if(codCanalVentaLbl.equals("") || codCanalVentaLbl == null){
RequestContext.getCurrentInstance().execute("PF('dlgBusMercaFact').hide();");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Debe seleccionar el canal de venta."));
return;
}
model = new LazyDataModel<Existencias>() {
private static final long serialVersionUID = 1L;
@Override
public List<Existencias> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
//List<Envios> envioss;
int count;
if("".equals(filtro)){
listaExistencias = existenciasFacade.buscarPorCodigoDepositoOrigenTodasMerca(codDepositoLbl, new int[]{first, pageSize}, codCanalVentaLbl);
count = existenciasFacade.CountBuscarPorCodigoDepositoOrigenTodasMerca(codDepositoLbl, codCanalVentaLbl);
model.setRowCount(count);
}else{
listaExistencias = existenciasFacade.buscarListaPorCodigoDepositoOrigenMercaDescripcion(filtro,codDepositoLbl,new int[]{first, pageSize}, codCanalVentaLbl );
count = existenciasFacade.CountBuscarPorCodigoDepositoOrigenTodasMercaConFiltro(filtro,codDepositoLbl,codCanalVentaLbl);
model.setRowCount(count);
}
return listaExistencias;
}
@Override
public Existencias getRowData(String rowKey) {
String tempIndex = rowKey;
System.out.println("1");
if (tempIndex != null) {
for (Existencias inc : listaExistencias) {
if (inc.getExistenciasPK().getCodMerca().equals(rowKey)) {
existencias = inc;
return inc;
}
}
}
return null;
}
@Override
public Object getRowKey(Existencias existenciass) {
return existenciass.getExistenciasPK().getCodMerca();
}
};
}
public void listarMercaderiasEnBuscador(){
}
public void onRowMercaderiasSelect(SelectEvent event) {
if (this.existencias != null) {
if (this.existencias.getExistenciasPK().getCodMerca() != null) {
codMercaDet = this.existencias.getExistenciasPK().getCodMerca();
descMercaDet = this.existencias.getMercaderias().getXdesc();
mPromoPackDet = this.existencias.getMercaderias().getMpromoPack();
codSublineaDet = this.existencias.getMercaderias().getCodSublinea().getCodSublinea();
nRelacionDet = this.existencias.getMercaderias().getNrelacion() == null ? 0 : this.existencias.getMercaderias().getNrelacion().shortValue();
RequestContext.getCurrentInstance().update("panel_buscador_articulo");
RequestContext.getCurrentInstance().execute("PF('dlgBusMercaFact').hide();");
}
}
}
public void onRowClientesSelect(SelectEvent event) {
if (getClientes() != null) {
if (getClientes().getXnombre() != null) {
codClienteLbl = getClientes().getCodCliente();
nombreClienteLbl = getClientes().getXnombre();
RequestContext.getCurrentInstance().update("panel_grid_nueva_factura");
RequestContext.getCurrentInstance().execute("PF('dlgBusClieConsultaFactura').hide();");
}
}
}
public void cambiarFechaFactura(){
fechaVencLbl = null;
fechaVencImpresLbl = null;
try {
if (tipoDocumentoSeleccionadoLbl.getCtipoDocum().equals("FCR")) {
fechaVencLbl = DateUtil.sumarRestarDiasFecha(fechaFactLbl, clienteBuscado.getNplazoCredito());
fechaVencImpresLbl = DateUtil.sumarRestarDiasFecha(fechaFactLbl, clienteBuscado.getNplazoImpresion());
}
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al sumar plazos de crédito a la fecha de la factura.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public String verificarCliente(){
if(codClienteLbl != null){
if(codClienteLbl == 0){
//mostrar busqueda de clientes
RequestContext.getCurrentInstance().execute("PF('dlgBusClieConsultaFactura').show();");
}else{
try{
clienteBuscado = clientesFacade.find(codClienteLbl);
if(clienteBuscado == null){
//mostrar busqueda de clientes
RequestContext.getCurrentInstance().execute("PF('dlgBusClieConsultaFactura').show();");
}else{
this.nombreClienteLbl = clienteBuscado.getXnombre();
if(clienteBuscado.getMformaPago() == 'C' && !tipoDocumentoSeleccionadoLbl.getCtipoDocum().equals("FCO")){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atención", "Tipo inválido de factura."));
return null;
}
if(clienteBuscado.getMformaPago() == 'F' && !tipoDocumentoSeleccionadoLbl.getCtipoDocum().equals("FCR")){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atención", "Tipo inválido de factura."));
return null;
}
if(clienteBuscado.getMformaPago() != 0 && !tipoDocumentoSeleccionadoLbl.getCtipoDocum().equals("FCO")){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atención", "Tipo inválido de factura."));
return null;
}
listadoTiposVentas = new ArrayList<>();
try{
//buscar los tipos de venta habilitados para ese cliente para poblar el combo
listadoTiposVentas = tiposVentasFacade.obtenerTiposVentasDelCliente(codClienteLbl);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de tipos de ventas de clientes.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
try {
//busar los depositos habilitados para poblar el combo
listadoDepositos = depositosFacade.obtenerDepositosPorTipoCliente(clienteBuscado.getCtipoCliente());
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de depósitos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de datos de clientes.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}
return null;
}
public String verificarFechaVencimiento(){
try{
if(clienteBuscado.getMformaPago() == 'C'){
if(tipoDocumentoSeleccionadoLbl.getCtipoDocum().equals("FCO")){
mostrarCantDiasChequesLbl = true;
mostrarCantDiasImpresionChequesLbl = true;
mostrarPlazosChequesLbl = false;
}else{
mostrarCantDiasChequesLbl = false;
mostrarCantDiasImpresionChequesLbl = false;
mostrarPlazosChequesLbl = true;
}
}else{
plazosChequesLbl = 0;
mostrarCantDiasChequesLbl = true;
mostrarCantDiasImpresionChequesLbl = true;
mostrarPlazosChequesLbl = true;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al verificar la fecha de vencimiento.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
return null;
}
public String verificarFechaVencimientoImpresion(){
try{
if(clienteBuscado.getMformaPago() == 'C'){
if(tipoDocumentoSeleccionadoLbl.getCtipoDocum().equals("FCO")){
mostrarCantDiasChequesLbl = true;
mostrarCantDiasImpresionChequesLbl = true;
mostrarPlazosChequesLbl = false;
}else{
mostrarCantDiasChequesLbl = false;
mostrarCantDiasImpresionChequesLbl = false;
mostrarPlazosChequesLbl = true;
}
}else{
plazosChequesLbl = 0;
mostrarCantDiasChequesLbl = true;
mostrarCantDiasImpresionChequesLbl = true;
mostrarPlazosChequesLbl = true;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al verificar la fecha de vencimiento de impresión.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
return null;
}
public String visualizarFactura(){
//limpiarFormulario(); //inicialmente.
try{
FacturasPK facturaPK = new FacturasPK();
facturaPK.setCodEmpr(Short.parseShort("2"));
facturaPK.setCtipoDocum(facturaSeleccionada.getFacturasPK().getCtipoDocum());
facturaPK.setFfactur(facturaSeleccionada.getFacturasPK().getFfactur());
facturaPK.setNrofact(facturaSeleccionada.getFacturasPK().getNrofact());
facturaSeleccionada = facturasFacade.find(facturaPK);
if (facturaSeleccionada.getFacturasPK().getFfactur() == null) {
//cabecera de la factura
try {
List<Facturas> listado = facturasFacade.listadoDeFacturas(facturaSeleccionada.getFacturasPK().getCtipoDocum(), facturaSeleccionada.getFacturasPK().getNrofact());
if (listado.isEmpty()) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "El nro. de factura no existe."));
return null;
} else {
for (Facturas f : listado) {
tipoDocumentoSeleccionadoLbl = tiposDocumentosFacade.find(f.getFacturasPK().getCtipoDocum());
fechaFactLbl = f.getFacturasPK().getFfactur();
codClienteLbl = f.getCodCliente().getCodCliente();
nombreClienteLbl = f.getCodCliente().getXnombre();
nPuntoEstabLbl = Short.parseShort(String.valueOf(f.getFacturasPK().getNrofact()).substring(0, 1));
nPuntoExpedLbl = Short.parseShort(String.valueOf(f.getFacturasPK().getNrofact()).substring(1, 3));
nroFactLbl = Short.parseShort(String.valueOf(f.getFacturasPK().getNrofact()).substring(3));
ctipoVtaLbl = f.getCtipoVta();
codVendedorLbl = f.getEmpleados1().getEmpleadosPK().getCodEmpleado();
codDepositoLbl = f.getDepositos().getDepositosPK().getCodDepo();
fechaVencLbl = f.getFvenc();
fechaVencImpresLbl = f.getFvencImpre();
codCanalVentaLbl = f.getCodCanal().getCodCanal();
nroPedidoLbl = f.getPedidos() != null ? f.getPedidos().getPedidosPK().getNroPedido() : 0;
plazosChequesLbl = f.getNplazoCheque();
codEntregadorLbl = f.getEmpleados().getEmpleadosPK().getCodEmpleado();
observacionLbl = f.getXobs();
codZonaLbl = f.getZonas().getZonasPK().getCodZona();
totalExentas = f.getTexentas();
totalGravadas = f.getTgravadas();
totalIva = f.getTimpuestos();
totalFinal = f.getTtotal();
totalDescuentos = f.getTdescuentos();
}
//detalles de la factura
try {
listadoDetalle = new ArrayList<>();
String lFFacturaStr = dateToString(facturaSeleccionada.getFacturasPK().getFfactur());
List<FacturasDet> listadoDet = facturasDetFacade.obtenerDetallesDeFacturas(facturaSeleccionada.getFacturasPK().getCtipoDocum(), facturaSeleccionada.getFacturasPK().getNrofact(), lFFacturaStr);
for(FacturasDet f: listadoDet){
FacturaDetDto fddto = new FacturaDetDto();
fddto.setFacturasDet(f);
PromocionesPK promoPK = new PromocionesPK();
promoPK.setCodEmpr(Short.parseShort("2"));
promoPK.setNroPromo(f.getNroPromo());
fddto.setDescPromo(promocionesFacade.find(promoPK).getXdesc());
listadoDetalle.add(fddto);
}
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al obtener detalles de la factura.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al obtener datos de la factura.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}else{
String lFFacturaStr = dateToString(facturaSeleccionada.getFacturasPK().getFfactur());
List<Facturas> listado = facturasFacade.listadoDeFacturas(facturaSeleccionada.getFacturasPK().getCtipoDocum(), facturaSeleccionada.getFacturasPK().getNrofact(), lFFacturaStr);
if(listado.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "El nro. de factura no existe."));
return null;
}else{
for (Facturas f : listado) {
tipoDocumentoSeleccionadoLbl = tiposDocumentosFacade.find(f.getFacturasPK().getCtipoDocum());
fechaFactLbl = f.getFacturasPK().getFfactur();
codClienteLbl = f.getCodCliente().getCodCliente();
nombreClienteLbl = f.getCodCliente().getXnombre();
nPuntoEstabLbl = Short.parseShort(String.valueOf(f.getFacturasPK().getNrofact()).substring(0, 1));
nPuntoExpedLbl = Short.parseShort(String.valueOf(f.getFacturasPK().getNrofact()).substring(1, 3));
nroFactLbl = Long.parseLong(String.valueOf(f.getFacturasPK().getNrofact()).substring(3));
ctipoVtaLbl = f.getCtipoVta();
codVendedorLbl = f.getEmpleados1().getEmpleadosPK().getCodEmpleado();
codDepositoLbl = f.getDepositos().getDepositosPK().getCodDepo();
fechaVencLbl = f.getFvenc();
fechaVencImpresLbl = f.getFvencImpre();
codCanalVentaLbl = f.getCodCanal().getCodCanal();
nroPedidoLbl = f.getPedidos() != null ? f.getPedidos().getPedidosPK().getNroPedido() : 0;
plazosChequesLbl = f.getNplazoCheque();
codEntregadorLbl = f.getEmpleados().getEmpleadosPK().getCodEmpleado();
observacionLbl = f.getXobs();
codZonaLbl = f.getZonas().getZonasPK().getCodZona();
totalExentas = f.getTexentas();
totalGravadas = f.getTgravadas();
totalIva = f.getTimpuestos();
totalFinal = f.getTtotal();
totalDescuentos = f.getTdescuentos();
}
//detalles de la factura
try {
listadoDetalle = new ArrayList<>();
lFFacturaStr = dateToString(facturaSeleccionada.getFacturasPK().getFfactur());
List<FacturasDet> listadoDet = facturasDetFacade.obtenerDetallesDeFacturas(facturaSeleccionada.getFacturasPK().getCtipoDocum(), facturaSeleccionada.getFacturasPK().getNrofact(), lFFacturaStr);
for(FacturasDet f: listadoDet){
FacturaDetDto fddto = new FacturaDetDto();
fddto.setFacturasDet(f);
if(f.getNroPromo() != null){
PromocionesPK promoPK = new PromocionesPK();
promoPK.setCodEmpr(Short.parseShort("2"));
promoPK.setNroPromo(f.getNroPromo());
fddto.setDescPromo(promocionesFacade.find(promoPK).getXdesc());
}else{
fddto.setDescPromo(null);
}
listadoDetalle.add(fddto);
}
} catch (Exception e) {
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al obtener detalles de la factura.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al visualizar la factura.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
return null;
}
public String anularFactura(){
try{
FacturasPK facturaPK = new FacturasPK();
facturaPK.setCodEmpr(Short.parseShort("2"));
facturaPK.setCtipoDocum(facturaSeleccionada.getFacturasPK().getCtipoDocum());
facturaPK.setFfactur(facturaSeleccionada.getFacturasPK().getFfactur());
facturaPK.setNrofact(facturaSeleccionada.getFacturasPK().getNrofact());
facturaSeleccionada = facturasFacade.find(facturaPK);
long lNroFactura = facturaSeleccionada.getFacturasPK().getNrofact();
Date lFFactura = facturaSeleccionada.getFacturasPK().getFfactur();
String lFFacturaStr = dateToString(lFFactura);
String lCTipoDocum = facturaSeleccionada.getFacturasPK().getCtipoDocum();
TiposDocumentos td = tiposDocumentosFacade.find(lCTipoDocum);
if(facturaSeleccionada.getMestado() == 'A'){
if(facturaSeleccionada.getTnotas() > 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Esta factura tiene notas de créditos relacionadas."));
return null;
}
if(validarDatosAnulacion()){
try{
//String lFFactura = dateToString(fechaFactLbl);
listadoFacturasDet = facturasDetFacade.obtenerDetallesDeFacturas(lCTipoDocum, lNroFactura, lFFacturaStr);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al obtener los datos del detalle de factura.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
if(!listadoFacturasDet.isEmpty()){
for(FacturasDet f: listadoFacturasDet){
//INSERCION DE MOVIMIENTOS MERCADERIAS
try{
MovimientosMerca mov = new MovimientosMerca();
mov.setNroMovim(1L);
mov.setCodEmpr(Short.parseShort("2"));
mov.setCodMerca(f.getFacturasDetPK().getCodMerca());
mov.setCodDepo(facturaSeleccionada.getDepositos().getDepositosPK().getCodDepo());
if(td.getMindice() == null){
td.setMindice(Float.parseFloat("0"));
}
mov.setCantCajas(((f.getCantCajas() + f.getCajasBonif())*td.getMindice().intValue())*-1);
mov.setCantUnid(((f.getCantUnid()+ f.getUnidBonif())*td.getMindice().intValue())*-1);
mov.setPrecioCaja(f.getIprecioCaja());
mov.setPrecioUnidad(f.getIprecioUnidad());
long lGravadas = 0; BigDecimal lImpuestos = null;
if(f.getImpuestos().compareTo(BigDecimal.ZERO) == -1){
lGravadas = f.getIgravadas() - (f.getImpuestos().multiply(BigDecimal.valueOf(-1))).longValue();
}else{
lImpuestos = (f.getImpuestos().multiply(BigDecimal.valueOf(-1)));
}
long lExentas = f.getIexentas() * -1;
lGravadas = lGravadas * -1;
mov.setIgravadas(lGravadas);
mov.setIexentas(lExentas);
mov.setImpuestos(lImpuestos == null ? 0 : lImpuestos.longValue());
mov.setCodVendedor(facturaSeleccionada.getEmpleados1().getEmpleadosPK().getCodEmpleado());
mov.setCodCliente(facturaSeleccionada.getCodCliente().getCodCliente());
mov.setCodZona(facturaSeleccionada.getZonas().getZonasPK().getCodZona());
mov.setCodRuta(facturaSeleccionada.getCodRuta());
mov.setNpeso(BigDecimal.ZERO);
mov.setManulado(Short.parseShort("-1"));
mov.setFmovim(fechaAnulacionLbl);
mov.setCtipoDocum(lCTipoDocum);
mov.setNdocum(lNroFactura);
mov.setNrofact(lNroFactura);
mov.setFacCtipoDocum(lCTipoDocum);
mov.setFalta(new Date());
String usuario = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("usuario").toString();
mov.setCusuario(usuario);
mov.setCodEntregador(facturaSeleccionada.getEmpleados().getEmpleadosPK().getCodEmpleado());
movimientosMercaFacade.insertarMovimientosMerca(mov);
}catch(Exception e){
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al insertar en movimientos mercaderías.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
//reservar las cantidades en camion si el motivo es 15
if(cMotivoLbl == 15){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Actualizando reserva de mercadería "+f.getFacturasDetPK().getCodMerca()));
}
}
}
try{
Date lFFacturaMenosDos = DateUtil.sumarRestarDiasFecha(lFFactura, -2);
String lFFacturaMenosDosStr = dateToString(lFFacturaMenosDos);
List<MovimientoMercaDto> listadoMovimientosMerca = movimientosMercaFacade.obtenerMovimientosMercaderiasPorTipoNroFechaMovimiento(lCTipoDocum, lNroFactura, lFFacturaMenosDosStr);
if(!listadoMovimientosMerca.isEmpty()){
for(MovimientoMercaDto m: listadoMovimientosMerca){
if(m.getCantCajas() != 0 || m.getCantUnid() != 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Sin movimientos mercaderías de la factura anulada."));
return null;
}
}
}
}catch(Exception e){
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al obtener datos en movimientos mercaderías.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
//INSERCION EN CUENTAS CORRIENTES
if(td.getMafectaCtacte() == 'S'){
try{
CuentasCorrientes c = new CuentasCorrientes();
c.setCodEmpr(Short.parseShort("2"));
c.setCtipoDocum(lCTipoDocum);
c.setFmovim(facturaSeleccionada.getFacturasPK().getFfactur());
c.setNdocumCheq(String.valueOf(lNroFactura));
c.setIpagado(0);
c.setIretencion(0);
c.setCodCliente(facturaSeleccionada.getCodCliente());
c.setIsaldo(facturaSeleccionada.getTtotal());
c.setManulado(Short.parseShort("-1"));
c.setTexentas(facturaSeleccionada.getTexentas()*-1);
long lTImpuestos = 0; long lTGravadas = 0;
lTImpuestos = facturaSeleccionada.getTimpuestos();
if(lTImpuestos < 0){
lTImpuestos *= -1;
lTGravadas -= lTImpuestos;
}
lTGravadas *= -1;
c.setTgravadas(lTGravadas);
lTImpuestos = facturaSeleccionada.getTimpuestos() < 0 ? facturaSeleccionada.getTimpuestos() : (facturaSeleccionada.getTimpuestos() * -1);
c.setTimpuestos(lTImpuestos);
c.setFvenc(facturaSeleccionada.getFvenc());
c.setCtipoDocum(lCTipoDocum);
c.setNrofact(lNroFactura);
if(td.getMindice() == null){
td.setMindice(Float.parseFloat("0"));
}
c.setMindice((short)(td.getMindice().intValue() * -1));
c.setFfactur(facturaSeleccionada.getFacturasPK().getFfactur());
cuentasCorrientesFacade.insertarCuentas(c);
}catch(Exception e){
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al insertar en cuentas corrientes.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
//ACTUALIZACION DE PEDIDOS
try{
List<Facturas> listado = new ArrayList<>();
if(facturaSeleccionada.getPedidos() != null){
listado = facturasFacade.obtenerFacturasActivasPorNroPedidoYFactura(facturaSeleccionada.getPedidos().getPedidosPK().getNroPedido(), lNroFactura);
}
if(listado.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "El Pedido no cambia de estado. Existen otras facturas a anular."));
}else{
try{
pedidosFacade.actualizarPedidosPorNro(facturaSeleccionada.getPedidos().getPedidosPK().getNroPedido());
}catch(Exception e){
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al actualizar pedidos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}catch(Exception e){
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al obtener datos de facturas.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
//actualizar facturas
try {
String lFAnulacion = dateToString(fechaAnulacionLbl);
String usuario = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("usuario").toString();
facturasFacade.actualizarFacturas(lFAnulacion, usuario, cMotivoLbl, lFFacturaStr, lNroFactura, lCTipoDocum);
} catch (Exception e) {
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al actualizar facturas.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Factura anulada.", ""));
limpiarFormulario();
RequestContext.getCurrentInstance().execute("PF('dlgAnularFactura').hide();");
return null;
}
}else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Estado inválido de la factura."));
return null;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al anular la factura.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
return null;
}
public void inicializarDatosAnulacion(){
fechaAnulacionLbl = null;
cMotivoLbl = 0;
}
private boolean validarDatosAnulacion(){
if(fechaAnulacionLbl == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención", "Debe ingresar fecha de anulación."));
return false;
}else{
if(cMotivoLbl == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención", "Debe seleccionar un motivo de anulación."));
return false;
}else{
if(fechaAnulacionLbl.compareTo(DateUtil.sumarRestarDiasFecha(fechaFactLbl, 2)) == 1){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atención", "Fecha máxima de anulación: "+DateUtil.sumarRestarDiasFecha(fechaFactLbl, 2)));
return false;
}
}
}
return true;
}
public void borrarFilaFactura(FacturaDetDto facturaABorrar){
try{
Iterator itr = listadoDetalle.iterator();
while (itr.hasNext()) {
FacturaDetDto facturaDetDtoEnLista = (FacturaDetDto) itr.next();
if(facturaDetDtoEnLista.getFacturasDet().getFacturasDetPK().getCtipoDocum().equals(facturaABorrar.getFacturasDet().getFacturasDetPK().getCtipoDocum()) &&
facturaDetDtoEnLista.getFacturasDet().getFacturasDetPK().getNrofact() == facturaABorrar.getFacturasDet().getFacturasDetPK().getNrofact() &&
facturaDetDtoEnLista.getFacturasDet().getFacturasDetPK().getCodMerca().equals(facturaABorrar.getFacturasDet().getFacturasDetPK().getCodMerca()) &&
facturaDetDtoEnLista.getFacturasDet().getFacturasDetPK().getFfactur().compareTo(facturaABorrar.getFacturasDet().getFacturasDetPK().getFfactur()) == 0){
itr.remove();
calcularTotales();
return;
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al borrar un detalle de la grilla de facturas.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
}
public String agregarMercaderia(){
try{
if(verificarArticulo()){
FacturasDet f = new FacturasDet();
FacturasDetPK pk = new FacturasDetPK();
pk.setCodEmpr(Short.parseShort("2"));
pk.setCodMerca(codMercaDet);
pk.setCtipoDocum(tipoDocumentoSeleccionadoLbl.getCtipoDocum());
pk.setFfactur(fechaFactLbl);
pk.setNrofact(obtenerNroFacturaCompleto());
f.setFacturasDetPK(pk);
f.setXdesc(descMercaDet);
f.setCantCajas(cantCajasDet);
f.setCantUnid(cantUnidDet);
f.setIprecioCaja(precioCajaDet);
f.setIprecioUnidad(precioUnidDet);
f.setIgravadas(gravadasDet);
f.setIexentas(exentasDet);
f.setIdescuentos(descuentosDet);
f.setImpuestos(BigDecimal.valueOf(impuestosDet));
f.setItotal(gravadasDet);
f.setPimpues(pimpuesDet); //tipo de iva (5, 10, etc.)
f.setPdesc(pdescDet); //% de descuento.
f.setNroPromo(nroPromoDet); //nro de promocion.
f.setCajasBonif(cantCajasBonifDet);
f.setUnidBonif(cantUnidBonifDet);
FacturaDetDto fdto = new FacturaDetDto();
fdto.setFacturasDet(f);
fdto.setnRelacion(nRelacionDet);
fdto.setDescPromo(descPromoDet);
fdto.setmPromoPackDet(mPromoPackDet);
fdto.setCodSublineaDet(codSublineaDet);
fdto.setnPesoCajas(nPesoCajaDet);
fdto.setnPesoUnidad(nPesoUnidadDet);
listadoDetalle.add(fdto);
calcularTotales();
//limpiar variables
codMercaDet = null;
descMercaDet = null;
cantCajasDet = 0;
cantUnidDet = 0;
cantCajasBonifDet = 0;
cantUnidBonifDet = 0;
pdescDet = BigDecimal.ZERO;
nroPromoDet = null;
descPromoDet = null;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al agregar una mercadería.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
return null;
}
public boolean verificarArticulo() {
List<Existencias> listado = new ArrayList<>();
long hayUnidad = 0;
Mercaderias mercaderia = null;
try{
if(pdescDet.compareTo(BigDecimal.ZERO) != 0){
//si hay descuento, es obligatorio el nro. de promocion.
if(nroPromoDet == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Debe ingresar el nro. de promoción."));
return false;
}
}
//Recupera la existencia actual
listado = existenciasFacade.buscarPorCodigoDepositoOrigenYArticulo(codDepositoLbl, codMercaDet);
if(listado.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "No existe el articulo en depósito "+codDepositoLbl));
return false;
}else{
//Busca Mercaderia
try{
mercaderia = mercaderiasFacade.buscarPorCodigoMercaderia(codMercaDet);
if(mercaderia == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "La mercadería no existe."));
return false;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al leer datos de mercaderías.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
//BUSCA SI YA EXISTE EN LA FACTURA
if(!verificarMecaderiaDuplicada(codMercaDet, obtenerNroFacturaCompleto())){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Mercadería ya existe en la factura."));
return false;
}
//CALCULAR EXISTENCIA
for(Existencias e: listado){
long unidadesExist = e.getCantCajas()*e.getNrelacion() + e.getCantUnid();
long unidadesReser = e.getReserCajas()*e.getNrelacion() + e.getReserUnid();
hayUnidad = unidadesExist - unidadesReser;
nRelacionDet = e.getMercaderias().getNrelacion() == null ? 0 : e.getMercaderias().getNrelacion().shortValue();
nPesoCajaDet = e.getMercaderias().getNpesoCaja();
nPesoUnidadDet = e.getMercaderias().getNpesoUnidad();
mGravExeDet = e.getMercaderias().getMgravExe();
if(hayUnidad < ((cantCajasDet * e.getNrelacion())+cantUnidDet)){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Solo existen "+hayUnidad+" en depósito."));
return false;
}
}
//Verifica Canal de Venta
//la mercadería debe existir en merca_canales
try{
if(!mercaderiasFacade.buscarMercaderiaEnCanalDeVenta(codMercaDet, codCanalVentaLbl)){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "La mercadería no está relacionada con el canal: "+codCanalVentaLbl));
return false;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al leer datos de mercaderías_canales.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
//PRECIOS
try{
String lFFactura = dateToString(fechaFactLbl);
List<Precios> listadoPrecios = preciosFacade.obtenerPreciosPorFechaFacturaCodigoMercaYTipoVenta(lFFactura, codMercaDet, ctipoVtaLbl);
if(listadoPrecios.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "No existe precio vigente para: cod_empresa = 2, cod_merca: "+codMercaDet+", y tipo de venta: "+ctipoVtaLbl));
return false;
}else{
for(Precios p: listadoPrecios){
if(p.getIprecioCaja() <= 0 || p.getIprecioUnidad() <= 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Precio caja/unidad es igual a cero."));
return false;
}else{
precioCajaDet = p.getIprecioCaja();
precioUnidDet = p.getIprecioUnidad();
precioCajaSimDet = precioCajaDet;
precioUnidadSimDet = precioUnidDet;
}
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al leer datos de precios.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
//El precio recuperado es SIN IVA
//Calcular el impuesto
if(mGravExeDet == 'G'){ //si el tipo de IVA de la mercaderia es gravada.
String lFFactura = dateToString(fechaFactLbl);
HashMap<String,Long> resultado = calcularPrecio(codMercaDet,
precioCajaDet,
precioUnidDet,
ctipoVtaLbl,
lFFactura);
long calculaBien = resultado.get("calcula_bien");
if(calculaBien == 0){
return false;
}
precioCajaDet = resultado.get("precio_caja");
precioUnidDet = resultado.get("precio_unidad");
pimpuesDet = BigDecimal.valueOf(resultado.get("pimpuest"));
}
//Validación de columna Cajas
//validar cantidad con el stock : la columna "hay_unid" se cargó en la validación de la mercadería
//iexentas es la columna que se visualiza en pantalla
if(mGravExeDet == 'E'){
exentasDet = precioCajaDet * cantCajasDet + precioUnidDet * cantUnidDet;
exentasDet = exentasDet - (exentasDet * (pdescDet.longValue())/100);
}else{
/*
** igravadas2 NO se visualiza en pantalla . Es para guardar el importe sin el impuesto (pre_caja_sim es el precio asi como está guardado en la tabla PRECIOS
*/
gravadas2Det = precioCajaSimDet * cantCajasDet + precioUnidadSimDet * cantUnidDet;
tipoDocumentoSeleccionadoLbl = tipoDocumentoEnMemoria.get("tipo_documento");
// igravadas es la columna que se visualiza en pantalla
if(tipoDocumentoSeleccionadoLbl.getMincluIva() == 'S'){
gravadasDet = precioCajaDet * cantCajasDet + precioUnidDet * cantUnidDet;
impuestosDet = pimpuesDet.compareTo(BigDecimal.valueOf(10)) == 0 ? (gravadasDet/11) : (gravadasDet/21);
}else{
gravadasDet = gravadas2Det;
impuestosDet = gravadas2Det * (pimpuesDet.longValue()/100);
}
//Aplica el porcentaje ingresado
gravadasDet = gravadasDet - (gravadasDet * (pdescDet.longValue())/100);
//Calcula el impuesto nuevamente ya con el descuento aplicado
if(tipoDocumentoSeleccionadoLbl.getMincluIva() == 'S'){
impuestosDet = pimpuesDet.compareTo(BigDecimal.valueOf(10)) == 0 ? (gravadasDet/11) : (gravadasDet/21);
}else{
gravadasDet = gravadas2Det;
impuestosDet = gravadas2Det * (pimpuesDet.longValue()/100);
}
}
//nPesoCajaDet = cantCajasDet * nPesoCajaDet;
//Validación de columna Unidades
//validar cantidad con el stock : la columna "hay_unid" se cargó en la validación de la mercadería
if(mGravExeDet == 'E'){
exentasDet = precioCajaDet * cantCajasDet + precioUnidDet * cantUnidDet;
//Aplica el descuento
exentasDet = exentasDet - (exentasDet * (pdescDet.longValue())/100);
}else{
//guardar el monto sin impuesto
gravadas2Det = precioCajaSimDet * cantCajasDet + precioUnidadSimDet * cantUnidDet;
// igravadas es la columna que se visualiza en pantalla
if(tipoDocumentoSeleccionadoLbl.getMincluIva() == 'S'){
gravadasDet = precioCajaDet * cantCajasDet + precioUnidDet * cantUnidDet;
impuestosDet = pimpuesDet.compareTo(BigDecimal.valueOf(10)) == 0 ? (gravadasDet/11) : (gravadasDet/21);
}else{
gravadasDet = gravadas2Det;
impuestosDet = gravadas2Det * (pimpuesDet.longValue()/100);
}
// Aplica el descuento
gravadasDet = gravadasDet - (gravadasDet * (pdescDet.longValue())/100);
gravadas2Det = gravadas2Det - (gravadas2Det * (pdescDet.longValue())/100);
//vuelve a calcular el impuesto con el descuento aplicado
if(tipoDocumentoSeleccionadoLbl.getMincluIva() == 'S'){
impuestosDet = pimpuesDet.compareTo(BigDecimal.valueOf(10)) == 0 ? (gravadasDet/11) : (gravadasDet/21);
}else{
gravadasDet = gravadas2Det;
impuestosDet = gravadas2Det * (pimpuesDet.longValue()/100);
}
}
//Validación de columna % de Descuento
//Validar que cajas y/o unidades se hayan ingresado
if(cantCajasDet <= 0 && cantUnidDet <= 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Ingrese cantidad cajas/unidades."));
return false;
}else{
mPromoPackDet = 'N';
codSublineaDet = mercaderia.getCodSublinea().getCodSublinea();
// Recalcular los importes de exentas y gravadas aplicando el descuento
if(mGravExeDet == 'E'){
exentasDet = precioCajaDet * cantCajasDet + precioUnidDet * cantUnidDet;
descuentosDet = descuentosDet + (exentasDet * (pdescDet.longValue())/100);
//Aplica el descuento
exentasDet = exentasDet - (exentasDet * (pdescDet.longValue())/100);
}
if(gravadasDet != 0){
descuentosDet = descuentosDet + (gravadasDet * (pdescDet.longValue())/100);
gravadasDet = gravadasDet - (gravadasDet * (pdescDet.longValue())/100);
gravadas2Det = gravadas2Det - (gravadas2Det * (pdescDet.longValue())/100);
if(tipoDocumentoSeleccionadoLbl.getMincluIva() == 'S'){
impuestosDet = pimpuesDet.compareTo(BigDecimal.valueOf(10)) == 0 ? (gravadasDet/11) : (gravadasDet/21);
}else{
gravadasDet = gravadas2Det;
impuestosDet = gravadas2Det * (pimpuesDet.longValue()/100);
}
}
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al verificar una mercadería.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
return true;
}
public void calcularTotales(){
//Procedimiento interno Suma Total
//suma las columnas EXENTAS, GRAVADAS, IMPUESTOS
totalExentas = 0; totalGravadas = 0; totalIva = 0; totalDescuentos = 0; totalFinal = 0;
for(FacturaDetDto f: listadoDetalle){
totalExentas += f.getFacturasDet().getIexentas();
totalGravadas += f.getFacturasDet().getIgravadas();
totalIva += f.getFacturasDet().getImpuestos().longValue();
totalDescuentos += f.getFacturasDet().getIdescuentos();
}
totalFinal = totalExentas + totalGravadas + totalIva;
}
public HashMap<String,Long> calcularPrecio( String lCodMerca,
long lPrecioCaja,
long lPrecioUnidad,
Character lTipoVenta,
String lFechaFactura){
HashMap<String,Long> retorno = new HashMap<>();
BigDecimal gImpuesto = BigDecimal.ZERO;
try{
try{
List<Impuestos> listadoImpuestos = mercaImpuestosFacade.obtenerTipoImpuestoPorMercaderia(codMercaDet);
if(!listadoImpuestos.isEmpty()){
for(Impuestos i: listadoImpuestos){
if(i.getPimpues().compareTo(BigDecimal.ZERO) > 0 || i.getIfijo().compareTo(Integer.parseInt("0")) > 0){
lPrecioCaja = ((new BigDecimal(lPrecioCaja).multiply(i.getPimpues().add(new BigDecimal("1")))).add(new BigDecimal(i.getIfijo()))).longValue();
//lPrecioUnidad = (lPrecioUnidad * (i.getPimpues().longValue() + 1)) + i.getIfijo().longValue();
lPrecioUnidad = ((new BigDecimal(lPrecioUnidad).multiply(i.getPimpues().add(new BigDecimal("1")))).add(new BigDecimal(i.getIfijo()))).longValue();
}
gImpuesto = i.getPimpues().multiply(BigDecimal.valueOf(100));
}
}
List<RetornosPrecios> listadoRetornos = retornosPreciosFacade.obtenerRetornosPrecios(lCodMerca, lTipoVenta, lFechaFactura);
if(!listadoRetornos.isEmpty()){
for(RetornosPrecios rp: listadoRetornos){
lPrecioCaja = lPrecioCaja - rp.getIretornoCaja();
lPrecioUnidad = lPrecioUnidad - rp.getIretornoUnidad();
}
}
retorno.put("precio_caja", lPrecioCaja);
retorno.put("precio_unidad", lPrecioUnidad);
retorno.put("pimpuest", gImpuesto.longValue());
retorno.put("calcula_bien", Long.parseLong("1"));
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la generación del cursor de impuestos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
retorno.put("precio_caja", lPrecioCaja);
retorno.put("precio_unidad", lPrecioUnidad);
retorno.put("pimpuest", gImpuesto.longValue());
retorno.put("calcula_bien", Long.parseLong("0"));
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al calcular el precio.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
retorno.put("precio_caja", lPrecioCaja);
retorno.put("precio_unidad", lPrecioUnidad);
retorno.put("pimpuest", gImpuesto.longValue());
retorno.put("calcula_bien", Long.parseLong("0"));
}
return retorno;
}
public boolean verificarMecaderiaDuplicada(String lCodMerca, long lNroFact){
for(FacturaDetDto f: listadoDetalle){
if(f.getFacturasDet().getFacturasDetPK().getCodMerca().equals(lCodMerca) && f.getFacturasDet().getFacturasDetPK().getNrofact() == lNroFact){
return false;
}
}
return true;
}
public String agregarNuevaFactura(){
try{
if(clienteBuscado.getMformaPago() == 'C' && !tipoDocumentoSeleccionadoLbl.getCtipoDocum().equals("FCO")){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Tipo inválido de factura."));
return null;
}
if(clienteBuscado.getMformaPago() == 'F' && !tipoDocumentoSeleccionadoLbl.getCtipoDocum().equals("FCR")){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Tipo inválido de factura."));
return null;
}
if(clienteBuscado.getMformaPago() != 0 && !tipoDocumentoSeleccionadoLbl.getCtipoDocum().equals("FCO")){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Tipo inválido de factura."));
return null;
}
//no ingresó el nro de factura
if(nroFactLbl == 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Nro factura inválido."));
return null;
}
//total = 0 o negativo
if(totalFinal == 0 || totalFinal < 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Monto total inválido."));
return null;
}
//validar que el establecimiento corresponda al deposito relacionado a la factura.. Buscar en la tabla deposito el punto de establecimiento correspondiente
depositoSeleccionado = depositoEnMemoria.get("deposito");
if(depositoSeleccionado.getNpuntoEst().compareTo(nPuntoEstabLbl) != 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "El establecimiento debe ser "+depositoSeleccionado.getNpuntoEst()));
return null;
}
//validar el limite de compra del cliente
if(clienteBuscado.getIlimiteCompra() > 0){
long deuda = 0;
deuda = calcularDeudaCliente();
if((deuda + totalFinal) > clienteBuscado.getIlimiteCompra()){
long dif = (deuda + totalFinal) - clienteBuscado.getIlimiteCompra();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Límite de compra superado en "+dif));
return null;
}
}
//verificar si ya existe el nro. de factura
List<Facturas> listadoFacturas = new ArrayList<>();
long nroFacturaCompleto = 0;
try{
String fechaFacturaStr = dateToString(fechaFactLbl);
nroFacturaCompleto = obtenerNroFacturaCompleto();
listadoFacturas = facturasFacade.obtenerFacturasPorNroYFecha(nroFacturaCompleto, fechaFacturaStr);
if(!listadoFacturas.isEmpty()){
if(listadoFacturas.size() > 0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Ya existe factura de venta."));
return null;
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al obtener facturas.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
//validar rango de documentos
try{
List<RangosDocumentos> listadoRangos = rangosDocumentosFacade.obtenerRangosDeDocumentos(tipoDocumentoSeleccionadoLbl.getCtipoDocum(), nroFacturaCompleto);
if(listadoRangos.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Nro. no definido como factura formulario continuo en rangos documentos."));
return null;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al obtener rango de documentos.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
//validar existencia
//para cada detalle
for(FacturaDetDto d: listadoDetalle){
if(!d.getFacturasDet().getFacturasDetPK().getCodMerca().equals("") || d.getFacturasDet().getFacturasDetPK().getCodMerca() != null){
List<Existencias> listado = new ArrayList<>();
try{
listado = existenciasFacade.buscarPorCodigoDepositoOrigenYArticulo(codDepositoLbl, d.getFacturasDet().getFacturasDetPK().getCodMerca());
if(listado.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "No existe el articulo en depósito "+codDepositoLbl));
return null;
}else{
for(Existencias e: listado){
long unidadesExist = e.getCantCajas()*e.getNrelacion() + e.getCantUnid();
long unidadesReser = e.getReserCajas()*e.getNrelacion() + e.getReserUnid();
long hayUnidad = unidadesExist - unidadesReser;
if(hayUnidad < ((d.getFacturasDet().getCantCajas() * e.getNrelacion())+d.getFacturasDet().getCantUnid())){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Solo existen "+hayUnidad+" en depósito."));
return null;
}
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al validar existencia.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}
//Calcular total factura sumando los detalles
long lTotalImpuestos = 0;
tipoDocumentoSeleccionadoLbl = tipoDocumentoEnMemoria.get("tipo_documento");
if(tipoDocumentoSeleccionadoLbl.getMincluIva() == 'S'){
lTotalImpuestos = totalIva * -1;
totalFinal = totalExentas + totalGravadas;
}else{
lTotalImpuestos = totalIva;
totalFinal = totalExentas + totalGravadas + lTotalImpuestos;
}
if(!tipoDocumentoSeleccionadoLbl.getCtipoDocum().equals("FCR")){
fechaVencLbl = null;
fechaVencImpresLbl = null;
}
Short lCodRuta = clienteBuscado.getCodRuta();
long lTGravadas10 = 0; long lGravadas10 = 0;
long lTGravadas5 = 0; long lGravadas5 = 0;
long lTIva10 = 0; long lIva5 = 0;
long lTIva5 = 0; long lIva10 = 0;
//Calcular total IVA 10 e IVA 5 de los detalles (en memoria)
for (FacturaDetDto f : listadoDetalle) {
if (f.getFacturasDet().getFacturasDetPK().getNrofact() == obtenerNroFacturaCompleto()
&& f.getFacturasDet().getFacturasDetPK().getCtipoDocum().equals(tipoDocumentoSeleccionadoLbl.getCtipoDocum())) {
if (f.getFacturasDet().getPimpues().compareTo(BigDecimal.valueOf(10)) == 0) {
lGravadas10 += f.getFacturasDet().getIgravadas();
lIva10 += f.getFacturasDet().getImpuestos() == null ? 0 : f.getFacturasDet().getImpuestos().longValue();
}
if (f.getFacturasDet().getPimpues().compareTo(BigDecimal.valueOf(5)) == 0) {
lGravadas5 += f.getFacturasDet().getIgravadas();
lIva5 += f.getFacturasDet().getImpuestos() == null ? 0 : f.getFacturasDet().getImpuestos().longValue();
}
}
}
lTGravadas10 = lGravadas10;
lTGravadas5 = lGravadas5;
lTIva10 = lIva10;
lTIva5 = lIva5;
String lXFactura = obtenerNroFacturaCompletoConFormato();
long lNewfactura = obtenerNroFacturaCompleto();
String lXRuc = "";
if(clienteBuscado.getXruc().equals("") || clienteBuscado.getXruc() == null){
if(clienteBuscado.getXcedula() != null || clienteBuscado.getXcedula() != 0){
lXRuc = "C.I:"+clienteBuscado.getXcedula();
}
}else{
lXRuc = clienteBuscado.getXruc();
}
String lFFactura = dateToString(fechaFactLbl);
String lFVenc = fechaVencLbl != null ? dateToString(fechaVencLbl) : "";
String lFVencImpre = fechaVencImpresLbl != null ? dateToString(fechaVencImpresLbl) : "";
//insertar en FACTURAS
try{
facturasFacade.insertarFactura( tipoDocumentoSeleccionadoLbl.getCtipoDocum(),
lNewfactura,
codClienteLbl,
codCanalVentaLbl,
codDepositoLbl,
codZonaLbl,
lCodRuta,
lFFactura,
ctipoVtaLbl,
observacionLbl,
codVendedorLbl,
totalExentas,
totalGravadas,
lTotalImpuestos,
totalFinal,
codEntregadorLbl,
totalFinal,
totalDescuentos,
direccionLbl == null ? "" : direccionLbl,
razonSocialLbl == null ? "" : razonSocialLbl,
lXRuc == null ? "" : lXRuc,
telefonoLbl == null ? "" : telefonoLbl,
ciudadLbl == null ? "" : ciudadLbl,
lFVenc,
lFVencImpre,
lTGravadas10,
lTGravadas5,
BigDecimal.valueOf(lTIva10),
BigDecimal.valueOf(lTIva5),
lXFactura,
plazosChequesLbl,
nroPedidoLbl == 0 ? null: nroPedidoLbl);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al insertar en facturas.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
if(tipoDocumentoSeleccionadoLbl.getMafectaCtacte() == 'S'){
//INSERTAR EN CUENTAS CORRIENTES
try{
if(lTotalImpuestos < 0){
lTotalImpuestos *= -1;
totalGravadas -= lTotalImpuestos;
}
CuentasCorrientes c = new CuentasCorrientes();
c.setCodEmpr(Short.parseShort("2"));
c.setCtipoDocum(tipoDocumentoSeleccionadoLbl.getCtipoDocum());
c.setFvenc(fechaVencLbl);
c.setFmovim(fechaFactLbl);
c.setNdocumCheq(String.valueOf(obtenerNroFacturaCompleto()));
c.setIpagado(0);
c.setIretencion(0);
c.setCodCliente(clienteBuscado);
c.setIsaldo(totalFinal);
c.setManulado(Short.parseShort("1"));
c.setTexentas(totalExentas);
c.setTgravadas(totalGravadas);
c.setTimpuestos(lTotalImpuestos);
c.setCtipoDocum(tipoDocumentoSeleccionadoLbl.getCtipoDocum());
c.setNrofact(obtenerNroFacturaCompleto());
if(tipoDocumentoSeleccionadoLbl.getMdebCred() == 'D'){
c.setMindice(Short.parseShort("1"));
}else{
c.setMindice(Short.parseShort("-1"));
}
c.setFfactur(fechaFactLbl);
cuentasCorrientesFacade.insertarCuentas(c);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al insertar en cuentas corrientes.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
//INSERTAR DETALLES
for(FacturaDetDto f: listadoDetalle){
if(f.getFacturasDet().getFacturasDetPK().getCodMerca() != null || !f.getFacturasDet().getFacturasDetPK().getCodMerca().equals("")){
long lExentas = f.getFacturasDet().getIexentas();
long lImpuestos = f.getFacturasDet().getImpuestos() != null ? f.getFacturasDet().getImpuestos().longValue() : 0;
long lGravadas = f.getFacturasDet().getIgravadas();
long lPrecioCaja = 0, lPrecioUnid = 0;
long lItotal = 0;
if(tipoDocumentoSeleccionadoLbl.getMincluIva() == 'S'){
lImpuestos = lImpuestos * -1;
lPrecioCaja = f.getFacturasDet().getIprecioCaja();
lPrecioUnid = f.getFacturasDet().getIprecioUnidad();
lItotal = lGravadas + lExentas;
}else{
lPrecioCaja = f.getFacturasDet().getIprecioCaja();
lPrecioUnid = f.getFacturasDet().getIprecioUnidad();
lItotal = lGravadas + lExentas + lImpuestos;
}
int lCantCajas = f.getFacturasDet().getCantCajas();
int lCantUnid = f.getFacturasDet().getCantUnid();
long lPDescLong = f.getFacturasDet().getPdesc() != null ? f.getFacturasDet().getPdesc().longValue() : 0;
long lIDescuentos = f.getFacturasDet().getIdescuentos();
String lCodMerca = f.getFacturasDet().getFacturasDetPK().getCodMerca();
String lXDesc = f.getFacturasDet().getXdesc();
String lCTipo = tipoDocumentoSeleccionadoLbl.getCtipoDocum();
BigDecimal lPImpues = f.getFacturasDet().getPimpues();
long nPeso = 0;
//todas las filas de la grilla si tiene descuento debe tener una promo que respalde el descuento
if(lPDescLong > 0 || f.getmPromoPackDet() == 'S'){
if(f.getFacturasDet().getNroPromo() == null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Ingrese el nro. de promoción"));
return null;
}else{
try{
List<Promociones> listadoPromo = promocionesFacade.findByNroPromoYFechaFactura(f.getFacturasDet().getNroPromo(), lFFactura);
if(listadoPromo.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "No existe promoción"));
return null;
}
if(lCantCajas > 0 || lCantUnid > 0){
//validar promocion
if(f.getmPromoPackDet() == 'N'){
if(validarPromocion(f.getFacturasDet().getNroPromo(),
codZonaLbl,
f.getFacturasDet().getFacturasDetPK().getCodMerca(),
lCantCajas,
lCantUnid,
f.getFacturasDet().getUnidBonif(),
clienteBuscado.getCtipoCliente(),
f.getFacturasDet().getPdesc(),
f.getCodSublineaDet(),
ctipoVtaLbl,
"",
f.getnRelacion(),
f.getFacturasDet().getFacturasDetPK().getNrofact()));
}else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Ingrese cajas/unidades facturadas."));
return null;
}
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al obtener promociones.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}
nroPromoDet = (f.getFacturasDet().getNroPromo() == null || f.getFacturasDet().getNroPromo().compareTo(Integer.parseInt("0")) == 0) ? null : f.getFacturasDet().getNroPromo();
//INSERTA EL DETALLE
try{
facturasDetFacade.insertarFacturasDet( lCTipo,
obtenerNroFacturaCompleto(),
lCodMerca,
lXDesc,
lCantCajas,
lCantUnid,
lPrecioCaja,
lPrecioUnid,
lExentas,
lGravadas,
lImpuestos,
lIDescuentos,
lItotal,
BigDecimal.valueOf(lPDescLong),
lPImpues,
nroPromoDet,
lFFactura);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al insertar un detalle de facturas.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
//INSERTAR EN MOVIMIENTOS MERCA
try{
MovimientosMerca mov = new MovimientosMerca();
mov.setNroMovim(1L);
mov.setCodEmpr(Short.parseShort("2"));
mov.setCodMerca(lCodMerca);
mov.setCodDepo(codDepositoLbl);
mov.setCantCajas(Long.parseLong(String.valueOf(lCantCajas)));
mov.setCantUnid(Long.parseLong(String.valueOf(lCantUnid)));
mov.setPrecioCaja(lPrecioCaja);
mov.setPrecioUnidad(lPrecioUnid);
mov.setIgravadas(lGravadas);
mov.setIexentas(lExentas);
mov.setImpuestos(lImpuestos);
mov.setCodVendedor(codVendedorLbl);
mov.setCodCliente(codClienteLbl);
mov.setCodZona(codZonaLbl);
mov.setCodRuta(codRutaLbl);
mov.setNpeso(BigDecimal.valueOf(nPeso));
mov.setManulado(Short.parseShort("1"));
mov.setFmovim(fechaFactLbl);
mov.setCtipoDocum(lCTipo);
mov.setNdocum(obtenerNroFacturaCompleto());
mov.setNrofact(obtenerNroFacturaCompleto());
mov.setFacCtipoDocum(lCTipo);
mov.setCodEntregador(codEntregadorLbl);
mov.setFalta(new Date());
String usuario = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("usuario").toString();
mov.setCusuario(usuario);
movimientosMercaFacade.insertarMovimientosMerca(mov);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al insertar un movimiento merca.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Datos grabados con éxito."));
limpiarFormulario(); //volvemos a instanciar
RequestContext.getCurrentInstance().execute("PF('dlgNuevFactura').hide();");
return null;
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al agregar una nueva factura.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return null;
}
}
public boolean validarPromocion(Integer lNroPromo,
String lCodZona,
String lCodMerca,
int lCantCajas,
int lCantUnid,
long lBonifPedido,
Character lCTipoCliente,
BigDecimal lPDescPedido,
Short codSubLinea,
Character lCTipoVenta,
String lAccion,
Short nRelacion,
long lNroFactura){
try{
int lBonifPedidoY = 0; long lTotalKilos = 0;
int lCantCajasY = 0; int lCantUnidY = 0; int lTotalUnidPedidoY = 0; lBonifPedidoY = 0;
int lTotalUnidPedido = lCantCajas * nRelacion + lCantUnid;
Date lFPedido = fechaFactLbl;
lCTipoVenta = ctipoVtaLbl;
int lError = 1;
try{
String lFPedidoStr = dateToString(lFPedido);
List<PromocionesDetDto> promociones = promocionesFacade.obtenerPromociones(codSubLinea, lCodZona, lNroPromo, lCTipoVenta, lFPedidoStr, lCodMerca);
if(promociones.isEmpty()){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "No existen promociones para esta mercadería."));
return false;
}
for(PromocionesDetDto p: promociones){
if(p.getmTodos() == 'S'){
if(lAccion.equals("") || lAccion == null){
descPromoDet = p.getxDesc();
nroPromoDet = p.getNroPromo();
return true;
}
List<PromocionDto> listadoMercaPromo = new ArrayList<>();
try{
listadoMercaPromo = promocionesFacade.obtenerMercaderiasPromociones(lNroPromo);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de mercaderías de promoción.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
try{
listadoMercaPromo = promocionesFacade.obtenerMercaderiasPromocionesPorSublinea(lNroPromo);
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error en la lectura de mercaderías de promoción por sublinea.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
List<String> listaCodMercaDet = new ArrayList<>();
for(PromocionDto pro: listadoMercaPromo){
if(pro.getXdesc().equals("") || pro.getXdesc() == null){
listaCodMercaDet.add(p.getCodMerca());
}
}
//se verifica todas las mercaderias sin la marca de Y
lCantCajas = 0; lCantUnid = 0; lTotalUnidPedido = 0; lBonifPedido = 0;
for(FacturaDetDto fddto: listadoDetalle){
if( fddto.getFacturasDet().getFacturasDetPK().getNrofact() == lNroFactura &&
verificarCodMercaEnListado(fddto.getFacturasDet().getFacturasDetPK().getCodMerca(), listaCodMercaDet)){
lCantCajas += fddto.getFacturasDet().getCantCajas();
lTotalUnidPedido += (fddto.getFacturasDet().getCantCajas()*fddto.getnRelacion())+fddto.getFacturasDet().getCantUnid();
lCantUnid += fddto.getFacturasDet().getCantUnid();
lBonifPedido += (fddto.getFacturasDet().getCajasBonif()*fddto.getnRelacion())+fddto.getFacturasDet().getUnidBonif();
}
}
//calcular total kilos
listaCodMercaDet = new ArrayList<>();
for(PromocionDto pro: listadoMercaPromo){
if(!verificarCodMercaEnListado(pro.getCodMerca(), listaCodMercaDet)){
listaCodMercaDet.add(pro.getCodMerca());
}
}
lCantCajas = 0; lCantUnid = 0; lTotalKilos = 0;
if(p.getkKilosIni().compareTo(BigDecimal.ZERO) == 1 || p.getkKilosFin().compareTo(BigDecimal.ZERO) == 1){
//p.getkKilosIni() > 0 || p.getkKilosFin() > 0
for(FacturaDetDto fddto: listadoDetalle){
if( fddto.getFacturasDet().getFacturasDetPK().getNrofact() == lNroFactura &&
verificarCodMercaEnListado(fddto.getFacturasDet().getFacturasDetPK().getCodMerca(), listaCodMercaDet)){
if(fddto.getnPesoCajas() == null){
fddto.setnPesoCajas(BigDecimal.ZERO);
}
lCantCajas += fddto.getFacturasDet().getCantCajas() * fddto.getnPesoCajas().intValue();
if(fddto.getnPesoUnidad() == null){
fddto.setnPesoUnidad(BigDecimal.ZERO);
}
lCantUnid += fddto.getFacturasDet().getCantUnid() * fddto.getnPesoUnidad().intValue();
}
}
lTotalKilos = lCantCajas + lCantUnid;
}
//SE VERIFICA TODAS LAS MERCADERIAS CON MARCA DE Y
listaCodMercaDet = new ArrayList<>();
for(PromocionDto pro: listadoMercaPromo){
if(!pro.getXdesc().equals("") || pro.getXdesc() != null){
listaCodMercaDet.add(p.getCodMerca());
}
}
for(FacturaDetDto fddto: listadoDetalle){
if( fddto.getFacturasDet().getFacturasDetPK().getNrofact() == lNroFactura &&
verificarCodMercaEnListado(fddto.getFacturasDet().getFacturasDetPK().getCodMerca(), listaCodMercaDet)){
lCantCajasY += fddto.getFacturasDet().getCantCajas();
lTotalUnidPedidoY += (fddto.getFacturasDet().getCantCajas()*fddto.getnRelacion())+fddto.getFacturasDet().getCantUnid();
lCantUnidY += fddto.getFacturasDet().getCantUnid();
lBonifPedidoY += (fddto.getFacturasDet().getCajasBonif()*fddto.getnRelacion())+fddto.getFacturasDet().getUnidBonif();
}
}
}
}
short lKMaxBonif = 0;
BigDecimal pMaxDesc = null;
for(PromocionesDetDto p: promociones){
if(p.getmY() == 0){
if(p.getkKilosIni().compareTo(BigDecimal.ZERO) == 1 || p.getkKilosFin().compareTo(BigDecimal.ZERO) == 1){
if(p.getkKilosIni().compareTo(BigDecimal.valueOf(lTotalKilos)) <= 0 && p.getkKilosFin().compareTo(BigDecimal.valueOf(lTotalKilos)) >= 0){
if(p.getPorKUnidad() > 0){
int lNroMax = lTotalUnidPedido/p.getPorKUnidad();
lKMaxBonif = (short) (p.getkUnidBonif().intValue()*lNroMax);
pMaxDesc = p.getpDesc();
}else if(p.getPorKCajas() > 0){
int lNroMax = lCantCajas/p.getPorKCajas();
lKMaxBonif = (short) (p.getkUnidBonif().intValue()*lNroMax);
pMaxDesc = p.getpDesc();
}else{
lKMaxBonif = p.getkMaxUnidBonif();
pMaxDesc = p.getpDesc();
}
if(lKMaxBonif > p.getkMaxUnidBonif()){
lKMaxBonif = p.getkMaxUnidBonif();
}
}
}else{
if( p.getkCajasIni().compareTo(BigDecimal.valueOf(lCantCajas)) <= 0 &&
(p.getkCajasFin().compareTo(BigDecimal.valueOf(lCantCajas)) >= 0 || p.getkCajasFin().compareTo(BigDecimal.ZERO) == 0) &&
(p.getkUnidIni().compareTo(BigDecimal.valueOf(lCantUnid)) <= 0 || p.getkUnidIni().compareTo(BigDecimal.valueOf(lTotalUnidPedido)) <= 0) &&
(p.getkUnidFin().compareTo(BigDecimal.valueOf(lCantUnid)) >= 0 || p.getkUnidFin().compareTo(BigDecimal.valueOf(lTotalUnidPedido)) >= 0 || p.getkUnidFin().compareTo(BigDecimal.ZERO) == 0) &&
(p.getcTipoCliente() == lCTipoCliente || p.getcTipoCliente() == 0) &&
(p.getmTodos() == 'N' && p.getCodMerca().equals(lCodMerca)) || (p.getmTodos() == 'S') ){
if (p.getPorKUnidad() > 0) {
int lNroMax = lTotalUnidPedido / p.getPorKUnidad();
lKMaxBonif = (short) (p.getkUnidBonif().intValue() * lNroMax);
pMaxDesc = p.getpDesc();
} else if (p.getPorKCajas() > 0) {
int lNroMax = lCantCajas / p.getPorKCajas();
lKMaxBonif = (short) (p.getkUnidBonif().intValue() * lNroMax);
pMaxDesc = p.getpDesc();
} else {
lKMaxBonif = p.getkMaxUnidBonif();
pMaxDesc = p.getpDesc();
}
if (lKMaxBonif > p.getkMaxUnidBonif()) {
lKMaxBonif = p.getkMaxUnidBonif();
}
}
}
descPromoDet = p.getxDesc();
if(lBonifPedido <= lKMaxBonif && lPDescPedido.compareTo(pMaxDesc) <= 0){
lError = 0;
nroPromoDet = p.getNroPromo();
return true;
}
}else{
if (p.getkCajasIni().compareTo(BigDecimal.valueOf(lCantCajasY)) <= 0
&& (p.getkCajasFin().compareTo(BigDecimal.valueOf(lCantCajasY)) >= 0 || p.getkCajasFin().compareTo(BigDecimal.ZERO) == 0)
&& (p.getkUnidIni().compareTo(BigDecimal.valueOf(lCantUnidY)) <= 0)
&& (p.getkUnidFin().compareTo(BigDecimal.valueOf(lCantUnidY)) >= 0 || p.getkUnidFin().compareTo(BigDecimal.ZERO) == 0)
&& (p.getcTipoCliente() == lCTipoCliente || p.getcTipoCliente() == 0)
&& (p.getmTodos() == 'N' && p.getCodMerca().equals(lCodMerca)) || (p.getmTodos() == 'S')) {
if (p.getPorKUnidad() > 0) {
int lNroMax = lTotalUnidPedido / p.getPorKUnidad();
lKMaxBonif = (short) (p.getkUnidBonif().intValue() * lNroMax);
pMaxDesc = p.getpDesc();
} else if (p.getPorKCajas() > 0) {
int lNroMax = lCantCajas / p.getPorKCajas();
lKMaxBonif = (short) (p.getkUnidBonif().intValue() * lNroMax);
pMaxDesc = p.getpDesc();
} else {
lKMaxBonif = p.getkMaxUnidBonif();
pMaxDesc = p.getpDesc();
}
if (lKMaxBonif > p.getkMaxUnidBonif()) {
lKMaxBonif = p.getkMaxUnidBonif();
}
}
descPromoDet = p.getxDesc();
if(lBonifPedido <= lKMaxBonif && lPDescPedido.compareTo(pMaxDesc) <= 0){
lError = 0;
nroPromoDet = p.getNroPromo();
return true;
}
}
}
if(lError == 1){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", "Max. descuento: "+pMaxDesc+". Max unidad bonificación: "+lKMaxBonif+". Mercadería: "+lCodMerca));
return false;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al obtener datos de promoción.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al validar una promoción.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
return false;
}
return true;
}
private boolean verificarCodMercaEnListado(String codMerca, List<String> listado){
for(String m: listado){
if(codMerca.equals(m)){
return true;
}
}
return false;
}
private long obtenerNroFacturaCompleto(){
long nroFacturaCompleto = (long) (nPuntoEstabLbl*1000000000.00 + nPuntoExpedLbl * 10000000.00 + nroFactLbl);
return nroFacturaCompleto;
}
private String obtenerNroFacturaCompletoConFormato(){
String puntoEstablec = String.valueOf(nPuntoEstabLbl);
String puntoExped = String.valueOf(nPuntoExpedLbl);
String nroFact = String.valueOf(nroFactLbl);
String resultado = rellenarConCeros(puntoEstablec, 3)+"-"+rellenarConCeros(puntoExped, 3)+"-"+rellenarConCeros(nroFact, 7);
return resultado;
}
private static String rellenarConCeros(String cadena, int numCeros) {
String ceros = "";
for (int i = cadena.length(); i < numCeros; i++) {
ceros += "0";
}
return ceros + cadena;
}
private long calcularDeudaCliente(){
long deuda = 0;
try{
String fechaStr = dateToString(fechaFactLbl);
long saldoInicial = calcularSaldoInicial(codClienteLbl, fechaStr);
long totalPedido = pedidosFacade.obtenerTotalPedidosPorClienteFecha(codClienteLbl, fechaStr);
deuda = saldoInicial + totalPedido;
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al calcular la deuda del cliente.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
return deuda;
}
private long calcularSaldoInicial(Integer codCliente, String fecha){
long saldoInicial = 0;
String fechaSaldo = null;
try{
List<SaldosClientes> listadoSaldos = saldosClientesFacade.obtenerSaldosClientesPorClienteFechaMovimiento(codCliente, fecha);
if(listadoSaldos.isEmpty()){
fechaSaldo = "20050831";
saldoInicial = 0;
}else{
for(SaldosClientes s: listadoSaldos){
saldoInicial += (s.getIsaldo() + s.getAcumDebi() - s.getAcumCredi());
fechaSaldo = dateToString(s.getSaldosClientesPK().getFmovim());
}
}
if(!fecha.equals(fechaSaldo)){
long totalMovim = cuentasCorrientesFacade.obtenerTotalCtaCtePorClienteEnRangoDeFechas(codCliente, fechaSaldo, fecha);
saldoInicial += totalMovim;
}
}catch(Exception e){
RequestContext.getCurrentInstance().update("exceptionDialog");
contenidoError = ExceptionHandlerView.getStackTrace(e);
tituloError = "Error al calcular el saldo inicial.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, tituloError, tituloError));
RequestContext.getCurrentInstance().execute("PF('exceptionDialog').show();");
}
return saldoInicial;
}
private String dateToString(Date fecha) {
String resultado = "";
try {
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
resultado = dateFormat.format(fecha);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atencion", "Error al convertir fecha"));
}
return resultado;
}
public void onRowSelect(SelectEvent event) {
if(facturaSeleccionada != null){
if(facturaSeleccionada.getFacturasPK().getNrofact() != 0){
setHabilitaBotonEliminar(false);
setHabilitaBotonVisualizar(false);
}else{
setHabilitaBotonEliminar(true);
setHabilitaBotonVisualizar(true);
}
}
}
public void cerrarDialogoSinGuardar() {
RequestContext.getCurrentInstance().execute("PF('dlgSinGuardarRecibos').hide();");
RequestContext.getCurrentInstance().execute("PF('dlgNuevReciboCompra').hide();");
}
public static String convertidorFecha(Date fecha){
return DateUtil.formaterDateToString(fecha);
}
public Date getFechaFactLbl() {
return fechaFactLbl;
}
public void setFechaFactLbl(Date fechaFactLbl) {
this.fechaFactLbl = fechaFactLbl;
}
public Integer getCodClienteLbl() {
return codClienteLbl;
}
public void setCodClienteLbl(Integer codClienteLbl) {
this.codClienteLbl = codClienteLbl;
}
public String getNombreClienteLbl() {
return nombreClienteLbl;
}
public void setNombreClienteLbl(String nombreClienteLbl) {
this.nombreClienteLbl = nombreClienteLbl;
}
public Short getNPuntoEstabLbl() {
return nPuntoEstabLbl;
}
public void setNPuntoEstabLbl(Short nPuntoEstabLbl) {
this.nPuntoEstabLbl = nPuntoEstabLbl;
}
public Short getNPuntoExpedLbl() {
return nPuntoExpedLbl;
}
public void setNPuntoExpedLbl(Short nPuntoExpedLbl) {
this.nPuntoExpedLbl = nPuntoExpedLbl;
}
public long getNroFactLbl() {
return nroFactLbl;
}
public void setNroFactLbl(long nroFactLbl) {
this.nroFactLbl = nroFactLbl;
}
public short getCodDepositoLbl() {
return codDepositoLbl;
}
public void setCodDepositoLbl(short codDepositoLbl) {
this.codDepositoLbl = codDepositoLbl;
}
public long getNroPedidoLbl() {
return nroPedidoLbl;
}
public void setNroPedidoLbl(long nroPedidoLbl) {
this.nroPedidoLbl = nroPedidoLbl;
}
public Character getCtipoVtaLbl() {
return ctipoVtaLbl;
}
public void setCtipoVtaLbl(Character ctipoVtaLbl) {
this.ctipoVtaLbl = ctipoVtaLbl;
}
public Date getFechaVencLbl() {
return fechaVencLbl;
}
public void setFechaVencLbl(Date fechaVencLbl) {
this.fechaVencLbl = fechaVencLbl;
}
public Date getFechaVencImpresLbl() {
return fechaVencImpresLbl;
}
public void setFechaVencImpresLbl(Date fechaVencImpresLbl) {
this.fechaVencImpresLbl = fechaVencImpresLbl;
}
public int getCantDiasChequesLbl() {
return cantDiasChequesLbl;
}
public void setCantDiasChequesLbl(int cantDiasChequesLbl) {
this.cantDiasChequesLbl = cantDiasChequesLbl;
}
public int getCantDiasImpresionChequesLbl() {
return cantDiasImpresionChequesLbl;
}
public void setCantDiasImpresionChequesLbl(int cantDiasImpresionChequesLbl) {
this.cantDiasImpresionChequesLbl = cantDiasImpresionChequesLbl;
}
public short getCodVendedorLbl() {
return codVendedorLbl;
}
public void setCodVendedorLbl(short codVendedorLbl) {
this.codVendedorLbl = codVendedorLbl;
}
public String getCodCanalVentaLbl() {
return codCanalVentaLbl;
}
public void setCodCanalVentaLbl(String codCanalVentaLbl) {
this.codCanalVentaLbl = codCanalVentaLbl;
}
public short getPlazosChequesLbl() {
return plazosChequesLbl;
}
public void setPlazosChequesLbl(short plazosChequesLbl) {
this.plazosChequesLbl = plazosChequesLbl;
}
public TiposDocumentos getTipoDocumentoSeleccionadoLbl() {
return tipoDocumentoSeleccionadoLbl;
}
public void setTipoDocumentoSeleccionadoLbl(TiposDocumentos tipoDocumentoSeleccionadoLbl) {
this.tipoDocumentoSeleccionadoLbl = tipoDocumentoSeleccionadoLbl;
}
public String getContenidoError() {
return contenidoError;
}
public void setContenidoError(String contenidoError) {
this.contenidoError = contenidoError;
}
public String getTituloError() {
return tituloError;
}
public void setTituloError(String tituloError) {
this.tituloError = tituloError;
}
public List<TiposVentas> getListadoTiposVentas() {
return listadoTiposVentas;
}
public void setListadoTiposVentas(List<TiposVentas> listadoTiposVentas) {
this.listadoTiposVentas = listadoTiposVentas;
}
public List<Depositos> getListadoDepositos() {
return listadoDepositos;
}
public void setListadoDepositos(List<Depositos> listadoDepositos) {
this.listadoDepositos = listadoDepositos;
}
public Clientes getClienteBuscado() {
return clienteBuscado;
}
public void setClienteBuscado(Clientes clienteBuscado) {
this.clienteBuscado = clienteBuscado;
}
public boolean isMostrarCantDiasChequesLbl() {
return mostrarCantDiasChequesLbl;
}
public void setMostrarCantDiasChequesLbl(boolean mostrarCantDiasChequesLbl) {
this.mostrarCantDiasChequesLbl = mostrarCantDiasChequesLbl;
}
public boolean isMostrarCantDiasImpresionChequesLbl() {
return mostrarCantDiasImpresionChequesLbl;
}
public void setMostrarCantDiasImpresionChequesLbl(boolean mostrarCantDiasImpresionChequesLbl) {
this.mostrarCantDiasImpresionChequesLbl = mostrarCantDiasImpresionChequesLbl;
}
public boolean isMostrarPlazosChequesLbl() {
return mostrarPlazosChequesLbl;
}
public void setMostrarPlazosChequesLbl(boolean mostrarPlazosChequesLbl) {
this.mostrarPlazosChequesLbl = mostrarPlazosChequesLbl;
}
public long getTotalFinal() {
return totalFinal;
}
public void setTotalFinal(long totalFinal) {
this.totalFinal = totalFinal;
}
public long getTotalIva() {
return totalIva;
}
public void setTotalIva(long totalIva) {
this.totalIva = totalIva;
}
public long getTotalExentas() {
return totalExentas;
}
public void setTotalExentas(long totalExentas) {
this.totalExentas = totalExentas;
}
public long getTotalGravadas() {
return totalGravadas;
}
public void setTotalGravadas(long totalGravadas) {
this.totalGravadas = totalGravadas;
}
public long getTotalDescuentos() {
return totalDescuentos;
}
public void setTotalDescuentos(long totalDescuentos) {
this.totalDescuentos = totalDescuentos;
}
public Depositos getDepositoSeleccionado() {
return depositoSeleccionado;
}
public void setDepositoSeleccionado(Depositos depositoSeleccionado) {
this.depositoSeleccionado = depositoSeleccionado;
}
public String getCodZonaLbl() {
return codZonaLbl;
}
public void setCodZonaLbl(String codZonaLbl) {
this.codZonaLbl = codZonaLbl;
}
public String getObservacionLbl() {
return observacionLbl;
}
public void setObservacionLbl(String observacionLbl) {
this.observacionLbl = observacionLbl;
}
public short getCodEntregadorLbl() {
return codEntregadorLbl;
}
public void setCodEntregadorLbl(short codEntregadorLbl) {
this.codEntregadorLbl = codEntregadorLbl;
}
public String getDireccionLbl() {
return direccionLbl;
}
public void setDireccionLbl(String direccionLbl) {
this.direccionLbl = direccionLbl;
}
public String getRazonSocialLbl() {
return razonSocialLbl;
}
public void setRazonSocialLbl(String razonSocialLbl) {
this.razonSocialLbl = razonSocialLbl;
}
public String getTelefonoLbl() {
return telefonoLbl;
}
public void setTelefonoLbl(String telefonoLbl) {
this.telefonoLbl = telefonoLbl;
}
public String getCiudadLbl() {
return ciudadLbl;
}
public void setCiudadLbl(String ciudadLbl) {
this.ciudadLbl = ciudadLbl;
}
public short getCodRutaLbl() {
return codRutaLbl;
}
public void setCodRutaLbl(short codRutaLbl) {
this.codRutaLbl = codRutaLbl;
}
public Facturas getFacturaSeleccionada() {
return facturaSeleccionada;
}
public void setFacturaSeleccionada(Facturas facturaSeleccionada) {
this.facturaSeleccionada = facturaSeleccionada;
}
public List<Facturas> getListadoFacturas() {
return listadoFacturas;
}
public void setListadoFacturas(List<Facturas> listadoFacturas) {
this.listadoFacturas = listadoFacturas;
}
public Short getMotivoLbl() {
return cMotivoLbl;
}
public void setMotivoLbl(Short cMotivoLbl) {
this.cMotivoLbl = cMotivoLbl;
}
public Date getFechaAnulacionLbl() {
return fechaAnulacionLbl;
}
public void setFechaAnulacionLbl(Date fechaAnulacionLbl) {
this.fechaAnulacionLbl = fechaAnulacionLbl;
}
public String getCodMercaDet() {
return codMercaDet;
}
public void setCodMercaDet(String codMercaDet) {
this.codMercaDet = codMercaDet;
}
public int getCantCajasDet() {
return cantCajasDet;
}
public void setCantCajasDet(int cantCajasDet) {
this.cantCajasDet = cantCajasDet;
}
public int getCantUnidDet() {
return cantUnidDet;
}
public void setCantUnidDet(int cantUnidDet) {
this.cantUnidDet = cantUnidDet;
}
public int getCantCajasBonifDet() {
return cantCajasBonifDet;
}
public void setCantCajasBonifDet(int cantCajasBonifDet) {
this.cantCajasBonifDet = cantCajasBonifDet;
}
public int getCantUnidBonifDet() {
return cantUnidBonifDet;
}
public void setCantUnidBonifDet(int cantUnidBonifDet) {
this.cantUnidBonifDet = cantUnidBonifDet;
}
public Mercaderias getMercaderiaDet() {
return mercaderiaDet;
}
public void setMercaderiaDet(Mercaderias mercaderiaDet) {
this.mercaderiaDet = mercaderiaDet;
}
public List<FacturaDetDto> getListadoDetalle() {
return listadoDetalle;
}
public void setListadoDetalle(List<FacturaDetDto> listadoDetalle) {
this.listadoDetalle = listadoDetalle;
}
public List<FacturasDet> getListadoFacturasDet() {
return listadoFacturasDet;
}
public void setListadoFacturasDet(List<FacturasDet> listadoFacturasDet) {
this.listadoFacturasDet = listadoFacturasDet;
}
public String getDescMercaDet() {
return descMercaDet;
}
public void setDescMercaDet(String descMercaDet) {
this.descMercaDet = descMercaDet;
}
public long getPrecioCajaDet() {
return precioCajaDet;
}
public void setPrecioCajaDet(long precioCajaDet) {
this.precioCajaDet = precioCajaDet;
}
public long getPrecioUnidDet() {
return precioUnidDet;
}
public void setPrecioUnidDet(long precioUnidDet) {
this.precioUnidDet = precioUnidDet;
}
public long getGravadasDet() {
return gravadasDet;
}
public void setGravadasDet(long gravadasDet) {
this.gravadasDet = gravadasDet;
}
public long getExentasDet() {
return exentasDet;
}
public void setExentasDet(long exentasDet) {
this.exentasDet = exentasDet;
}
public long getImpuestosDet() {
return impuestosDet;
}
public void setImpuestosDet(long impuestosDet) {
this.impuestosDet = impuestosDet;
}
public long getDescuentosDet() {
return descuentosDet;
}
public void setDescuentosDet(long descuentosDet) {
this.descuentosDet = descuentosDet;
}
public Integer getNroPromoDet() {
return nroPromoDet;
}
public void setNroPromoDet(Integer nroPromoDet) {
this.nroPromoDet = nroPromoDet;
}
public String getDescPromoDet() {
return descPromoDet;
}
public void setDescPromoDet(String descPromoDet) {
this.descPromoDet = descPromoDet;
}
public BigDecimal getPdescDet() {
return pdescDet;
}
public void setPdescDet(BigDecimal pdescDet) {
this.pdescDet = pdescDet;
}
public BigDecimal getPimpuesDet() {
return pimpuesDet;
}
public void setPimpuesDet(BigDecimal pimpuesDet) {
this.pimpuesDet = pimpuesDet;
}
public Short getnRelacionDet() {
return nRelacionDet;
}
public void setnRelacionDet(Short nRelacionDet) {
this.nRelacionDet = nRelacionDet;
}
public Character getmPromoPackDet() {
return mPromoPackDet;
}
public void setmPromoPackDet(Character mPromoPackDet) {
this.mPromoPackDet = mPromoPackDet;
}
public Short getCodSublineaDet() {
return codSublineaDet;
}
public void setCodSublineaDet(Short codSublineaDet) {
this.codSublineaDet = codSublineaDet;
}
public BigDecimal getnPesoCajaDet() {
return nPesoCajaDet;
}
public void setnPesoCajaDet(BigDecimal nPesoCajaDet) {
this.nPesoCajaDet = nPesoCajaDet;
}
public BigDecimal getnPesoUnidadDet() {
return nPesoUnidadDet;
}
public void setnPesoUnidadDet(BigDecimal nPesoUnidadDet) {
this.nPesoUnidadDet = nPesoUnidadDet;
}
public boolean isHabilitaBotonEliminar() {
return habilitaBotonEliminar;
}
public void setHabilitaBotonEliminar(boolean habilitaBotonEliminar) {
this.habilitaBotonEliminar = habilitaBotonEliminar;
}
public List<TiposDocumentos> getListadoTiposDocumentos() {
return listadoTiposDocumentos;
}
public void setListadoTiposDocumentos(List<TiposDocumentos> listadoTiposDocumentos) {
this.listadoTiposDocumentos = listadoTiposDocumentos;
}
public List<EmpleadosZonas> getListadoVendedores() {
return listadoVendedores;
}
public void setListadoVendedores(List<EmpleadosZonas> listadoVendedores) {
this.listadoVendedores = listadoVendedores;
}
public List<CanalesVendedores> getListadoCanales() {
return listadoCanales;
}
public void setListadoCanales(List<CanalesVendedores> listadoCanales) {
this.listadoCanales = listadoCanales;
}
public List<Empleados> getListadoEntregadores() {
return listadoEntregadores;
}
public void setListadoEntregadores(List<Empleados> listadoEntregadores) {
this.listadoEntregadores = listadoEntregadores;
}
public List<Existencias> getListaExistencias() {
return listaExistencias;
}
public void setListaExistencias(List<Existencias> listaExistencias) {
this.listaExistencias = listaExistencias;
}
public Existencias getExistencias() {
return existencias;
}
public void setExistencias(Existencias existencias) {
this.existencias = existencias;
}
public String getFiltro() {
return filtro;
}
public void setFiltro(String filtro) {
this.filtro = filtro;
}
public FacturaDetDto getFacturaDetDtoSeleccionada() {
return facturaDetDtoSeleccionada;
}
public void setFacturaDetDtoSeleccionada(FacturaDetDto facturaDetDtoSeleccionada) {
this.facturaDetDtoSeleccionada = facturaDetDtoSeleccionada;
}
public boolean isMostrarTotalIva() {
return mostrarTotalIva;
}
public void setMostrarTotalIva(boolean mostrarTotalIva) {
this.mostrarTotalIva = mostrarTotalIva;
}
public Clientes getClientes() {
return clientes;
}
public void setClientes(Clientes clientes) {
this.clientes = clientes;
}
public List<Clientes> getListaClientes() {
return listaClientes;
}
public void setListaClientes(List<Clientes> listaClientes) {
this.listaClientes = listaClientes;
}
public LazyDataModel<Existencias> getModel() {
return model;
}
public void setModel(LazyDataModel<Existencias> model) {
this.model = model;
}
public boolean isHabilitaBotonVisualizar() {
return habilitaBotonVisualizar;
}
public void setHabilitaBotonVisualizar(boolean habilitaBotonVisualizar) {
this.habilitaBotonVisualizar = habilitaBotonVisualizar;
}
public boolean isMostrarFechaVencimiento() {
return mostrarFechaVencimiento;
}
public void setMostrarFechaVencimiento(boolean mostrarFechaVencimiento) {
this.mostrarFechaVencimiento = mostrarFechaVencimiento;
}
public boolean isMostrarFechaVencimientoImpresion() {
return mostrarFechaVencimientoImpresion;
}
public void setMostrarFechaVencimientoImpresion(boolean mostrarFechaVencimientoImpresion) {
this.mostrarFechaVencimientoImpresion = mostrarFechaVencimientoImpresion;
}
public Short getcMotivoLbl() {
return cMotivoLbl;
}
public void setcMotivoLbl(Short cMotivoLbl) {
this.cMotivoLbl = cMotivoLbl;
}
public List<Motivos> getListadoMotivos() {
return listadoMotivos;
}
public void setListadoMotivos(List<Motivos> listadoMotivos) {
this.listadoMotivos = listadoMotivos;
}
}
| 3175c79fd0f89d1e213543743b99659245fe1065 | [
"Java"
] | 128 | Java | HugoF92/SisVenLog-WEB | f41f39baa1c232567c52e76764e298e5f4c47f51 | 1bb209b88d79635c34636910d69855f0b32fb270 |
refs/heads/main | <file_sep># Smart Car com L298P
<file_sep>//Código base Smart Car Arduino
//Servo, Sensor, Bluetooth
// <NAME>
// <EMAIL>
// Skype: <EMAIL>
// Licença: CC BY-NC-SA
// https://br.creativecommons.org/
#include <Servo.h>
Servo servo1;
int E1 = 10; //E1
int M1 = 12; //M1
int E2 = 11; //E2
int M2 = 13; //M2
int vel = 255; //Velocidade
int estado = 'c'; //Estado inicial (Parado)
int pecho = 2; // Sensor Ultrassonico
int ptrig = 3;
int duracion, distancia;
int pisca[] = {4, 7, 8, 13}; // Pisca Alerta
int contador = 0;
int timer = 100; //1000 = 1 Segundo
void setup() {
Serial.begin(9600);
pinMode(E2, OUTPUT);
pinMode(M2, OUTPUT);
pinMode(E1, OUTPUT);
pinMode(M1, OUTPUT);
pinMode(pecho, INPUT);
pinMode(ptrig, OUTPUT);
pinMode(13, OUTPUT); //Led do Sensor Ultrassonico
pinMode(7, OUTPUT); //Pisca Farol
pinMode(8, OUTPUT); //Pisca Farol
pinMode(4, OUTPUT); //Buzina
servo1.attach(11);
servo1.write(101);
{
for (contador = 0; contador < 4; contador++) {
pinMode(pisca[contador], OUTPUT);
}
}
}
void loop() {
if (Serial.available() > 0) {
estado = Serial.read();
}
if (estado == 'a') { //Frente
analogWrite(M2, 0);
analogWrite(M1, 0);
analogWrite(E2, vel);
analogWrite(E1, vel);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
}
if (estado == 'b') { //Esquerda
analogWrite(M2, 0);
analogWrite(M1, 0);
analogWrite(E2, 0);
analogWrite(E1, vel);
//digitalWrite(50, LOW);
}
if (estado == 'c') {
analogWrite(M2, 0);
analogWrite(M1, 0);
analogWrite(E2, 0);
analogWrite(E1, 0);
digitalWrite(7, LOW); //Pisca
digitalWrite(8, LOW); //Pisca
digitalWrite(4, LOW); //Buzina
digitalWrite(13, LOW); //LED
//digitalWrite(50, HIGH);
//servo1.write(101);
}
if (estado == 'd') { //Direita
analogWrite(M2, 0);
analogWrite(M1, 0);
analogWrite(E1, 0);
analogWrite(E2, vel);
//digitalWrite(50, LOW);
}
if (estado == 'e') { //Atrás
analogWrite(E2, 0);
analogWrite(E1, 0);
analogWrite(M2, vel);
analogWrite(M1, vel);
//digitalWrite(50, LOW);
}
if (estado == 'f') { //Auto
digitalWrite(ptrig, HIGH);
delay(0.01);
digitalWrite(ptrig, LOW);
duracion = pulseIn(pecho, HIGH);
distancia = (duracion / 2) / 29;
delay(10);
if (distancia <= 30 && distancia >= 2) {
digitalWrite(13, HIGH);
analogWrite(M2, 0);
analogWrite(M1, 0);
analogWrite(E2, 0);
analogWrite(E1, 0);
delay (200);
analogWrite(M2, vel);
analogWrite(M1, vel);
delay(500);
analogWrite(M2, 0);
analogWrite(M1, 0);
analogWrite(E2, 0);
analogWrite(E1, vel);
delay(600);
digitalWrite(13, LOW);
}
else {
analogWrite(M2, 0);
analogWrite(M1, 0);
analogWrite(E2, vel);
analogWrite(E1, vel);
}
}
if (estado == 'g') {
servo1.write(30);
delay(1000);
servo1.write(90);
delay(700);
servo1.write(150);
delay(700);
}
if (estado == 'h') {
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(13, HIGH);
}
if (estado == 'm') {
digitalWrite(13, 0);
}
if (estado == 'i') {
digitalWrite(30, HIGH);
}
if (estado == 'n') {
digitalWrite(M2, 0);
}
if (estado == 'z') {
digitalWrite(4, HIGH); // Buzina
}
if (estado == 'o') {
digitalWrite(E2, 0);
}
if (estado == 'k') {
digitalWrite(M1, 1);
}
if (estado == 'p') {
digitalWrite(M1, 0);
}
if (estado == 'l') {
digitalWrite(E1, 1);
}
if (estado == 'q') {
for (contador = 0; contador < 4; contador++) {
digitalWrite(pisca[contador], HIGH);
delay(timer);
digitalWrite(pisca[contador], LOW);
delay(timer);
}
}
}
| 1c7c4c17c77cde3177fd153e57c0ce51eb011c3b | [
"Markdown",
"C++"
] | 2 | Markdown | tecagv/Smart-Car-com-L298P | 943e1d01d90207688f16de49ae43925d28d16f44 | 7b4a986f0b2a001996df7b850deb669159c0adec |
refs/heads/master | <repo_name>CompJose/github-upload<file_sep>/src/Main.java
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void menu(int n) {
if(n > 0) {
for(int i = 0; i < n; i++)
System.out.print("-");
}
System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Livro> livros = new ArrayList<>();
ArrayList<LivroEmprestado> livrosEmp = new ArrayList<>();
ArrayList<Aluno> alunos = new ArrayList<>();
Livro livro1 = new Livro(50, "Aprender Java", "<NAME>", 2);
Livro livro2 = new Livro(25, "Sistema de Banco de Dados", "<NAME>", 2);
Livro livro3 = new Livro(32, "2001 Uma odisseia no espaco", "<NAME>", 4);
Livro livro4 = new Livro(44, "Calculo 1", "<NAME>", 4);
Livro livro5 = new Livro(80, "<NAME>", "<NAME>", 9);
Livro livro6 = new Livro(70, "Calculo 2", "<NAME>", 1);
Livro livro7 = new Livro(223, "Logica", "<NAME>", 8);
Livro livro8 = new Livro(55, "Brasil 90", "<NAME>", 7);
LivroEmprestado emprestimo1 = new LivroEmprestado
(livro1.getIdLivro(),livro1.getTitulo(), livro1.getAutor(), livro1.getEdicao(), 2020, "19/12/2020");
LivroEmprestado emprestimo2 = new LivroEmprestado
(livro2.getIdLivro(),livro2.getTitulo(), livro2.getAutor(), livro2.getEdicao(), 2021, "10/11/2020");
LivroEmprestado emprestimo3 = new LivroEmprestado
(livro4.getIdLivro(),livro4.getTitulo(), livro4.getAutor(), livro4.getEdicao(), 2022, "22/12/2020");
LivroEmprestado emprestimo4 = new LivroEmprestado
(livro8.getIdLivro(),livro8.getTitulo(), livro8.getAutor(), livro8.getEdicao(), 2022, "23/12/2020");
LivroEmprestado emprestimo5 = new LivroEmprestado
(livro3.getIdLivro(),livro3.getTitulo(), livro3.getAutor(), livro3.getEdicao(), 2024, "12/07/2020");
Aluno aluno1 = new Aluno("<NAME>", 2020);
Aluno aluno2 = new Aluno("<NAME>", 2021);
Aluno aluno3 = new Aluno("<NAME>", 2022);
Aluno aluno4 = new Aluno("<NAME>", 2024);
livros.add(livro1);
livros.add(livro2);
livros.add(livro3);
livros.add(livro4);
livros.add(livro5);
livros.add(livro6);
livros.add(livro7);
livros.add(livro8);
livrosEmp.add(emprestimo1);
livrosEmp.add(emprestimo2);
livrosEmp.add(emprestimo3);
livrosEmp.add(emprestimo4);
livrosEmp.add(emprestimo5);
alunos.add(aluno1);
alunos.add(aluno2);
alunos.add(aluno3);
alunos.add(aluno4);
Livro colecaoLivros = new Livro(livros);
LivroEmprestado livrosEmprestados = new LivroEmprestado(livrosEmp);
Aluno alunosMatriculados = new Aluno(alunos);
try {
livrosEmprestados.checkEmprestimo();
}catch(ParseException e)
{
e.printStackTrace();
}
System.out.println("Qual funcao deseja usar?\n");
System.out.println("1 - Fazer emprestimo");
System.out.println("2 - Devolucao");
System.out.println("3 - Listar livros emprestados");
System.out.println("4 - Listar todos os livros");
System.out.println("5 - Cadastrar um novo livro");
System.out.println("6 - Listar Alunos");
System.out.println("7 - Cadastrar novo aluno");
System.out.println("-1 - Encerra o programa");
Scanner scanner = new Scanner(System.in);
int numero;
do {
numero = scanner.nextInt();
switch(numero) {
case 1:
menu(30);
livrosEmprestados.fazerEmprestimo();
break;
case 2:
menu(30);
livrosEmprestados.devolucao();
break;
case 3:
menu(30);
livrosEmprestados.imprimirListaDeEmprestimo();
break;
case 4:
menu(30);
colecaoLivros.imprimirListaDeLivros();
break;
case 5:
menu(30);
colecaoLivros.cadastrarNovoLivro();
break;
case 6:
menu(30);
alunosMatriculados.imprimirListaAlunos();
break;
case 7:
menu(30);
alunosMatriculados.cadastrarAluno();
break;
case -1:
menu(30);
System.out.println("\n\nPrograma Encerrado");
System.exit(0);
default:
menu(30);
System.out.println("\n\nValor Invalido!!!");
break;
}
menu(30);
System.out.println("\n\n\nQual funcao deseja usar?\n");
}while(numero != -1);
}
}
<file_sep>/src/LivroEmprestado.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class LivroEmprestado extends Livro {
private static ArrayList<LivroEmprestado> livroEmpArray = new ArrayList<>();
private String dataDevo;
private int matricula;
public int getMatricula() {
return this.matricula;
}
public void setMatricula(int matricula) {
this.matricula = matricula;
}
public String getDataDevo() {
return this.dataDevo;
}
public void setDataDevo(String dataDevo) {
this.dataDevo = dataDevo;
}
public LivroEmprestado(int idLivro,String title, String autor, int edicao, int matricula, String dataDevo2) {
super(idLivro, title, autor, edicao);
setMatricula(matricula);
setDataDevo(dataDevo2);
}
public LivroEmprestado(ArrayList<LivroEmprestado> livrosEmp) {
livroEmpArray = livrosEmp;
}
static Scanner scanner = new Scanner(System.in);
public void fazerEmprestimo() {
System.out.println();
System.out.format("%1$30s", "Solicitar Emprestimo\n\n");
System.out.println("Digite o idLivro:");
int idTemp = scanner.nextInt();
if(checarExistencia(livroTemp, idTemp) == true) {
System.out.println("\nLivro nao cadastrado!");
return;
}
else {
Livro temp = new Livro();
temp = pegarInformacaoLivro(idTemp);
System.out.println("\nDigite a matricula do aluno: ");
int matricula = scanner.nextInt();
String dataDevo = dataDevolucao();
LivroEmprestado livroTemp = new LivroEmprestado(idTemp,temp.getTitulo(), temp.getAutor(), temp.getEdicao(), matricula, dataDevo);
emprestimo(livroTemp);
System.out.println("\nEmprestimo feito com sucesso!!!");
System.out.println("Data de devolucao: " + livroTemp.getDataDevo());
}
}
public static void emprestimo(LivroEmprestado livroTemp) {
livroEmpArray.add(livroTemp);
}
public static void imprimirEmprestimo(ArrayList<LivroEmprestado> emp, int ind) {
System.out.format("%-15d", livroEmpArray.get(ind).getIdLivro());
System.out.format("%1$-30s%2$-25s%3$-15d%4$-15d%5$-15s", livroEmpArray.get(ind).getTitulo(),
livroEmpArray.get(ind).getAutor(), livroEmpArray.get(ind).getEdicao(),
livroEmpArray.get(ind).getMatricula() , livroEmpArray.get(ind).getDataDevo());
System.out.println();
}
public void imprimirListaDeEmprestimo() {
System.out.format("%1$35s", "Lista de livros emprestados\n\n");
printCabecalho();
boolean imp = livroEmpArray.isEmpty();
if(imp == false) {
for(int i = 0; i< livroEmpArray.size(); i++) {
imprimirEmprestimo(livroEmpArray, i);
}
}
else
System.out.println("Lista de Emprestimo Vazia");
}
public static String dataDevolucao() {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 8);
Date data = c.getTime();
SimpleDateFormat formatar = new SimpleDateFormat("dd/MM/yyyy");
return formatar.format(data);
}
public void checkEmprestimo() throws ParseException{
int i = 0;
Calendar c = Calendar.getInstance();
for (i = 0; i < livroEmpArray.size() ; i++) {
Date data2 = new SimpleDateFormat("dd/MM/yyyy").parse(livroEmpArray.get(i).getDataDevo());
Date data1 = c.getTime();
long diferenca = data1.getTime() - data2.getTime();
long diffInDays = TimeUnit.MILLISECONDS.toDays(diferenca);
if(diffInDays > 0)
Aluno.multar(livroEmpArray.get(i).getMatricula(), diffInDays);
}
}
public void devolucao() {
System.out.println("\nQual o id do livro que deseja devolver?");
int id = scanner.nextInt();
for(int i = 0; i< livroEmpArray.size(); i++) {
if(livroEmpArray.get(i).getIdLivro() == id) {
System.out.println();
printCabecalho();
imprimirEmprestimo(livroEmpArray, i);
System.out.println("\n\nDevolucao concluida");
livroEmpArray.remove(i);
return;
}
}
System.out.println("\n\nLivro nao encontrado.");
}
public static void printCabecalho() {
System.out.format("%1$-15s%2$-30s%3$-25s%4$-15s%5$-15s%6$-15s",
"Identificao", "Titulo", "Autor", "Edicao", "Matricula", "Data Devolucao");
System.out.println("\n");
}
}
<file_sep>/src/Livro.java
import java.util.ArrayList;
import java.util.Scanner;
public class Livro {
protected int idLivro;
private String titulo;
private String autor;
private int edicao;
protected static ArrayList<Livro> livroTemp = new ArrayList<>();
public int getIdLivro(){
return this.idLivro;
}
public String getTitulo() {
return this.titulo;
}
public String getAutor() {
return this.autor;
}
public int getEdicao() {
return this.edicao;
}
public void setIdLivro(int idLivro) {
this.idLivro = idLivro;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public void setAutor(String autor) {
this.autor = autor;
}
public void setEdicao(int edicao) {
this.edicao = edicao;
}
public Livro() {
}
public Livro(int id) {
idLivro = id;
}
public Livro(int id, String titulo, String autor, int edicao) {
setIdLivro(id);
setTitulo(titulo);
setAutor(autor);
setEdicao(edicao);
}
public Livro(ArrayList<Livro> book) {
livroTemp = book;
}
static Scanner scanner = new Scanner(System.in);
public static boolean checarExistencia(ArrayList<Livro> book, int id) {
int i = 0;
for(i = 0; i< book.size() ; i++) {
if(book.get(i).getIdLivro() == id) {
System.out.format("%1$30s", "\nLivro encontrado\n\n");
printCabecalho();
imprimirLivro(livroTemp, i);
return false;
}
}
return true;
}
public static void cadastrar(Livro livroNovo) {
livroTemp.add(livroNovo);
int a = livroTemp.size() - 1;
printCabecalho();
imprimirLivro(livroTemp, a);
}
public void cadastrarNovoLivro(){
System.out.println("\nDigite as informacoes do livro\n");
System.out.println("Numero de identificação: ");
int id = scanner.nextInt();
if(Livro.checarExistencia(livroTemp, id) == false) {
System.out.println("\nImpossivel efetuar o cadastro.");
return;}
else {
scanner.nextLine();
System.out.println("Digite o titulo: ");
String titulo = scanner.nextLine();
System.out.println("Digite o nome do autor: ");
String autor = scanner.nextLine();
System.out.println("Digite a edicao: ");
int edicao = scanner.nextInt();
Livro livro0 = new Livro(id, titulo, autor, edicao);
System.out.println("\nLivro cadastrado com sucesso");
cadastrar(livro0);
}
}
public static void printCabecalho() {
System.out.format("%1$-15s%2$-30s%3$-25s%4$-15s", "Identificao", "Titulo", "Autor", "Edicao");
System.out.println("\n");
}
public static void imprimirLivro(ArrayList<Livro> book, int id) {
System.out.format("%-15d", livroTemp.get(id).getIdLivro());
System.out.format("%1$-30s%2$-25s%3$-15d",
livroTemp.get(id).getTitulo(), livroTemp.get(id).getAutor(), livroTemp.get(id).getEdicao());
System.out.println();
}
public void imprimirListaDeLivros() {
boolean empt = livroTemp.isEmpty();
if(empt == false) {
System.out.format("%1$40s", "Lista dos livros disponiveis\n\n");
printCabecalho();
for(int i = 0; i< livroTemp.size(); i++) {
imprimirLivro(livroTemp, i);
}
}
else
System.out.println("Nenhum livro cadastrado");
}
public Livro pegarInformacaoLivro(int id) {
for(int i = 0; i < livroTemp.size(); i++)
if(livroTemp.get(i).getIdLivro() == id){
Livro copia = new Livro (id, livroTemp.get(i).getTitulo(), livroTemp.get(i).getAutor(), livroTemp.get(i).getEdicao());
return copia;
}
return null;
}
}
| ac654b6837a54172ef1d3f1155779a747027411d | [
"Java"
] | 3 | Java | CompJose/github-upload | 22c6fc1aa8d163a53a4f0426e16524e6a3ec8508 | bf7bdf51140a9274ebf69dff280b5258ad3ee502 |
refs/heads/master | <repo_name>luposlip/Android-AltBeacon-Library<file_sep>/Samples/Forms/AltBeaconLibrary.Sample/Android/MainActivity.cs
using System;
using Android.App;
using Android.OS;
using Xamarin.Forms.Platform.Android;
using AltBeaconOrg.BoundBeacon;
namespace AltBeaconLibrary.Sample.Droid
{
[Activity(Label = "AltBeacon Forms Sample",
Theme = "@style/Theme.AltBeacon",
Icon = "@drawable/altbeacon",
MainLauncher = true,
LaunchMode = Android.Content.PM.LaunchMode.SingleInstance)]
public class MainActivity : FormsApplicationActivity, IBeaconConsumer
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
#region IBeaconConsumer Implementation
public void OnBeaconServiceConnect()
{
var beaconService = Xamarin.Forms.DependencyService.Get<IAltBeaconService>();
beaconService.StartMonitoring();
beaconService.StartRanging();
}
#endregion
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/Service/Scanner/DistinctPacketDetectorTest.cs
using System;
using AltBeaconOrg.BoundBeacon.Service.Scanner;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class DistinctPacketDetectorTest
{
[Test]
public void testSecondDuplicatePacketIsNotDistinct() {
DistinctPacketDetector dpd = new DistinctPacketDetector();
dpd.IsPacketDistinct("01:02:03:04:05:06", new byte[] {0x01, 0x02});
bool secondResult = dpd.IsPacketDistinct("01:02:03:04:05:06", new byte[] {0x01, 0x02});
AssertEx.False("second call with same packet should not be distinct", secondResult);
}
[Test]
public void testSecondNonDuplicatePacketIsDistinct() {
DistinctPacketDetector dpd = new DistinctPacketDetector();
dpd.IsPacketDistinct("01:02:03:04:05:06", new byte[] {0x01, 0x02});
bool secondResult = dpd.IsPacketDistinct("01:02:03:04:05:06", new byte[] {0x03, 0x04});
AssertEx.True("second call with different packet should be distinct", secondResult);
}
[Test]
public void testSamePacketForDifferentMacIsDistinct() {
DistinctPacketDetector dpd = new DistinctPacketDetector();
dpd.IsPacketDistinct("01:02:03:04:05:06", new byte[] {0x01, 0x02});
bool secondResult = dpd.IsPacketDistinct("01:01:01:01:01:01", new byte[] {0x01, 0x02});
AssertEx.True("second packet with different mac should be distinct", secondResult);
}
[Test]
public void clearingDetectionsPreventsDistinctDetection() {
DistinctPacketDetector dpd = new DistinctPacketDetector();
dpd.IsPacketDistinct("01:02:03:04:05:06", new byte[] {0x01, 0x02});
dpd.ClearDetections();
bool secondResult = dpd.IsPacketDistinct("01:02:03:04:05:06", new byte[] {0x01, 0x02});
AssertEx.True("second call with same packet after clear should be distinct", secondResult);
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/Simulator/BeaconSimulatorTest.cs
using System;
using AltBeaconOrg.BoundBeacon;
using AltBeaconOrg.BoundBeacon.Simulator;
using NUnit.Framework;
using System.Collections.Generic;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class BeaconSimulatorTest : TestBase
{
[Test]
public void testSetBeacons(){
StaticBeaconSimulator staticBeaconSimulator = new StaticBeaconSimulator();
byte[] beaconBytes = HexStringToByteArray("02011a1bff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c509");
Beacon beacon = new AltBeaconParser().FromScanData(beaconBytes, -55, null);
List<Beacon> beacons = new List<Beacon>();
beacons.Add(beacon);
staticBeaconSimulator.Beacons = beacons;
AssertEx.AreEqual("getBeacons should match values entered with setBeacons", staticBeaconSimulator.Beacons, beacons);
}
[Test]
public void testSetBeaconsEmpty(){
StaticBeaconSimulator staticBeaconSimulator = new StaticBeaconSimulator();
List<Beacon> beacons = new List<Beacon>();
staticBeaconSimulator.Beacons = beacons;
AssertEx.AreEqual("getBeacons should match values entered with setBeacons even when empty", staticBeaconSimulator.Beacons, beacons);
}
[Test]
public void testSetBeaconsNull(){
StaticBeaconSimulator staticBeaconSimulator = new StaticBeaconSimulator();
staticBeaconSimulator.Beacons = null;
AssertEx.AreEqual("getBeacons should return null",staticBeaconSimulator.Beacons, null);
}
}
}
<file_sep>/Samples/Native/BeaconReference.Droid/RangingActivity.cs
using System.Collections.Generic;
using System.Linq;
using AltBeaconOrg.BoundBeacon;
using Android.App;
using Android.OS;
using Android.Widget;
namespace BeaconReference.Droid
{
[Activity]
public class RangingActivity : Activity, IBeaconConsumer, IRangeNotifier
{
protected const string TAG = "RangingActivity";
BeaconManager beaconManager = null;
public RangingActivity()
{
beaconManager = BeaconManager.GetInstanceForApplication(this);
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Title = "Ranging";
SetContentView(Resource.Layout.activity_ranging);
beaconManager.Bind(this);
}
protected override void OnDestroy()
{
base.OnDestroy();
beaconManager.Unbind(this);
}
protected override void OnPause()
{
base.OnPause();
if (beaconManager.IsBound(this)) beaconManager.SetBackgroundMode(true);
}
protected override void OnResume()
{
base.OnResume();
if (beaconManager.IsBound(this)) beaconManager.SetBackgroundMode(false);
}
public void LogToDisplay(string line)
{
RunOnUiThread(() =>
{
var editText = FindViewById<EditText>(Resource.Id.rangingText);
editText.Append(line+"\n");
});
}
#region IBeaconConsumer implementation
public void OnBeaconServiceConnect()
{
beaconManager.AddRangeNotifier(this);
try {
beaconManager.StartRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
}
catch (RemoteException ex) {
}
}
#endregion
#region IRangeNotifier implementation
public void DidRangeBeaconsInRegion(ICollection<Beacon> beacons, Region region)
{
if (beacons.Count > 0) {
Beacon firstBeacon = beacons.First();
LogToDisplay("The first beacon " + firstBeacon.ToString() + " is about " + firstBeacon.Distance + " meters away.");
}
}
#endregion
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary/Beacon.cs
using System;
using Android.Runtime;
namespace AltBeaconOrg.BoundBeacon
{
// Metadata.xml XPath class reference: path="/api/package[@<EMAIL>='org.<EMAIL>']/class[@name='Beacon']"
public partial class Beacon
{
public int DescribeContents()
{
return 0;
}
public void WriteToParcel(Android.OS.Parcel p, Android.OS.ParcelableWriteFlags f)
{
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/Service/BeaconServiceTest.cs
using System;
using AltBeaconOrg.BoundBeacon;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class BeaconServiceTest
{
[SetUp]
public void before() {
BeaconManager.SetsManifestCheckingDisabled(true);
}
/**
* This test verifies that processing a beacon in a scan (which starts its own thread) does not
* affect the size of the available threads in the main Android AsyncTask.THREAD_POOL_EXECUTOR
* @throws Exception
*/
[Test]
[Ignore("Can't test real beacons")]
public void beaconScanCallbackTest() {
//final ServiceController<BeaconService> beaconServiceServiceController =
// Robolectric.buildService(BeaconService.class);
//beaconServiceServiceController.attach();
//BeaconService beaconService = beaconServiceServiceController.get();
//beaconService.onCreate();
//CycledLeScanCallback callback = beaconService.mCycledLeScanCallback;
//ThreadPoolExecutor executor = (ThreadPoolExecutor) AsyncTask.THREAD_POOL_EXECUTOR;
//int activeThreadCountBeforeScan = executor.getActiveCount();
//byte[] scanRecord = new byte[1];
//callback.onLeScan(null, -59, scanRecord);
//int activeThreadCountAfterScan = executor.getActiveCount();
//assertEquals("The size of the Android thread pool should be unchanged by beacon scanning",
// activeThreadCountBeforeScan, activeThreadCountAfterScan);
//// Need to sleep here until the thread in the above method completes, otherwise an exception
//// is thrown. Maybe we don't care about this exception, so we could remove this.
//Thread.sleep(100);
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/BeaconTest.cs
using System;
using System.Collections.Generic;
using AltBeaconOrg.BoundBeacon;
using AltBeaconOrg.BoundBeacon.Distance;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class BeaconTest : TestBase
{
[SetUp]
public void BeforeEachTest()
{
Beacon.SetHardwareEqualityEnforced(false);
}
[Test]
public void TestAccessBeaconIdentifiers() {
Beacon beacon = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
AssertEx.AreEqual("First beacon id should be 1", beacon.GetIdentifier(0).ToString(), "1");
AssertEx.AreEqual("Second beacon id should be 1", beacon.GetIdentifier(1).ToString(), "2");
AssertEx.AreEqual("Third beacon id should be 1", beacon.GetIdentifier(2).ToString(), "3");
AssertEx.AreEqual("First beacon id should be 1", beacon.Id1.ToString(), "1");
AssertEx.AreEqual("Second beacon id should be 1", beacon.Id2.ToString(), "2");
AssertEx.AreEqual("Third beacon id should be 1", beacon.Id3.ToString(), "3");
}
[Test]
public void TestBeaconsWithSameIdentifersAreEqual() {
Beacon beacon1 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
Beacon beacon2 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
//AssertEx.AreEqual("Beacons with same identifiers are equal", beacon1, beacon2);
AssertEx.True("Beacons with same identifiers are equal", beacon1.Equals(beacon2));
}
[Test]
public void TestBeaconsWithDifferentId1AreNotEqual() {
Beacon beacon1 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
Beacon beacon2 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("11").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
AssertEx.True("Beacons with different id1 are not equal", !beacon1.Equals(beacon2));
}
[Test]
public void TestBeaconsWithDifferentId2AreNotEqual() {
Beacon beacon1 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
Beacon beacon2 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("12").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
AssertEx.True("Beacons with different id2 are not equal", !beacon1.Equals(beacon2));
}
[Test]
public void TestBeaconsWithDifferentId3AreNotEqual() {
Beacon beacon1 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
Beacon beacon2 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("13").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
AssertEx.True("Beacons with different id3 are not equal", !beacon1.Equals(beacon2));
}
[Test]
public void TestBeaconsWithSameMacsAreEqual() {
Beacon.SetHardwareEqualityEnforced(true);
Beacon beacon1 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
Beacon beacon2 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
AssertEx.True("Beacons with same same macs are equal", beacon1.Equals(beacon2));
}
[Test]
public void TestBeaconsWithDifferentMacsAreNotEqual() {
Beacon.SetHardwareEqualityEnforced(true);
Beacon beacon1 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
Beacon beacon2 = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:666666").Build();
AssertEx.True("Beacons with different same macs are not equal", !beacon1.Equals(beacon2));
}
[Test]
public void TestCalculateAccuracyWithRssiEqualsPower() {
Beacon.DistanceCalculator = new ModelSpecificDistanceCalculator(null, null);
double accuracy = Beacon.DistanceCalculator.CalculateDistance(-55, -55);
AssertEx.AreEqual("Distance should be one meter if mRssi is the same as power", 1.0, accuracy, 0.1);
}
[Test]
public void TestCalculateAccuracyWithRssiGreaterThanPower() {
Beacon.DistanceCalculator = new ModelSpecificDistanceCalculator(null, null);
double accuracy = Beacon.DistanceCalculator.CalculateDistance(-55, -50);
AssertEx.True("Distance should be under one meter if mRssi is less negative than power. Accuracy was " + accuracy, accuracy < 1.0);
}
[Test]
public void TestCalculateAccuracyWithRssiLessThanPower() {
Beacon.DistanceCalculator = new ModelSpecificDistanceCalculator(null, null);
double accuracy = Beacon.DistanceCalculator.CalculateDistance(-55, -60);
AssertEx.True("Distance should be over one meter if mRssi is less negative than power. Accuracy was "+accuracy, accuracy > 1.0);
}
[Test]
public void TestCalculateAccuracyWithRssiEqualsPowerOnInternalProperties() {
Beacon.DistanceCalculator = new ModelSpecificDistanceCalculator(null, null);
var beacon = new Beacon.Builder().SetTxPower(-55).SetRssi(-55).Build();
double distance = beacon.Distance;
AssertEx.AreEqual("Distance should be one meter if mRssi is the same as power", 1.0, distance, 0.1);
}
[Test]
public void TestCalculateAccuracyWithRssiEqualsPowerOnInternalPropertiesAndRunningAverage() {
var beacon = new Beacon.Builder().SetTxPower(-55).SetRssi(0).Build();
beacon.SetRunningAverageRssi(-55);
double distance = beacon.Distance;
AssertEx.AreEqual("Distance should be one meter if mRssi is the same as power", 1.0, distance, 0.1);
}
[Test]
[Ignore]
//TODO: Implement ISerializable
public void TestCanSerialize() {
var beacon = new AltBeacon.Builder().SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothName("xx")
.SetBluetoothAddress("1:2:3:4:5:6").SetDataFields(new List<Java.Lang.Long> { new Java.Lang.Long(100L) }).Build();
byte[] serializedBeacon = ConvertToBytes(beacon);
Beacon beacon2 = (Beacon) ConvertFromBytes(serializedBeacon);
AssertEx.AreEqual("Right number of identifiers after deserialization", 3, beacon2.Identifiers.Count);
AssertEx.AreEqual("id1 is same after deserialization", beacon.GetIdentifier(0), beacon2.GetIdentifier(0));
AssertEx.AreEqual("id2 is same after deserialization", beacon.GetIdentifier(1), beacon2.GetIdentifier(1));
AssertEx.AreEqual("id3 is same after deserialization", beacon.GetIdentifier(2), beacon2.GetIdentifier(2));
AssertEx.AreEqual("txPower is same after deserialization", beacon.TxPower, beacon2.TxPower);
AssertEx.AreEqual("rssi is same after deserialization", beacon.Rssi, beacon2.Rssi);
AssertEx.AreEqual("distance is same after deserialization", beacon.Distance, beacon2.Distance, 0.001);
AssertEx.AreEqual("bluetoothAddress is same after deserialization", beacon.BluetoothAddress, beacon2.BluetoothAddress);
AssertEx.AreEqual("bluetoothAddress is same after deserialization", beacon.BluetoothName, beacon2.BluetoothName);
AssertEx.AreEqual("beaconTypeCode is same after deserialization", beacon.BeaconTypeCode, beacon2.BeaconTypeCode);
AssertEx.AreEqual("manufacturer is same after deserialization", beacon.Manufacturer, beacon2.Manufacturer);
AssertEx.AreEqual("data field 0 is the same after deserialization", beacon.DataFields[0], beacon2.DataFields[0]);
AssertEx.AreEqual("data field 0 is the right value", beacon.DataFields[0], new Java.Lang.Long(100L));
}
[Test]
public void NoDoubleWrappingOfExtraDataFields() {
Beacon beacon = new AltBeacon.Builder().SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothName("xx")
.SetBluetoothAddress("1:2:3:4:5:6").SetDataFields(new List<Java.Lang.Long> { new Java.Lang.Long(100L) }).Build();
var list = beacon.ExtraDataFields;
beacon.ExtraDataFields = list;
AssertEx.True("getter should return same object after first wrap ", beacon.ExtraDataFields == list);
}
[Test]
public void TestHashCodeWithNullIdentifier() {
Beacon beacon = new AltBeacon.Builder()
.SetIdentifiers(new List<Identifier> { Identifier.Parse("0x1234"), null })
.Build();
AssertEx.True("hashCode() should not throw exception", beacon.GetHashCode() >= int.MinValue);
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/MainActivity.cs
using System.Reflection;
using Android.App;
using Android.OS;
using Xamarin.Android.NUnitLite;
namespace AndroidAltBeaconLibrary.UnitTests
{
[Activity(Label = "AltBeacon Tests", MainLauncher = true)]
public class MainActivity : TestSuiteActivity
{
protected override void OnCreate(Bundle bundle)
{
// tests can be inside the main assembly
AddTest(Assembly.GetExecutingAssembly());
// or in any reference assemblies
// AddTest (typeof (Your.Library.TestClass).Assembly);
// Once you called base.OnCreate(), you cannot add more assemblies.
base.OnCreate(bundle);
}
}
public static class Helpers
{
public static T Cast<T>(this Java.Lang.Object obj) where T : class
{
var propertyInfo = obj.GetType().GetProperty("Instance");
return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}
}
}<file_sep>/Samples/Forms/AltBeaconLibrary.Sample/AltBeaconLibrary.Sample/ListItemView.cs
using System;
using Xamarin.Forms;
namespace AltBeaconLibrary.Sample
{
public class ListItemView : ViewCell
{
public ListItemView()
{
View = BuildContent();
}
private View BuildContent()
{
var viewLayout = new StackLayout()
{
Orientation = StackOrientation.Vertical,
VerticalOptions = LayoutOptions.Fill,
Spacing = 0,
Padding = 0,
};
var beaconId = new Label {
Text = "E4C8A4FC-F68B-470D-959F-29382AF72CE7",
TextColor = Color.Black,
FontFamily = "sans-serif",
FontSize = 17
};
beaconId.SetBinding(Label.TextProperty, "Id");
var beaconIdLayout = new StackLayout {
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.End,
Spacing = 0,
Padding = new Thickness(0, 10, 10, 5),
Children = { beaconId }
};
viewLayout.Children.Add(beaconIdLayout);
var beaconDistance = new Label {
Text = "1.3m",
TextColor = Color.Black,
FontFamily = "sans-serif-light",
FontSize = 36
};
beaconDistance.SetBinding(Label.TextProperty, "Distance");
var beaconDistanceLayout = new StackLayout {
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.End,
Spacing = 0,
Padding = new Thickness(0, 0, 10, 10),
Children = { beaconDistance }
};
viewLayout.Children.Add(beaconDistanceLayout);
return viewLayout;
}
}
}
<file_sep>/README.md
Android AltBeacon Library 
==============================
A Xamarin.Android binding of the [AltBeacon Android Beacon Library](https://github.com/AltBeacon/android-beacon-library). This library allows Android apps to interact with BLE beacons in accordance with the open and interoperable [AltBeacon proximity beacon protocol specification](https://github.com/AltBeacon/spec).
Note: This library uses the Java library version 2.15, and is Android Oreo (8.x) compatible!
## Use
- [Nuget Package](https://www.nuget.org/packages/AndroidAltBeaconLibrary/)
- [Xamarin Component](http://components.xamarin.com/view/android-altbeacon-library)
- Download the binary from [Releases](https://github.com/chrisriesgo/Android-AltBeacon-Library/releases)
## Reference Application
A simple [sample application](https://github.com/chrisriesgo/Android-AltBeacon-Library/tree/master/Samples/Android/AndroidAltBeaconLibrary.Sample) has been included with this repository to demonstrate ranging proximity beacons and a battery-saving background ranging feature.
## Xamarin Component
The [Android AltBeacon Library](http://components.xamarin.com/view/android-altbeacon-library) component is available in the Xamarin Component Store.
## Changes
[current version] - Using java library 2.15: Android Oreo compatible!
_v2.10.0 - [Work in Progress](https://github.com/chrisriesgo/Android-AltBeacon-Library/issues/25)_
[v2.7](https://github.com/chrisriesgo/Android-AltBeacon-Library/releases/tag/2.7)
- Binding of version [2.7](https://github.com/AltBeacon/android-beacon-library/releases/tag/2.7) of the android-beacon-library
[v2.1.4](https://github.com/chrisriesgo/Android-AltBeacon-Library/releases/tag/2.1.4)
- Binding of version [2.1.4](https://github.com/AltBeacon/android-beacon-library/releases/tag/2.1.4) of the android-beacon-library
[v2.1.3](https://github.com/chrisriesgo/Android-AltBeacon-Library/releases/tag/2.1.3)
- Binding of version [2.1.3](https://github.com/AltBeacon/android-beacon-library/releases/tag/2.1.3) of the android-beacon-library
[v2.1.0](https://github.com/chrisriesgo/Android-AltBeacon-Library/releases/tag/2.1.0)
- Binding of version [2.1.2](https://github.com/AltBeacon/android-beacon-library/releases/tag/2.1.2) of the android-beacon-library
[v2.0](https://github.com/chrisriesgo/Android-AltBeacon-Library/releases/tag/2.0)
- Initial binding of the android-beacon-library
## Have I Missed Something?
Log a new issue, or fork this repository, and submit a pull request
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/TestBase.cs
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Java.IO;
namespace AndroidAltBeaconLibrary.UnitTests
{
public class TestBase
{
public static byte[] HexStringToByteArray(String s)
{
int len = s.Length;
var data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
{
data[i / 2] = (byte)((Convert.ToByte(s.Substring(i, 1), 16) << 4) + (Convert.ToByte(s.Substring(i + 1, 1), 16)));
}
return data;
}
public static String ByteArrayToHexString(byte[] bytes)
{
var sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++) {
sb.AppendFormat("{0:x2}", bytes[i]);
}
return sb.ToString();
}
// utilty methods for testing serialization
protected byte[] ConvertToBytes(Java.Lang.Object obj)
{
// var bf = new BinaryFormatter();
//using (var ms = new MemoryStream())
//{
// bf.Serialize(ms, obj);
// return ms.ToArray();
//}
using(var bos = new MemoryStream())
using(var oos = new Java.IO.ObjectOutputStream(bos))
{
oos.WriteObject(obj);
return bos.ToArray();
}
}
protected Java.Lang.Object ConvertFromBytes(byte[] bytes)
{
using (var ms = new MemoryStream())
using (var ois = new ObjectInputStream(ms))
{
//var binForm = new BinaryFormatter();
//memStream.Write(bytes, 0, bytes.Length);
//memStream.Seek(0, SeekOrigin.Begin);
//var obj = binForm.Deserialize(memStream);
//return obj;
return ois.ReadObject();
}
}
}
}<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/RegionTest.cs
using System;
using System.Collections.Generic;
using AltBeaconOrg.BoundBeacon;
using Java.Lang;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class RegionTest
{
[Test]
public void testBeaconMatchesRegionWithSameIdentifiers() {
Beacon beacon = new AltBeacon.Builder().SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothAddress("1:2:3:4:5:6").Build();
Region region = new Region("myRegion", Identifier.Parse("1"), Identifier.Parse("2"), Identifier.Parse("3"));
AssertEx.True("Beacon should match region with all identifiers the same", region.MatchesBeacon(beacon));
}
[Test]
public void testBeaconMatchesRegionWithSameIdentifier1() {
Beacon beacon = new AltBeacon.Builder().SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothAddress("1:2:3:4:5:6").Build();
Region region = new Region("myRegion", Identifier.Parse("1"), null, null);
AssertEx.True("Beacon should match region with first identifier the same", region.MatchesBeacon(beacon));
}
[Test]
public void testBeaconMatchesRegionWithSameIdentifier1And2() {
Beacon beacon = new AltBeacon.Builder().SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothAddress("1:2:3:4:5:6").Build();
Region region = new Region("myRegion", Identifier.Parse("1"), Identifier.Parse("2"), null);
AssertEx.True("Beacon should match region with first two identifiers the same", region.MatchesBeacon(beacon));
}
[Test]
public void testBeaconMatchesRegionWithDifferentIdentifier1() {
Beacon beacon = new AltBeacon.Builder().SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothAddress("1:2:3:4:5:6").Build();
Region region = new Region("myRegion", Identifier.Parse("22222"), null, null);
AssertEx.True("Beacon should not match region with first identifier different", !region.MatchesBeacon(beacon));
}
[Test]
public void testBeaconMatchesRegionWithShorterIdentifierList() {
Beacon beacon = new AltBeacon.Builder().SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothAddress("1:2:3:4:5:6").Build();
Region region = new Region("myRegion", new List<Identifier> { Identifier.Parse("1") });
AssertEx.True("Beacon should match region with first identifier equal and shorter Identifier list", region.MatchesBeacon(beacon));
}
[Test]
public void testBeaconMatchesRegionWithSingleNullIdentifierList() {
Beacon beacon = new AltBeacon.Builder().SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothAddress("1:2:3:4:5:6").Build();
var identifiers = new List<Identifier>();
identifiers.Add(null);
Region region = new Region("all-beacons-region", identifiers);
AssertEx.True("Beacon should match region with first identifier null and shorter Identifier list", region.MatchesBeacon(beacon));
}
[Test]
public void testBeaconDoesntMatchRegionWithLongerIdentifierList() {
Beacon beacon = new Beacon.Builder().SetId1("1").SetId2("2").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothAddress("1:2:3:4:5:6").Build();
Region region = new Region("myRegion", Identifier.Parse("1"), Identifier.Parse("2"), Identifier.Parse("3"));
AssertEx.False("Beacon should not match region with more identifers than the beacon", region.MatchesBeacon(beacon));
}
[Test]
public void testBeaconDoesMatchRegionWithLongerIdentifierListWithSomeNull() {
Beacon beacon = new Beacon.Builder().SetId1("1").SetId2("2").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothAddress("1:2:3:4:5:6").Build();
Region region = new Region("myRegion", null, null, null);
AssertEx.True("Beacon should match region with more identifers than the beacon, if the region identifiers are null", region.MatchesBeacon(beacon));
}
[Test]
public void testBeaconMatchesRegionWithSameBluetoothMac() {
Beacon beacon = new AltBeacon.Builder().SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothAddress("01:02:03:04:05:06").Build();
Region region = new Region("myRegion", "01:02:03:04:05:06");
AssertEx.True("Beacon should match region with mac the same", region.MatchesBeacon(beacon));
}
[Test]
public void testBeaconDoesNotMatchRegionWithDiffrentBluetoothMac() {
Beacon beacon = new AltBeacon.Builder().SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothAddress("01:02:03:04:05:06").Build();
Region region = new Region("myRegion", "01:02:03:04:05:99");
AssertEx.False("Beacon should match region with mac the same", region.MatchesBeacon(beacon));
}
[Test]
public void testBeaconMatchesRegionWithSameBluetoothMacAndIdentifiers() {
Beacon beacon = new AltBeacon.Builder().SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6).SetBluetoothAddress("01:02:03:04:05:06").Build();
var identifiers = new List<Identifier>();
identifiers.Add(Identifier.Parse("1"));
identifiers.Add(Identifier.Parse("2"));
identifiers.Add(Identifier.Parse("3"));
Region region = new Region("myRegion", identifiers , "01:02:03:04:05:06");
AssertEx.True("Beacon should match region with mac the same", region.MatchesBeacon(beacon));
}
[Test]
[Ignore("Figure out serialization")]
public void testCanSerialize() {
Region region = new Region("myRegion", Identifier.Parse("1"), Identifier.Parse("2"), null);
//TODO: figure out serialization
//byte[] serializedRegion = convertToBytes(region);
//Region region2 = (Region) convertFromBytes(serializedRegion);
//AssertEx.AreEqual("Right number of identifiers after deserialization", 3, region2.Identifiers.Count);
//AssertEx.AreEqual("uniqueId is same after deserialization", region.UniqueId, region2.UniqueId);
//AssertEx.AreEqual("id1 is same after deserialization", region.GetIdentifier(0), region2.GetIdentifier(0));
//AssertEx.AreEqual("id2 is same after deserialization", region.GetIdentifier(1), region2.GetIdentifier(1));
//AssertEx.Null("id3 is null before deserialization", region.GetIdentifier(2));
//AssertEx.Null("id3 is null after deserialization", region2.GetIdentifier(2));
}
[Test]
[Ignore("Figure out serialization")]
public void testCanSerializeWithMac() {
Region region = new Region("myRegion", "1B:2a:03:4C:6E:9F");
//TODO: figure out serialization
//byte[] serializedRegion = convertToBytes(region);
//Region region2 = (Region) convertFromBytes(serializedRegion);
//AssertEx.AreEqual("Right number of identifiers after deserialization", 0, region2.Identifiers.Count);
//AssertEx.AreEqual("ac is same after deserialization", region.BluetoothAddress, region2.BluetoothAddress);
}
[Test]
public void rejectsInvalidMac() {
try {
Region region = new Region("myRegion", "this string is not a valid mac address!");
AssertEx.True("IllegalArgumentException should have been thrown", false);
}
catch (IllegalArgumentException e) {
AssertEx.AreEqual("Error message should be as expected",
"Invalid mac address: 'this string is not a valid mac address!' Must be 6 hex bytes separated by colons.",
e.Message);
}
}
[Test]
public void testToString() {
Region region = new Region("myRegion", Identifier.Parse("1"), Identifier.Parse("2"), null);
AssertEx.AreEqual("Not equal", "id1: 1 id2: 2 id3: null", region.ToString());
}
[Test]
public void testConvenienceIdentifierAccessors() {
Region region = new Region("myRegion", Identifier.Parse("1"), Identifier.Parse("2"), Identifier.Parse("3"));
AssertEx.AreEqual("Not equal", "1", region.Id1.ToString());
AssertEx.AreEqual("Not equal", "2", region.Id2.ToString());
AssertEx.AreEqual("Not equal", "3", region.Id3.ToString());
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/BeaconTransmitterTest.cs
using System;
using System.Collections.Generic;
using AltBeaconOrg.BoundBeacon;
using Android.App;
using Android.Content;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class BeaconTransmitterTest
{
[Test]
[Ignore]
public void TestBeaconAdvertisingBytes() {
Context context = Application.Context;
Beacon beacon = new Beacon.Builder()
.SetId1("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6")
.SetId2("1")
.SetId3("2")
.SetManufacturer(0x0118)
.SetTxPower(-59)
.SetDataFields(new List<Java.Lang.Long> { new Java.Lang.Long(0L) })
.Build();
BeaconParser beaconParser = new BeaconParser()
.SetBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
byte[] data = beaconParser.GetBeaconAdvertisementData(beacon);
BeaconTransmitter beaconTransmitter = new BeaconTransmitter(context, beaconParser);
// TODO: can't actually start transmitter here because Robolectric does not support API 21
AssertEx.AreEqual("Data should be 24 bytes long", 24, data.Length);
String byteString = "";
for (int i = 0; i < data.Length; i++) {
byteString += String.Format("{0:x2}", data[i]);
byteString += " ";
}
AssertEx.AreEqual("Advertisement bytes should be as expected", "BE AC 2F 23 44 54 CF 6D 4A 0F AD F2 F4 91 1B A9 FF A6 00 01 00 02 C5 00 ", byteString);
}
[Test]
[Ignore]
public void TestBeaconAdvertisingBytesForEddystone() {
Context context = Application.Context;
Beacon beacon = new Beacon.Builder()
.SetId1("0x2f234454f4911ba9ffa6")
.SetId2("0x000000000001")
.SetManufacturer(0x0118)
.SetTxPower(-59)
.Build();
BeaconParser beaconParser = new BeaconParser()
.SetBeaconLayout("s:0-1=feaa,m:2-2=00,p:3-3:-41,i:4-13,i:14-19");
byte[] data = beaconParser.GetBeaconAdvertisementData(beacon);
BeaconTransmitter beaconTransmitter = new BeaconTransmitter(context, beaconParser);
// TODO: can't actually start transmitter here because Robolectric does not support API 21
String byteString = "";
for (int i = 0; i < data.Length; i++) {
byteString += String.Format("{0:x2}", data[i]);
byteString += " ";
}
AssertEx.AreEqual("Data should be 24 bytes long", 18, data.Length);
AssertEx.AreEqual("Advertisement bytes should be as expected", "00 C5 2F 23 44 54 F4 91 1B A9 FF A6 00 00 00 00 00 01 ", byteString);
}
}
}
<file_sep>/Samples/Forms/AltBeaconLibrary.Sample/AltBeaconLibrary.Sample/BeaconViewModel.cs
using System;
using System.Collections.ObjectModel;
using Xamarin.Forms;
using System.Collections.Generic;
namespace AltBeaconLibrary.Sample
{
public class BeaconViewModel
{
public BeaconViewModel()
{
Data = new List<SharedBeacon>();
}
public event EventHandler ListChanged;
public List<SharedBeacon> Data { get; set; }
public void Init()
{
var beaconService = DependencyService.Get<IAltBeaconService>();
beaconService.ListChanged += (sender, e) =>
{
Data = e.Data;
OnListChanged();
};
beaconService.DataClearing += (sender, e) =>
{
Data.Clear();
OnListChanged();
};
beaconService.InitializeService();
}
private void OnListChanged()
{
var handler = ListChanged;
if(handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/Service/RunningAverageRssiFilterTest.cs
using System;
using NUnit.Framework;
using AltBeaconOrg.BoundBeacon.Service;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class RunningAverageRssiFilterTest
{
[Test]
public void initTest1() {
RunningAverageRssiFilter filter = new RunningAverageRssiFilter();
filter.AddMeasurement(new Java.Lang.Integer(-50));
AssertEx.AreEqual("First measurement should be -50", filter.CalculateRssi().ToString("F1"), "-50.0");
}
}
}
<file_sep>/Samples/Native/BeaconReference.Droid/BeaconReferenceApplication.cs
using System;
using Android.App;
using AltBeaconOrg.BoundBeacon.Startup;
using AltBeaconOrg.BoundBeacon;
using AltBeaconOrg.BoundBeacon.Powersave;
using System.Diagnostics;
using Android.Content;
using NotificationCompat = Android.Support.V4.App.NotificationCompat;
using Android.Runtime;
namespace BeaconReference.Droid
{
[Application]
public class BeaconReferenceApplication : Application, IBootstrapNotifier
{
const string TAG = "BeaconReferenceApp";
RegionBootstrap regionBootstrap;
BackgroundPowerSaver backgroundPowerSaver;
bool haveDetectedBeaconsSinceBoot = false;
MonitoringActivity monitoringActivity = null;
public BeaconReferenceApplication(IntPtr handle, JniHandleOwnership ownerShip) : base(handle, ownerShip)
{
}
public override void OnCreate()
{
base.OnCreate();
var beaconManager = BeaconManager.GetInstanceForApplication(this);
// By default the AndroidBeaconLibrary will only find AltBeacons. If you wish to make it
// find a different type of beacon, you must specify the byte layout for that beacon's
// advertisement with a line like below. The example shows how to find a beacon with the
// same byte layout as AltBeacon but with a beaconTypeCode of 0xaabb. To find the proper
// layout expression for other beacon types, do a web search for "setBeaconLayout"
// including the quotes.
//
//beaconManager.getBeaconParsers().clear();
//beaconManager.getBeaconParsers().add(new BeaconParser().
// setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
//
// Estimote
// iBeacons
//beaconManager.getBeaconParsers().add(new BeaconParser().
// setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
var altBeaconParser = new BeaconParser();
altBeaconParser.SetBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
beaconManager.BeaconParsers.Add(altBeaconParser);
var iBeaconParser = new BeaconParser();
iBeaconParser.SetBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24");
beaconManager.BeaconParsers.Add(iBeaconParser);
Debug.WriteLine("setting up background monitoring for beacons and power saving", TAG);
// wake up the app when a beacon is seen
var region = new Region("backgroundRegion", null, null, null);
regionBootstrap = new RegionBootstrap(this, region);
// simply constructing this class and holding a reference to it in your custom Application
// class will automatically cause the BeaconLibrary to save battery whenever the application
// is not visible. This reduces bluetooth power usage by about 60%
backgroundPowerSaver = new BackgroundPowerSaver(this);
// If you wish to test beacon detection in the Android Emulator, you can use code like this:
//BeaconManager.BeaconSimulator = new TimedBeaconSimulator();
//if (BeaconManager.BeaconSimulator is TimedBeaconSimulator simulator) {
// //simulator.CreateTimedSimulatedBeacons();
// simulator.CreateBasicSimulatedBeacons();
//}
}
public void SetMonitoringActivity(MonitoringActivity activity)
{
monitoringActivity = activity;
}
#region IBootstrapNotifier implementation
public void DidEnterRegion(Region region)
{
// In this example, this class sends a notification to the user whenever a Beacon
// matching a Region (defined above) are first seen.
Debug.WriteLine("did enter region.", TAG);
if (!haveDetectedBeaconsSinceBoot)
{
Debug.WriteLine("auto launching MainActivity", TAG);
// The very first time since boot that we detect an beacon, we launch the
// MainActivity
var intent = new Intent(this, typeof(MonitoringActivity));
intent.SetFlags(ActivityFlags.NewTask);
// Important: make sure to add android:launchMode="singleInstance" in the manifest
// to keep multiple copies of this activity from getting created if the user has
// already manually launched the app.
this.StartActivity(intent);
haveDetectedBeaconsSinceBoot = true;
}
else
{
if (monitoringActivity != null)
{
// If the Monitoring Activity is visible, we log info about the beacons we have
// seen on its display
monitoringActivity.LogToDisplay("I see a beacon again");
}
else
{
// If we have already seen beacons before, but the monitoring activity is not in
// the foreground, we send a notification to the user on subsequent detections.
Debug.WriteLine("Sending notification.", TAG);
SendNotification();
}
}
}
public void DidExitRegion(Region region)
{
if (monitoringActivity != null)
{
monitoringActivity.LogToDisplay("I no longer see a beacon.");
}
}
public void DidDetermineStateForRegion(int state, Region region)
{
if (monitoringActivity != null)
{
monitoringActivity.LogToDisplay("I have just switched from seeing/not seeing beacons: " + state);
}
}
#endregion
void SendNotification()
{
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.SetContentTitle("Beacon Reference Application")
.SetContentText("An beacon is nearby.")
.SetSmallIcon(Resource.Mipmap.Icon);
var stackBuilder = TaskStackBuilder.Create(this);
stackBuilder.AddNextIntent(new Intent(this, typeof(MonitoringActivity)));
PendingIntent resultPendingIntent =
stackBuilder.GetPendingIntent(
0,
PendingIntentFlags.UpdateCurrent
);
builder.SetContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager)this.GetSystemService(Context.NotificationService);
notificationManager.Notify(1, builder.Build());
}
}
}
<file_sep>/Samples/Forms/AltBeaconLibrary.Sample/AltBeaconLibrary.Sample/MainPage.cs
using System;
using Xamarin.Forms;
using System.Collections.ObjectModel;
namespace AltBeaconLibrary.Sample
{
public class MainPage : ContentPage
{
ListView _list;
BeaconViewModel _viewModel;
public MainPage()
{
BackgroundColor = Color.White;
Title = "AltBeacon Forms Sample";
_viewModel = new BeaconViewModel();
_viewModel.ListChanged += (sender, e) =>
{
_list.ItemsSource = _viewModel.Data;
};
BindingContext = _viewModel;
Content = BuildContent();
}
private View BuildContent()
{
_list = new ListView {
VerticalOptions = LayoutOptions.FillAndExpand,
ItemTemplate = new DataTemplate(typeof(ListItemView)),
RowHeight = 90,
};
_list.SetBinding(ListView.ItemsSourceProperty, "Data");
return _list;
}
protected override void OnAppearing()
{
base.OnAppearing();
_viewModel.Init();
}
}
}<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary/ModelSpecificInstanceUpdater.cs
using System;
namespace AltBeaconOrg.BoundBeacon.Distance {
// Metadata.xml XPath class reference: path="/api/package[@<EMAIL>='org.<EMAIL>']/class[@name='ModelSpecificDistanceUpdater']"
public partial class ModelSpecificDistanceUpdater {
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
{
_DoInBackground((Java.Lang.Void[])@params);
return null;
}
}
}<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/Service/MonitoringStatusTest.cs
using System;
using AltBeaconOrg.BoundBeacon;
using AltBeaconOrg.BoundBeacon.Service;
using Android.Content;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class MonitoringStatusTest
{
//[SetUp]
//public void before() {
// BeaconManager.SetsManifestCheckingDisabled(true);
//}
//[Test]
//public void savesStatusOfUpTo50RegionsTest() {
// Context context = Android.App.Application.Context;
// MonitoringStatus monitoringStatus = new MonitoringStatus(context);
// for (int i = 0; i < 50; i++) {
// Region region = new Region(""+i, null, null, null);
// monitoringStatus.AddRegion(region, null);
// }
// monitoringStatus.saveMonitoringStatusIfOn();
// MonitoringStatus monitoringStatus2 = new MonitoringStatus(context);
// AssertEx.AreEqual("restored regions should be same number as saved", 50, monitoringStatus2.regions().size());
//}
//[Test]
//public void clearsStatusOfOver50RegionsTest() {
// Context context = Android.App.Application.Context;
// MonitoringStatus monitoringStatus = new MonitoringStatus(context);
// for (int i = 0; i < 51; i++) {
// Region region = new Region(""+i, null, null, null);
// monitoringStatus.AddRegion(region, null);
// }
// monitoringStatus.saveMonitoringStatusIfOn();
// MonitoringStatus monitoringStatus2 = new MonitoringStatus(context);
// AssertEx.AreEqual("restored regions should be none", 0, monitoringStatus2.regions().size());
//}
//[Test]
//public void refusesToRestoreRegionsIfTooMuchTimeHasPassedSinceSavingTest() {
// Context context = Android.App.Application.Context;
// MonitoringStatus monitoringStatus = new MonitoringStatus(context);
// for (int i = 0; i < 50; i++) {
// Region region = new Region(""+i, null, null, null);
// monitoringStatus.AddRegion(region, null);
// }
// monitoringStatus.saveMonitoringStatusIfOn();
// // Set update time to one hour ago
// monitoringStatus.updateMonitoringStatusTime(System.currentTimeMillis() - 1000*3600l);
// MonitoringStatus monitoringStatus2 = new MonitoringStatus(context);
// AssertEx.AreEqual("restored regions should be none", 0, monitoringStatus2.regions().size());
//}
//[Test]
//public void allowsAccessToRegionsAfterRestore() {
// Context context = Android.App.Application.Context;
// MonitoringStatus monitoringStatus = new MonitoringStatus(context);
// for (int i = 0; i < 50; i++) {
// Region region = new Region(""+i, null, null, null);
// monitoringStatus.AddRegion(region, null);
// }
// monitoringStatus.saveMonitoringStatusIfOn();
// BeaconManager beaconManager = BeaconManager.GetInstanceForApplication(context);
// var regions = beaconManager.MonitoredRegions;
// AssertEx.AreEqual("beaconManager should return restored regions", 50, regions.size());
//}
}
}
<file_sep>/Samples/Forms/AltBeaconLibrary.Sample/Android/Services/AltBeaconService.cs
using System;
using AltBeaconOrg.BoundBeacon;
using AltBeaconLibrary.Sample.Droid.Services;
using Android.Widget;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Android.App;
[assembly: Xamarin.Forms.Dependency(typeof(AltBeaconService))]
namespace AltBeaconLibrary.Sample.Droid.Services
{
public class AltBeaconService : Java.Lang.Object, IAltBeaconService
{
private readonly MonitorNotifier _monitorNotifier;
private readonly RangeNotifier _rangeNotifier;
private BeaconManager _beaconManager;
Region _tagRegion;
Region _emptyRegion;
private ListView _list;
private readonly List<Beacon> _data;
public AltBeaconService()
{
_monitorNotifier = new MonitorNotifier();
_rangeNotifier = new RangeNotifier();
_data = new List<Beacon>();
}
public event EventHandler<ListChangedEventArgs> ListChanged;
public event EventHandler DataClearing;
public BeaconManager BeaconManagerImpl
{
get {
if (_beaconManager == null)
{
_beaconManager = InitializeBeaconManager();
}
return _beaconManager;
}
}
public void InitializeService()
{
_beaconManager = InitializeBeaconManager();
}
private BeaconManager InitializeBeaconManager()
{
// Enable the BeaconManager
BeaconManager bm = BeaconManager.GetInstanceForApplication(Xamarin.Forms.Forms.Context);
#region Set up Beacon Simulator if testing without a BLE device
// var beaconSimulator = new BeaconSimulator();
// beaconSimulator.CreateBasicSimulatedBeacons();
//
// BeaconManager.BeaconSimulator = beaconSimulator;
#endregion
var iBeaconParser = new BeaconParser();
// Estimote > 2013
iBeaconParser.SetBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24");
bm.BeaconParsers.Add(iBeaconParser);
_monitorNotifier.EnterRegionComplete += EnteredRegion;
_monitorNotifier.ExitRegionComplete += ExitedRegion;
_monitorNotifier.DetermineStateForRegionComplete += DeterminedStateForRegionComplete;
_rangeNotifier.DidRangeBeaconsInRegionComplete += RangingBeaconsInRegion;
_tagRegion = new AltBeaconOrg.BoundBeacon.Region("myUniqueBeaconId", Identifier.Parse("E4C8A4FC-F68B-470D-959F-29382AF72CE7"), null, null);
_tagRegion = new AltBeaconOrg.BoundBeacon.Region("myUniqueBeaconId", Identifier.Parse("B9407F30-F5F8-466E-AFF9-25556B57FE6D"), null, null);
_emptyRegion = new AltBeaconOrg.BoundBeacon.Region("myEmptyBeaconId", null, null, null);
bm.SetBackgroundMode(false);
bm.Bind((IBeaconConsumer)Xamarin.Forms.Forms.Context);
return bm;
}
public void StartMonitoring()
{
BeaconManagerImpl.SetForegroundBetweenScanPeriod(5000); // 5000 milliseconds
BeaconManagerImpl.SetMonitorNotifier(_monitorNotifier);
_beaconManager.StartMonitoringBeaconsInRegion(_tagRegion);
_beaconManager.StartMonitoringBeaconsInRegion(_emptyRegion);
}
public void StartRanging()
{
BeaconManagerImpl.SetForegroundBetweenScanPeriod(5000); // 5000 milliseconds
BeaconManagerImpl.SetRangeNotifier(_rangeNotifier);
_beaconManager.StartRangingBeaconsInRegion(_tagRegion);
_beaconManager.StartRangingBeaconsInRegion(_emptyRegion);
}
private void DeterminedStateForRegionComplete(object sender, MonitorEventArgs e)
{
Console.WriteLine("DeterminedStateForRegionComplete");
}
private void ExitedRegion(object sender, MonitorEventArgs e)
{
Console.WriteLine("ExitedRegion");
}
private void EnteredRegion(object sender, MonitorEventArgs e)
{
Console.WriteLine("EnteredRegion");
}
async void RangingBeaconsInRegion(object sender, RangeEventArgs e)
{
await ClearData();
var allBeacons = new List<Beacon>();
if(e.Beacons.Count > 0)
{
foreach(var b in e.Beacons)
{
allBeacons.Add(b);
}
var orderedBeacons = allBeacons.OrderBy(b => b.Distance).ToList();
await UpdateData(orderedBeacons);
}
else
{
// unknown
await ClearData();
}
}
private async Task UpdateData(List<Beacon> beacons)
{
await Task.Run(() =>
{
var newBeacons = new List<Beacon>();
foreach(var beacon in beacons)
{
if(_data.All(b => b.Id1.ToString() == beacon.Id1.ToString()))
{
newBeacons.Add(beacon);
}
}
((Activity)Xamarin.Forms.Forms.Context).RunOnUiThread(() =>
{
foreach(var beacon in newBeacons)
{
_data.Add(beacon);
}
if (newBeacons.Count > 0)
{
_data.Sort((x,y) => x.Distance.CompareTo(y.Distance));
UpdateList();
}
});
});
}
private async Task ClearData()
{
((Activity)Xamarin.Forms.Forms.Context).RunOnUiThread(() =>
{
_data.Clear();
OnDataClearing();
});
}
private void OnDataClearing()
{
var handler = DataClearing;
if(handler != null)
{
handler(this, EventArgs.Empty);
}
}
private void UpdateList()
{
((Activity)Xamarin.Forms.Forms.Context).RunOnUiThread(() =>
{
OnListChanged();
});
}
private void OnListChanged()
{
var handler = ListChanged;
if(handler != null)
{
var data = new List<SharedBeacon>();
_data.ForEach(b =>
{
data.Add(new SharedBeacon { Id = b.Id1.ToString(), Distance = string.Format("{0:N2}m", b.Distance)});
});
handler(this, new ListChangedEventArgs(data));
}
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/Distance/ModelSpecificDistanceCalculatorTest.cs
using System;
using AltBeaconOrg.BoundBeacon.Distance;
using Android.Content;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class ModelSpecificDistanceCalculatorTest
{
[Test]
public void testCalculatesDistance() {
ModelSpecificDistanceCalculator distanceCalculator = new ModelSpecificDistanceCalculator(null, null);
Double distance = distanceCalculator.CalculateDistance(-59, -59);
AssertEx.AreEqual("Distance should be 1.0 for same power and rssi", 1.0, distance, 0.1);
}
[Test]
public void testSelectsDefaultModel() {
ModelSpecificDistanceCalculator distanceCalculator = new ModelSpecificDistanceCalculator(null, null);
AssertEx.AreEqual("Default model should be Nexus 5", "Nexus 5", distanceCalculator.Model.Model);
}
[Test]
public void testSelectsNexus4OnExactMatch() {
AndroidModel model = new AndroidModel("4.4.2", "KOT49H","Nexus 4","LGE");
ModelSpecificDistanceCalculator distanceCalculator = new ModelSpecificDistanceCalculator(null, null, model);
AssertEx.AreEqual("should be Nexus 4", "Nexus 4", distanceCalculator.Model.Model);
}
[Test]
public void testCalculatesDistanceForMotoXPro() {
Context applicationContext = Android.App.Application.Context;
AndroidModel model = new AndroidModel("5.0.2", "LXG22.67-7.1", "Moto X Pro", "XT1115");
ModelSpecificDistanceCalculator distanceCalculator = new ModelSpecificDistanceCalculator(applicationContext, null, model);
AssertEx.AreEqual("should be Moto X Pro", "Moto X Pro", distanceCalculator.Model.Model);
Double distance = distanceCalculator.CalculateDistance(-49, -58);
AssertEx.AreEqual("Distance should be as predicted by coefficients at 3 meters", 2.661125466, distance, 0.1);
}
[Test]
[Ignore("Can't test private methods")]
public void testConcurrentModificationException() {
//Context applicationContext = Android.App.Application.Context;
//AndroidModel model = new AndroidModel("4.4.2", "KOT49H", "Nexus 4", "LGE");
//String modelMapJson =
// "{\"models\":[ \"coefficient1\": 0.89976,\"coefficient2\": 7.7095,\"coefficient3\": 0.111," +
// "\"version\":\"4.4.2\",\"build_number\":\"KOT49H\",\"model\":\"Nexus 4\"," +
// "\"manufacturer\":\"LGE\"},{\"coefficient1\": 0.42093,\"coefficient2\": 6.9476," +
// "\"coefficient3\": 0.54992,\"version\":\"4.4.2\",\"build_number\":\"LPV79\"," +
// "\"model\":\"Nexus 5\",\"manufacturer\":\"LGE\",\"default\": true}]}";
//ModelSpecificDistanceCalculator distanceCalculator =
// new ModelSpecificDistanceCalculator(applicationContext, null, model);
//Runnable runnable2 = new Runnable() {
// @Override
// public void run() {
// try {
// while (true) {
// distanceCalculator.buildModelMapWithLock(modelMapJson);
// }
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// }
//};
//Thread thread2 = new Thread(runnable2);
//thread2.start();
//int i = 0;
//while (++i < 1000 && thread2.getState() != Thread.State.TERMINATED) {
// distanceCalculator.findCalculatorForModelWithLock(model);
//}
//thread2.interrupt();
}
}
}
<file_sep>/Samples/Native/BeaconReference.Droid/TimedBeaconSimulator.cs
using System;
using System.Collections.Generic;
using AltBeaconOrg.BoundBeacon;
using AltBeaconOrg.BoundBeacon.Simulator;
using Java.Lang;
using Java.Util.Concurrent;
namespace BeaconReference.Droid
{
public class TimedBeaconSimulator : Java.Lang.Object, IBeaconSimulator
{
protected const string TAG = "TimedBeaconSimulator";
IScheduledExecutorService scheduleTaskExecutor;
public IList<Beacon> Beacons { get; set; }
public TimedBeaconSimulator()
{
Beacons = new List<Beacon>();
}
/*
* You may simulate detection of beacons by creating a class like this in your project.
* This is especially useful for when you are testing in an Emulator or on a device without BluetoothLE capability.
*
* Uncomment the lines in BeaconReferenceApplication starting with:
* // If you wish to test beacon detection in the Android Emulator, you can use code like this:
* Then set USE_SIMULATED_BEACONS = true to initialize the sample code in this class.
* If using a Bluetooth incapable test device (i.e. Emulator), you will want to comment
* out the verifyBluetooth() in MonitoringActivity.java as well.
*
* Any simulated beacons will automatically be ignored when building for production.
*/
public bool USE_SIMULATED_BEACONS = true;
public void CreateBasicSimulatedBeacons() {
if (USE_SIMULATED_BEACONS) {
Beacon beacon1 = new AltBeacon.Builder().SetId1("DF7E1C79-43E9-44FF-886F-1D1F7DA6997A")
.SetId2("1").SetId3("1").SetRssi(-55).SetTxPower(-55).Build();
Beacon beacon2 = new AltBeacon.Builder().SetId1("DF7E1C79-43E9-44FF-886F-1D1F7DA6997A")
.SetId2("1").SetId3("2").SetRssi(-55).SetTxPower(-55).Build();
Beacon beacon3 = new AltBeacon.Builder().SetId1("DF7E1C79-43E9-44FF-886F-1D1F7DA6997A")
.SetId2("1").SetId3("3").SetRssi(-55).SetTxPower(-55).Build();
Beacon beacon4 = new AltBeacon.Builder().SetId1("DF7E1C79-43E9-44FF-886F-1D1F7DA6997A")
.SetId2("1").SetId3("4").SetRssi(-55).SetTxPower(-55).Build();
Beacons.Add(beacon1);
Beacons.Add(beacon2);
Beacons.Add(beacon3);
Beacons.Add(beacon4);
}
}
public void CreateTimedSimulatedBeacons() {
if (USE_SIMULATED_BEACONS){
Beacons = new List<Beacon>();
Beacon beacon1 = new AltBeacon.Builder().SetId1("DF7E1C79-43E9-44FF-886F-1D1F7DA6997A")
.SetId2("1").SetId3("1").SetRssi(-55).SetTxPower(-55).Build();
Beacon beacon2 = new AltBeacon.Builder().SetId1("DF7E1C79-43E9-44FF-886F-1D1F7DA6997A")
.SetId2("1").SetId3("2").SetRssi(-55).SetTxPower(-55).Build();
Beacon beacon3 = new AltBeacon.Builder().SetId1("DF7E1C79-43E9-44FF-886F-1D1F7DA6997A")
.SetId2("1").SetId3("3").SetRssi(-55).SetTxPower(-55).Build();
Beacon beacon4 = new AltBeacon.Builder().SetId1("DF7E1C79-43E9-44FF-886F-1D1F7DA6997A")
.SetId2("1").SetId3("4").SetRssi(-55).SetTxPower(-55).Build();
Beacons.Add(beacon1);
Beacons.Add(beacon2);
Beacons.Add(beacon3);
Beacons.Add(beacon4);
var finalBeacons = new List<Beacon>(Beacons);
//Clearing beacons list to prevent all beacons from appearing immediately.
//These will be added back into the beacons list from finalBeacons later.
Beacons.Clear();
scheduleTaskExecutor = Executors.NewScheduledThreadPool(5);
// This schedules an beacon to appear every 10 seconds:
scheduleTaskExecutor.ScheduleAtFixedRate(new Runnable(() =>
{
try{
//putting a single beacon back into the beacons list.
if (finalBeacons.Count > Beacons.Count)
Beacons.Add(finalBeacons[Beacons.Count]);
else
scheduleTaskExecutor.Shutdown();
}
catch(Java.Lang.Exception ex) {
ex.PrintStackTrace();
}
}), 0, 10, TimeUnit.Seconds);
}
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/Service/ExtraDataBeaconTrackerTest.cs
using System;
using System.Collections.Generic;
using AltBeaconOrg.BoundBeacon;
using AltBeaconOrg.BoundBeacon.Service;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class ExtraDataBeaconTrackerTest
{
Beacon getManufacturerBeacon() {
return new Beacon.Builder().SetId1("1")
.SetBluetoothAddress("01:02:03:04:05:06")
.Build();
}
Beacon getGattBeacon() {
return new Beacon.Builder().SetId1("1")
.SetBluetoothAddress("01:02:03:04:05:06")
.SetServiceUuid(1234)
.Build();
}
Beacon getGattBeaconUpdate() {
return new Beacon.Builder().SetId1("1")
.SetBluetoothAddress("01:02:03:04:05:06")
.SetServiceUuid(1234)
.SetRssi(-50)
.SetDataFields(getDataFields())
.Build();
}
List<Java.Lang.Long> getDataFields() {
List<Java.Lang.Long> list = new List<Java.Lang.Long>();
list.Add(new Java.Lang.Long(1L));
list.Add(new Java.Lang.Long(2L));
return list;
}
List<Java.Lang.Long> getDataFields2() {
List<Java.Lang.Long> list = new List<Java.Lang.Long>();
list.Add(new Java.Lang.Long(3L));
list.Add(new Java.Lang.Long(4L));
return list;
}
Beacon getGattBeaconExtraData() {
return new Beacon.Builder()
.SetBluetoothAddress("01:02:03:04:05:06")
.SetServiceUuid(1234)
.SetDataFields(getDataFields())
.Build();
}
Beacon getGattBeaconExtraData2() {
return new Beacon.Builder()
.SetBluetoothAddress("01:02:03:04:05:06")
.SetServiceUuid(1234)
.SetDataFields(getDataFields2())
.Build();
}
Beacon getMultiFrameBeacon() {
return new Beacon.Builder().SetId1("1")
.SetBluetoothAddress("01:02:03:04:05:06")
.SetServiceUuid(1234)
.SetMultiFrameBeacon(true)
.Build();
}
Beacon getMultiFrameBeaconUpdateDifferentServiceUUID() {
return new Beacon.Builder()
.SetBluetoothAddress("01:02:03:04:05:06")
.SetServiceUuid(5678)
.SetRssi(-50)
.SetDataFields(getDataFields())
.SetMultiFrameBeacon(true)
.Build();
}
[Test]
public void trackingManufacturerBeaconReturnsSelf() {
Beacon beacon = getManufacturerBeacon();
ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker();
Beacon trackedBeacon = tracker.Track(beacon);
AssertEx.AreEqual("Returns itself", trackedBeacon, beacon);
}
[Test]
public void gattBeaconExtraDataIsNotReturned() {
Beacon extraDataBeacon = getGattBeaconExtraData();
ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker();
Beacon trackedBeacon = tracker.Track(extraDataBeacon);
AssertEx.Null("trackedBeacon should be null", trackedBeacon);
}
[Test]
public void gattBeaconExtraDataGetUpdated() {
Beacon beacon = getGattBeacon();
Beacon extraDataBeacon = getGattBeaconExtraData();
Beacon extraDataBeacon2 = getGattBeaconExtraData2();
ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker();
tracker.Track(beacon);
tracker.Track(extraDataBeacon);
tracker.Track(extraDataBeacon2);
Beacon trackedBeacon = tracker.Track(beacon);
AssertEx.AreEqual("extra data is updated", extraDataBeacon2.DataFields, trackedBeacon.ExtraDataFields);
}
[Test]
public void gattBeaconExtraDataAreNotOverwritten() {
Beacon beacon = getGattBeacon();
Beacon extraDataBeacon = getGattBeaconExtraData();
ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker();
tracker.Track(beacon);
tracker.Track(extraDataBeacon);
Beacon trackedBeacon = tracker.Track(beacon);
AssertEx.AreEqual("extra data should not be overwritten", extraDataBeacon.DataFields, trackedBeacon.ExtraDataFields);
}
[Test]
public void gattBeaconFieldsGetUpdated() {
Beacon beacon = getGattBeacon();
Beacon beaconUpdate = getGattBeaconUpdate();
Beacon extraDataBeacon = getGattBeaconExtraData();
ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker();
tracker.Track(beacon);
Beacon trackedBeacon = tracker.Track(beaconUpdate);
AssertEx.AreEqual("rssi should be updated", beaconUpdate.Rssi, trackedBeacon.Rssi);
AssertEx.AreEqual("data fields should be updated", beaconUpdate.DataFields, trackedBeacon.DataFields);
}
[Test]
public void multiFrameBeaconDifferentServiceUUIDFieldsNotUpdated() {
Beacon beacon = getMultiFrameBeacon();
Beacon beaconUpdate = getMultiFrameBeaconUpdateDifferentServiceUUID();
ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker();
tracker.Track(beacon);
tracker.Track(beaconUpdate);
Beacon trackedBeacon = tracker.Track(beacon);
AssertEx.AreNotEqual("rssi should NOT be updated", beaconUpdate.Rssi, trackedBeacon.Rssi);
AssertEx.AreNotEqual("data fields should NOT be updated", beaconUpdate.DataFields, trackedBeacon.ExtraDataFields);
}
[Test]
public void multiFrameBeaconProgramaticParserAssociationDifferentServiceUUIDFieldsGetUpdated() {
Beacon beacon = getMultiFrameBeacon();
Beacon beaconUpdate = getMultiFrameBeaconUpdateDifferentServiceUUID();
ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker(false);
tracker.Track(beacon);
tracker.Track(beaconUpdate);
Beacon trackedBeacon = tracker.Track(beacon);
AssertEx.AreEqual("rssi should be updated", beaconUpdate.Rssi, trackedBeacon.Rssi);
AssertEx.AreEqual("data fields should be updated", beaconUpdate.DataFields, trackedBeacon.ExtraDataFields);
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/IdentifierTest.cs
using AltBeaconOrg.BoundBeacon;
using Java.Lang;
using Java.Util;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class IdentifierTest
{
[Test]
public void testEqualsNormalizationIgnoresCase() {
Identifier identifier1 = Identifier.Parse("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6");
Identifier identifier2 = Identifier.Parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6");
AssertEx.True("Identifiers of different case should match", identifier1.Equals(identifier2));
}
[Test]
public void testToStringNormalizesCase() {
Identifier identifier1 = Identifier.Parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6");
AssertEx.AreEqual("Identifiers of different case should match", "2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", identifier1.ToString());
}
[Test]
public void testToStringEqualsUuid() {
Identifier identifier1 = Identifier.Parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6");
AssertEx.AreEqual("uuidString of Identifier should match", "2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", identifier1.ToUuid().ToString());
}
[Test]
[Ignore("ToUuidString is deprecated")]
public void testToUuidEqualsToUuidString() {
Identifier identifier1 = Identifier.Parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6");
//AssertEx.AreEqual("uuidString of Identifier should match", identifier1.ToUuid().ToString(), identifier1.ToUuidString());
}
[Test]
public void testToByteArrayConvertsUuids() {
Identifier identifier1 = Identifier.Parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6");
byte[] bytes = identifier1.ToByteArrayOfSpecifiedEndianness(true);
AssertEx.AreEqual("byte array is correct length", bytes.Length, 16);
AssertEx.AreEqual("first byte of uuid converted properly", 0x2f, bytes[0] & 0xFF);
AssertEx.AreEqual("second byte of uuid converted properly", 0x23, bytes[1] & 0xFF);
AssertEx.AreEqual("last byte of uuid converted properly", 0xa6, bytes[15] & 0xFF);
}
[Test]
public void testToByteArrayConvertsUuidsAsLittleEndian() {
Identifier identifier1 = Identifier.Parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6");
byte[] bytes = identifier1.ToByteArrayOfSpecifiedEndianness(false);
AssertEx.AreEqual("byte array is correct length", bytes.Length, 16);
AssertEx.AreEqual("first byte of uuid converted properly", 0xa6, bytes[0] & 0xFF);
AssertEx.AreEqual("last byte of uuid converted properly", 0x2f, bytes[15] & 0xFF);
}
[Test]
public void testToByteArrayConvertsHex() {
Identifier identifier1 = Identifier.Parse("0x010203040506");
byte[] bytes = identifier1.ToByteArrayOfSpecifiedEndianness(true);
AssertEx.AreEqual("byte array is correct length", bytes.Length, 6);
AssertEx.AreEqual("first byte of hex is converted properly", 0x01, bytes[0] & 0xFF);
AssertEx.AreEqual("last byte of hex is converted properly", 0x06, bytes[5] & 0xFF);
}
[Test]
public void testToByteArrayConvertsDecimal() {
Identifier identifier1 = Identifier.Parse("65534");
byte[] bytes = identifier1.ToByteArrayOfSpecifiedEndianness(true);
AssertEx.AreEqual("byte array is correct length", bytes.Length, 2);
AssertEx.AreEqual("reported byte array is correct length", identifier1.ByteCount, 2);
AssertEx.AreEqual("first byte of decimal converted properly", 0xff, bytes[0] & 0xFF);
AssertEx.AreEqual("last byte of decimal converted properly", 0xfe, bytes[1] & 0xFF);
}
[Test]
public void testToByteArrayConvertsInt() {
Identifier identifier1 = Identifier.FromInt(65534);
byte[] bytes = identifier1.ToByteArrayOfSpecifiedEndianness(true);
AssertEx.AreEqual("byte array is correct length", bytes.Length, 2);
AssertEx.AreEqual("reported byte array is correct length", identifier1.ByteCount, 2);
AssertEx.AreEqual("conversion back equals original value", identifier1.ToInt(), 65534);
AssertEx.AreEqual("first byte of decimal converted properly", 0xff, bytes[0] & 0xFF);
AssertEx.AreEqual("last byte of decimal converted properly", 0xfe, bytes[1] & 0xFF);
}
[Test]
public void testToByteArrayFromByteArray() {
byte[] byteVal = new byte[] {(byte) 0xFF, (byte) 0xAB, 0x12, 0x25};
Identifier identifier1 = Identifier.FromBytes(byteVal, 0, byteVal.Length, false);
byte[] bytes = identifier1.ToByteArrayOfSpecifiedEndianness(true);
AssertEx.AreEqual("byte array is correct length", bytes.Length, 4);
AssertEx.AreEqual("correct string representation", identifier1.ToString(), "0xffab1225");
AssertEx.True("arrays equal", Arrays.Equals(byteVal, bytes));
AssertEx.AreNotSame("arrays are copied", bytes, byteVal);
}
[Test]
public void testComparableDifferentLength() {
byte[] value1 = new byte[] {(byte) 0xFF, (byte) 0xAB, 0x12, 0x25};
Identifier identifier1 = Identifier.FromBytes(value1, 0, value1.Length, false);
byte[] value2 = new byte[] {(byte) 0xFF, (byte) 0xAB, 0x12, 0x25, 0x11, 0x11};
Identifier identifier2 = Identifier.FromBytes(value2, 0, value2.Length, false);
AssertEx.AreEqual("identifier1 is smaller than identifier2", identifier1.CompareTo(identifier2), -1);
AssertEx.AreEqual("identifier2 is larger than identifier1", identifier2.CompareTo(identifier1), 1);
}
[Test]
public void testComparableSameLength() {
byte[] value1 = new byte[] {(byte) 0xFF, (byte) 0xAB, 0x12, 0x25, 0x22, 0x25};
Identifier identifier1 = Identifier.FromBytes(value1, 0, value1.Length, false);
byte[] value2 = new byte[] {(byte) 0xFF, (byte) 0xAB, 0x12, 0x25, 0x11, 0x11};
Identifier identifier2 = Identifier.FromBytes(value2, 0, value2.Length, false);
AssertEx.AreEqual("identifier1 is equal to identifier2", identifier1.CompareTo(identifier1), 0);
AssertEx.AreEqual("identifier1 is larger than identifier2", identifier1.CompareTo(identifier2), 1);
AssertEx.AreEqual("identifier2 is smaller than identifier1", identifier2.CompareTo(identifier1), -1);
}
[Test]
public void testParseIntegerMaxInclusive() {
Identifier.Parse("65535");
}
[Test]
public void testParseIntegerAboveMax() {
Assert.Throws(typeof(IllegalArgumentException), () =>
{
Identifier.Parse("65536");
});
}
[Test]
public void testParseIntegerMinInclusive() {
Identifier.Parse("0");
}
[Test]
public void testParseIntegerBelowMin() {
Assert.Throws(typeof(IllegalArgumentException), () =>
{
Identifier.Parse("-1");
});
}
[Test]
public void testParseIntegerWayTooBig() {
Assert.Throws(typeof(IllegalArgumentException), () =>
{
Identifier.Parse("3133742");
});
}
/*
* This is here because Identifier.parse wrongly accepts UUIDs without
* dashes, but we want to be backward compatible.
*/
[Test]
[Ignore("Technically this works, but the Equals comparer isn't working right.")]
public void testParseInvalidUuid() {
UUID uuid = UUID.FromString("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6");
Identifier id = Identifier.Parse("2f234454cf6d4a0fadf2f4911ba9ffa6");
AssertEx.AreEqual("Malformed UUID was parsed as expected.", id.ToUuid(), uuid);
}
[Test]
public void testParseHexWithNoPrefix() {
Identifier id = Identifier.Parse("abcd");
AssertEx.AreEqual("Should parse and get back equivalent decimal value for small numbers", "43981", id.ToString());
}
[Test]
public void testParseBigHexWithNoPrefix() {
Identifier id = Identifier.Parse("123456789abcdef");
AssertEx.AreEqual("Should parse and get prefixed hex value for big numbers", "0x0123456789abcdef", id.ToString());
}
[Test]
public void testParseZeroPrefixedDecimalNumberAsHex() {
Identifier id = Identifier.Parse("0010");
AssertEx.AreEqual("Should be treated as hex in parse, but converted back to decimal because it is small", "16", id.ToString());
}
[Test]
public void testParseNonZeroPrefixedDecimalNumberAsDecimal() {
Identifier id = Identifier.Parse("10");
AssertEx.AreEqual("Should be treated as decimal", "10", id.ToString());
}
[Test]
public void testParseDecimalNumberWithSpecifiedLength() {
Identifier id = Identifier.Parse("10", 8);
AssertEx.AreEqual("Should be treated as hex because it is long", "0x000000000000000a", id.ToString());
AssertEx.AreEqual("Byte count should be as specified", 8, id.ByteCount);
}
[Test]
public void testParseDecimalNumberWithSpecifiedShortLength() {
Identifier id = Identifier.Parse("10", 2);
AssertEx.AreEqual("Should be treated as decimal because it is short", "10", id.ToString());
AssertEx.AreEqual("Byte count should be as specified", 2, id.ByteCount);
}
[Test]
public void testParseHexNumberWithSpecifiedLength() {
Identifier id = Identifier.Parse("2fffffffffffffffffff", 10);
AssertEx.AreEqual("Should be treated as hex because it is long", "0x2fffffffffffffffffff", id.ToString());
AssertEx.AreEqual("Byte count should be as specified", 10, id.ByteCount);
}
[Test]
public void testParseZeroAsInteger() {
Identifier id = Identifier.Parse("0");
AssertEx.AreEqual("Should be treated as int because it is a common integer", "0", id.ToString());
AssertEx.AreEqual("Byte count should be 2 for integers", 2, id.ByteCount);
}
}
}
<file_sep>/Samples/Forms/AltBeaconLibrary.Sample/AltBeaconLibrary.Sample/ListChangedEventArgs.cs
using System;
namespace AltBeaconLibrary.Sample
{
public class ListChangedEventArgs : EventArgs
{
public System.Collections.Generic.List<SharedBeacon> Data { get; protected set; }
public ListChangedEventArgs(System.Collections.Generic.List<SharedBeacon> data)
{
Data = data;
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/Service/Scanner/ScanFilterUtilsTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using AltBeaconOrg.BoundBeacon;
using AltBeaconOrg.BoundBeacon.Service.Scanner;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class ScanFilterUtilsTest
{
[Test]
public void testGetAltBeaconScanFilter() {
BeaconParser parser = new AltBeaconParser();
BeaconManager.SetsManifestCheckingDisabled(true); // no manifest available in robolectric
var scanFilterDatas = new ScanFilterUtils().CreateScanFilterDataForBeaconParser(parser);
AssertEx.AreEqual("scanFilters should be of correct size", 1, scanFilterDatas.Count);
ScanFilterUtils.ScanFilterData sfd = scanFilterDatas[0];
AssertEx.AreEqual("manufacturer should be right", 0x0118, sfd.Manufacturer);
AssertEx.AreEqual("mask length should be right", 2, sfd.Mask.Count);
AssertEx.AreEqual("mask should be right", new byte[] {(byte)0xff, (byte)0xff}, sfd.Mask);
AssertEx.AreEqual("filter should be right", new byte[] {(byte)0xbe, (byte)0xac}, sfd.Filter);
}
[Test]
public void testGenericScanFilter() {
BeaconParser parser = new BeaconParser();
parser.SetBeaconLayout("m:2-3=1111,i:4-6,p:24-24");
BeaconManager.SetsManifestCheckingDisabled(true); // no manifest available in robolectric
var scanFilterDatas = new ScanFilterUtils().CreateScanFilterDataForBeaconParser(parser);
AssertEx.AreEqual("scanFilters should be of correct size", 1, scanFilterDatas.Count);
ScanFilterUtils.ScanFilterData sfd = scanFilterDatas[0];
AssertEx.AreEqual("manufacturer should be right", 0x004c, sfd.Manufacturer);
AssertEx.AreEqual("mask length should be right", 2, sfd.Mask.Count);
AssertEx.AreEqual("mask should be right", new byte[]{(byte) 0xff, (byte) 0xff}, sfd.Mask.ToArray());
AssertEx.AreEqual("filter should be right", new byte[] {(byte)0x11, (byte) 0x11}, sfd.Filter.ToArray());
AssertEx.Null("serviceUuid should be null", sfd.ServiceUuid);
}
[Test]
public void testEddystoneScanFilterData() {
BeaconParser parser = new BeaconParser();
parser.SetBeaconLayout(BeaconParser.EddystoneUidLayout);
BeaconManager.SetsManifestCheckingDisabled(true); // no manifest available in robolectric
var scanFilterDatas = new ScanFilterUtils().CreateScanFilterDataForBeaconParser(parser);
AssertEx.AreEqual("scanFilters should be of correct size", 1, scanFilterDatas.Count);
ScanFilterUtils.ScanFilterData sfd = scanFilterDatas[0];
AssertEx.AreEqual("serviceUuid should be right", new Java.Lang.Long(0xfeaa).LongValue(), sfd.ServiceUuid.LongValue());
}
[Test]
public void testZeroOffsetScanFilter() {
BeaconParser parser = new BeaconParser();
parser.SetBeaconLayout("m:0-3=11223344,i:4-6,p:24-24");
BeaconManager.SetsManifestCheckingDisabled(true); // no manifest available in robolectric
var scanFilterDatas = new ScanFilterUtils().CreateScanFilterDataForBeaconParser(parser);
AssertEx.AreEqual("scanFilters should be of correct size", 1, scanFilterDatas.Count);
ScanFilterUtils.ScanFilterData sfd = scanFilterDatas[0];
AssertEx.AreEqual("manufacturer should be right", 0x004c, sfd.Manufacturer);
AssertEx.AreEqual("mask length should be right", 2, sfd.Mask.Count);
AssertEx.AreEqual("mask should be right", new byte[] {(byte)0xff, (byte)0xff}, sfd.Mask.ToArray());
AssertEx.AreEqual("filter should be right", new byte[] {(byte)0x33, (byte)0x44}, sfd.Filter.ToArray());
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Bluetooth/BleAdvertisementTest.cs
using System;
using NUnit.Framework;
using AltBeaconOrg.Bluetooth;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class BleAdvertisementTest : TestBase
{
[Test]
public void testCanParsePdusFromAltBeacon() {
byte[] bytes = HexStringToByteArray("02011a1aff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c50900000000000000000000000000000000000000000000000000000000000000");
BleAdvertisement bleAdvert = new BleAdvertisement(bytes);
AssertEx.AreEqual("An AltBeacon advert should have two PDUs", 3, bleAdvert.Pdus.Count);
}
[Test]
public void testCanParsePdusFromOtherBeacon() {
byte[] bytes = HexStringToByteArray("0201060303aafe1516aafe00e72f234454f4911ba9ffa60000000000010c09526164426561636f6e20470000000000000000000000000000000000000000");
BleAdvertisement bleAdvert = new BleAdvertisement(bytes);
AssertEx.AreEqual("An otherBeacon advert should four three PDUs", 4, bleAdvert.Pdus.Count);
AssertEx.AreEqual("First PDU should be flags type 1", 1, bleAdvert.Pdus[0].Type);
AssertEx.AreEqual("Second PDU should be services type 3", 3, bleAdvert.Pdus[1].Type);
AssertEx.AreEqual("Third PDU should be serivce type 0x16", 0x16, bleAdvert.Pdus[2].Type);
AssertEx.AreEqual("Fourth PDU should be scan response type 9", 9, bleAdvert.Pdus[3].Type);
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/Service/RangingDataTest.cs
using System;
using AltBeaconOrg.BoundBeacon;
using AltBeaconOrg.BoundBeacon.Service;
using System.Collections.Generic;
using Android.Content;
using Android.OS;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class RangingDataTest
{
[SetUp]
public void before() {
BeaconManager.SetsManifestCheckingDisabled(true);
}
[Test]
[Ignore("Not testing serialization")]
public void testSerialization() {
//Context context = Android.App.Application.Context;
//var identifiers = new List<Identifier>();
//identifiers.Add(Identifier.Parse("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6"));
//identifiers.Add(Identifier.Parse("1"));
//identifiers.Add(Identifier.Parse("2"));
//Region region = new Region("testRegion", identifiers);
//var beacons = new List<Beacon>();
//Beacon beacon = new Beacon.Builder().SetIdentifiers(identifiers).SetRssi(-1).setRunningAverageRssi(-2).setTxPower(-50).setBluetoothAddress("01:02:03:04:05:06").build();
//for (int i=0; i < 10; i++) {
// beacons.Add(beacon);
//}
//RangingData data = new RangingData(beacons, region);
//Bundle bundle = data.ToBundle();
//RangingData data2 = RangingData.fromBundle(bundle);
//assertEquals("beacon count shouild be restored", 10, data2.getBeacons().size());
//assertEquals("beacon identifier 1 shouild be restored", "2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", data2.getBeacons().iterator().next().getId1().toString());
//assertEquals("region identifier 1 shouild be restored", "2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", data2.getRegion().getId1().toString());
}
[Test]
[Ignore("Not testing serialization")]
// On MacBookPro 2.5 GHz Core I7, 10000 serialization/deserialiation cycles of RangingData took 22ms
public void testSerializationBenchmark() {
//Context context = Android.App.Application.Context;
//var identifiers = new List<Identifier>();
//identifiers.Add(Identifier.Parse("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6"));
//identifiers.Add(Identifier.Parse("1"));
//identifiers.Add(Identifier.Parse("2"));
//Region region = new Region("testRegion", identifiers);
//ArrayList<Beacon> beacons = new List<Beacon>();
//Beacon beacon = new Beacon.Builder().SetIdentifiers(identifiers).SetRssi(-1).setRunningAverageRssi(-2).setTxPower(-50).setBluetoothAddress("01:02:03:04:05:06").build();
//for (int i=0; i < 10; i++) {
// beacons.Add(beacon);
//}
//RangingData data = new RangingData(beacons, region);
//long time1 = System.currentTimeMillis();
//for (int i=0; i< 10000; i++) {
// Bundle bundle = data.toBundle();
// RangingData data2 = RangingData.fromBundle(bundle);
//}
//long time2 = System.currentTimeMillis();
//System.out.println("*** Ranging Data Serialization benchmark: "+(time2-time1));
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/AltBeaconParserTest.cs
using System;
using AltBeaconOrg.BoundBeacon;
using AltBeaconOrg.BoundBeacon.Logging;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
public class AltBeaconParserTest : TestBase
{
[Test]
public void TestRecognizeBeacon()
{
var beaconManager = BeaconManager.GetInstanceForApplication(Android.App.Application.Context);
var bytes = HexStringToByteArray("02011a1bff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c50900");
AltBeaconParser parser = new AltBeaconParser();
Beacon beacon = parser.FromScanData(bytes, -55, null);
Assert.AreEqual(1, beacon.DataFields.Count, "Beacon should have one data field");
Assert.AreEqual(9, ((AltBeacon) beacon).MfgReserved, "manData should be parsed");
}
[Test]
public void TestDetectsDaveMHardwareBeacon()
{
var bytes = HexStringToByteArray("02011a1bff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600050003be020e09526164426561636f6e20555342020a0300000000000000000000000000");
var parser = new AltBeaconParser();
var beacon = parser.FromScanData(bytes, -55, null);
Assert.NotNull(beacon, "Beacon should be not null if parsed successfully");
}
[Test]
public void TestDetectsAlternateBeconType()
{
var bytes = HexStringToByteArray("02011a1bff1801aabb2f234454cf6d4a0fadf2f4911ba9ffa600010002c50900");
var parser = new AltBeaconParser();
parser.SetMatchingBeaconTypeCode(new Java.Lang.Long(0xaabbL));
var beacon = parser.FromScanData(bytes, -55, null);
Assert.NotNull(beacon, "Beacon should be not null if parsed successfully");
}
[Test]
public void TestParseWrongFormatReturnsNothing()
{
LogManager.D("XXX", "testParseWrongFormatReturnsNothing start");
var bytes = HexStringToByteArray("02011a1aff1801ffff2f234454cf6d4a0fadf2f4911ba9ffa600010002c509");
var parser = new AltBeaconParser();
var beacon = parser.FromScanData(bytes, -55, null);
LogManager.D("XXX", "testParseWrongFormatReturnsNothing end");
Assert.Null(beacon, "Beacon should be null if not parsed successfully");
}
[Test]
public void TestParsesBeaconMissingDataField()
{
var bytes = HexStringToByteArray("02011a1aff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c5000000");
var parser = new AltBeaconParser();
var beacon = parser.FromScanData(bytes, -55, null);
Assert.AreEqual(-55, beacon.Rssi, "mRssi should be as passed in");
Assert.AreEqual("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", beacon.GetIdentifier(0).ToString(), "uuid should be parsed");
Assert.AreEqual("1", beacon.GetIdentifier(1).ToString(), "id2 should be parsed");
Assert.AreEqual("2", beacon.GetIdentifier(2).ToString(), "id3 should be parsed");
Assert.AreEqual(-59, beacon.TxPower, "txPower should be parsed");
Assert.AreEqual(0x118 ,beacon.Manufacturer, "manufacturer should be parsed");
Assert.AreEqual(Convert.ToInt64(new Java.Lang.Long(0)), Convert.ToInt64(beacon.DataFields[0]), "missing data field zero should be zero");
}
}
}<file_sep>/Samples/Forms/AltBeaconLibrary.Sample/AltBeaconLibrary.Sample/IAltBeaconService.cs
using System;
namespace AltBeaconLibrary.Sample
{
public interface IAltBeaconService
{
void InitializeService();
void StartMonitoring();
void StartRanging();
event EventHandler<ListChangedEventArgs> ListChanged;
event EventHandler DataClearing;
}
}<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/SBeaconTest.cs
using System;
using NUnit.Framework;
using AltBeaconOrg.BoundBeacon;
using Android.OS;
using System.Text;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class SBeaconTest : TestBase
{
[Test]
public void testDetectsSBeacon() {
byte[] bytes = HexStringToByteArray("02011a1bff1801031501000100c502000000000000000003");
SBeaconParser parser = new SBeaconParser();
SBeacon sBeacon = (SBeacon) parser.FromScanData(bytes, -55, null);
AssertEx.NotNull("SBeacon should be not null if parsed successfully", sBeacon);
AssertEx.AreEqual("id should be parsed", "0x000000000003", sBeacon.Id);
AssertEx.AreEqual("group should be parsed", 1, sBeacon.Group);
AssertEx.AreEqual("time should be parsed", 2, sBeacon.Time);
AssertEx.AreEqual("txPower should be parsed", -59, sBeacon.TxPower);
}
protected class SBeacon : Beacon {
int mTime;
public SBeacon(int grouping, String id, int time, int txPower, int rssi, int beaconTypeCode, String bluetoothAddress) {
TxPower = txPower;
Rssi = rssi;
BeaconTypeCode = beaconTypeCode;
BluetoothAddress = bluetoothAddress;
Identifiers = new System.Collections.Generic.List<Identifier>();
Identifiers.Add(Identifier.FromInt(grouping));
Identifiers.Add(Identifier.Parse(id));
mTime = time;
}
public SBeacon(Parcel parcel) {
// TODO: Implement me
}
public int Group => ((Identifier)Identifiers[0]).ToInt();
public int Time => mTime;
public String Id => Identifiers[1].ToString();
public override int DescribeContents()
{
return 0;
}
public override void WriteToParcel(Parcel @out, ParcelableWriteFlags flags)
{
// TODO: Implement me
}
}
internal class SBeaconParser : BeaconParser {
//private static final String TAG = "SBeaconParser";
public override Beacon FromScanData(byte[] scanData, int rssi, Android.Bluetooth.BluetoothDevice device)
{
int startByte = 2;
while (startByte <= 5) {
// "m:2-3=0203,i:2-2,i:7-8,i:14-19,d:10-13,p:9-9"
if (((int)scanData[startByte+3] & 0xff) == 0x03 &&
((int)scanData[startByte+4] & 0xff) == 0x15) {
//BeaconManager.logDebug(TAG, "This is a SBeacon beacon advertisement");
// startByte+0 company id (2 bytes)
// startByte+2 = 02 (1) byte header
// startByte+3 = 0315 (2 bytes) header
// startByte+5 = Beacon Type 0x01
// startByte+6 = Reserved (1 bytes)
// startByte+7 = Security Code (2 bytes) => Major little endian
// startByte+9 = Tx Power => Tx Power
// startByte+10 = Timestamp (4 bytes) => Minor (2 LSBs) little endian
// startByte+14 = Beacon ID (6 bytes) -> UUID little endian
int grouping = (scanData[startByte+8] & 0xff) * 0x100 + (scanData[startByte+7] & 0xff);
int clock = (scanData[startByte+13] & 0xff) * 0x1000000 + (scanData[startByte+12] & 0xff) * 0x10000 + (scanData[startByte+11] & 0xff) * 0x100 + (scanData[startByte+10] & 0xff);
int txPower = (int)(sbyte)scanData[startByte+9]; // this one is signed
byte[] beaconId = new byte[6];
//Java.Lang.JavaSystem.Arraycopy(scanData, startByte+14, beaconId, 0, 6);
Array.Copy(scanData, startByte+14, beaconId, 0, 6);
String hexString = BytesToHex(beaconId);
StringBuilder sb = new StringBuilder();
sb.Append(hexString.Substring(0,12));
String id = "0x" + sb.ToString();
int beaconTypeCode = (scanData[startByte+3] & 0xff) * 0x100 + (scanData[startByte+2] & 0xff);
String mac = null;
if (device != null) {
mac = device.Address;
}
Beacon beacon = new SBeacon(grouping, id, clock, txPower, rssi, beaconTypeCode, mac);
return beacon;
}
startByte++;
}
return null;
}
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary/Identifier.cs
using System;
namespace AltBeaconOrg.BoundBeacon {
// Metadata.xml XPath class reference: path="/api/package[@<EMAIL>='org.<EMAIL>']/class[@name='Identifier']"
public partial class Identifier {
public int CompareTo(Java.Lang.Object another)
{
return _CompareTo((Identifier)another);
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/BeaconParserTest.cs
using System;
using System.Collections.Generic;
using AltBeaconOrg.BoundBeacon;
using Android.Annotation;
using Android.Runtime;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class BeaconParserTest : TestBase
{
[Test]
public void TestSetBeaconLayout()
{
var bytes = HexStringToByteArray("02011a1bffbeac2f234454cf6d4a0fadf2f4911ba9ffa600010002c509000000");
var parser = new BeaconParser();
parser.SetBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
Assert.AreEqual(2, parser.MatchingBeaconTypeCodeStartOffset, "parser should get beacon type code start offset");
Assert.AreEqual(3, parser.MatchingBeaconTypeCodeEndOffset, "parser should get beacon type code end offset");
Assert.AreEqual(Convert.ToInt64(0xbeacL), Convert.ToInt64(parser.MatchingBeaconTypeCode), "parser should get beacon type code");
Assert.AreEqual(4, parser.IdentifierStartOffsets[0], "parser should get identifier start offset");
AssertEx.AreEqual("parser should get identifier end offset", 19, parser.IdentifierEndOffsets[0]);
AssertEx.AreEqual("parser should get identifier start offset", 20, parser.IdentifierStartOffsets[1]);
AssertEx.AreEqual("parser should get identifier end offset", 21, parser.IdentifierEndOffsets[1]);
AssertEx.AreEqual("parser should get identifier start offset", 22, parser.IdentifierStartOffsets[2]);
AssertEx.AreEqual("parser should get identifier end offset", 23, parser.IdentifierEndOffsets[2]);
AssertEx.AreEqual("parser should get power start offset", 24, Convert.ToInt32(parser.PowerStartOffset));
AssertEx.AreEqual("parser should get power end offset", 24, Convert.ToInt32(parser.PowerEndOffset));
AssertEx.AreEqual("parser should get data start offset", 25, parser.DataStartOffsets[0]);
AssertEx.AreEqual("parser should get data end offset", 25, parser.DataEndOffsets[0]);
}
[Test]
public void TestLongToByteArray()
{
var bytes = BeaconParser.LongToByteArray(10, 1);
AssertEx.AreEqual("first byte should be 10", 10, bytes[0]);
}
[Test]
public void TestRecognizeBeacon()
{
var bytes = HexStringToByteArray("02011a1aff180112342f234454cf6d4a0fadf2f4911ba9ffa600010002c5");
var parser = new BeaconParser();
parser.SetBeaconLayout("m:2-3=1234,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
var beacon = parser.FromScanData(bytes, -55, null);
AssertEx.AreEqual("mRssi should be as passed in", -55, beacon.Rssi);
AssertEx.AreEqual("uuid should be parsed", "2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", beacon.GetIdentifier(0).ToString());
AssertEx.AreEqual("id2 should be parsed", "1", beacon.GetIdentifier(1).ToString());
AssertEx.AreEqual("id3 should be parsed", "2", beacon.GetIdentifier(2).ToString());
AssertEx.AreEqual("txPower should be parsed", -59, beacon.TxPower);
AssertEx.AreEqual("manufacturer should be parsed", 0x118 ,beacon.Manufacturer);
}
[Test]
public void TestAllowsAccessToParserIdentifier()
{
var bytes = HexStringToByteArray("02011a1aff180112342f234454cf6d4a0fadf2f4911ba9ffa600010002c5");
var parser = new BeaconParser("my_beacon_type");
parser.SetBeaconLayout("m:2-3=1234,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
var beacon = parser.FromScanData(bytes, -55, null);
AssertEx.AreEqual("parser identifier should be accessible", "my_beacon_type", beacon.ParserIdentifier);
}
[Test]
public void TestParsesBeaconMissingDataField()
{
var bytes = HexStringToByteArray("02011a1aff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c5000000");
var parser = new BeaconParser();
parser.SetBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
var beacon = parser.FromScanData(bytes, -55, null);
AssertEx.AreEqual("mRssi should be as passed in", -55, beacon.Rssi);
AssertEx.AreEqual("uuid should be parsed", "2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", beacon.GetIdentifier(0).ToString());
AssertEx.AreEqual("id2 should be parsed", "1", beacon.GetIdentifier(1).ToString());
AssertEx.AreEqual("id3 should be parsed", "2", beacon.GetIdentifier(2).ToString());
AssertEx.AreEqual("txPower should be parsed", -59, beacon.TxPower);
AssertEx.AreEqual("manufacturer should be parsed", 0x118 ,beacon.Manufacturer);
AssertEx.AreEqual("missing data field zero should be zero", Convert.ToInt64(0), Convert.ToInt64(beacon.DataFields[0]));
}
[Test]
public void TestRecognizeBeaconWithFormatSpecifyingManufacturer()
{
var bytes = HexStringToByteArray("02011a1bff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c509000000");
var parser = new BeaconParser();
parser.SetBeaconLayout("m:0-3=1801beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
var beacon = parser.FromScanData(bytes, -55, null);
AssertEx.AreEqual("mRssi should be as passed in", -55, beacon.Rssi);
AssertEx.AreEqual("uuid should be parsed", "2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", beacon.GetIdentifier(0).ToString());
AssertEx.AreEqual("id2 should be parsed", "1", beacon.GetIdentifier(1).ToString());
AssertEx.AreEqual("id3 should be parsed", "2", beacon.GetIdentifier(2).ToString());
AssertEx.AreEqual("txPower should be parsed", -59, beacon.TxPower);
AssertEx.AreEqual("manufacturer should be parsed", 0x118 ,beacon.Manufacturer);
}
[Test]
[TargetApi(Value = 10)]
public void TestReEncodesBeacon()
{
var bytes = HexStringToByteArray("02011a1bff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c509");
var parser = new BeaconParser();
parser.SetBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
var beacon = parser.FromScanData(bytes, -55, null);
var regeneratedBytes = parser.GetBeaconAdvertisementData(beacon);
var expectedMatch = Java.Util.Arrays.CopyOfRange(bytes, 7, bytes.Length);
AssertEx.AreEqual("beacon advertisement bytes should be the same after re-encoding", expectedMatch, regeneratedBytes);
}
[TargetApi(Value = 10)]
[Test]
public void TestReEncodesBeaconForEddystoneTelemetry()
{
var bytes = HexStringToByteArray("0201060303aafe1516aafe2001021203130414243405152535");
var parser = new BeaconParser();
parser.SetBeaconLayout(BeaconParser.EddystoneTlmLayout);
var beacon = parser.FromScanData(bytes, -55, null);
var regeneratedBytes = parser.GetBeaconAdvertisementData(beacon);
var expectedMatch = Java.Util.Arrays.CopyOfRange(bytes, 11, bytes.Length);
AssertEx.AreEqual("beacon advertisement bytes should be the same after re-encoding", ByteArrayToHexString(expectedMatch), ByteArrayToHexString(regeneratedBytes));
}
[Test]
public void TestLittleEndianIdentifierParsing()
{
var bytes = HexStringToByteArray("02011a1bff1801beac0102030405060708090a0b0c0d0e0f1011121314c50900000000");
var parser = new BeaconParser();
parser.SetBeaconLayout("m:2-3=beac,i:4-9,i:10-15l,i:16-23,p:24-24,d:25-25");
var beacon = parser.FromScanData(bytes, -55, null);
AssertEx.AreEqual("mRssi should be as passed in", -55, beacon.Rssi);
AssertEx.AreEqual("id1 should be big endian", "0x010203040506", beacon.GetIdentifier(0).ToString());
AssertEx.AreEqual("id2 should be little endian", "0x0c0b0a090807", beacon.GetIdentifier(1).ToString());
AssertEx.AreEqual("id3 should be big endian", "0x0d0e0f1011121314", beacon.GetIdentifier(2).ToString());
AssertEx.AreEqual("txPower should be parsed", -59, beacon.TxPower);
AssertEx.AreEqual("manufacturer should be parsed", 0x118, beacon.Manufacturer);
}
[TargetApi(Value = 10)]
[Test]
public void TestReEncodesLittleEndianBeacon()
{
var bytes = HexStringToByteArray("02011a1bff1801beac0102030405060708090a0b0c0d0e0f1011121314c509");
var parser = new BeaconParser();
parser.SetBeaconLayout("m:2-3=beac,i:4-9,i:10-15l,i:16-23,p:24-24,d:25-25");
var beacon = parser.FromScanData(bytes, -55, null);
var regeneratedBytes = parser.GetBeaconAdvertisementData(beacon);
var expectedMatch = Java.Util.Arrays.CopyOfRange(bytes, 7, bytes.Length);
AssertEx.AreEqual("beacon advertisement bytes should be the same after re-encoding", ByteArrayToHexString(expectedMatch), ByteArrayToHexString(regeneratedBytes));
}
[Test]
public void TestRecognizeBeaconCapturedManufacturer()
{
var bytes = HexStringToByteArray("0201061bffaabbbeace2c56db5dffb48d2b060d0f5a71096e000010004c50000000000000000000000000000000000000000000000000000000000000000");
var parser = new BeaconParser();
parser.SetBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
var beacon = parser.FromScanData(bytes, -55, null);
AssertEx.AreEqual("manufacturer should be parsed", "bbaa", beacon.Manufacturer.ToString("X").ToLowerInvariant());
}
[Test]
public void TestParseGattIdentifierThatRunsOverPduLength()
{
var bytes = HexStringToByteArray("0201060303aafe0d16aafe10e702676f6f676c65000c09526164426561636f6e204700000000000000000000000000000000000000000000000000000000");
var parser = new BeaconParser();
parser.SetAllowPduOverflow(Java.Lang.Boolean.False);
parser.SetBeaconLayout("s:0-1=feaa,m:2-2=10,p:3-3:-41,i:4-20");
var beacon = parser.FromScanData(bytes, -55, null);
AssertEx.Null("beacon should not be parsed", beacon);
}
[Test]
public void TestLongUrlBeaconIdentifier()
{
var bytes = HexStringToByteArray("0201060303aafe0d16aafe10e70102030405060708090a0b0c0d0e0f0102030405060708090a0b0c0d0e0f00000000000000000000000000000000000000");
var parser = new BeaconParser();
parser.SetBeaconLayout("s:0-1=feaa,m:2-2=10,p:3-3:-41,i:4-20v");
var beacon = parser.FromScanData(bytes, -55, null);
AssertEx.AreEqual("URL Identifier should be truncated at 8 bytes", 8, beacon.Id1.ToByteArray().Length);
}
[Test]
public void TestParseManufacturerIdentifierThatRunsOverPduLength()
{
// Note that the length field below is 0x16 instead of 0x1b, indicating that the packet ends
// one byte before the second identifier field starts
var bytes = HexStringToByteArray("02011a16ff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c509000000");
var parser = new BeaconParser();
parser.SetAllowPduOverflow(Java.Lang.Boolean.False);
parser.SetBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
var beacon = parser.FromScanData(bytes, -55, null);
AssertEx.Null("beacon should not be parsed", beacon);
}
[Test]
public void TestParseProblematicBeaconFromIssue229()
{
// Note that the length field below is 0x16 instead of 0x1b, indicating that the packet ends
// one byte before the second identifier field starts
var bytes = HexStringToByteArray("0201061bffe000beac7777772e626c756b692e636f6d000100010001abaa000000");
var parser = new BeaconParser();
parser.SetBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
var beacon = parser.FromScanData(bytes, -55, null);
AssertEx.NotNull("beacon should be parsed", beacon);
}
[Test]
public void TestCanParseLocationBeacon()
{
double latitude = 38.93;
double longitude = -77.23;
var beacon = new Beacon.Builder()
.SetManufacturer(0x0118) // Radius Networks
.SetId1("1") // device sequence number
.SetId2(String.Format("{0:X8}", (long)((latitude+90)*10000.0)))
.SetId3(String.Format("{0:X8}", (long)((longitude+180)*10000.0)))
.SetTxPower(-59) // The measured transmitter power at one meter in dBm
.Build();
// TODO: make this pass if data fields are little endian or > 4 bytes (or even > 2 bytes)
var p = new BeaconParser().
SetBeaconLayout("m:2-3=10ca,i:4-9,i:10-13,i:14-17,p:18-18");
var bytes = p.GetBeaconAdvertisementData(beacon);
var headerBytes = HexStringToByteArray("02011a1bff1801");
var advBytes = new byte[bytes.Length + headerBytes.Length];
Array.Copy(headerBytes, 0, advBytes, 0, headerBytes.Length);
Array.Copy(bytes, 0, advBytes, headerBytes.Length, bytes.Length);
Beacon parsedBeacon = p.FromScanData(advBytes, -59, null);
AssertEx.NotNull(String.Format("Parsed beacon from {0} should not be null", ByteArrayToHexString(advBytes)), parsedBeacon);
double parsedLatitude = Int64.Parse(parsedBeacon.Id2.ToString().Substring(2), System.Globalization.NumberStyles.HexNumber) / 10000.0 - 90.0;
double parsedLongitude = Int64.Parse(parsedBeacon.Id3.ToString().Substring(2), System.Globalization.NumberStyles.HexNumber) / 10000.0 - 180.0;
long encodedLatitude = (long)((latitude + 90)*10000.0);
AssertEx.AreEqual("encoded latitude hex should match", string.Format("0x{0:x8}", encodedLatitude).ToLowerInvariant(), parsedBeacon.Id2.ToString().ToLowerInvariant());
AssertEx.AreEqual("device sequence num should be same", "0x000000000001", parsedBeacon.Id1.ToString());
AssertEx.AreEqual("latitude should be about right", latitude, parsedLatitude, 0.0001);
AssertEx.AreEqual("longitude should be about right", longitude, parsedLongitude, 0.0001);
}
[Test]
public void TestCanGetAdvertisementDataForUrlBeacon()
{
var beacon = new Beacon.Builder()
.SetManufacturer(0x0118)
.SetId1("02646576656c6f7065722e636f6d") // http://developer.com
.SetTxPower(-59) // The measured transmitter power at one meter in dBm
.Build();
var p = new BeaconParser().
SetBeaconLayout("s:0-1=feaa,m:2-2=10,p:3-3:-41,i:4-20v");
var bytes = p.GetBeaconAdvertisementData(beacon);
AssertEx.AreEqual("First byte of url should be in position 3", 0x02, bytes[2]);
}
[Test]
public void DoesNotCashWithOverflowingByteCodeComparisonOnPdu() {
// Test for https://github.com/AltBeacon/android-beacon-library/issues/323
// Note that the length field below is 0x16 instead of 0x1b, indicating that the packet ends
// one byte before the second identifier field starts
var bytes = HexStringToByteArray("02010604ffe000be");
var parser = new BeaconParser();
parser.SetBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
var beacon = parser.FromScanData(bytes, -55, null);
AssertEx.Null("beacon not be parsed without an exception being thrown", beacon);
}
[Test]
public void TestCanParseLongDataTypeOfDifferentSize()
{
// Create a beacon parser
var parser = new BeaconParser();
parser.SetBeaconLayout("m:2-3=0118,i:4-7,p:8-8,d:9-16,d:18-21,d:22-25");
// Generate sample beacon for test purpose.
var sampleData = new List<Java.Lang.Long>();
var now = DateTimeOffset.Now.ToUnixTimeMilliseconds();
sampleData.Add(new Java.Lang.Long(now));
sampleData.Add(new Java.Lang.Long(1234L));
sampleData.Add(new Java.Lang.Long(9876L));
var beacon = new Beacon.Builder()
.SetManufacturer(0x0118)
.SetId1("02646576656c6f7065722e636f6d")
.SetTxPower(-59)
.SetDataFields(sampleData)
.Build();
AssertEx.AreEqual("beacon contains a valid data on index 0", now, beacon.DataFields[0].LongValue());
// Make byte array
byte[] headerBytes = HexStringToByteArray("1bff1801");
byte[] bodyBytes = parser.GetBeaconAdvertisementData(beacon);
byte[] bytes = new byte[headerBytes.Length + bodyBytes.Length];
Array.Copy(headerBytes, 0, bytes, 0, headerBytes.Length);
Array.Copy(bodyBytes, 0, bytes, headerBytes.Length, bodyBytes.Length);
// Try parsing the byte array
Beacon parsedBeacon = parser.FromScanData(bytes, -59, null);
AssertEx.AreEqual("parsed beacon should contain a valid data on index 0", now, parsedBeacon.DataFields[0].LongValue());
AssertEx.AreEqual("parsed beacon should contain a valid data on index 1", Convert.ToInt64(1234L), parsedBeacon.DataFields[1].LongValue());
AssertEx.AreEqual("parsed beacon should contain a valid data on index 2", Convert.ToInt64(9876L), parsedBeacon.DataFields[2].LongValue());
}
}
}<file_sep>/Samples/Forms/AltBeaconLibrary.Sample/AltBeaconLibrary.Sample/App.cs
using System;
using Xamarin.Forms;
namespace AltBeaconLibrary.Sample
{
public class App : Application
{
public App()
{
MainPage = new NavigationPage( App.GetMainPage() );
}
public static Page GetMainPage()
{
return new MainPage();
}
}
}<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/Utils/UrlBeaconUrlCompressorTest.cs
using System;
using AltBeaconOrg.BoundBeacon.Utils;
using Java.Util;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class UrlBeaconUrlCompressorTest : TestBase
{
static char[] hexArray = "0123456789ABCDEF".ToCharArray();
/**
* URLs to test:
* <p/>
* http://www.radiusnetworks.com
* https://www.radiusnetworks.com
* http://radiusnetworks.com
* https://radiusnetworks.com
* https://radiusnetworks.com/
* https://radiusnetworks.com/v1/index.html
* https://api.v1.radiusnetworks.com
* https://www.api.v1.radiusnetworks.com
*/
[Test]
public void testCompressURL() {
String testURL = "http://www.radiusnetworks.com";
byte[] expectedBytes = {0x00,
Convert.ToByte('r'),
Convert.ToByte('a'),
Convert.ToByte('d'),
Convert.ToByte('i'),
Convert.ToByte('u'),
Convert.ToByte('s'),
Convert.ToByte('n'),
Convert.ToByte('e'),
Convert.ToByte('t'),
Convert.ToByte('w'),
Convert.ToByte('o'),
Convert.ToByte('r'),
Convert.ToByte('k'),
Convert.ToByte('s'),
0x07};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressHttpsURL() {
String testURL = "https://www.radiusnetworks.com";
byte[] expectedBytes = {0x01,
Convert.ToByte('r'),
Convert.ToByte('a'),
Convert.ToByte('d'),
Convert.ToByte('i'),
Convert.ToByte('u'),
Convert.ToByte('s'),
Convert.ToByte('n'),
Convert.ToByte('e'),
Convert.ToByte('t'),
Convert.ToByte('w'),
Convert.ToByte('o'),
Convert.ToByte('r'),
Convert.ToByte('k'),
Convert.ToByte('s'),
0x07};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithTrailingSlash() {
String testURL = "http://google.com/123";
byte[] expectedBytes = {0x02,
Convert.ToByte('g'),
Convert.ToByte('o'),
Convert.ToByte('o'),
Convert.ToByte('g'),
Convert.ToByte('l'),
Convert.ToByte('e'),
0x00,
Convert.ToByte('1'),
Convert.ToByte('2'),
Convert.ToByte('3')};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithoutTLD() {
String testURL = "http://xxx";
byte[] expectedBytes = {0x02,
Convert.ToByte('x'),
Convert.ToByte('x'),
Convert.ToByte('x')};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithSubdomains() {
String testURL = "http://www.forums.google.com";
byte[] expectedBytes = {0x00,
Convert.ToByte('f'),
Convert.ToByte('o'),
Convert.ToByte('r'),
Convert.ToByte('u'),
Convert.ToByte('m'),
Convert.ToByte('s'),
Convert.ToByte('.'),
Convert.ToByte('g'),
Convert.ToByte('o'),
Convert.ToByte('o'),
Convert.ToByte('g'),
Convert.ToByte('l'),
Convert.ToByte('e'),
0x07};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithSubdomainsWithTrailingSlash() {
String testURL = "http://www.forums.google.com/";
byte[] expectedBytes = {0x00,
Convert.ToByte('f'),
Convert.ToByte('o'),
Convert.ToByte('r'),
Convert.ToByte('u'),
Convert.ToByte('m'),
Convert.ToByte('s'),
Convert.ToByte('.'),
Convert.ToByte('g'),
Convert.ToByte('o'),
Convert.ToByte('o'),
Convert.ToByte('g'),
Convert.ToByte('l'),
Convert.ToByte('e'),
0x00};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithMoreSubdomains() {
String testURL = "http://www.forums.developer.google.com/123";
byte[] expectedBytes = {0x00,
Convert.ToByte('f'),
Convert.ToByte('o'),
Convert.ToByte('r'),
Convert.ToByte('u'),
Convert.ToByte('m'),
Convert.ToByte('s'),
Convert.ToByte('.'),
Convert.ToByte('d'),
Convert.ToByte('e'),
Convert.ToByte('v'),
Convert.ToByte('e'),
Convert.ToByte('l'),
Convert.ToByte('o'),
Convert.ToByte('p'),
Convert.ToByte('e'),
Convert.ToByte('r'),
Convert.ToByte('.'),
Convert.ToByte('g'),
Convert.ToByte('o'),
Convert.ToByte('o'),
Convert.ToByte('g'),
Convert.ToByte('l'),
Convert.ToByte('e'),
0x00,
Convert.ToByte('1'),
Convert.ToByte('2'),
Convert.ToByte('3')};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithSubdomainsAndSlashesInPath() {
String testURL = "http://www.forums.google.com/123/456";
byte[] expectedBytes = {0x00, (byte)'f', (byte)'o', (byte)'r', (byte)'u', (byte)'m', (byte)'s', (byte)'.', (byte)'g', (byte)'o', (byte)'o', (byte)'g', (byte)'l', (byte)'e', 0x00, (byte)'1', (byte)'2', (byte)'3', (byte)'/', (byte)'4', (byte)'5', (byte)'6'};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithDotCaTLD() {
String testURL = "http://google.ca";
byte[] expectedBytes = {0x02, (byte)'g', (byte)'o', (byte)'o', (byte)'g', (byte)'l', (byte)'e', (byte)'.', (byte)'c', (byte)'a'};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithDotInfoTLD() {
String testURL = "http://google.info";
byte[] expectedBytes = {0x02, (byte)'g', (byte)'o', (byte)'o', (byte)'g', (byte)'l', (byte)'e', 0x0b};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithDotCaTLDWithSlash() {
String testURL = "http://google.ca/";
byte[] expectedBytes = {0x02, (byte)'g', (byte)'o', (byte)'o', (byte)'g', (byte)'l', (byte)'e', (byte)'.', (byte)'c', (byte)'a', (byte)'/'};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithDotCoTLD() {
String testURL = "http://google.co";
byte[] expectedBytes = {0x02, (byte)'g', (byte)'o', (byte)'o', (byte)'g', (byte)'l', (byte)'e', (byte)'.', (byte)'c', (byte)'o'};
String hexBytes = bytesToHex(UrlBeaconUrlCompressor.Compress(testURL));
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithShortenedURLContainingCaps() {
String testURL = "http://goo.gl/C2HC48";
byte[] expectedBytes = {0x02, (byte)'g', (byte)'o', (byte)'o', (byte)'.', (byte)'g', (byte)'l', (byte)'/', (byte)'C', (byte)'2', (byte)'H', (byte)'C', (byte)'4', (byte)'8'};
String hexBytes = bytesToHex(UrlBeaconUrlCompressor.Compress(testURL));
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithSchemeInCaps() {
String testURL = "HTTP://goo.gl/C2HC48";
byte[] expectedBytes = {0x02, (byte)'g', (byte)'o', (byte)'o', (byte)'.', (byte)'g', (byte)'l', (byte)'/', (byte)'C', (byte)'2', (byte)'H', (byte)'C', (byte)'4', (byte)'8'};
String hexBytes = bytesToHex(UrlBeaconUrlCompressor.Compress(testURL));
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressWithDomainInCaps() {
String testURL = "http://GOO.GL/C2HC48";
byte[] expectedBytes = {0x02, (byte)'g', (byte)'o', (byte)'o', (byte)'.', (byte)'g', (byte)'l', (byte)'/', (byte)'C', (byte)'2', (byte)'H', (byte)'C', (byte)'4', (byte)'8'};
String hexBytes = bytesToHex(UrlBeaconUrlCompressor.Compress(testURL));
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressHttpsAndWWWInCaps() {
String testURL = "HTTPS://WWW.radiusnetworks.com";
byte[] expectedBytes = {0x01, (byte)'r', (byte)'a', (byte)'d', (byte)'i', (byte)'u', (byte)'s', (byte)'n', (byte)'e', (byte)'t', (byte)'w', (byte)'o', (byte)'r', (byte)'k', (byte)'s', 0x07};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressEntireURLInCaps() {
String testURL = "HTTPS://WWW.RADIUSNETWORKS.COM";
byte[] expectedBytes = {0x01, (byte)'r', (byte)'a', (byte)'d', (byte)'i', (byte)'u', (byte)'s', (byte)'n', (byte)'e', (byte)'t', (byte)'w', (byte)'o', (byte)'r', (byte)'k', (byte)'s', 0x07};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testCompressEntireURLInCapsWithPath() {
String testURL = "HTTPS://WWW.RADIUSNETWORKS.COM/C2HC48";
byte[] expectedBytes = {0x01, (byte)'r', (byte)'a', (byte)'d', (byte)'i', (byte)'u', (byte)'s', (byte)'n', (byte)'e', (byte)'t', (byte)'w', (byte)'o', (byte)'r', (byte)'k', (byte)'s', 0x00, (byte)'C', (byte)'2', (byte)'H', (byte)'C', (byte)'4', (byte)'8'};
Assert.True(Arrays.Equals(expectedBytes, UrlBeaconUrlCompressor.Compress(testURL)));
}
[Test]
public void testDecompressWithDotCoTLD() {
String testURL = "http://google.co";
byte[] testBytes = {0x02, (byte)'g', (byte)'o', (byte)'o', (byte)'g', (byte)'l', (byte)'e', (byte)'.', (byte)'c', (byte)'o'};
Assert.AreEqual(testURL, UrlBeaconUrlCompressor.Uncompress(testBytes));
}
[Test]
public void testDecompressWithPath() {
String testURL = "http://google.com/123";
byte[] testBytes = {0x02, (byte)'g', (byte)'o', (byte)'o', (byte)'g', (byte)'l', (byte)'e', 0x00, (byte)'1', (byte)'2', (byte)'3'};
Assert.AreEqual(testURL, UrlBeaconUrlCompressor.Uncompress(testBytes));
}
[Test]
public void testUncompressHttpsURL() {
String testURL = "https://www.radiusnetworks.com";
byte[] testBytes = {0x01, (byte)'r', (byte)'a', (byte)'d', (byte)'i', (byte)'u', (byte)'s', (byte)'n', (byte)'e', (byte)'t', (byte)'w', (byte)'o', (byte)'r', (byte)'k', (byte)'s', 0x07};
Assert.AreEqual(testURL, UrlBeaconUrlCompressor.Uncompress(testBytes));
}
[Test]
public void testUncompressHttpsURLWithTrailingSlash() {
String testURL = "https://www.radiusnetworks.com/";
byte[] testBytes = {0x01, (byte)'r', (byte)'a', (byte)'d', (byte)'i', (byte)'u', (byte)'s', (byte)'n', (byte)'e', (byte)'t', (byte)'w', (byte)'o', (byte)'r', (byte)'k', (byte)'s', 0x00};
Assert.AreEqual(testURL, UrlBeaconUrlCompressor.Uncompress(testBytes));
}
[Test]
public void testUncompressWithoutTLD() {
String testURL = "http://xxx";
byte[] testBytes = {0x02, (byte)'x', (byte)'x', (byte)'x'};
Assert.AreEqual(testURL, UrlBeaconUrlCompressor.Uncompress(testBytes));
}
[Test]
public void testUncompressWithSubdomains() {
String testURL = "http://www.forums.google.com";
byte[] testBytes = {0x00, (byte)'f', (byte)'o', (byte)'r', (byte)'u', (byte)'m', (byte)'s', (byte)'.', (byte)'g', (byte)'o', (byte)'o', (byte)'g', (byte)'l', (byte)'e', 0x07};
Assert.AreEqual(testURL, UrlBeaconUrlCompressor.Uncompress(testBytes));
}
[Test]
public void testUncompressWithSubdomainsAndTrailingSlash() {
String testURL = "http://www.forums.google.com/";
byte[] testBytes = {0x00, (byte)'f', (byte)'o', (byte)'r', (byte)'u', (byte)'m', (byte)'s', (byte)'.', (byte)'g', (byte)'o', (byte)'o', (byte)'g', (byte)'l', (byte)'e', 0x00};
Assert.AreEqual(testURL, UrlBeaconUrlCompressor.Uncompress(testBytes));
}
[Test]
public void testUncompressWithSubdomainsAndSlashesInPath() {
String testURL = "http://www.forums.google.com/123/456";
byte[] testBytes = {0x00, (byte)'f', (byte)'o', (byte)'r', (byte)'u', (byte)'m', (byte)'s', (byte)'.', (byte)'g', (byte)'o', (byte)'o', (byte)'g', (byte)'l', (byte)'e', 0x00, (byte)'1', (byte)'2', (byte)'3', (byte)'/', (byte)'4', (byte)'5', (byte)'6'};
Assert.AreEqual(testURL, UrlBeaconUrlCompressor.Uncompress(testBytes));
}
[Test]
public void testUncompressWithDotInfoTLD() {
String testURL = "http://google.info";
byte[] testBytes = {0x02, (byte)'g', (byte)'o', (byte)'o', (byte)'g', (byte)'l', (byte)'e', 0x0b};
Assert.AreEqual(testURL, UrlBeaconUrlCompressor.Uncompress(testBytes));
}
String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.Length * 2];
for (int j = 0; j < bytes.Length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/AssertEx.cs
using System.Linq;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
public static class AssertEx
{
public static void AreEqual(string message, int expected, int actual)
{
Assert.AreEqual(expected, actual, message);
}
public static void AreEqual(string message, long expected, long actual)
{
Assert.AreEqual(expected, actual, message);
}
public static void AreEqual(string message, byte[] expected, byte[] actual)
{
Assert.IsTrue(actual.SequenceEqual(expected), message);
}
public static void AreEqual(string message, double expected, double actual, double delta)
{
Assert.AreEqual(expected, actual, delta, message);
}
public static void AreEqual(string message, object expected, object actual)
{
Assert.AreEqual(expected, actual, message);
}
public static void AreNotEqual(string message, int expected, int actual)
{
Assert.AreNotEqual(expected, actual, message);
}
public static void AreNotEqual(string message, object expected, object actual)
{
Assert.AreNotEqual(expected, actual, message);
}
public static void Null(string message, object anObject)
{
Assert.Null(anObject, message);
}
public static void NotNull(string message, object anObject)
{
Assert.NotNull(anObject, message);
}
public static void True(string message, bool condition)
{
Assert.True(condition, message);
}
public static void False(string message, bool condition)
{
Assert.False(condition, message);
}
public static void AreNotSame(string message, object expected, object actual)
{
Assert.AreNotSame(expected, actual, message);
}
}
}<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/Utils/EddystoneTelemetryAccessorTest.cs
using System;
using NUnit.Framework;
using AltBeaconOrg.BoundBeacon;
using System.Collections.Generic;
using AltBeaconOrg.BoundBeacon.Utils;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class EddystoneTelemetryAccessorTest : TestBase
{
[Test]
public void testAllowsAccessToTelemetryBytes() {
var telemetryFields = new List<Java.Lang.Long>();
telemetryFields.Add(new Java.Lang.Long(0x01L)); // version
telemetryFields.Add(new Java.Lang.Long(0x0212L)); // battery level
telemetryFields.Add(new Java.Lang.Long(0x0313L)); // temperature
telemetryFields.Add(new Java.Lang.Long(0x04142434L)); // pdu count
telemetryFields.Add(new Java.Lang.Long(0x05152535L)); // uptime
Beacon beaconWithTelemetry = new Beacon.Builder().SetId1("0x0102030405060708090a").SetId2("0x01020304050607").SetTxPower(-59).SetExtraDataFields(telemetryFields).Build();
byte[] telemetryBytes = new EddystoneTelemetryAccessor().GetTelemetryBytes(beaconWithTelemetry);
byte[] expectedBytes = {0x20, 0x01, 0x02, 0x12, 0x03, 0x13, 0x04, 0x14, 0x24, 0x34, 0x05, 0x15, 0x25, 0x35};
AssertEx.AreEqual("Should be equal", ByteArrayToHexString(telemetryBytes), ByteArrayToHexString(expectedBytes));
}
[Test]
public void testAllowsAccessToBase64EncodedTelemetryBytes() {
var telemetryFields = new List<Java.Lang.Long>();
telemetryFields.Add(new Java.Lang.Long(0x01L)); // version
telemetryFields.Add(new Java.Lang.Long(0x0212L)); // battery level
telemetryFields.Add(new Java.Lang.Long(0x0313L)); // temperature
telemetryFields.Add(new Java.Lang.Long(0x04142434L)); // pdu count
telemetryFields.Add(new Java.Lang.Long(0x05152535L)); // uptime
Beacon beaconWithTelemetry = new Beacon.Builder().SetId1("0x0102030405060708090a").SetId2("0x01020304050607").SetTxPower(-59).SetExtraDataFields(telemetryFields).Build();
byte[] telemetryBytes = new EddystoneTelemetryAccessor().GetTelemetryBytes(beaconWithTelemetry);
String encodedTelemetryBytes = new EddystoneTelemetryAccessor().GetBase64EncodedTelemetry(beaconWithTelemetry);
AssertEx.NotNull("Should not be null", telemetryBytes);
}
}
}
<file_sep>/Samples/Forms/AltBeaconLibrary.Sample/AltBeaconLibrary.Sample/SharedBeacon.cs
namespace AltBeaconLibrary.Sample
{
public class SharedBeacon
{
public string Id { get; set; }
public string Distance { get; set; }
}
}
<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/AltBeaconTest.cs
using System;
using AltBeaconOrg.BoundBeacon;
using Android.OS;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class AltBeaconTest : TestBase
{
[Test]
public void TestRecognizeBeacon()
{
var bytes = HexStringToByteArray("02011a1bff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c509");
var parser = new AltBeaconParser();
var beacon = parser.FromScanData(bytes, -55, null);
Assert.AreEqual(9, ((AltBeacon) beacon).MfgReserved, "manData should be parsed");
}
[Test]
public void TestCanSerializeParcelable()
{
var parcel = Parcel.Obtain();
var beacon = new AltBeacon.Builder().SetMfgReserved(7).SetId1("1").SetId2("2").SetId3("3").SetRssi(4)
.SetBeaconTypeCode(5).SetTxPower(6)
.SetBluetoothAddress("1:2:3:4:5:6").Build();
beacon.WriteToParcel(parcel, 0);
parcel.SetDataPosition(0);
var beacon2 = new AltBeacon(parcel);
Assert.AreEqual(((AltBeacon)beacon).MfgReserved, ((AltBeacon)beacon2).MfgReserved, "beaconMfgReserved is same after deserialization");
}
}
}<file_sep>/AndroidAltBeaconLibrary/AndroidAltBeaconLibrary.UnitTests/Tests/Beacon/GattBeaconTest.cs
using System;
using System.Collections.Generic;
using AltBeaconOrg.BoundBeacon;
using AltBeaconOrg.BoundBeacon.Utils;
using Android.App;
using Android.Content;
using NUnit.Framework;
namespace AndroidAltBeaconLibrary.UnitTests
{
[TestFixture]
public class GattBeaconTest : TestBase
{
[Test]
public void TestDetectsGattBeacon() {
byte[] bytes = HexStringToByteArray("020106030334121516341200e72f234454f4911ba9ffa6000000000001000000000000000000000000000000000000000000000000000000000000000000");
BeaconParser parser = new BeaconParser().SetBeaconLayout("s:0-1=1234,m:2-2=00,p:3-3:-41,i:4-13,i:14-19");
AssertEx.NotNull("Service uuid parsed should not be null", parser.ServiceUuid);
Beacon gattBeacon = parser.FromScanData(bytes, -55, null);
AssertEx.NotNull("GattBeacon should be not null if parsed successfully", gattBeacon);
AssertEx.AreEqual("id1 should be parsed", "0x2f234454f4911ba9ffa6", gattBeacon.Id1.ToString());
AssertEx.AreEqual("id2 should be parsed", "0x000000000001", gattBeacon.Id2.ToString());
AssertEx.AreEqual("serviceUuid should be parsed", 0x1234, gattBeacon.ServiceUuid);
AssertEx.AreEqual("txPower should be parsed", -66, gattBeacon.TxPower);
}
[Test]
public void TestDetectsGattBeacon2MaxLength() {
byte[] bytes = HexStringToByteArray("020106030334121616341210ec007261646975736e6574776f726b7373070000000000000000000000000000000000000000000000000000000000000000");
BeaconParser parser = new BeaconParser().SetBeaconLayout("s:0-1=1234,m:2-2=10,p:3-3:-41,i:4-20v");
Beacon gattBeacon = parser.FromScanData(bytes, -55, null);
AssertEx.NotNull("GattBeacon should be not null if parsed successfully", gattBeacon);
AssertEx.AreEqual("GattBeacon identifier length should be proper length",
17,
gattBeacon.Id1.ToByteArray().Length);
}
[Test]
public void TestDetectsGattBeacon2WithShortIdentifier() {
byte[] bytes = HexStringToByteArray("020106030334121516341210ec007261646975736e6574776f726b7307000000000000000000000000000000000000000000000000000000000000000000");
BeaconParser parser = new BeaconParser().SetBeaconLayout("s:0-1=1234,m:2-2=10,p:3-3:-41,i:4-20v");
Beacon gattBeacon = parser.FromScanData(bytes, -55, null);
AssertEx.NotNull("GattBeacon should be not null if parsed successfully", gattBeacon);
AssertEx.AreEqual("GattBeacon identifier length should be adjusted smaller if packet is short",
16,
gattBeacon.Id1.ToByteArray().Length);
AssertEx.AreEqual("GattBeacon identifier should have proper first byte",
(byte)0x00,
gattBeacon.Id1.ToByteArray()[0]);
AssertEx.AreEqual("GattBeacon identifier should have proper second to last byte",
(byte) 0x73,
gattBeacon.Id1.ToByteArray()[14]);
AssertEx.AreEqual("GattBeacon identifier should have proper last byte",
(byte)0x07,
gattBeacon.Id1.ToByteArray()[15]);
}
[Test]
public void TestDetectsEddystoneUID() {
byte[] bytes = HexStringToByteArray("0201060303aafe1516aafe00e700010203040506070809010203040506000000000000000000000000000000000000000000000000000000000000000000");
BeaconParser parser = new BeaconParser().SetBeaconLayout(BeaconParser.EddystoneUidLayout);
Beacon eddystoneUidBeacon = parser.FromScanData(bytes, -55, null);
AssertEx.NotNull("Eddystone-UID should be not null if parsed successfully", eddystoneUidBeacon);
}
[Test]
public void TestDetectsGattBeaconWithCnn() {
byte[] bytes = HexStringToByteArray("020106030334120a16341210ed00636e6e070000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
BeaconParser parser = new BeaconParser().SetBeaconLayout("s:0-1=1234,m:2-2=10,p:3-3:-41,i:4-20v");
Beacon gattBeacon = parser.FromScanData(bytes, -55, null);
AssertEx.NotNull("GattBeacon should be not null if parsed successfully", gattBeacon);
AssertEx.AreEqual("GattBeacon identifier length should be adjusted smaller if packet is short",
5,
gattBeacon.Id1.ToByteArray().Length);
}
[Test]
[Ignore]
public void testBeaconAdvertisingBytes() {
Context context = Application.Context;
Beacon beacon = new Beacon.Builder()
.SetId1("0x454452e29735323d81c0")
.SetId2("0x060504030201")
.SetDataFields(new List<Java.Lang.Long> { new Java.Lang.Long(0x25L) })
.SetTxPower(-59)
.Build();
// TODO: need to use something other than the d: prefix here for an internally generated field
BeaconParser beaconParser = new BeaconParser()
.SetBeaconLayout("s:0-1=0123,m:2-2=00,d:3-3,p:4-4,i:5-14,i:15-20");
byte[] data = beaconParser.GetBeaconAdvertisementData(beacon);
BeaconTransmitter beaconTransmitter = new BeaconTransmitter(context, beaconParser);
// TODO: can't actually start transmitter here because Robolectric does not support API 21
AssertEx.AreEqual("Data should be 19 bytes long", 19, data.Length);
String byteString = "";
for (int i = 0; i < data.Length; i++) {
byteString += String.Format("{0:x2}", data[i]);
byteString += " ";
}
AssertEx.AreEqual("Advertisement bytes should be as expected", "00 25 C5 45 44 52 E2 97 35 32 3D 81 C0 06 05 04 03 02 01 ", byteString);
}
[Test]
public void TestDetectsUriBeacon() {
//"https://goo.gl/hqBXE1"
byte[] bytes = {2, 1, 4, 3, 3, (byte) 216, (byte) 254, 19, 22, (byte) 216, (byte) 254, 0, (byte) 242, 3, 103, 111, 111, 46, 103, 108, 47, 104, 113, 66, 88, 69, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
BeaconParser parser = new BeaconParser().SetBeaconLayout("s:0-1=fed8,m:2-2=00,p:3-3:-41,i:4-21v");
Beacon uriBeacon = parser.FromScanData(bytes, -55, null);
AssertEx.NotNull("UriBeacon should be not null if parsed successfully", uriBeacon);
AssertEx.AreEqual("UriBeacon identifier length should be correct",
14,
uriBeacon.Id1.ToByteArray().Length);
String urlString = UrlBeaconUrlCompressor.Uncompress(uriBeacon.Id1.ToByteArray());
AssertEx.AreEqual("URL should be decompressed successfully", "https://goo.gl/hqBXE1", urlString);
}
}
}
<file_sep>/Samples/Native/BeaconReference.Droid/MonitoringActivity.cs
using System;
using AltBeaconOrg.BoundBeacon;
using Android;
using Android.Annotation;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;
using Java.Interop;
using Java.Lang;
using Debug = System.Diagnostics.Debug;
namespace BeaconReference.Droid
{
[Activity(MainLauncher = true, LaunchMode = Android.Content.PM.LaunchMode.SingleInstance)]
public class MonitoringActivity : Activity, IDialogInterfaceOnDismissListener
{
protected const string TAG = "MonitoringActivity";
const int PERMISSION_REQUEST_COARSE_LOCATION = 1;
protected override void OnCreate(Bundle savedInstanceState)
{
Debug.WriteLine("onCreate", TAG);
base.OnCreate(savedInstanceState);
Title = "Monitoring";
SetContentView(Resource.Layout.activity_monitoring);
VerifyBluetooth();
LogToDisplay("Application just launched");
if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
{
// Android M Permission check
if (this.CheckSelfPermission(Manifest.Permission.AccessCoarseLocation) != Android.Content.PM.Permission.Granted)
{
var builder = new AlertDialog.Builder(this);
builder.SetTitle("This app needs location access");
builder.SetMessage("Please grant location access so this app can detect beacons in the background.");
builder.SetPositiveButton(Android.Resource.String.Ok, (sender, args) => { });
builder.SetOnDismissListener(this);
builder.Show();
}
}
}
protected override void OnResume()
{
base.OnResume();
if (this.ApplicationContext is BeaconReferenceApplication app) {
app.SetMonitoringActivity(this);
}
}
protected override void OnPause()
{
base.OnPause();
if (this.ApplicationContext is BeaconReferenceApplication app) {
app.SetMonitoringActivity(null);
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults[0] == Android.Content.PM.Permission.Granted) {
Debug.WriteLine("coarse location permission granted", TAG);
}
else {
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Functionality limited");
builder.SetMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
builder.SetPositiveButton(Android.Resource.String.Ok, (obj, sender) => { });
builder.SetOnDismissListener(null);
builder.Show();
}
return;
}
}
}
void VerifyBluetooth()
{
try {
if (!BeaconManager.GetInstanceForApplication(this).CheckAvailability()) {
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Bluetooth not enabled");
builder.SetMessage("Please enable bluetooth in settings and restart this application.");
builder.SetPositiveButton(Android.Resource.String.Ok, (obj, sender) => { });
builder.SetOnDismissListener(new DialogExitOnDismissListener(this));
builder.Show();
}
}
catch (RuntimeException ex) {
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Bluetooth LE not available");
builder.SetMessage("Sorry, this device does not support Bluetooth LE.");
builder.SetPositiveButton(Android.Resource.String.Ok, (obj, sender) => { });
builder.SetOnDismissListener(new DialogExitOnDismissListener(this));
builder.Show();
}
}
[Export("OnRangingClicked")]
public void OnRangingClicked(View view)
{
Intent myIntent = new Intent(this, typeof(RangingActivity));
this.StartActivity(myIntent);
}
public void LogToDisplay(string line)
{
RunOnUiThread(() =>
{
var editText = FindViewById<EditText>(Resource.Id.monitoringText);
editText.Append(line + "\n");
});
}
#region IDialogInterfaceOnDismissListener implementation
[TargetApi(Value = 23)]
public void OnDismiss(IDialogInterface dialog)
{
RequestPermissions(new string[]{Manifest.Permission.AccessCoarseLocation},
PERMISSION_REQUEST_COARSE_LOCATION);
}
#endregion
class DialogExitOnDismissListener : Java.Lang.Object, IDialogInterfaceOnDismissListener
{
WeakReference<Activity> _weakActivity;
public DialogExitOnDismissListener(Activity activity)
{
_weakActivity = new WeakReference<Activity>(activity);
}
public void OnDismiss(IDialogInterface dialog)
{
if (_weakActivity.TryGetTarget(out Activity activity))
{
activity.Finish();
JavaSystem.Exit(0);
}
}
}
}
}
| 61822eaadc5262e089036133eaa86230fe2ce5de | [
"Markdown",
"C#"
] | 41 | C# | luposlip/Android-AltBeacon-Library | f10eef66fc348a8cb6397a3719572d04c66f6138 | d0a765a0fadbff01ea3f8f6c2f4601a8c9138a6d |
refs/heads/master | <repo_name>ElisaME/lab-mongoose-movies<file_sep>/starter-code/bin/seeds.js
const mongoose = require('mongoose');
const Celebrity = require('../models/Celebrity');
const Movie = require('../models/Movie');
const dbName = 'celebrities';
mongoose.connect(`mongodb://localhost/${dbName}`);
// const celebrities = [
// {
// name: '<NAME>',
// occupation: 'Singer',
// catchPhrase:
// 'Whenever I watch TV and see those poor starving kids all over the world, I cant help but cry. I mean Id love to be skinny like that, but not with all those flies and death and stuff.'
// },
// {
// name: '<NAME>',
// occupation: 'Model',
// catchPhrase: 'Happy Birthday to you'
// },
// {
// name: '<NAME>',
// occupation: 'Model',
// catchPhrase: 'Thats hot!'
// }
// ];
// Celebrity.create(celebrities, err => {
// if (err) {
// throw err;
// }
// console.log(`${celebrities.length} "celebrities" created.`);
// mongoose.connection.close();
// });
// const movies = [
// {
// title: "movie 1",
// genre: "comedy",
// plot: "blah blah",
// },
// {
// title: "movie 2",
// genre: "Romance",
// plot: "blah blah blah blah",
// },
// {
// title: "movie 3",
// genre: "Gore",
// plot: "blah blah blah blah blah blah",
// },
// ];
// Movie.create(movies, (err) => {
// if (err) {
// throw (err)
// }
// console.log(`${movies.length} "movies" created.`)
// mongoose.connection.close()
// })
| 8a7d1784ae96f6eafd1bbe2abdd586261da80174 | [
"JavaScript"
] | 1 | JavaScript | ElisaME/lab-mongoose-movies | feaf5694cd2c84b55c785fc9c27cdc6c9a13d617 | a80168a04663c17083a30ec48c2941f5237be306 |
refs/heads/master | <file_sep>const moment = require('moment');
const logger = require('../logging');
const Birthdays = require('../model/birthdays.model');
// create birthday
const createBirthdays = function(birthdays, cb) {
if(birthdays) {
logger.info("create birthday request - birthdays: " + JSON.stringify(birthdays));
Birthdays.create(birthdays, cb);
}
};
Object.prototype.hasOwnProperty = function(property) {
return this[property] !== undefined;
};
// get birthdays
const getBirthdays = function(filter, cb) {
logger.info("getBirthdays request");
var findConditions = {}; // starts empty
// check for filter present
if(filter.hasOwnProperty("from") && filter.hasOwnProperty("to")) {
logger.info("filter: " + JSON.stringify(filter));
var validFilter = true;
// validate incoming "from" date
if(!filter.from || !moment(new Date(filter.from)).isValid()) {
logger.info("missing 'from' attribute or invalid date");
validFilter = false;
}
// validate incoming "to" date
if(!filter.to || !moment(new Date(filter.to)).isValid()) {
logger.info("missing 'to' attribute or invalid date");
validFilter = false;
}
if(!validFilter) {
cb({error: "invalid request filter - aborting"});
return; // couldn't use filter
} else {
findConditions = {
birthday: {
$gte: moment(filter.from).toDate(),
$lte: moment(filter.to).toDate()
}
};
}
}
Birthdays.find(findConditions, cb);
};
const updateBirthday = function(birthday, cb) {
logger.info("updating birthday: " + JSON.stringify(birthday));
Birthdays.update(birthday, cb);
};
const deleteBirthday = function(birthday, cb) {
logger.info("deleting birthday: " + JSON.stringify(birthday));
Birthdays.deleteOne({_id: birthday._id}, cb);
};
module.exports = {
getBirthdays: getBirthdays,
createBirthdays: createBirthdays,
updateBirthday: updateBirthday,
deleteBirthday: deleteBirthday
};<file_sep>var app = angular.module('BirthdaysApp', ['ngMaterial', 'ngMessages']);
app.service(
'birthdays',
function($http) {
this.getBirthdays = function(filter, cb) {
$http({
url: '/api/birthdays',
method: "GET",
params: filter
}).then(function (response) {
cb(null, response);
});
};
}
);
app.controller('BirthdaysListCtrl', function($scope, birthdays) {
birthdays.getBirthdays(
{},
function(err, response) {
$scope.allBirthdays = response.data;
}
);
var from = moment().subtract(1,'days').startOf('day');
var to = moment().subtract(1,'days').endOf('day');
console.log("from: " + from + " to: " + to);
birthdays.getBirthdays(
{
from: from,
to: to
},
function(err, response) {
$scope.todaysBirthdays = response.data;
}
)
});
<file_sep>const logger = require('../logging');
const express = require('express');
const router = express.Router();
const Birthdays = require('./birthdays.controller');
router.get(
'/',
function(req, res) {
Birthdays.getBirthdays(
req.query,
function(err, birthdays) {
if(err) {
logger.error(err);
res.json(err);
} else {
logger.info("getBirthdays Response: " + JSON.stringify(birthdays));
res.json(birthdays);
}
}
);
}
);
router.post(
'/',
function(req, res) {
Birthdays.createBirthdays(
req.body,
function(err, birthdays) {
if(err) {
logger.error(err);
res.json(err);
} else {
logger.info("createBirthday Response: " + JSON.stringify(birthdays));
res.json(birthdays);
}
}
)
}
);
router.put( // update
'/',
function(req, res) {
Birthdays.updateBirthday(
req.body,
function(err, birthday) {
if(err) {
logger.error(err);
res.json(err);
} else {
logger.info("updateBirthday Response: " + JSON.stringify(birthday));
res.json(birthday);
}
}
);
}
);
router.delete(
'/',
function(req, res) {
Birthdays.deleteBirthday(
req.body,
function(err, birthday) {
if(err) {
logger.error(err);
res.json(err);
} else {
logger.info("deleteBirthday Response: " + JSON.stringify(birthday));
res.json(birthday);
}
}
);
}
);
module.exports = router;<file_sep># coding-challenge-birthdays-app
### Approach
I have tried to respect the recommended time constraints for this exercise
The approach I have taken when constructing this app is as follows:
#### Model
I have developed a persistent model for birthdays using MongoDB and Mongoose
A "Birthday" object consists of two attributes, a name (string) and a birthday (date)
#### API
To interact with the model I have developed a REST API using the Express.js framework. The API is separated into a router module and a controller module.
#### Web App
I have developed part of a web app (unfinished) using the AngularJS framwork in conjunction with the Material Design UI framework. I have included some of their components, mainly the list.
Currently it will only display items. But there are serverside APIs availabile to modify and remove entries from the DB
#### Logging
The winston library is used to record info and errors
### Deploying
To run the app you will require
```
- Node.js
- MongoDB
```
You will be required to create the application a user account within MongoDB
```
~$ mongo setup/mongo-user.js
```
We will also need the Node dependencies
```
~$ npm install
```
Once you have created the DB user, you can start up the server app using
```
~$ node .
```
You can visit the client webpage at
```
http://localhost:8080/
```
and experiment with the API at
```
http://localhost:8080/api/birthdays/
```
There are some postman scripts in the test directory to provide examples of API usage
<file_sep>const mongoose = require("mongoose");
const BirthdaySchema = new mongoose.Schema({
name: String,
birthday: Date
});
const Birthdays = mongoose.model('Birthday', BirthdaySchema);
module.exports = Birthdays; | ef33c35376b46520a59d441d8eb0f83c3dacd256 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | Ziyad/coding-challenge-birthdays-app | b8cab1150533032aa17dfc4bfcda0f2b1e62a6ba | d9ac60c4fd5f62ff00c353d1e9efa322a7962f86 |
refs/heads/master | <file_sep>#include <stdint.h>
#include "tty.h"
#include "io.h"
#include "serial.h"
static size_t cur_x = 0;
static size_t cur_y = 0;
void set_cursor_pos(int x, int y)
{
uint16_t pos = y * VGA_WIDTH + x;
outb(0x3D4, 0x0F);
outb(0x3D5, (uint8_t)(pos & 0xFF));
outb(0x3D4, 0x0E);
outb(0x3D5, (uint8_t)((pos >> 8) & 0xFF));
}
void scroll_down()
{
volatile uint16_t *prev_line = VGA_ADDR;
volatile uint16_t *cur_line = prev_line + VGA_WIDTH;
while (cur_line != VGA_END)
{
*(prev_line++) = *(cur_line++);
}
while (prev_line != VGA_END)
{
*(prev_line++) = 0x0;
}
}
void print(char *string)
{
volatile char *vga = (char *)VGA_ADDR + 2 * cur_x + cur_y * VGA_WIDTH * 2;
while (*string != 0)
{
if (*string == 10 || cur_x >= VGA_WIDTH)
{
cur_x = 0;
if (cur_y + 1 >= VGA_HEIGHT)
{
scroll_down();
}
else
{
cur_y++;
}
string++;
continue;
}
cur_x++;
*vga++ = *string;
*vga++ = 0x0a;
string++;
}
set_cursor_pos(cur_x, cur_y);
}
<file_sep>#pragma once
#include <stddef.h>
#include <stdint.h>
static uint16_t *const VGA_ADDR = (uint16_t *)0xb8000;
static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 25;
static uint16_t *const VGA_END = VGA_ADDR + VGA_WIDTH * 2 * VGA_HEIGHT;
void print(char *string);
<file_sep>#include "serial.h"
#include "tty.h"
#include "utils.h"
#include "idt.h"
#include "../shared/memory_map.h"
#ifndef OSNAME
#define OSNAME "NO_OSNAME_PROVIDED"
#endif
extern SMAP_entry_t memory_map_start[];
extern uint32_t memory_map_entries_count;
void main()
{
init_serial();
init_idt();
print(
"welcome to " OSNAME "\n");
print("Detected memory:\n");
int total_memory = 0;
for (uint32_t i = 0; i < memory_map_entries_count; i++)
{
total_memory += memory_map_start[i].Length;
}
print(itoa(total_memory / 1024 / 1024, 10));
print("MB\n");
int a = 0;
print("Ble");
int b = 5 / a;
print(itoa(b, 10));
while (1)
{
}
}
<file_sep>#pragma once
void init_idt(void);
<file_sep>#pragma once
typedef struct SMAP_entry
{
uint64_t Base; // base address uint64_t
uint64_t Length; // length uint64_t
uint32_t Type; // entry Type
uint32_t ACPI; // extended
} __attribute__((packed)) SMAP_entry_t;
void read_memory_map();
<file_sep>#include "idt.h"
#include "serial.h"
#include "io.h"
#include "tty.h"
#include "utils.h"
char kbd_US[128] =
{
0, 27, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '\b',
'\t', /* <-- Tab */
'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n',
0, /* <-- control key */
'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '`', 0, '\\', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', 0,
'*',
0, /* Alt */
' ', /* Space bar */
0, /* Caps lock */
0, /* 59 - F1 key ... > */
0, 0, 0, 0, 0, 0, 0, 0,
0, /* < ... F10 */
0, /* 69 - Num lock*/
0, /* Scroll Lock */
0, /* Home key */
0, /* Up Arrow */
0, /* Page Up */
'-',
0, /* Left Arrow */
0,
0, /* Right Arrow */
'+',
0, /* 79 - End key*/
0, /* Down Arrow */
0, /* Page Down */
0, /* Insert Key */
0, /* Delete Key */
0, 0, 0,
0, /* F11 Key */
0, /* F12 Key */
0, /* All other keys are undefined */
};
static const char GDT_SELECTOR = 0x08;
typedef void (*irq_handler_t)();
typedef union {
irq_handler_t irq_handler;
uint16_t u16[2];
} irq_handler_u;
typedef enum
{
INTERRUPT_GATE = 0x8e
} gate_t;
typedef struct
{
uint16_t offset_lowerbits;
uint16_t selector;
uint8_t zero;
uint8_t type_attr;
uint16_t offset_higherbits;
} IDT_entry;
IDT_entry IDT[256];
static inline void rempap_pic()
{
outb(0x20, 0x11);
outb(0xA0, 0x11);
outb(0x21, 0x20);
outb(0xA1, 40);
outb(0x21, 0x04);
outb(0xA1, 0x02);
outb(0x21, 0x01);
outb(0xA1, 0x01);
outb(0x21, 0x0);
outb(0xA1, 0x0);
}
static void exception0_handler()
{
print_serial("division by zero");
outb(0x20, 0x20); //EOI
}
static void exception1_handler()
{
print_serial("division by zero");
outb(0x20, 0x20); //EOI
}
static void exception2_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception3_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception4_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception5_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception6_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception7_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception8_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception9_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception10_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception11_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception12_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception13_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception14_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception15_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception16_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception17_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception18_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception19_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception20_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception21_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception22_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception23_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception24_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception25_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception26_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception27_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception28_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception29_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception30_handler()
{
outb(0x20, 0x20); //EOI
}
static void exception31_handler()
{
outb(0x20, 0x20); //EOI
}
static void irq0_handler()
{
outb(0x20, 0x20); //EOI
}
static void irq1_handler()
{
unsigned char scan_code = inb(0x60);
if (scan_code < 128)
{
char letter = kbd_US[scan_code];
if (letter != 0)
{
char string[2];
string[0] = letter;
string[1] = 0;
print(string);
}
}
outb(0x20, 0x20); //EOI
}
static void irq2_handler()
{
outb(0x20, 0x20); //EOI
}
static void irq3_handler()
{
outb(0x20, 0x20); //EOI
}
static void irq4_handler()
{
outb(0x20, 0x20); //EOI
}
static void irq5_handler()
{
outb(0x20, 0x20); //EOI
}
static void irq6_handler()
{
outb(0x20, 0x20); //EOI
}
static void irq7_handler()
{
outb(0x20, 0x20); //EOI
}
static void irq8_handler()
{
outb(0xA0, 0x20);
outb(0x20, 0x20); //EOI
}
static void irq9_handler()
{
outb(0xA0, 0x20);
outb(0x20, 0x20); //EOI
}
static void irq10_handler()
{
outb(0xA0, 0x20);
outb(0x20, 0x20); //EOI
}
static void irq11_handler()
{
outb(0xA0, 0x20);
outb(0x20, 0x20); //EOI
}
static void irq12_handler()
{
outb(0xA0, 0x20);
outb(0x20, 0x20); //EOI
}
static void irq13_handler()
{
outb(0xA0, 0x20);
outb(0x20, 0x20); //EOI
}
static void irq14_handler()
{
outb(0xA0, 0x20);
outb(0x20, 0x20); //EOI
}
static void irq15_handler()
{
outb(0xA0, 0x20);
outb(0x20, 0x20); //EOI
}
static inline void lidt(void *base, uint16_t size)
{ // This function works in 32 and 64bit mode
struct
{
uint16_t length;
void *base;
} __attribute__((packed)) IDTR = {size, base};
asm("lidt %0"
:
: "m"(IDTR));
}
typedef struct interrupt_frame interrupt_frame_t;
#define DEFINE_IRQ_HANDLER(irq_idx) \
__attribute__((interrupt)) void irq##irq_idx(__attribute__((unused)) interrupt_frame_t *frame) \
{ \
irq##irq_idx##_handler(); \
}
#define DEFINE_EXCEPTION_HANDLER(exception_idx) \
__attribute__((interrupt)) void exception##exception_idx(__attribute__((unused)) interrupt_frame_t *frame) \
{ \
exception##exception_idx##_handler(); \
}
static void bind_irq(uint8_t irq, irq_handler_t irq_handler)
{
irq_handler_u irq_address;
irq_address.irq_handler = irq_handler;
uint8_t idx = irq + 32;
IDT[idx].offset_lowerbits = irq_address.u16[1];
IDT[idx].selector = GDT_SELECTOR;
IDT[idx].zero = 0;
IDT[idx].type_attr = INTERRUPT_GATE;
IDT[idx].offset_lowerbits = irq_address.u16[0];
}
static void bind_exception(uint8_t exception, irq_handler_t exception_handler)
{
irq_handler_u irq_address;
irq_address.irq_handler = exception_handler;
uint8_t idx = exception;
IDT[idx].offset_lowerbits = irq_address.u16[1];
IDT[idx].selector = GDT_SELECTOR;
IDT[idx].zero = 0;
IDT[idx].type_attr = INTERRUPT_GATE;
IDT[idx].offset_lowerbits = irq_address.u16[0];
}
#define BIND_IRQ(irq_idx) \
bind_irq(irq_idx, irq##irq_idx);
#define BIND_EXCEPTION(exception_idx) \
bind_exception(exception_idx, exception##exception_idx);
DEFINE_IRQ_HANDLER(0)
DEFINE_IRQ_HANDLER(1)
DEFINE_IRQ_HANDLER(2)
DEFINE_IRQ_HANDLER(3)
DEFINE_IRQ_HANDLER(4)
DEFINE_IRQ_HANDLER(5)
DEFINE_IRQ_HANDLER(6)
DEFINE_IRQ_HANDLER(7)
DEFINE_IRQ_HANDLER(8)
DEFINE_IRQ_HANDLER(9)
DEFINE_IRQ_HANDLER(10)
DEFINE_IRQ_HANDLER(11)
DEFINE_IRQ_HANDLER(12)
DEFINE_IRQ_HANDLER(13)
DEFINE_IRQ_HANDLER(14)
DEFINE_IRQ_HANDLER(15)
DEFINE_EXCEPTION_HANDLER(0)
DEFINE_EXCEPTION_HANDLER(1)
DEFINE_EXCEPTION_HANDLER(2)
DEFINE_EXCEPTION_HANDLER(3)
DEFINE_EXCEPTION_HANDLER(4)
DEFINE_EXCEPTION_HANDLER(5)
DEFINE_EXCEPTION_HANDLER(6)
DEFINE_EXCEPTION_HANDLER(7)
DEFINE_EXCEPTION_HANDLER(8)
DEFINE_EXCEPTION_HANDLER(9)
DEFINE_EXCEPTION_HANDLER(10)
DEFINE_EXCEPTION_HANDLER(11)
DEFINE_EXCEPTION_HANDLER(12)
DEFINE_EXCEPTION_HANDLER(13)
DEFINE_EXCEPTION_HANDLER(14)
DEFINE_EXCEPTION_HANDLER(15)
DEFINE_EXCEPTION_HANDLER(16)
DEFINE_EXCEPTION_HANDLER(17)
DEFINE_EXCEPTION_HANDLER(18)
DEFINE_EXCEPTION_HANDLER(19)
DEFINE_EXCEPTION_HANDLER(20)
DEFINE_EXCEPTION_HANDLER(21)
DEFINE_EXCEPTION_HANDLER(22)
DEFINE_EXCEPTION_HANDLER(23)
DEFINE_EXCEPTION_HANDLER(24)
DEFINE_EXCEPTION_HANDLER(25)
DEFINE_EXCEPTION_HANDLER(26)
DEFINE_EXCEPTION_HANDLER(27)
DEFINE_EXCEPTION_HANDLER(28)
DEFINE_EXCEPTION_HANDLER(29)
DEFINE_EXCEPTION_HANDLER(30)
DEFINE_EXCEPTION_HANDLER(31)
void init_idt()
{
rempap_pic();
BIND_EXCEPTION(0)
BIND_EXCEPTION(1)
BIND_EXCEPTION(2)
BIND_EXCEPTION(3)
BIND_EXCEPTION(4)
BIND_EXCEPTION(5)
BIND_EXCEPTION(6)
BIND_EXCEPTION(7)
BIND_EXCEPTION(8)
BIND_EXCEPTION(9)
BIND_EXCEPTION(10)
BIND_EXCEPTION(11)
BIND_EXCEPTION(12)
BIND_EXCEPTION(13)
BIND_EXCEPTION(14)
BIND_EXCEPTION(15)
BIND_EXCEPTION(16)
BIND_EXCEPTION(17)
BIND_EXCEPTION(18)
BIND_EXCEPTION(19)
BIND_EXCEPTION(20)
BIND_EXCEPTION(21)
BIND_EXCEPTION(22)
BIND_EXCEPTION(23)
BIND_EXCEPTION(24)
BIND_EXCEPTION(25)
BIND_EXCEPTION(26)
BIND_EXCEPTION(27)
BIND_EXCEPTION(28)
BIND_EXCEPTION(29)
BIND_EXCEPTION(30)
BIND_EXCEPTION(31)
BIND_IRQ(0)
BIND_IRQ(1)
BIND_IRQ(2)
BIND_IRQ(3)
BIND_IRQ(4)
BIND_IRQ(5)
BIND_IRQ(6)
BIND_IRQ(7)
BIND_IRQ(8)
BIND_IRQ(9)
BIND_IRQ(10)
BIND_IRQ(11)
BIND_IRQ(12)
BIND_IRQ(13)
BIND_IRQ(14)
BIND_IRQ(15)
lidt(
IDT,
sizeof(IDT));
asm("sti");
print_serial("idt iniitalized\n");
}
<file_sep>#include "paging.h"
#include <stdint.h>
uint32_t page_directory[1024] __attribute__((aligned(4096)));
void init_paging()
{
for (int i = 0; i < 1024; i++)
{
// This sets the following flags to the pages:
// Supervisor: Only kernel-mode can access them
// Write Enabled: It can be both read from and written to
// Not Present: The page table is not present
page_directory[i] = 0x00000002;
}
}
<file_sep>#pragma once
void init_serial();
void write_serial(char a);
void print_serial(char *a);
<file_sep>OSNAME=noOS
SRC_DIR=src
BOOT_SOURCES=$(wildcard ${SRC_DIR}/boot/*.asm)
AS=nasm
CC=i386-elf-gcc
AR=i386-elf-ar
LD=i386-elf-ld
ASFLAGS=-f elf32
MKDIR_P=mkdir -p
OUT_DIR=bin
ROOTFS_DIR =${OUT_DIR}/rootfs
ROOTFS_FILE=rootfs.dmg
RAWROOTFS_FILE=rootfs.raw
OS_IMAGE_FILE=os.img
CFLAGS=-std=gnu99 -ffreestanding -O2 -Wall -Wextra -nostdlib -pedantic -Werror -lgcc -D OSNAME="\"${OSNAME}\"" -masm=intel
KERNEL_SRC_DIR=${SRC_DIR}/kernel
DEPS=$(wildcard ${KERNEL_SRC_DIR}/*.h)
_OBJ=kernel.o serial.o utils.o tty.o idt.o paging.o
OBJ = $(patsubst %,$(OUT_DIR)/%,$(_OBJ))
BOOT_SRC_DIR=${SRC_DIR}/boot
BOOT_ASM_FILE=${BOOT_SRC_DIR}/boot.asm
LOG_DIR=log
SERIAL_LOG_FILE=${LOG_DIR}/serial.log
.PHONY: all clean run-bochs run-qemu directories
all: ${OUT_DIR}/${OS_IMAGE_FILE} ${OUT_DIR}/${ROOTFS_FILE}
${OUT_DIR}:
${MKDIR_P} ${OUT_DIR}
${ROOTFS_DIR}:
${MKDIR_P} ${ROOTFS_DIR}
${OUT_DIR}/%.o: ${KERNEL_SRC_DIR}/%.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS)
${OUT_DIR}/boot_main.o: $(BOOT_SOURCES) ${OUT_DIR}
$(AS) $(ASFLAGS) ${BOOT_ASM_FILE} -o $@
${OUT_DIR}/boot_memory.o: ${OUT_DIR} src/shared/memory_map.c
${CC} -m16 -c -o $@ $(CFLAGS) src/shared/memory_map.c
${OUT_DIR}/boot.a: ${OUT_DIR} ${OUT_DIR}/boot_main.o ${OUT_DIR}/boot_memory.o
$(AR) cr $@ ${OUT_DIR}/boot_main.o ${OUT_DIR}/boot_memory.o
run-qemu: ${OUT_DIR}/${OS_IMAGE_FILE} ${OUT_DIR}/${RAWROOTFS_FILE}
qemu-system-x86_64 \
-m 128M \
-drive format=raw,file=${OUT_DIR}/${OS_IMAGE_FILE} \
-chardev stdio,id=char0,mux=on,logfile=${SERIAL_LOG_FILE},signal=off \
-serial chardev:char0
${OUT_DIR}/idt.o : CFLAGS+=-mgeneral-regs-only
run-bochs: ${OUT_DIR}/${OS_IMAGE_FILE}
bochs -q
${OUT_DIR}/os.bin: ${OUT_DIR}/boot.a ${OBJ} linker.ld
${CC} -T linker.ld -o $@ $(CFLAGS) ${OUT_DIR}/boot.a ${OBJ}
${OUT_DIR}/${ROOTFS_FILE}: ${ROOTFS_DIR}
hdiutil create $@ -ov -volname "rootfs" -fs FAT32 -srcfolder ${OUT_DIR}/rootfs
${OUT_DIR}/${RAWROOTFS_FILE}: ${OUT_DIR}/${ROOTFS_FILE}
qemu-img convert $< $@
bin/${OS_IMAGE_FILE}: bin/os.bin
dd bs=512 count=2880 if=/dev/zero of=$@
dd if=$< of=$@ conv=notrunc
clean:
rm -rf bin/*
<file_sep>#include <stdint.h>
#include "memory_map.h"
extern SMAP_entry_t memory_map_start;
extern SMAP_entry_t memory_map_end;
extern uint32_t memory_map_entries_count;
void read_memory_map()
{
SMAP_entry_t *buffer = &memory_map_start;
int smap_size = (int)&memory_map_end - (int)&memory_map_start;
int maxentries = smap_size / sizeof(SMAP_entry_t);
int contID = 0;
int entries = 0, signature, bytes;
do
{
__asm__ __volatile__("int 0x15"
: "=a"(signature), "=c"(bytes), "=b"(contID)
: "a"(0xE820), "b"(contID), "c"(24), "d"(0x534D4150), "D"(buffer));
if (signature != 0x534D4150)
asm("hlt");
if (bytes > 20 && (buffer->ACPI & 0x0001) == 0)
continue;
buffer++;
entries++;
} while (contID != 0 && entries < maxentries);
memory_map_entries_count = entries;
}
| 66a24010790d30f59aca66fdf11d04e1280aeee8 | [
"C",
"Makefile"
] | 10 | C | jarkonik/fun | 50d972478095cf96e54c31f3bc5125e9c7a5c3ad | a47806c125a75de30716840c379daaa1f0350261 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.