branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>import React from "react";
const Home = () => {
return (
<div className="container text-center my-5 w-75">
<h1 className="display-4 text-black-50">HOME</h1>
<h3 className="mt-4 text-black-50">
When starting a React project, a simple HTML page with script tags might
still be the best option. It only takes a minute to set up! As your
application grows, you might want to consider a more integrated setup.
There are several JavaScript toolchains we recommend for larger
applications. Each of them can work with little to no configuration and
lets you take full advantage of the rich React ecosystem.
</h3>
</div>
);
};
export default Home;
<file_sep>import axios from "axios";
import React,{ useState } from "react";
import { Link,Route,Switch } from "react-router-dom";
import ReactModal from "react-modal";
import FrontEnd from "./Dashboard Components/FrontEnd";
import FullStack from "./Dashboard Components/FullStack";
import MeanStack from "./Dashboard Components/MeanStack";
import Node from "./Dashboard Components/Node";
import ModalComponent from "./Dashboard Components/ModalComponent";
const Dashboard = () => {
const [data,setData] = useState([]);
const [result,setResult] = useState({});
const [updateStatus,setUpdateStatus] = useState({});
const [isOpen,setIsOpen] = useState(false);
const CustomStyle = {
content: {
top: "50%",
left: "50%",
right: "auto",
bottom: "auto",
marginRight: "-50%",
transform: "translate(-50%, -50%)",
backgroundColor: "white",
},
};
axios
.get("http://dct-application-form.herokuapp.com/users/application-forms")
.then((resp) => {
const result = resp.data;
setData(result);
})
.catch((err) => {
alert(err.message);
});
const handleClick = (_id) => {
axios
.get(
`http://dct-application-form.herokuapp.com/users/application-form/${_id}`
)
.then((resp) => {
const res = resp.data;
setResult(res);
})
.catch((err) => {
alert(err.message);
});
setIsOpen(true);
};
const handleClose = () => {
setIsOpen(false);
};
const handleChange1 = (_id) => {
const input = {
status: "rejected",
};
axios
.put(
`http://dct-application-form.herokuapp.com/users/application-form/update/${_id}`,
input
)
.then((resp) => {
const res1 = resp.data;
setUpdateStatus(res1);
})
.catch((err) => {
alert(err.message);
});
};
const handleChange2 = (_id) => {
const input = {
status: "shortlisted",
};
axios
.put(
`http://dct-application-form.herokuapp.com/users/application-form/update/${_id}`,
input
)
.then((resp) => {
const res1 = resp.data;
setUpdateStatus(res1);
})
.catch((err) => {
alert(err.message);
});
};
return (
<>
<div className="container mt-5" style={{ display: "flex",flexWrap: "wrap",justifyContent: "space-between",alignItems: "center" }}>
<Link to="/dashboard/frontend" className="btn btn-lg btn-primary">
FrontEnd Developer
</Link>
<Link to="/dashboard/nodejs" className="btn btn-lg btn-primary">
Node.js Developer
</Link>
<Link to="/dashboard/meanstack" className="btn btn-lg btn-primary">
Mean Stack Developer
</Link>
<Link to="/dashboard/fullstack" className="btn btn-lg btn-primary">
Full Stack Developer
</Link>
</div>
<Switch>
<Route
path="/dashboard/fullstack"
render={(props) => {
return (
<FullStack
{...props}
data={data}
handleClick={handleClick}
handleChange1={handleChange1}
handleChange2={handleChange2}
/>
);
}}
/>
<Route
path="/dashboard/meanstack"
render={(props) => {
return (
<MeanStack
{...props}
data={data}
handleClick={handleClick}
handleChange1={handleChange1}
handleChange2={handleChange2}
/>
);
}}
/>
<Route
path="/dashboard/nodejs"
render={(props) => {
return (
<Node
{...props}
data={data}
handleClick={handleClick}
handleChange1={handleChange1}
handleChange2={handleChange2}
/>
);
}}
/>
<Route
path="/dashboard/frontend"
render={(props) => {
return (
<FrontEnd
{...props}
data={data}
status={updateStatus}
handleClick={handleClick}
handleChange1={handleChange1}
handleChange2={handleChange2}
/>
);
}}
/>
</Switch>
<ReactModal
isOpen={isOpen}
style={CustomStyle}
onRequestClose={handleClose}
>
<ModalComponent result={result} />
</ReactModal>
</>
);
};
export default Dashboard;
<file_sep>import axios from 'axios';
import React, { useState } from 'react';
const Register = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [jobTitle, setJobTitle] = useState('');
const [experience, setExperiance] = useState('');
const [skills, setSkils] = useState('');
const handleChange = (e) => {
if (e.target.name === 'FullName') {
setName(e.target.value);
} else if (e.target.name === 'Email') {
setEmail(e.target.value);
} else if (e.target.name === 'contact') {
setPhone(e.target.value);
} else if (e.target.name === 'Select') {
setJobTitle(e.target.value);
} else if (e.target.name === 'Experiance') {
setExperiance(e.target.value);
} else if (e.target.name === 'Skills') {
setSkils(e.target.value);
}
};
const handleSubmit = (e) => {
e.preventDefault();
const formData = {
name: name,
email: email,
phone: phone,
skills: skills,
jobTitle: jobTitle,
experience: experience,
};
axios
.post(
'http://dct-application-form.herokuapp.com/users/application-form',
formData,
)
.then((response) => {
const result = response.data;
console.log(result);
})
.catch((err) => {
alert(err.message);
});
};
return (
<div className="container w-50">
<h1 className="display-3 text-center my-5">Registration Form</h1>
<form onSubmit={handleSubmit}>
<div className="row mb-4">
<label className="form-label" htmlFor="FullName">
FullName
</label>
<div className="col-12">
<input
className="form-control"
type="text"
name="FullName"
id="FullName"
value={name}
onChange={handleChange}
placeholder="Enter your FullName"
required
/>
</div>
</div>
<div className="row mb-4">
<label className="form-label" htmlFor="Email">
Email
</label>
<div className="col-12">
<input
className="form-control"
type="email"
name="Email"
id="Email"
value={email}
onChange={handleChange}
placeholder="<EMAIL>"
required
/>
</div>
</div>
<div className="row mb-4">
<label className="form-label">Contact Number</label>
<div className="col-12">
<input
className="form-control"
type="tel"
pattern="[0-9]{10}"
name="contact"
value={phone}
onChange={handleChange}
placeholder="+91-9876543210"
required
/>
</div>
</div>
<div className="row mb-4">
<label className="form-label">Appling for Job</label>
<div className="col-12">
<select
className="form-select"
aria-label=".form-select-lg example"
name="Select"
value={jobTitle}
onChange={handleChange}
required
>
<option>Front-End Developer</option>
<option>Node.js Developer</option>
<option>MEAN Stack Developer</option>
<option>FULL Stack Developer</option>
</select>
</div>
</div>
<div className="row mb-4">
<label className="form-label">Experience</label>
<div className="col-12">
<input
className="form-control"
type="text"
name="Experiance"
value={experience}
onChange={handleChange}
placeholder="Experiance(2years,3months)"
required
/>
</div>
</div>
<div className="row mb-4">
<label className="form-label">Technical Skils</label>
<div className="col-12">
<input
type="textarea"
className="form-control"
name="Skills"
value={skills}
onChange={handleChange}
placeholder="Technical Skils"
required
/>
</div>
</div>
<div className="col-12">
<input
className="btn btn-primary mb-4"
type="submit"
value="Send Application"
/>
</div>
</form>
</div>
);
};
export default Register;
| b0a10a19a6eede03b43b74b4ddfc302bd527c152 | [
"JavaScript"
] | 3 | JavaScript | bibhu-3214/Job-App-for-user | bcc63ca40e4b7a60f99197b263e736cd15aefea0 | 26a3b38e05bf1f6305afd57cbe87c180c472a61f |
refs/heads/master | <repo_name>jaydesl/TOSCAKubed<file_sep>/toscakubed.py
import os
import subprocess
import logging
import shutil
import filecmp
import time
from toscaparser.tosca_template import ToscaTemplate
import utils
logger = logging.getLogger("adaptors." + __name__)
TOSCA_TYPES = (
DOCKER_CONTAINER,
CONTAINER_VOLUME,
VOLUME_ATTACHMENT,
KUBERNETES_INTERFACE,
) = (
"tosca.nodes.MiCADO.Container.Application.Docker",
"tosca.nodes.MiCADO.Container.Volume",
"tosca.relationships.AttachesTo",
"Kubernetes",
)
SUPPORTED_WORKLOADS = ("Pod", "Job", "Deployment", "StatefulSet", "DaemonSet")
SWARM_PROPERTIES = ["expose"]
POD_SPEC_FIELDS = (
"activeDeadlineSeconds",
"affinity",
"automountServiceAccountToken",
"dnsConfig",
"dnsPolicy",
"enableServiceLinks",
"hostAliases",
"hostIPC",
"hostNetwork",
"hostPID",
"hostname",
"imagePullSecrets",
"initContainers",
"nodeName",
"nodeSelector",
"priority",
"priorityClassName",
"readinessGates",
"restartPolicy",
"runtimeClassName",
"schedulerName",
"securityContext",
"serviceAccount",
"serviceAccountName",
"shareProcessNamespace",
"subdomain",
"terminationGracePeriodSeconds",
"tolerations",
"volumes",
)
class KubernetesAdaptor:
""" The Kubernetes Adaptor class
Carry out a translation from a TOSCA ADT to a Kubernetes Manifest
"""
def __init__(self, application_id, template):
""" init method of the Adaptor """
super().__init__()
logger.debug("Initialising Kubernetes Adaptor class...")
self.status = "Initialising..."
self.tpl = ToscaTemplate(template)
self.short_id = application_id
self.manifest_path = "{}.yaml".format(self.short_id)
self.manifests = []
self.services = []
self.volumes = {}
self.output = {}
logger.info("Kubernetes Adaptor is ready.")
self.status = "Initialised"
def translate(self):
""" Translate the relevant sections of the ADT into a Kubernetes Manifest """
logger.info("Translating into Kubernetes Manifests")
self.status = "Translating..."
nodes = self.tpl.nodetemplates
repositories = self.tpl.repositories
for node in sorted(nodes, key=lambda x: x.type, reverse=True):
interface = {}
kube_interface = [
x for x in node.interfaces if KUBERNETES_INTERFACE in x.type
]
for operation in kube_interface:
interface[operation.name] = operation.inputs or {}
if DOCKER_CONTAINER in node.type and interface:
if "_" in node.name:
logger.error(
"ERROR: Use of underscores in {} workload name prohibited".format(
node.name
)
)
raise ValueError(
"ERROR: Use of underscores in {} workload name prohibited".format(
node.name
)
)
self._create_manifests(node, interface, repositories)
elif CONTAINER_VOLUME in node.type and interface:
name = node.get_property_value("name") or node.name
if "_" in name:
logger.error(
"ERROR: Use of underscores in {} volume name prohibited".format(
name
)
)
raise ValueError(
"ERROR: Use of underscores in {} volume name prohibited".format(
name
)
)
size = node.get_property_value("size") or "1Gi"
pv_inputs = interface.get("create", {})
labels = self._create_persistent_volume(name, pv_inputs, size)
pvc_inputs = interface.get("configure", {})
pvc_name = self._create_persistent_volume_claim(
name, pvc_inputs, labels, size
)
self.volumes.setdefault(node.name, pvc_name)
if not self.manifests:
logger.info("No nodes to orchestrate with Kubernetes")
self.status = "Skipped Translation"
return
utils.dump_list_yaml(self.manifests, self.manifest_path)
logger.info("Translation complete")
self.status = "Translated"
def cleanup(self):
""" Cleanup """
logger.info("Cleaning-up...")
self.status = "Cleaning-up..."
try:
os.remove(self.manifest_path)
except OSError:
logger.warning("Could not remove manifest file")
self.status = "Clean!"
def _create_manifests(self, node, interface, repositories):
""" Create the manifest from the given node """
workload_inputs = interface.get("create", {})
pod_inputs = interface.get("configure", {})
properties = {key: val.value for key, val in node.get_properties().items()}
resource = self._get_resource(node.name, workload_inputs)
kind = resource.get("kind")
if kind not in SUPPORTED_WORKLOADS:
logger.warning(
"Kubernetes *kind: {}* is unsupported - no manifest created".format(
kind
)
)
return
resource_metadata = resource.get("metadata", {})
resource_namespace = resource_metadata.get("namespace")
# Get container spec
container = _get_container(node, properties, repositories, pod_inputs)
# Get service spec
self._get_service_manifests(node, container, resource, pod_inputs)
# Get and set volume info
volumes, volume_mounts = self._get_volumes(node)
if volumes:
vol_list = pod_inputs.setdefault("volumes", [])
vol_list += volumes
if volume_mounts:
vol_list = properties.setdefault("volumeMounts", [])
vol_list += volume_mounts
# Get pod metadata from container or resource
pod_metadata = pod_inputs.pop("metadata", {})
pod_metadata.setdefault("labels", {"run": node.name})
pod_labels = pod_metadata.get("labels")
pod_metadata.setdefault("namespace", resource_namespace)
# Separate data for pod.spec
pod_data = _separate_data(POD_SPEC_FIELDS, workload_inputs)
pod_inputs.update(pod_data)
# Cleanup metadata and spec inputs
pod_metadata = {key: val for key, val in pod_metadata.items() if val}
pod_inputs = {key: val for key, val in pod_inputs.items() if val}
# Set pod spec and selector
pod_spec = {"containers": [container], **pod_inputs}
selector = {"matchLabels": pod_labels}
# Set template & pod spec
if kind == "Pod":
spec = {"containers": [container], **workload_inputs}
elif kind == "Job":
template = {"spec": pod_spec}
spec = {"template": template, **workload_inputs}
else:
template = {"metadata": pod_metadata, "spec": pod_spec}
spec = {"selector": selector, "template": template, **workload_inputs}
# Build manifests
resource.setdefault("spec", spec)
self.manifests.append(resource)
return
def _get_service_manifests(self, node, container, resource, inputs):
""" Build a service based on the provided port spec and template """
# Find ports/clusterIP for service creation
ports = _get_service_info(container, node.name)
services_to_build = {}
service_types = ["clusterip", "nodeport", "LoadBalancer", "ExternalIP"]
for port in ports:
metadata = port.pop("metadata", {})
service_name = metadata.get("name")
port_type = port.pop("type", None)
cluster_ip = port.pop("clusterIP", None)
if not service_name:
service_name = "{}-{}".format(node.name, port_type.lower())
service_entry = services_to_build.setdefault(service_name, {})
service_entry.setdefault("type", port_type)
service_entry.setdefault("metadata", metadata)
service_entry.setdefault("clusterIP", cluster_ip)
service_entry.setdefault("ports", []).append(port)
if node.name not in services_to_build.keys():
for s_type in service_types:
entry = services_to_build.pop("{}-{}".format(node.name, s_type), None)
if entry:
services_to_build.setdefault(node.name, entry)
break
for name, service in services_to_build.items():
manifest, service_info = _build_service(
name, service, resource, node.name, inputs
)
if not manifest:
continue
self.manifests.append(manifest)
self.services.append(service_info)
def _get_volumes(self, container_node):
""" Return the volume spec for the workload """
related = container_node.related_nodes
requirements = container_node.requirements
volumes = []
volume_mounts = []
for node in related:
volume_mount_list = []
pvc_name = self.volumes.get(node.name)
if pvc_name:
pvc = {"claimName": pvc_name}
volume_spec = {"name": node.name, "persistentVolumeClaim": pvc}
else:
continue
for requirement in requirements:
volume = requirement.get("volume", {})
relationship = volume.get("relationship", {}).get("type")
path = (
volume.get("relationship", {}).get("properties", {}).get("location")
)
if path and relationship == VOLUME_ATTACHMENT:
if volume.get("node") == node.name:
volume_mount_spec = {"name": node.name, "mountPath": path}
volume_mount_list.append(volume_mount_spec)
if volume_mount_list:
volumes.append(volume_spec)
volume_mounts += volume_mount_list
return volumes, volume_mounts
def _create_persistent_volume(self, name, inputs, size):
""" Create a PV """
name = inputs.get("metadata", {}).get(
"name", inputs.get("name")
) or "{}-pv".format(name)
inputs.setdefault("metadata", {}).setdefault("labels", {}).setdefault(
"volume", name
)
manifest = self._get_resource(name, inputs, "PersistentVolume")
manifest.setdefault("spec", inputs)
labels = manifest.get("metadata", {}).get("labels", {})
spec = manifest.get("spec")
spec.setdefault("capacity", {}).setdefault("storage", size)
spec.setdefault("accessModes", []).append("ReadWriteMany")
spec.setdefault("persistentVolumeReclaimPolicy", "Retain")
self.manifests.append(manifest)
return labels
def _create_persistent_volume_claim(self, name, inputs, labels, size):
""" Create a PVC """
name = inputs.get("metadata", {}).get(
"name", inputs.get("name")
) or "{}-pvc".format(name)
inputs.setdefault("metadata", {}).setdefault("labels", {}).setdefault(
"volume", name
)
manifest = self._get_resource(name, inputs, "PersistentVolumeClaim")
manifest.setdefault("spec", inputs)
spec = manifest.get("spec")
spec.setdefault("resources", {}).setdefault("requests", {}).setdefault(
"storage", size
)
spec.setdefault("accessModes", []).append("ReadWriteMany")
spec.setdefault("selector", {}).setdefault("matchLabels", labels)
self.manifests.append(manifest)
return name
def _get_resource(self, name, inputs, kind="Deployment"):
""" Build and return the basic data for the workload """
# kind and apiVersion
kind = inputs.pop("kind", kind)
api_version = inputs.pop("apiVersion", _get_api(kind))
# metadata
metadata = inputs.pop("metadata", {})
metadata.setdefault("name", inputs.pop("name", name))
metadata.setdefault("labels", inputs.pop("labels", {}))
metadata.setdefault("labels", {}).setdefault("app", self.short_id)
resource = {"apiVersion": api_version, "kind": kind, "metadata": metadata}
return resource
def _get_api(kind):
""" Return the apiVersion according to kind """
# supported workloads & their api versions
api_versions = {
"DaemonSet": "apps/v1",
"Deployment": "apps/v1",
"Job": "batch/v1",
"Pod": "v1",
"ReplicaSet": "apps/v1",
"StatefulSet": "apps/v1",
"Ingress": "extensions/v1beta1",
"Service": "v1",
"PersistentVolume": "v1",
"PersistentVolumeClaim": "v1",
"Volume": "v1",
"Namespace": "v1",
}
for resource, api in api_versions.items():
if kind.lower() == resource.lower():
return api
logger.warning("Unknown kind: {}. Not supported...".format(kind))
return "unknown"
def _build_service(service_name, service, resource, node_name, inputs):
""" Build service and return a manifest """
# Check for ports
ports = service.get("ports")
if not ports:
logger.warning(
"No ports in service {}. Will not be created".format(service_name)
)
return None, None
# Get resource metadata
metadata = resource.get("metadata", {})
resource_namespace = metadata.get("namespace")
resource_labels = metadata.get("labels")
# Get container metadata
metadata = inputs.get("metadata", {})
pod_labels = metadata.get("labels", {"run": node_name})
# Set service metadata
metadata = service.get("metadata", {})
metadata.setdefault("name", service_name)
metadata.setdefault("namespace", resource_namespace)
metadata.setdefault("labels", resource_labels)
# Set service info for outputs
namespace = metadata.get("namespace") or "default"
service_info = {"node": node_name, "name": service_name, "namespace": namespace}
# Cleanup metadata
metadata = {key: val for key, val in metadata.items() if val}
# Set type, clusterIP, ports
port_type = service.get("type")
cluster_ip = service.get("clusterIP")
spec_ports = []
for port in ports:
spec_ports.append(port)
# Set spec
spec = {"ports": spec_ports, "selector": pod_labels}
if port_type != "ClusterIP":
spec.setdefault("type", port_type)
if cluster_ip:
spec.setdefault("clusterIP", cluster_ip)
manifest = {
"apiVersion": "v1",
"kind": "Service",
"metadata": metadata,
"spec": spec,
}
return manifest, service_info
def _get_container(node, properties, repositories, inputs):
""" Return container spec """
# Get image
image = _get_image(node.entity_tpl, repositories)
if not image:
raise ValueError("No image specified for {}!".format(node.name))
properties.setdefault("image", image)
# Remove any known swarm-only keys
for key in SWARM_PROPERTIES:
if properties.pop(key, None):
logger.warning("Removed Swarm-option {}".format(key))
# Translate common properties
properties.setdefault("name", properties.pop("container_name", node.name))
properties.setdefault("command", properties.pop("entrypoint", "").split())
properties.setdefault("args", properties.pop("cmd", "").split())
docker_env = properties.pop("environment", {})
env = []
for key, value in docker_env:
env.append({"name": key, "value": value})
properties.setdefault("env", env)
# Translate other properties
docker_labels = properties.pop("labels", None)
if docker_labels:
inputs.setdefault("metadata", {}).setdefault("labels", {}).update(docker_labels)
docker_grace = properties.pop("stop_grace_period", None)
if docker_grace:
inputs.setdefault("terminationGracePeriodSeconds", docker_grace)
docker_priv = properties.pop("privileged", None)
if docker_priv:
properties.setdefault("securityContext", {}).setdefault(
"privileged", docker_priv
)
docker_pid = properties.pop("pid", None)
if docker_pid == "host":
inputs.setdefault("hostPID", True)
docker_netmode = properties.pop("network_mode", None)
if docker_netmode == "host":
inputs.setdefault("hostNetwork", True)
properties.setdefault("stdin", properties.pop("stdin_open", None))
properties.setdefault("livenessProbe", properties.pop("healthcheck", None))
return {key: val for key, val in properties.items() if val}
def _separate_data(key_names, container):
""" Separate workload specific data from the container spec """
data = {}
for x in key_names:
try:
data[x] = container.pop(x)
except KeyError:
pass
return data
def _get_image(node, repositories):
""" Return the full path to the Docker container image """
details = node.get("artifacts", {}).get("image", {})
image = details.get("file")
repo = details.get("repository")
if not image or not repo or not repositories:
logger.warning(
"Missing top-level repository or file/repository in artifact - no image!"
)
return ""
if repo.lower().replace(" ", "").replace("-", "").replace("_", "") != "dockerhub":
path = [x.reposit for x in repositories if x.name == repo]
if path:
image = "/".join([path[0].strip("/"), image])
return image
def _get_service_info(container, node_name):
""" Return the info for creating a service """
port_list = []
ports = container.pop("ports", None)
if ports:
for port in ports:
container_port = port.get("containerPort")
if container_port:
container.setdefault("ports", []).append(port)
continue
port_spec = _build_port_spec(port, node_name)
if port_spec:
port_list.append(port_spec)
return port_list
def _build_port_spec(port, node_name):
""" Return port spec """
# Check if we have a port
target = port.get("targetPort", port.get("target"))
publish = int(port.get("port", port.get("published", target)))
if not publish and not target:
logger.warning("No port in ports of {}".format(node_name))
return
if isinstance(target, str) and target.isdigit():
target = int(target)
# Check for a clusterIP
cluster_ip = port.get("clusterIP")
if cluster_ip:
ip_split = cluster_ip.split(".")
# Check if the ip is within range (kind of)
if ip_split[0] == "10" and 96 <= int(ip_split[1]) <= 111:
cluster_ip = cluster_ip
elif ip_split[0] == "None":
cluster_ip = "None"
else:
logger.warning(
"ClusterIP out of range 10.96.x.x - 10.111.x.x Kubernetes will assign one"
)
# Assign protocol, name, type, metadata
protocol = port.get("protocol", "TCP").upper()
name = port.get("name", "{}-{}".format(target, protocol.lower()))
port_type = port.get("type", port.get("mode"))
metadata = port.get("metadata")
# Assign node port if valid
node_port = port.get("nodePort")
if node_port:
port_type = port_type or "NodePort"
if 30000 > int(node_port) > 32767:
node_port = None
logger.warning(
"nodePort out of range 30000-32767... Kubernetes will assign one"
)
# Determine type if Swarm-style or empty
if port_type == "host":
port_type = "NodePort"
elif port_type == "ingress" or not port_type:
port_type = "ClusterIP"
# Build a port spec
port_spec = {
"name": name,
"targetPort": target,
"port": publish,
"protocol": protocol,
"type": port_type,
"nodePort": node_port,
"metadata": metadata,
"clusterIP": cluster_ip,
}
port_spec = {key: val for key, val in port_spec.items() if val}
return port_spec
<file_sep>/utils.py
import random
import string
import ruamel.yaml as yaml
from six.moves import urllib
import codecs
import logging
logger=logging.getLogger("submitter."+__name__)
class NoAliasRTDumper(yaml.RoundTripDumper):
""" Turn off aliases, preserve order """
def ignore_aliases(self, data):
return True
def dump_order_yaml(data, path):
""" Dump the dictionary to a yaml file """
with open(path, 'w') as file:
yaml.dump(data, file,
default_flow_style=False, Dumper=NoAliasRTDumper)
def dump_list_yaml(data, path):
""" Dump a list of dictionaries to a single yaml file """
with open(path, 'w') as file:
yaml.dump_all(data, file,
default_flow_style=False, Dumper=NoAliasRTDumper)
def get_yaml_data(path):
""" Retrieve the yaml dictionary form a yaml file and return it """
logger.debug("{}".format(path))
try:
f = urllib.request.urlopen(str(path))
except ValueError as exc:
logger.error("file is local: {}".format(exc))
f = codecs.open(path, encoding='utf-8', errors='strict')
return yaml.round_trip_load(f.read())
<file_sep>/README.md
# TOSCAKubed
## A TOSCA-ADT to Kubernetes-manifest Translation Tool
### Reference for the TOSCA type *tosca.nodes.MiCADO.Container.Application.Docker*
## Supported field names for Docker Container Properties
|Docker Runtime Option| 0.7.1 | 0.7.2 | Swarm Docker-Compose Name | Kubernetes Manifest (Pod.Spec.Container) Name | Mesos Marathon Name | TOSCA ADT Name |
|--|:--:|:--:|--|--|--|--|
| Container Run Command | :heavy_check_mark: | :heavy_check_mark: | entrypoint | command | args/cmd | *Swarm or Kube*|
| Container Arguments | :heavy_check_mark: | :heavy_check_mark: | command | args | args/cmd |*Swarm or Kube*|
| Container Name | :heavy_check_mark: | :heavy_check_mark: | container_name | name | id |*Swarm or Kube*|
| Environment Variables | :heavy_check_mark: | :heavy_check_mark: | environment *(map)* | env *(list)* | env *(map)* |*Swarm or Kube*|
| Ports| :heavy_check_mark: | :heavy_check_mark: | ports | Service.Spec.ports | portMappings | ports |
| Container Labels | :heavy_check_mark: | :heavy_check_mark: | labels | Pod.Spec.metadata.labels | labels |*any*|
| Healthcheck | :heavy_check_mark: | :heavy_check_mark: | healthcheck | livenessProbe | healthchecks | livenessProbe|
| Host Network| :x: | :heavy_check_mark: | network_mode | Pod.Spec.hostNetwork | networks.mode | *Swarm or Kube*|
| Host PID| :heavy_check_mark: | :heavy_check_mark: | pid | Pod.Spec.hostPID | parameters.pid | *Swarm or Kube*|
| Elevate privileges | :x: | :heavy_check_mark: | *not supported* (as of v18.09) | privileged | privileged | *Kube or Mesos* |
| Shutdown Grace Period | :heavy_check_mark: | :heavy_check_mark: | stop_grace_period | Pod.Spec. terminationGracePeriodSeconds |taskKillGracePeriodSeconds|*Swarm or Kube*|
| Allocate a TTY | :heavy_check_mark: | :heavy_check_mark: | tty | tty | parameters.tty | *Swarm or Kube*|
| Keep STDIN open | :heavy_check_mark: | :heavy_check_mark: | stdin_open | stdin | parameters.ineractive |*Swarm or Kube*|
## Supported field names for Kubernetes create interface inputs (Workload creation)
* [Deployment](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.13/#deployment-v1-apps)
* [DaemonSet](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.13/#daemonset-v1-apps)
* [StatefulSet (no volumeClaim functionality)](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.13/#statefulset-v1-apps)
* [Job](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.13/#job-v1-batch)
* [Pod](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.13/#pod-v1-core)
## Supported field names for Kubernetes configure interface inputs (Pod configuration)
* [template.Spec](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.13/#podspec-v1-core)
| 2ac1b80700dd9080e4d3ebc6013b2adb3da0c3a6 | [
"Markdown",
"Python"
] | 3 | Python | jaydesl/TOSCAKubed | 94750153ea4c0c4368a59bfe1e7afcd2979a7881 | 4e0a1ccba200e8e3c52b77fb1b7cac0d64831406 |
refs/heads/master | <repo_name>misakayao/ClipManager<file_sep>/app/src/main/java/com/raisnet/kotlindemo/adapter/ItemTouchHelperAdapter.kt
package com.raisnet.kotlindemo.adapter
/**
* Description :
* Copyright : Copyright (c) 2017
* Company : Raisecom
* Author : yxl
* Date : 2017-11-26 21:56
*/
interface ItemTouchHelperAdapter {
//数据交换
fun onItemMove(fromPosition: Int, toPosition: Int)
//数据删除
fun onItemDismiss(position: Int)
}
<file_sep>/app/src/main/java/com/raisnet/kotlindemo/MyApplication.kt
package com.raisnet.kotlindemo
import android.app.Application
import cn.bmob.v3.Bmob
import com.raisnet.kotlindemo.bean.DaoMaster
import com.raisnet.kotlindemo.bean.DaoSession
/**
* Description :
* Copyright : Copyright (c) 2017
* Company : Raisecom
* Author : yxl
* Date : 2017-12-26 14:15
*/
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
//配置数据库
setupDatabase()
//初始化后端云
Bmob.initialize(this, "de9f77d4be67b2be0f2dfca5c44c14f1")
}
private fun setupDatabase() {
//创建数据库
val helper = DaoMaster.DevOpenHelper(this, "clip.db", null)
//获取可写数据库
val db = helper.writableDatabase
//获取数据库对象
val daoMaster = DaoMaster(db)
//获取Dao对象管理者
newSession = daoMaster.newSession()
}
companion object {
var newSession: DaoSession? = null
fun getDaoInstance(): DaoSession {
return this.newSession!!
}
}
}<file_sep>/README.md
# ClipManager
## ClipManager 是一个用于管理Android手机剪切板的应用,使用Kotlin进行编码,使用GreenDao进行数据存储,Bomb后端云进行云备份与还原,没有账号系统,基于IMEI来识别用户
<file_sep>/app/src/main/java/com/raisnet/kotlindemo/adapter/ClipAdapter.kt
package com.raisnet.kotlindemo.adapter
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import com.raisnet.kotlindemo.R
import com.raisnet.kotlindemo.bean.ClipItem
import java.text.SimpleDateFormat
import java.util.*
/**
* Description :
* Copyright : Copyright (c) 2017
* Company : Raisecom
* Author : yxl
* Date : 2017-12-26 15:20
*/
class ClipAdapter(private val context: Context) : RecyclerView.Adapter<ClipAdapter.ClipHolder>(), ItemTouchHelperAdapter {
override fun onItemMove(fromPosition: Int, toPosition: Int) {
//交换位置
Collections.swap(data, fromPosition, toPosition)
notifyItemMoved(fromPosition, toPosition)
}
override fun onItemDismiss(position: Int) {
//移除数据
data.removeAt(position)
notifyItemRemoved(position)
}
fun restoreItem(position: Int, item: ClipItem) {
//撤销数据
data.add(position, item)
notifyItemInserted(position)
}
var clipboardManager: ClipboardManager? = null
var data = mutableListOf<ClipItem>()
set(value) {
field = value
notifyDataSetChanged()
println("${data.size} ${System.currentTimeMillis()}")
}
override fun getItemCount(): Int {
return data.size
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ClipHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_clip_history, parent, false)
clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
return ClipHolder(view)
}
override fun onBindViewHolder(holder: ClipHolder?, position: Int) {
val item = data[position]
holder?.tvContent?.text = if (item.content.length < 500) {
item.content
} else {
item.content.slice(0..500) + "..."
}
val sdf = SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINESE)
holder?.tvCreateTime?.text = sdf.format(Date(item.createTime))
holder?.itemView?.setOnClickListener({
/**
* 将文字信息放到剪贴板上
*/
val clipData = ClipData.newPlainText("text", item.content)
clipboardManager?.primaryClip = clipData
Toast.makeText(context, "已复制到剪切板", Toast.LENGTH_SHORT).show()
})
}
class ClipHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var tvContent = itemView.findViewById<TextView>(R.id.textView)!!
var tvCreateTime = itemView.findViewById<TextView>(R.id.tv_create_time)
}
}
<file_sep>/app/src/main/java/com/raisnet/kotlindemo/DaoSession.java
package com.raisnet.kotlindemo;
import java.util.Map;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;
import com.raisnet.kotlindemo.bean.ClipItem;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see org.greenrobot.greendao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig clipItemDaoConfig;
private final ClipItemDao clipItemDao;
public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
clipItemDaoConfig = daoConfigMap.get(ClipItemDao.class).clone();
clipItemDaoConfig.initIdentityScope(type);
clipItemDao = new ClipItemDao(clipItemDaoConfig, this);
registerDao(ClipItem.class, clipItemDao);
}
public void clear() {
clipItemDaoConfig.clearIdentityScope();
}
public ClipItemDao getClipItemDao() {
return clipItemDao;
}
}
<file_sep>/app/src/main/java/com/raisnet/kotlindemo/ClipService.kt
package com.raisnet.kotlindemo
import android.app.*
import android.content.ClipboardManager
import android.content.ContentValues.TAG
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.support.v4.app.NotificationCompat
import android.util.Log
import android.widget.Toast
import com.raisnet.kotlindemo.bean.ClipItem
import com.raisnet.kotlindemo.bean.ClipItemDao
import com.raisnet.kotlindemo.utils.LogUtils
/**
* Description :
* Copyright : Copyright (c) 2017
* Company : Raisecom
* Author : yxl
* Date : 2017-12-26 17:21
*/
class ClipService : Service() {
private var previousTime: Long = 0
private lateinit var cm: ClipboardManager
private lateinit var clipChangedListener: ClipboardManager.OnPrimaryClipChangedListener
override fun onBind(p0: Intent?): IBinder {
return ClipBinder(cm, clipChangedListener)
}
override fun onCreate() {
super.onCreate()
println("ClipService onCreate")
val builder: NotificationCompat.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel("misaka", "misaka", NotificationManager.IMPORTANCE_NONE)
} else {
null
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
NotificationCompat.Builder(this, channel!!.id)
} else {
NotificationCompat.Builder(this)
}
builder.setContentTitle("剪切板助手")
.setWhen(0)
.setContentText("剪切板助手正在监控中...")
.setSmallIcon(R.drawable.ic_launcher_round)
.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher))
.setContentIntent(PendingIntent.getActivity(this, 0, Intent(this, Class.forName("com.raisnet.kotlindemo.MainActivity")), PendingIntent.FLAG_UPDATE_CURRENT))
val notification: Notification = builder.build()
startForeground(10000, notification)
cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val dao = MyApplication.getDaoInstance()
clipChangedListener = ClipboardManager.OnPrimaryClipChangedListener {
if (cm.hasPrimaryClip() && cm.primaryClip.itemCount > 0 && (System.currentTimeMillis() - previousTime > 200)) {
val addedText = cm.primaryClip.getItemAt(0).text
if (addedText != null) {
builder.setContentTitle("剪切板助手")
.setWhen(0)
.setContentText(addedText)
.setSmallIcon(R.drawable.ic_launcher_round)
.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher))
.setContentIntent(PendingIntent.getActivity(this, 0, Intent(this, Class.forName("com.raisnet.kotlindemo.MainActivity")), PendingIntent.FLAG_UPDATE_CURRENT))
val n = builder.build()
startForeground(10000, n)
Log.d(TAG, "copied text: " + addedText)
previousTime = System.currentTimeMillis()
val clipItem = ClipItem(null, addedText.toString(), previousTime)
val list = dao.clipItemDao.queryBuilder().where(ClipItemDao.Properties.Content.eq(addedText)).build().list()
if (list.size == 0) {
Toast.makeText(this, "剪切板助手: 已保存", Toast.LENGTH_SHORT).show()
dao.clipItemDao.insert(clipItem)
}
}
}
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY
}
override fun onDestroy() {
super.onDestroy()
stopForeground(true)
}
inner class ClipBinder(private var cm: ClipboardManager, private var clipChangedListener: ClipboardManager.OnPrimaryClipChangedListener) : Binder() {
var isBackground = false
set(value) {
field = value
if (value) {
println("开启后台监听")
LogUtils.logToFile(this@ClipService, "主页面退出,开启后台监控")
cm.addPrimaryClipChangedListener(clipChangedListener)
} else {
println("关闭后台监听")
LogUtils.logToFile(this@ClipService, "主页面开启,退出后台监控")
cm.removePrimaryClipChangedListener(clipChangedListener)
}
}
}
}<file_sep>/app/src/main/java/com/raisnet/kotlindemo/MainActivity.kt
package com.raisnet.kotlindemo
import android.Manifest
import android.annotation.SuppressLint
import android.content.*
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.IBinder
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.telephony.TelephonyManager
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import cn.bmob.v3.listener.SaveListener
import cn.bmob.v3.listener.UpdateListener
import com.raisnet.kotlindemo.adapter.ClipAdapter
import com.raisnet.kotlindemo.adapter.SimpleItemTouchHelperCallback
import com.raisnet.kotlindemo.bean.ClipItem
import com.raisnet.kotlindemo.bean.ClipItemDao
import com.raisnet.kotlindemo.bean.DaoSession
import com.raisnet.kotlindemo.bean.User
import com.raisnet.kotlindemo.utils.LogUtils
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
class MainActivity : AppCompatActivity() {
private val TAG: String = "MainActivity"
private var previousTime: Long = 0
private var clipAdapter: ClipAdapter? = null
private lateinit var cm: ClipboardManager
private lateinit var clipChangedListener: ClipboardManager.OnPrimaryClipChangedListener
var clipBinder: ClipService.ClipBinder? = null
private val conn = ClipServiceConnection()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val dao = MyApplication.getDaoInstance()
clipChangedListener = ClipboardManager.OnPrimaryClipChangedListener {
if (cm.hasPrimaryClip() && cm.primaryClip.itemCount > 0 && (System.currentTimeMillis() - previousTime > 200)) {
val addedText = cm.primaryClip.getItemAt(0).text
if (addedText != null) {
Log.d(TAG, "copied text: " + addedText)
previousTime = System.currentTimeMillis()
val clipItem = ClipItem(null, addedText.toString(), previousTime)
val list = dao.clipItemDao.queryBuilder().where(ClipItemDao.Properties.Content.eq(addedText)).build().list()
if (list.size == 0) {
Toast.makeText(this, "剪切板助手: 已保存", Toast.LENGTH_SHORT).show()
dao.clipItemDao.insert(clipItem)
clipAdapter?.data?.add(clipItem)
clipAdapter?.notifyDataSetChanged()
}
}
}
}
initView(dao)
initData(dao)
}
private fun initView(dao: DaoSession) {
val clipList = findViewById<RecyclerView>(R.id.clipList)
clipList.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
clipList.layoutManager = LinearLayoutManager(this)
clipAdapter = ClipAdapter(this)
clipList.adapter = clipAdapter
val llContent = findViewById<CoordinatorLayout>(R.id.ll_content)
//先实例化Callback
val callback = object : SimpleItemTouchHelperCallback(clipAdapter!!) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
val item = clipAdapter?.data?.get(position)
clipAdapter?.onItemDismiss(viewHolder.adapterPosition)
dao.clipItemDao.delete(item)
Snackbar.make(llContent, "删除了1条剪切板记录", Snackbar.LENGTH_LONG).setAction("撤销", {
clipAdapter?.restoreItem(position, item!!)
dao.clipItemDao.insert(item)
}).show()
}
}
//用Callback构造ItemtouchHelper
val touchHelper = ItemTouchHelper(callback)
//调用ItemTouchHelper的attachToRecyclerView方法建立联系
touchHelper.attachToRecyclerView(clipList)
}
private fun initData(dao: DaoSession) {
Observable.create<MutableList<ClipItem>> {
Log.d(TAG, "开始查询")
val queryBuilder = dao.clipItemDao.queryBuilder()
Log.d(TAG, "查询完成")
it.onNext(queryBuilder.build().list())
}
.observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe({
clipAdapter?.data = it
for (clipItem in it) {
Log.d(TAG, clipItem.content)
}
})
val intent = Intent(this, Class.forName("com.raisnet.kotlindemo.ClipService"))
startService(intent)
bindService(intent, conn, BIND_AUTO_CREATE)
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "页面退出,开启后台监控")
LogUtils.logToFile(this, "页面退出,开启后台监控")
cm.removePrimaryClipChangedListener(clipChangedListener)
clipBinder?.isBackground = true
unbindService(conn)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return super.onCreateOptionsMenu(menu)
}
private val REQUEST_PHONE_STATE: Int = 10086
@SuppressLint("HardwareIds")
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
var IMEI = ""
//Android6.0需要动态获取权限
if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//toast("需要动态获取权限");
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE), REQUEST_PHONE_STATE)
} else {
//toast("不需要动态获取权限");
val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
IMEI = telephonyManager.deviceId
if (IMEI == null) {
Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show()
return true
}
}
//val intent = Intent(this, Class.forName("com.raisnet.kotlindemo.ClipService"))
when (item?.itemId) {
R.id.backup -> {
backup(IMEI)
}
R.id.restore -> {
val query: BmobQuery<User> = BmobQuery()
query.addWhereEqualTo("imei", IMEI).findObjects(object : FindListener<User>() {
override fun done(list: MutableList<User>?, e: BmobException?) {
Log.d(TAG, "查询完成")
if (e != null) {
Log.e(TAG, e.message)
Toast.makeText(applicationContext, "没有记录", Toast.LENGTH_SHORT).show()
} else {
val daoInstance = MyApplication.getDaoInstance()
list?.forEach {
for (clipItem in it.clipList) {
val result = daoInstance.clipItemDao.queryBuilder().where(ClipItemDao.Properties.Content.eq(clipItem.content)).build().list()
if (result.size == 0) {
daoInstance.clipItemDao.insert(clipItem)
clipAdapter?.data?.add(clipItem)
clipAdapter?.notifyDataSetChanged()
}
}
}
}
}
})
}
}
return super.onOptionsItemSelected(item)
}
private fun backup(IMEI: String) {
val user = User(IMEI, clipAdapter?.data?.toList()!!)
val query: BmobQuery<User> = BmobQuery()
query.addWhereEqualTo("imei", IMEI).findObjects(object : FindListener<User>() {
override fun done(list: MutableList<User>?, e: BmobException?) {
Log.d(TAG, "查询完成")
if (e != null) {
Log.e(TAG, e.message)
user.save(object : SaveListener<String>() {
override fun done(objectId: String?, e: BmobException?) {
if (e == null) Toast.makeText(applicationContext, "备份成功", Toast.LENGTH_SHORT).show()
Log.d(TAG, "插入完成")
Log.d(TAG, objectId)
}
})
} else {
if (list?.size!! > 0) {
user.update(list[0].objectId, object : UpdateListener() {
override fun done(e: BmobException?) {
Log.d(TAG, "更新完成")
if (e == null) {
Toast.makeText(applicationContext, "备份成功", Toast.LENGTH_SHORT).show()
} else {
Log.e(TAG, e.message)
}
}
})
} else {
user.save(object : SaveListener<String>() {
override fun done(objectId: String?, p1: BmobException?) {
Log.d(TAG, "插入完成")
Log.d(TAG, objectId)
}
})
}
}
}
})
}
/**
* 加个获取权限的监听
*/
@SuppressLint("MissingPermission", "HardwareIds")
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode == REQUEST_PHONE_STATE && grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "授权成功,继续下一步操作", Toast.LENGTH_SHORT).show()
}
}
inner class ClipServiceConnection : ServiceConnection {
override fun onServiceDisconnected(p0: ComponentName?) {
LogUtils.logToFile(this@MainActivity, "后台服务意外退出")
}
override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
clipBinder = p1 as ClipService.ClipBinder?
clipBinder?.isBackground = false
LogUtils.logToFile(this@MainActivity, "绑定后台服务,添加前台监听")
cm.addPrimaryClipChangedListener(clipChangedListener)
}
}
}
<file_sep>/app/src/main/java/com/raisnet/kotlindemo/adapter/SimpleItemTouchHelperCallback.kt
package com.raisnet.kotlindemo.adapter
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
/**
* Description :
* Copyright : Copyright (c) 2017
* Company : Raisecom
* Author : yxl
* Date : 2017-11-27 14:38
*/
abstract class SimpleItemTouchHelperCallback(private val mAdapter: ItemTouchHelperAdapter) : ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
val swipeFlags = ItemTouchHelper.LEFT
return ItemTouchHelper.Callback.makeMovementFlags(dragFlags, swipeFlags)
}
override fun isLongPressDragEnabled(): Boolean {
return false
}
override fun isItemViewSwipeEnabled(): Boolean {
return true
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
mAdapter.onItemMove(viewHolder.adapterPosition, target.adapterPosition)
return true
}
/*@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}*/
}
<file_sep>/app/src/main/java/com/raisnet/kotlindemo/bean/User.kt
package com.raisnet.kotlindemo.bean
import cn.bmob.v3.BmobObject
/**
* Description :
* Copyright : Copyright (c) 2017
* Company : Raisecom
* Author : yxl
* Date : 2018-01-03 17:13
*/
data class User(var imei: String, var clipList: List<ClipItem>) : BmobObject()<file_sep>/app/src/main/java/com/raisnet/kotlindemo/utils/LogUtils.kt
package com.raisnet.kotlindemo.utils
import android.content.Context
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
/**
* Description :
* Copyright : Copyright (c) 2017
* Company : Raisecom
* Author : yxl
* Date : 2018-01-04 15:56
*/
class LogUtils {
companion object {
fun logToFile(context: Context, content: String) {
val filesDir = context.filesDir
val file = File(filesDir, "log.txt")
file.appendText("$content --- ${SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINESE).format(Date(System.currentTimeMillis()))}\n")
}
}
}
<file_sep>/app/src/main/java/com/raisnet/kotlindemo/bean/ClipItem.java
package com.raisnet.kotlindemo.bean;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
/**
* Description :
* Copyright : Copyright (c) 2017
* Company : Raisecom
* Author : yxl
* Date : 2017-12-26 14:10
*/
@Entity
public class ClipItem {
@Id(autoincrement = true)
private Long id;
private String content;
private Long createTime;
@Generated(hash = 8303691)
public ClipItem(Long id, String content, Long createTime) {
this.id = id;
this.content = content;
this.createTime = createTime;
}
@Generated(hash = 794116089)
public ClipItem() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public Long getCreateTime() {
return this.createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
}
| 2a1c8ea18be10a360c36fdccbd2ad060ccdc6a44 | [
"Markdown",
"Java",
"Kotlin"
] | 11 | Kotlin | misakayao/ClipManager | 389d4e7ee3b47f6e949c18778515309c3fd3df19 | 9fd9c997a5a82c80f8b50fd215614799bd30eb09 |
refs/heads/master | <repo_name>sirrodgepodge/montyHall<file_sep>/montyHall.js
var montyHall = function (numTimes) {
var result = 0;
for (var i = 0; i < numTimes; i++) {
var prizeDoor = Math.floor(Math.random()*3);
var pick1 = Math.floor(Math.random()*3);
result += (pick1 === prizeDoor);
}
result = result/numTimes*100
console.log("stay won " + result + "%");
console.log("switch won " + (100 - result) + "%");
}
montyHall(1000);
| 46bab26aa0f37c97643b223792083733ae7841aa | [
"JavaScript"
] | 1 | JavaScript | sirrodgepodge/montyHall | 9a667ae53dd2736759b5ba68e4690aaa4a6f263e | 6d116c3c4635639ef35b00274c8bcc323136d354 |
refs/heads/master | <repo_name>DreamFlyC/yimi<file_sep>/src/com/lw/cms/bnusercode/service/impl/BnUserCodeServiceImpl.java
/**
*
*/
package com.lw.cms.bnusercode.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.cms.bnusercode.entity.BnUserCode;
import com.lw.cms.bnusercode.service.IBnUserCodeService;
import com.lw.core.base.service.impl.BaseServiceImpl;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:46:52
*/
@Transactional
@Service("BnUserCodeServiceImpl")
public class BnUserCodeServiceImpl extends BaseServiceImpl<BnUserCode> implements IBnUserCodeService{
}
<file_sep>/src/com/lw/dingtalkrecord/persistence/DingtalkRecordMapper.java
package com.lw.dingtalkrecord.persistence;
import com.lw.core.base.persistence.BaseMapper;
import com.lw.dingtalkrecord.entity.DingtalkRecord;
public interface DingtalkRecordMapper extends BaseMapper<DingtalkRecord>{
}
<file_sep>/src/com/lw/cms/bnmanagerlog/service/impl/BnManagerLogServiceImpl.java
/**
*
*/
package com.lw.cms.bnmanagerlog.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.cms.bnmanagerlog.entity.BnManagerLog;
import com.lw.cms.bnmanagerlog.service.IBnManagerLogService;
import com.lw.core.base.service.impl.BaseServiceImpl;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:46:52
*/
@Transactional
@Service("BnManagerLogServiceImpl")
public class BnManagerLogServiceImpl extends BaseServiceImpl<BnManagerLog> implements IBnManagerLogService{
}
<file_sep>/src/com/lw/aliyunmonitordsinfo/persistence/AliyunMonitoRdsinfoMapper.java
package com.lw.aliyunmonitordsinfo.persistence;
import com.lw.aliyunmonitordsinfo.entity.AliyunMonitoRdsinfo;
import com.lw.core.base.persistence.BaseMapper;
/**
* aliyunMonitoRdsinfoMapper继承基类
*/
public interface AliyunMonitoRdsinfoMapper extends BaseMapper<AliyunMonitoRdsinfo> {
}<file_sep>/src/com/lw/foodinfotype/service/IFoodInfoTypeService.java
package com.lw.foodinfotype.service;
import java.util.List;
import com.lw.core.base.service.IBaseService;
import com.lw.foodinfotype.entity.FoodInfoType;
public interface IFoodInfoTypeService extends IBaseService<FoodInfoType>{
/**
* @Desc
* @param id
* @return
* @author CZP
*/
public List<FoodInfoType> getByPid(Integer id);
/**
* @Desc
* @return
* @author CZP
*/
public List<FoodInfoType> getAllOne();
}
<file_sep>/src/com/lw/redpackage/persistence/UserRedPackageMapper.java
package com.lw.redpackage.persistence;
import org.springframework.stereotype.Repository;
import com.lw.core.base.persistence.BaseMapper;
import com.lw.redpackage.entity.UserRedPackage;
@Repository
public interface UserRedPackageMapper extends BaseMapper<UserRedPackage>{
/**
* 插入抢红包信息.
* @param userRedPacket ——抢红包信息
* @return 影响记录数.
*/
public int grapRedPacket(UserRedPackage userRedPacket);
}
<file_sep>/src/com/lw/dingtalkrecord/entity/DingtalkRecord.java
package com.lw.dingtalkrecord.entity;
import java.io.Serializable;
import java.util.Date;
public class DingtalkRecord implements Serializable{
private int id; //唯一标示ID
private int groupId; //考勤组ID
private int planId; //排班ID
private Date workDate; //工作日
private int userId; //用户ID
private int approveId; //关联的审批id
private int procInstId; //关联的审批实例id
private Date baseCheckTime; //计算迟到和早退,基准时间;也可作为排班打卡时间
private Date userCheckTime; //实际打卡时间
private int classId; //考勤班次id,没有的话表示该次打卡不在排班内
private String isLegal; //是否合法,,当timeResult和locationResult都为Normal时,该值为Y;否则为N
private String locationMethod; //定位方法
private int deviceId; //设备id
private String userAddress; //用户打卡地址
private String userLongitude; //用户打卡经度
private String userLatitude; //用户打卡纬度
private String userAccuracy; //用户打卡定位精度
private String userSsid; //用户打卡wifi SSID
private String userMacAddr; //用户打卡wifi Mac地址
private Date planCheckTime; //排班打卡时间
private String baseAddress; //基准地址
private String baseLongitude; //基准经度
private String baseLatitude; //基准纬度
private String baseAccuracy; //基准定位精度
private String baseSsid; //基准wifi ssid
private String baseMacAddr; //基准 Mac 地址
private String outsideRemark; //打卡备注
private String checkType; //考勤类型
private String sourceType; //数据来源
private String timeResult; //时间结果
private String locationResult;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public int getPlanId() {
return planId;
}
public void setPlanId(int planId) {
this.planId = planId;
}
public Date getWorkDate() {
return workDate;
}
public void setWorkDate(Date workDate) {
this.workDate = workDate;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getApproveId() {
return approveId;
}
public void setApproveId(int approveId) {
this.approveId = approveId;
}
public int getProcInstId() {
return procInstId;
}
public void setProcInstId(int procInstId) {
this.procInstId = procInstId;
}
public Date getBaseCheckTime() {
return baseCheckTime;
}
public void setBaseCheckTime(Date baseCheckTime) {
this.baseCheckTime = baseCheckTime;
}
public Date getUserCheckTime() {
return userCheckTime;
}
public void setUserCheckTime(Date userCheckTime) {
this.userCheckTime = userCheckTime;
}
public int getClassId() {
return classId;
}
public void setClassId(int classId) {
this.classId = classId;
}
public String getIsLegal() {
return isLegal;
}
public void setIsLegal(String isLegal) {
this.isLegal = isLegal;
}
public String getLocationMethod() {
return locationMethod;
}
public void setLocationMethod(String locationMethod) {
this.locationMethod = locationMethod;
}
public int getDeviceId() {
return deviceId;
}
public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
public String getUserLongitude() {
return userLongitude;
}
public void setUserLongitude(String userLongitude) {
this.userLongitude = userLongitude;
}
public String getUserLatitude() {
return userLatitude;
}
public void setUserLatitude(String userLatitude) {
this.userLatitude = userLatitude;
}
public String getUserAccuracy() {
return userAccuracy;
}
public void setUserAccuracy(String userAccuracy) {
this.userAccuracy = userAccuracy;
}
public String getUserSsid() {
return userSsid;
}
public void setUserSsid(String userSsid) {
this.userSsid = userSsid;
}
public String getUserMacAddr() {
return userMacAddr;
}
public void setUserMacAddr(String userMacAddr) {
this.userMacAddr = userMacAddr;
}
public Date getPlanCheckTime() {
return planCheckTime;
}
public void setPlanCheckTime(Date planCheckTime) {
this.planCheckTime = planCheckTime;
}
public String getBaseAddress() {
return baseAddress;
}
public void setBaseAddress(String baseAddress) {
this.baseAddress = baseAddress;
}
public String getBaseLongitude() {
return baseLongitude;
}
public void setBaseLongitude(String baseLongitude) {
this.baseLongitude = baseLongitude;
}
public String getBaseLatitude() {
return baseLatitude;
}
public void setBaseLatitude(String baseLatitude) {
this.baseLatitude = baseLatitude;
}
public String getBaseAccuracy() {
return baseAccuracy;
}
public void setBaseAccuracy(String baseAccuracy) {
this.baseAccuracy = baseAccuracy;
}
public String getBaseSsid() {
return baseSsid;
}
public void setBaseSsid(String baseSsid) {
this.baseSsid = baseSsid;
}
public String getBaseMacAddr() {
return baseMacAddr;
}
public void setBaseMacAddr(String baseMacAddr) {
this.baseMacAddr = baseMacAddr;
}
public String getOutsideRemark() {
return outsideRemark;
}
public void setOutsideRemark(String outsideRemark) {
this.outsideRemark = outsideRemark;
}
public String getCheckType() {
return checkType;
}
public void setCheckType(String checkType) {
this.checkType = checkType;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getTimeResult() {
return timeResult;
}
public void setTimeResult(String timeResult) {
this.timeResult = timeResult;
}
public String getLocationResult() {
return locationResult;
}
public void setLocationResult(String locationResult) {
this.locationResult = locationResult;
}
}
<file_sep>/src/com/lw/aliyunmonitordsinfo/service/IAliyunMonitoRdsinfoService.java
package com.lw.aliyunmonitordsinfo.service;
import com.lw.aliyunmonitordsinfo.entity.AliyunMonitoRdsinfo;
import com.lw.core.base.service.IBaseService;
public interface IAliyunMonitoRdsinfoService extends IBaseService<AliyunMonitoRdsinfo>{
}
<file_sep>/src/com/lw/cms/bnmanagerrolevalue/entity/BnManagerRoleValue.java
/**
*
*/
package com.lw.cms.bnmanagerrolevalue.entity;
import java.io.Serializable;
import java.util.Date;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:42:58
*/
public class BnManagerRoleValue implements Serializable{
private int id;
private int role_id;
private String channel_name;
private int channel_id;
private String action_type;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getRole_id() {
return role_id;
}
public void setRole_id(int role_id) {
this.role_id = role_id;
}
public String getChannel_name() {
return channel_name;
}
public void setChannel_name(String channel_name) {
this.channel_name = channel_name;
}
public int getChannel_id() {
return channel_id;
}
public void setChannel_id(int channel_id) {
this.channel_id = channel_id;
}
public String getAction_type() {
return action_type;
}
public void setAction_type(String action_type) {
this.action_type = action_type;
}
}<file_sep>/src/com/lw/cms/bnuserloginlog/action/BnUserLoginLogAction.java
/**
*
*/
package com.lw.cms.bnuserloginlog.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.cms.bnuserloginlog.entity.BnUserLoginLog;
import com.lw.cms.bnuserloginlog.service.IBnUserLoginLogService;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:41:52
*/
@Controller("BnUserLoginLogAction")
@RequestMapping(value="/manage/bnuserloginlog")
public class BnUserLoginLogAction extends BaseAction{
@Autowired
private IBnUserLoginLogService bnUserLoginLogService;
/**
*
* @Desc 信息列表
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:25
*/
@RequestMapping("")
public String list(){
instantPage(20);
List<BnUserLoginLog> list=bnUserLoginLogService.getList();
int total=bnUserLoginLogService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/bnuserloginlog/bnuserloginlog_list";
}
/**
*
* @Desc 跳转到新增页面
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:36
*/
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addbnuserloginlog(){
return "/WEB-INF/bnuserloginlog/bnuserloginlog_add";
}
/**
* @Desc 保存数据
* @param bnUserLoginLog
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:23
*/
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addAdpic(@ModelAttribute BnUserLoginLog bnUserLoginLog) throws Exception{
bnUserLoginLogService.save(bnUserLoginLog);
return "redirect:/manage/bnuserloginlog.html";
}
/**
*
* @Desc 删除信息
* @param id
* @param response
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:09
*/
@RequestMapping(value="/del/{id}")
public String deletebnuserloginlog(@PathVariable("id")int id,HttpServletResponse response){
bnUserLoginLogService.del(id);
return "redirect:/manage/bnuserloginlog.html";
}
/**
* @Desc 修改信息
* @param bnUserLoginLog
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:00
*/
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updatebnuserloginlog(BnUserLoginLog bnUserLoginLog)throws Exception{
bnUserLoginLogService.edit(bnUserLoginLog);
return "redirect:/manage/bnuserloginlog.html";
}
/**
*
* @Desc 编辑前根据id获取信息
* @param id
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:43
*/
@RequestMapping(value="/{id}")
public String viewbnuserloginlog(@PathVariable("id")int id)
{
BnUserLoginLog bnUserLoginLog=bnUserLoginLogService.get(id);
getRequest().setAttribute("bnUserLoginLog",bnUserLoginLog);
return "/WEB-INF/bnuserloginlog/bnuserloginlog_detail";
}
}
<file_sep>/src/com/lw/dingtalkrecord/service/IDingtalkRecordService.java
package com.lw.dingtalkrecord.service;
import com.lw.core.base.service.IBaseService;
import com.lw.dingtalkrecord.entity.DingtalkRecord;
public interface IDingtalkRecordService extends IBaseService<DingtalkRecord>{
}
<file_sep>/src/com/lw/kitchendevice/service/impl/KitchenDeviceServiceImpl.java
/**
*
*/
package com.lw.kitchendevice.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.core.base.service.impl.BaseServiceImpl;
import com.lw.kitchendevice.entity.KitchenDevice;
import com.lw.kitchendevice.service.IKitchenDeviceService;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:46:52
*/
@Transactional
@Service("KitchenDeviceServiceImpl")
public class KitchenDeviceServiceImpl extends BaseServiceImpl<KitchenDevice> implements IKitchenDeviceService{
}
<file_sep>/src/com/lw/restaurantsoftinfo/service/IRestaurantsoftinfoService.java
package com.lw.restaurantsoftinfo.service;
import com.lw.core.base.service.IBaseService;
import com.lw.restaurantsoftinfo.entity.RestaurantSoftInfo;
public interface IRestaurantsoftinfoService extends IBaseService<RestaurantSoftInfo>{
}
<file_sep>/src/com/lw/cms/bnarticlediggs/service/IBnArticleDiggsService.java
/**
*
*/
package com.lw.cms.bnarticlediggs.service;
import com.lw.cms.bnarticlediggs.entity.BnArticleDiggs;
import com.lw.core.base.service.IBaseService;
/**
* @Desc
* @author CZP
* @Date 2018年10月23日 下午2:59:08
*/
public interface IBnArticleDiggsService extends IBaseService<BnArticleDiggs>{
}
<file_sep>/src/com/lw/qaquestion/persistence/QaQuestionMapper.java
/**
*
*/
package com.lw.qaquestion.persistence;
import com.lw.core.base.persistence.BaseMapper;
import com.lw.qaquestion.entity.QaQuestion;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:46:31
*/
public interface QaQuestionMapper extends BaseMapper<QaQuestion>{
}
<file_sep>/src/com/lw/cms/bnarticledownload/service/impl/BnArticleDownloadServiceImpl.java
/**
*
*/
/**
* @Desc
* @author CZP
* @Date 2018年10月23日 下午4:04:58
*/
package com.lw.cms.bnarticledownload.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.cms.bnarticledownload.entity.BnArticleDownload;
import com.lw.cms.bnarticledownload.persistence.BnArticleDownloadMapper;
import com.lw.cms.bnarticledownload.service.IBnArticleDownloadService;
import com.lw.core.base.service.impl.BaseServiceImpl;
@Transactional
@Service("BnArticleDownloadServiceImpl")
public class BnArticleDownloadServiceImpl extends BaseServiceImpl<BnArticleDownload> implements IBnArticleDownloadService{
@Autowired
private BnArticleDownloadMapper bnArticleDownloadMapper;
}<file_sep>/src/com/lw/cms/bnarticlealbums/service/IBnArticleAlbumsService.java
/**
*
*/
package com.lw.cms.bnarticlealbums.service;
import com.lw.cms.bnarticlealbums.entity.BnArticleAlbums;
import com.lw.core.base.service.IBaseService;
/**
* @Desc
* @author CZP
* @Date 2018年10月23日 下午2:59:08
*/
public interface IBnArticleAlbumsService extends IBaseService<BnArticleAlbums>{
}
<file_sep>/src/com/lw/cms/bnusercode/action/BnUserCodeAction.java
/**
*
*/
package com.lw.cms.bnusercode.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.cms.bnusercode.entity.BnUserCode;
import com.lw.cms.bnusercode.service.IBnUserCodeService;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:41:52
*/
@Controller("BnUserCodeAction")
@RequestMapping(value="/manage/bnusercode")
public class BnUserCodeAction extends BaseAction{
@Autowired
private IBnUserCodeService bnUserCodeService;
/**
*
* @Desc 信息列表
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:25
*/
@RequestMapping("")
public String list(){
instantPage(20);
List<BnUserCode> list=bnUserCodeService.getList();
int total=bnUserCodeService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/bnusercode/bnusercode_list";
}
/**
*
* @Desc 跳转到新增页面
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:36
*/
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addbnusercode(){
return "/WEB-INF/bnusercode/bnusercode_add";
}
/**
* @Desc 保存数据
* @param bnUserCode
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:23
*/
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addAdpic(@ModelAttribute BnUserCode bnUserCode) throws Exception{
bnUserCodeService.save(bnUserCode);
return "redirect:/manage/bnusercode.html";
}
/**
*
* @Desc 删除信息
* @param id
* @param response
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:09
*/
@RequestMapping(value="/del/{id}")
public String deletebnusercode(@PathVariable("id")int id,HttpServletResponse response){
bnUserCodeService.del(id);
return "redirect:/manage/bnusercode.html";
}
/**
* @Desc 修改信息
* @param bnUserCode
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:00
*/
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updatebnusercode(BnUserCode bnUserCode)throws Exception{
bnUserCodeService.edit(bnUserCode);
return "redirect:/manage/bnusercode.html";
}
/**
*
* @Desc 编辑前根据id获取信息
* @param id
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:43
*/
@RequestMapping(value="/{id}")
public String viewbnusercode(@PathVariable("id")int id)
{
BnUserCode bnUserCode=bnUserCodeService.get(id);
getRequest().setAttribute("bnUserCode",bnUserCode);
return "/WEB-INF/bnusercode/bnusercode_detail";
}
}
<file_sep>/src/com/lw/tpartnerbasicinfo/service/ITPartnerBasicInfoService.java
/**
*
*/
package com.lw.tpartnerbasicinfo.service;
import com.lw.core.base.service.IBaseService;
import com.lw.tpartnerbasicinfo.entity.TPartnerBasicInfo;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:47:25
*/
public interface ITPartnerBasicInfoService extends IBaseService<TPartnerBasicInfo>{
}
<file_sep>/src/com/lw/redpackage/service/IUserRedPackageService.java
package com.lw.redpackage.service;
import com.lw.core.base.service.IBaseService;
import com.lw.redpackage.entity.UserRedPackage;
public interface IUserRedPackageService extends IBaseService<UserRedPackage> {
/**
* 保存抢红包信息.
* @param redPacketId 红包编号
* @param userId 抢红包用户编号
* @return 影响记录数.
*/
public int grapRedPacket(Long redPacketId, Long userId);
}
<file_sep>/src/com/lw/qaquestion/action/QaQuestionAction.java
/**
*
*/
package com.lw.qaquestion.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
import com.lw.qaquestion.entity.QaQuestion;
import com.lw.qaquestion.service.IQaQuestionService;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:41:52
*/
@Controller("QaQuestionAction")
@RequestMapping(value="/manage/qaquestion")
public class QaQuestionAction extends BaseAction{
@Autowired
private IQaQuestionService qaQuestionService;
/**
*
* @Desc 信息列表
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:25
*/
@RequestMapping("")
public String list(){
instantPage(20);
List<QaQuestion> list=qaQuestionService.getList();
int total=qaQuestionService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/qaquestion/qaquestion_list";
}
/**
*
* @Desc 跳转到新增页面
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:36
*/
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addqaquestion(){
return "/WEB-INF/qaquestion/qaquestion_add";
}
/**
* @Desc 保存数据
* @param qaQuestion
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:23
*/
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addAdpic(@ModelAttribute QaQuestion qaQuestion) throws Exception{
qaQuestionService.save(qaQuestion);
return "redirect:/manage/qaquestion.html";
}
/**
*
* @Desc 删除信息
* @param id
* @param response
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:09
*/
@RequestMapping(value="/del/{id}")
public String deleteqaquestion(@PathVariable("id")int id,HttpServletResponse response){
qaQuestionService.del(id);
return "redirect:/manage/qaquestion.html";
}
/**
* @Desc 修改信息
* @param qaQuestion
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:00
*/
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updateqaquestion(QaQuestion qaQuestion)throws Exception{
qaQuestionService.edit(qaQuestion);
return "redirect:/manage/qaquestion.html";
}
/**
*
* @Desc 编辑前根据id获取信息
* @param id
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:43
*/
@RequestMapping(value="/{id}")
public String viewqaquestion(@PathVariable("id")int id)
{
QaQuestion qaQuestion=qaQuestionService.get(id);
getRequest().setAttribute("qaQuestion",qaQuestion);
return "/WEB-INF/qaquestion/qaquestion_detail";
}
}
<file_sep>/src/com/lw/adpic/entity/Adpic.java
package com.lw.adpic.entity;
import java.io.Serializable;
/**
* @author CZP
*
* 2018年7月11日
*/
public class Adpic implements Serializable{
private int id;
private int type;
private String smallpic;
private String largepic;
private String title;
private String description;
private boolean isshow;
private String addtime;
private String starttime;
private String endtime;
private int component;
public int getComponent() {
return component;
}
public void setComponent(int component) {
this.component = component;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getSmallpic() {
return smallpic;
}
public void setSmallpic(String smallpic) {
this.smallpic = smallpic;
}
public String getLargepic() {
return largepic;
}
public void setLargepic(String largepic) {
this.largepic = largepic;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean getIsshow() {
return isshow;
}
public void setIsshow(boolean isshow) {
this.isshow = isshow;
}
public String getAddtime() {
return addtime;
}
public void setAddtime(String addtime) {
this.addtime = addtime;
}
public String getStarttime() {
return starttime;
}
public void setStarttime(String starttime) {
this.starttime = starttime;
}
public String getEndtime() {
return endtime;
}
public void setEndtime(String endtime) {
this.endtime = endtime;
}
}
<file_sep>/src/com/lw/cms/bnlink/entity/BnLink.java
/**
*
*/
package com.lw.cms.bnlink.entity;
import java.io.Serializable;
import java.util.Date;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:42:58
*/
public class BnLink implements Serializable{
private int id;
private String title;
private String user_name;
private String user_tel;
private String email;
private String site_url;
private String img_url;
private int is_image;
private int sort_id;
private int is_red;
private int is_lock;
private Date add_time;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_tel() {
return user_tel;
}
public void setUser_tel(String user_tel) {
this.user_tel = user_tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSite_url() {
return site_url;
}
public void setSite_url(String site_url) {
this.site_url = site_url;
}
public String getImg_url() {
return img_url;
}
public void setImg_url(String img_url) {
this.img_url = img_url;
}
public int getIs_image() {
return is_image;
}
public void setIs_image(int is_image) {
this.is_image = is_image;
}
public int getSort_id() {
return sort_id;
}
public void setSort_id(int sort_id) {
this.sort_id = sort_id;
}
public int getIs_red() {
return is_red;
}
public void setIs_red(int is_red) {
this.is_red = is_red;
}
public int getIs_lock() {
return is_lock;
}
public void setIs_lock(int is_lock) {
this.is_lock = is_lock;
}
public Date getAdd_time() {
return add_time;
}
public void setAdd_time(Date add_time) {
this.add_time = add_time;
}
}<file_sep>/src/com/lw/cms/bnattributes/service/impl/BnAttributesServiceImpl.java
/**
*
*/
package com.lw.cms.bnattributes.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.cms.bnattributes.entity.BnAttributes;
import com.lw.cms.bnattributes.service.IBnAttributesService;
import com.lw.core.base.service.impl.BaseServiceImpl;
/**
* @Desc
* @author CZP
* @Date 2018年10月25日 上午10:57:31
*/
@Transactional
@Service("BnAttributesServiceImpl")
public class BnAttributesServiceImpl extends BaseServiceImpl<BnAttributes> implements IBnAttributesService{
}
<file_sep>/src/com/lw/cms/bnarticledownload/action/BnArticleDownloadAction.java
/**
*
*/
/**
* @Desc
* @author CZP
* @Date 2018年10月23日 下午4:04:22
*/
package com.lw.cms.bnarticledownload.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.cms.bnarticledownload.entity.BnArticleDownload;
import com.lw.cms.bnarticledownload.service.IBnArticleDownloadService;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
@Controller("BnArticleDownloadAction")
@RequestMapping(value = "/manage/bnarticledownload")
@SuppressWarnings("all")
public class BnArticleDownloadAction extends BaseAction{
@Autowired
private IBnArticleDownloadService ArticleDownloadService;
//信息列表
@RequestMapping("")
public String list(){
instantPage(20);
List<BnArticleDownload> list=ArticleDownloadService.getList();
int total=ArticleDownloadService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/bnarticledownload/bnarticledownload_list";
}
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addbnarticledownload(){
return "/WEB-INF/bnarticledownload/bnarticledownload_add";
}
//新增信息
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addbnarticledownload(BnArticleDownload bnArticleDownload){
ArticleDownloadService.save(bnArticleDownload);
return "redirect:/manage/bnarticledownload.html";
}
//删除信息
@RequestMapping(value="/del/{id}")
public String deletebnarticledownload(@PathVariable("id")int id,HttpServletResponse response){
ArticleDownloadService.del(id);
return "redirect:/manage/bnarticledownload.html";
}
//修改信息
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updatebnarticledownload(BnArticleDownload bnArticleDownload,HttpServletResponse response){
ArticleDownloadService.edit(bnArticleDownload);
return "redirect:/manage/bnarticledownload.html";
}
//编辑前根据id获取信息
@RequestMapping(value="/{id}")
public String viewbnarticledownload(@PathVariable("id")int id)
{
BnArticleDownload bnArticleDownload=ArticleDownloadService.get(id);
getRequest().setAttribute("bnArticleDownload",bnArticleDownload);
return "/WEB-INF/bnarticledownload/bnarticledownload_detail";
}
}<file_sep>/src/com/lw/cms/bnmanager/entity/BnManager.java
/**
*
*/
package com.lw.cms.bnmanager.entity;
import java.io.Serializable;
import java.util.Date;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:42:58
*/
public class BnManager implements Serializable{
private int id;
private int role_id;
private int role_type;
private String user_name;
private String user_pwd;
private String real_name;
private String telephone;
private String email;
private int is_lock;
private Date add_time;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getRole_id() {
return role_id;
}
public void setRole_id(int role_id) {
this.role_id = role_id;
}
public int getRole_type() {
return role_type;
}
public void setRole_type(int role_type) {
this.role_type = role_type;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_pwd() {
return user_pwd;
}
public void setUser_pwd(String user_pwd) {
this.user_pwd = user_pwd;
}
public String getReal_name() {
return real_name;
}
public void setReal_name(String real_name) {
this.real_name = real_name;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getIs_lock() {
return is_lock;
}
public void setIs_lock(int is_lock) {
this.is_lock = is_lock;
}
public Date getAdd_time() {
return add_time;
}
public void setAdd_time(Date add_time) {
this.add_time = add_time;
}
}<file_sep>/src/com/lw/dingtalkrecord/service/impl/DingtalkRecordServiceImpl.java
package com.lw.dingtalkrecord.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.core.base.service.impl.BaseServiceImpl;
import com.lw.dingtalkrecord.entity.DingtalkRecord;
import com.lw.dingtalkrecord.persistence.DingtalkRecordMapper;
import com.lw.dingtalkrecord.service.IDingtalkRecordService;
@Service("DingtalkRecordServiceImpl")
@Transactional
public class DingtalkRecordServiceImpl extends BaseServiceImpl<DingtalkRecord> implements IDingtalkRecordService{
@Autowired
private DingtalkRecordMapper dingtalkRecordMapper;
}
<file_sep>/src/com/lw/yiminews/service/impl/YimiNewsServiceImpl.java
package com.lw.yiminews.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.core.base.service.impl.BaseServiceImpl;
import com.lw.yiminews.entity.YimiNews;
import com.lw.yiminews.service.IYimiNewsService;
@Service("YimiNewsServiceImpl")
@Transactional
public class YimiNewsServiceImpl extends BaseServiceImpl<YimiNews> implements IYimiNewsService{
}
<file_sep>/src/com/lw/traceabilitypoint/entity/TraceabilityPoint.java
package com.lw.traceabilitypoint.entity;
import java.io.Serializable;
public class TraceabilityPoint implements Serializable{
private int id;
private String name;
private String address;
private String phone;
private String logo;
private String longitude;
private String latitude;
private String remark;
private String authorkey;
private String user_name;
private String password;
private String salt;
private Boolean enable;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getAuthorkey() {
return authorkey;
}
public void setAuthorkey(String authorkey) {
this.authorkey = authorkey;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
}
<file_sep>/src/com/lw/newsinfo/service/impl/NewsInfoServiceImpl.java
package com.lw.newsinfo.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.core.base.service.impl.BaseServiceImpl;
import com.lw.newsinfo.entity.NewsInfo;
import com.lw.newsinfo.service.INewsInfoService;
/**
*@author qw
*@version 创建时间:2017年3月6日 上午11:17:28
*类说明
*/
@Service("NewsInfoServiceImpl")
@Transactional
public class NewsInfoServiceImpl extends BaseServiceImpl<NewsInfo> implements INewsInfoService{
}
<file_sep>/src/com/lw/cms/bnlink/action/BnLinkAction.java
/**
*
*/
package com.lw.cms.bnlink.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.cms.bnlink.entity.BnLink;
import com.lw.cms.bnlink.service.IBnLinkService;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:41:52
*/
@Controller("BnLinkAction")
@RequestMapping(value="/manage/bnlink")
public class BnLinkAction extends BaseAction{
@Autowired
private IBnLinkService bnLinkService;
/**
*
* @Desc 信息列表
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:25
*/
@RequestMapping("")
public String list(){
instantPage(20);
List<BnLink> list=bnLinkService.getList();
int total=bnLinkService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/bnlink/bnlink_list";
}
/**
*
* @Desc 跳转到新增页面
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:36
*/
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addbnlink(){
return "/WEB-INF/bnlink/bnlink_add";
}
/**
* @Desc 保存数据
* @param bnLink
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:23
*/
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addAdpic(@ModelAttribute BnLink bnLink) throws Exception{
bnLinkService.save(bnLink);
return "redirect:/manage/bnlink.html";
}
/**
*
* @Desc 删除信息
* @param id
* @param response
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:09
*/
@RequestMapping(value="/del/{id}")
public String deletebnlink(@PathVariable("id")int id,HttpServletResponse response){
bnLinkService.del(id);
return "redirect:/manage/bnlink.html";
}
/**
* @Desc 修改信息
* @param bnLink
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:00
*/
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updatebnlink(BnLink bnLink)throws Exception{
bnLinkService.edit(bnLink);
return "redirect:/manage/bnlink.html";
}
/**
*
* @Desc 编辑前根据id获取信息
* @param id
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:43
*/
@RequestMapping(value="/{id}")
public String viewbnlink(@PathVariable("id")int id)
{
BnLink bnLink=bnLinkService.get(id);
getRequest().setAttribute("bnLink",bnLink);
return "/WEB-INF/bnlink/bnlink_detail";
}
}
<file_sep>/src/com/lw/aliyunmonitoossinfo/entity/AliyunMonitoOssinfo.java
package com.lw.aliyunmonitoossinfo.entity;
import java.io.Serializable;
/**
* aliyun_monito_ossinfo
* @author
*/
public class AliyunMonitoOssinfo implements Serializable {
private Integer id;
/**
* 连接数使用率
*/
private String connectionusage;
/**
* 已用连接数
*/
private String usedconnection;
/**
* CPU使用率
*/
private String cpuusage;
/**
* 操作失败数
*/
private String cailedcount;
/**
* 写入网络带宽
*/
private String intranetin;
/**
* 写入带宽使用率
*/
private String intranetinratio;
/**
* 读取网络带宽
*/
private String intranetout;
/**
* 读取带宽使用率
*/
private String intranetoutratio;
/**
* 内存使用率
*/
private String memoryusage;
/**
* 内存使用量
*/
private String usedmemory;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getConnectionusage() {
return connectionusage;
}
public void setConnectionusage(String connectionusage) {
this.connectionusage = connectionusage;
}
public String getUsedconnection() {
return usedconnection;
}
public void setUsedconnection(String usedconnection) {
this.usedconnection = usedconnection;
}
public String getCpuusage() {
return cpuusage;
}
public void setCpuusage(String cpuusage) {
this.cpuusage = cpuusage;
}
public String getCailedcount() {
return cailedcount;
}
public void setCailedcount(String cailedcount) {
this.cailedcount = cailedcount;
}
public String getIntranetin() {
return intranetin;
}
public void setIntranetin(String intranetin) {
this.intranetin = intranetin;
}
public String getIntranetinratio() {
return intranetinratio;
}
public void setIntranetinratio(String intranetinratio) {
this.intranetinratio = intranetinratio;
}
public String getIntranetout() {
return intranetout;
}
public void setIntranetout(String intranetout) {
this.intranetout = intranetout;
}
public String getIntranetoutratio() {
return intranetoutratio;
}
public void setIntranetoutratio(String intranetoutratio) {
this.intranetoutratio = intranetoutratio;
}
public String getMemoryusage() {
return memoryusage;
}
public void setMemoryusage(String memoryusage) {
this.memoryusage = memoryusage;
}
public String getUsedmemory() {
return usedmemory;
}
public void setUsedmemory(String usedmemory) {
this.usedmemory = usedmemory;
}
}<file_sep>/src/com/lw/cms/bndownloadattach/entity/BnDownloadAttach.java
/**
*
*/
package com.lw.cms.bndownloadattach.entity;
import java.io.Serializable;
import java.util.Date;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:42:58
*/
public class BnDownloadAttach implements Serializable{
private int id;
private int article_id;
private String title;
private String file_path;
private String file_ext;
private int file_size;
private int down_num;
private int point;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getArticle_id() {
return article_id;
}
public void setArticle_id(int article_id) {
this.article_id = article_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFile_path() {
return file_path;
}
public void setFile_path(String file_path) {
this.file_path = file_path;
}
public String getFile_ext() {
return file_ext;
}
public void setFile_ext(String file_ext) {
this.file_ext = file_ext;
}
public int getFile_size() {
return file_size;
}
public void setFile_size(int file_size) {
this.file_size = file_size;
}
public int getDown_num() {
return down_num;
}
public void setDown_num(int down_num) {
this.down_num = down_num;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
}<file_sep>/src/com/lw/cms/bnusercode/service/IBnUserCodeService.java
/**
*
*/
package com.lw.cms.bnusercode.service;
import com.lw.cms.bnusercode.entity.BnUserCode;
import com.lw.core.base.service.IBaseService;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:47:25
*/
public interface IBnUserCodeService extends IBaseService<BnUserCode>{
}
<file_sep>/src/com/lw/cms/bnarticlediggs/action/BnArticleDiggsAction.java
/**
*
*/
package com.lw.cms.bnarticlediggs.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.cms.bnarticlediggs.entity.BnArticleDiggs;
import com.lw.cms.bnarticlediggs.service.IBnArticleDiggsService;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
/**
* @Desc
* @author CZP
* @Date 2018年10月23日 下午3:01:48
*/
@Controller("BnArticleDiggsAction")
@RequestMapping(value = "/manage/bnarticlediggs")
@SuppressWarnings("all")
public class BnArticleDiggsAction extends BaseAction{
@Autowired
private IBnArticleDiggsService bnArticleDiggsService;
/**
*
* @Desc 信息列表
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:25
*/
@RequestMapping("")
public String list(){
instantPage(20);
List<BnArticleDiggs> list=bnArticleDiggsService.getList();
int total=bnArticleDiggsService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/bnarticlediggs/bnarticlediggs_list";
}
/**
*
* @Desc 跳转到新增页面
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:36
*/
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addbnarticlediggs(){
return "/WEB-INF/bnarticlediggs/bnarticlediggs_add";
}
/**
* @Desc 保存数据
* @param bnArticleDiggs
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:23
*/
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addAdpic(@ModelAttribute BnArticleDiggs bnArticleDiggs) throws Exception{
bnArticleDiggsService.save(bnArticleDiggs);
return "redirect:/manage/bnarticlediggs.html";
}
/**
*
* @Desc 删除信息
* @param id
* @param response
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:09
*/
@RequestMapping(value="/del/{id}")
public String deletebnarticlediggs(@PathVariable("id")int id,HttpServletResponse response){
bnArticleDiggsService.del(id);
return "redirect:/manage/bnarticlediggs.html";
}
/**
* @Desc 修改信息
* @param bnArticleDiggs
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:00
*/
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updatebnarticlediggs(BnArticleDiggs bnArticleDiggs)throws Exception{
bnArticleDiggsService.edit(bnArticleDiggs);
return "redirect:/manage/bnarticlediggs.html";
}
/**
*
* @Desc 编辑前根据id获取信息
* @param id
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:43
*/
@RequestMapping(value="/{id}")
public String viewbnarticlediggs(@PathVariable("id")int id)
{
BnArticleDiggs bnArticleDiggs=bnArticleDiggsService.get(id);
getRequest().setAttribute("bnArticleDiggs",bnArticleDiggs);
return "/WEB-INF/bnarticlediggs/bnarticlediggs_detail";
}
}
<file_sep>/src/com/lw/sysmobmsnaccount/persistence/SysMobmsnAccountMapper.java
/**
*
*/
package com.lw.sysmobmsnaccount.persistence;
import com.lw.core.base.persistence.BaseMapper;
import com.lw.sysmobmsnaccount.entity.SysMobmsnAccount;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:46:31
*/
public interface SysMobmsnAccountMapper extends BaseMapper<SysMobmsnAccount>{
}
<file_sep>/src/com/lw/redpackage/persistence/RedPackageMapper.java
package com.lw.redpackage.persistence;
import org.springframework.stereotype.Repository;
import com.lw.core.base.persistence.BaseMapper;
import com.lw.redpackage.entity.RedPackage;
@Repository
public interface RedPackageMapper extends BaseMapper<RedPackage>{
/**
* 获取红包信息.
* @param id --红包id
* @return 红包具体信息
*/
public RedPackage getRedPacket(Long id);
/**
* 扣减抢红包数.
* @param id -- 红包id
* @return 更新记录条数
*/
public int decreaseRedPacket(Long id);
}
<file_sep>/src/com/lw/kitcheninfo/service/impl/KitchenInfoServiceImpl.java
/**
*
*/
package com.lw.kitcheninfo.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.core.base.service.impl.BaseServiceImpl;
import com.lw.kitcheninfo.entity.KitchenInfo;
import com.lw.kitcheninfo.persistence.KitchenInfoMapper;
import com.lw.kitcheninfo.service.IKitchenInfoService;
/**
* @Desc
* @author CZP
* @Date 2018年10月25日 上午10:57:31
*/
@Transactional
@Service("KitchenInfoServiceImpl")
public class KitchenInfoServiceImpl extends BaseServiceImpl<KitchenInfo> implements IKitchenInfoService{
@Autowired
private KitchenInfoMapper bnFeedBackMapper;
}
<file_sep>/src/com/lw/aliyunmonitordsinfo/action/AliyunMonitoRdsinfoAction.java
package com.lw.aliyunmonitordsinfo.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.aliyunmonitordsinfo.entity.AliyunMonitoRdsinfo;
import com.lw.aliyunmonitordsinfo.service.IAliyunMonitoRdsinfoService;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
@Controller("AliyunMonitoRdsinfoAction")
@RequestMapping(value = "/aliyunmonitordsinfo")
@SuppressWarnings("all")
public class AliyunMonitoRdsinfoAction extends BaseAction{
@Autowired
private IAliyunMonitoRdsinfoService aliyunMonitoRdsinfoService;
//信息列表
@RequestMapping("")
public String list(){
instantPage(20);
List<AliyunMonitoRdsinfo> list=aliyunMonitoRdsinfoService.getList();
int total=aliyunMonitoRdsinfoService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/aliyunmonitordsinfo/aliyunmonitordsinfo_list";
}
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addAliyunMonitoRdsinfo(){
return "/WEB-INF/aliyunmonitordsinfo/aliyunmonitordsinfo_add";
}
//新增信息
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addAliyunMonitoRdsinfo(AliyunMonitoRdsinfo AliyunMonitoRdsinfo){
aliyunMonitoRdsinfoService.save(AliyunMonitoRdsinfo);
return "redirect:/aliyunmonitordsinfo.html";
}
//删除信息
@RequestMapping(value="/del/{id}")
public String deleteAliyunMonitoRdsinfo(@PathVariable("id")int id,HttpServletResponse response){
aliyunMonitoRdsinfoService.del(id);
return "redirect:/aliyunmonitordsinfo.html";
}
//修改信息
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updateAliyunMonitoRdsinfo(AliyunMonitoRdsinfo AliyunMonitoRdsinfo,HttpServletResponse response){
aliyunMonitoRdsinfoService.edit(AliyunMonitoRdsinfo);
return "redirect:/aliyunmonitordsinfo.html";
}
//编辑前根据id获取信息
@RequestMapping(value="/{id}")
public String viewAliyunMonitoRdsinfo(@PathVariable("id")int id)
{
AliyunMonitoRdsinfo aliyunmonitordsinfo=aliyunMonitoRdsinfoService.get(id);
getRequest().setAttribute("aliyunmonitordsinfo",aliyunmonitordsinfo);
return "/WEB-INF/aliyunmonitordsinfo/aliyunmonitordsinfo_detail";
}
}
<file_sep>/src/com/lw/cms/bnusercode/entity/BnUserCode.java
/**
*
*/
package com.lw.cms.bnusercode.entity;
import java.io.Serializable;
import java.util.Date;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:42:58
*/
public class BnUserCode implements Serializable{
private int id;
private int userid;
private String username;
private String type;
private String strcode;
private int count;
private int status;
private Date efftime;
private Date addtime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStrcode() {
return strcode;
}
public void setStrcode(String strcode) {
this.strcode = strcode;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getEfftime() {
return efftime;
}
public void setEfftime(Date efftime) {
this.efftime = efftime;
}
public Date getAddtime() {
return addtime;
}
public void setAddtime(Date addtime) {
this.addtime = addtime;
}
}<file_sep>/src/com/lw/kitchendevice/entity/KitchenDevice.java
/**
*
*/
package com.lw.kitchendevice.entity;
import java.io.Serializable;
import java.util.Date;
/**
* @Desc
* @author CZP
* @Date 2018年10月25日 上午10:58:27
*/
public class KitchenDevice implements Serializable{
private int id;
private String name;
private String remark;
private String author_key;
private int kitchen_id;
private String device_sn;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getAuthor_key() {
return author_key;
}
public void setAuthor_key(String author_key) {
this.author_key = author_key;
}
public int getKitchen_id() {
return kitchen_id;
}
public void setKitchen_id(int kitchen_id) {
this.kitchen_id = kitchen_id;
}
public String getDevice_sn() {
return device_sn;
}
public void setDevice_sn(String device_sn) {
this.device_sn = device_sn;
}
}<file_sep>/src/com/lw/cms/bnmanagerrolevalue/action/BnManagerRoleValueAction.java
/**
*
*/
package com.lw.cms.bnmanagerrolevalue.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.cms.bnmanagerrolevalue.entity.BnManagerRoleValue;
import com.lw.cms.bnmanagerrolevalue.service.IBnManagerRoleValueService;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
/**
* @Desc
* @author CZP
* @Date 2018年10月31日 上午9:41:52
*/
@Controller("BnManagerRoleValueAction")
@RequestMapping(value="/manage/bnmanagerrolevalue")
public class BnManagerRoleValueAction extends BaseAction{
@Autowired
private IBnManagerRoleValueService bnManagerRoleValueService;
/**
*
* @Desc 信息列表
* @return
* @author CZP
*/
@RequestMapping("")
public String list(){
instantPage(20);
List<BnManagerRoleValue> list=bnManagerRoleValueService.getList();
int total=bnManagerRoleValueService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/bnmanagerrolevalue/bnmanagerrolevalue_list";
}
/**
*
* @Desc 跳转到新增页面
* @return
* @author CZP
*/
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addbnmanagerrolevalue(){
return "/WEB-INF/bnmanagerrolevalue/bnmanagerrolevalue_add";
}
/**
* @Desc 保存数据
* @param bnManagerRoleValue
* @return
* @throws Exception
* @author CZP
*/
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addAdpic(@ModelAttribute BnManagerRoleValue bnManagerRoleValue) throws Exception{
bnManagerRoleValueService.save(bnManagerRoleValue);
return "redirect:/manage/bnmanagerrolevalue.html";
}
/**
*
* @Desc 删除信息
* @param id
* @param response
* @return
* @author CZP
*/
@RequestMapping(value="/del/{id}")
public String deletebnmanagerrolevalue(@PathVariable("id")int id,HttpServletResponse response){
bnManagerRoleValueService.del(id);
return "redirect:/manage/bnmanagerrolevalue.html";
}
/**
* @Desc 修改信息
* @param bnManagerRoleValue
* @return
* @throws Exception
* @author CZP
*/
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updatebnmanagerrolevalue(BnManagerRoleValue bnManagerRoleValue)throws Exception{
bnManagerRoleValueService.edit(bnManagerRoleValue);
return "redirect:/manage/bnmanagerrolevalue.html";
}
/**
*
* @Desc 编辑前根据id获取信息
* @param id
* @return
* @author CZP
*/
@RequestMapping(value="/{id}")
public String viewbnmanagerrolevalue(@PathVariable("id")int id)
{
BnManagerRoleValue bnManagerRoleValue=bnManagerRoleValueService.get(id);
getRequest().setAttribute("bnManagerRoleValue",bnManagerRoleValue);
return "/WEB-INF/bnmanagerrolevalue/bnmanagerrolevalue_detail";
}
}
<file_sep>/src/com/lw/foodsetmealitemtype/service/impl/FoodSetMealItemTypeServiceImpl.java
package com.lw.foodsetmealitemtype.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.core.base.service.impl.BaseServiceImpl;
import com.lw.foodsetmealitemtype.entity.FoodSetMealItemType;
import com.lw.foodsetmealitemtype.persistence.FoodSetMealItemTypeMapper;
import com.lw.foodsetmealitemtype.service.IFoodSetMealItemTypeService;
@Service("FoodSetMealItemTypeServiceImpl")
@Transactional
public class FoodSetMealItemTypeServiceImpl extends BaseServiceImpl<FoodSetMealItemType> implements IFoodSetMealItemTypeService{
@Autowired
private FoodSetMealItemTypeMapper foodInfoTypeMapper;
}
<file_sep>/src/com/lw/cms/bnarticlealbums/service/impl/BnArticleAlbumsServiceImpl.java
/**
*
*/
package com.lw.cms.bnarticlealbums.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.cms.bnarticlealbums.entity.BnArticleAlbums;
import com.lw.cms.bnarticlealbums.persistence.BnArticleAlbumsMapper;
import com.lw.cms.bnarticlealbums.service.IBnArticleAlbumsService;
import com.lw.core.base.service.impl.BaseServiceImpl;
/**
* @Desc
* @author CZP
* @Date 2018年10月23日 下午3:02:38
*/
@Transactional
@Service("BnArticleAlbumsServiceImpl")
public class BnArticleAlbumsServiceImpl extends BaseServiceImpl<BnArticleAlbums> implements IBnArticleAlbumsService{
@Autowired
private BnArticleAlbumsMapper bnArticleAlbumsMapper;
}
<file_sep>/src/com/lw/foodsetmealitem/service/impl/FoodSetMealItemServiceImpl.java
package com.lw.foodsetmealitem.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.core.base.service.impl.BaseServiceImpl;
import com.lw.foodsetmealitem.entity.FoodSetMealItem;
import com.lw.foodsetmealitem.persistence.FoodSetMealItemMapper;
import com.lw.foodsetmealitem.service.IFoodSetMealItemService;
@Service("FoodSetMealItemServiceImpl")
@Transactional
public class FoodSetMealItemServiceImpl extends BaseServiceImpl<FoodSetMealItem> implements IFoodSetMealItemService{
@Autowired
private FoodSetMealItemMapper foodSetMealItemMapper;
}
<file_sep>/src/com/lw/redpackage/service/impl/UserRedPackageServiceImpl.java
package com.lw.redpackage.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.lw.core.base.service.impl.BaseServiceImpl;
import com.lw.redpackage.entity.RedPackage;
import com.lw.redpackage.entity.UserRedPackage;
import com.lw.redpackage.persistence.RedPackageMapper;
import com.lw.redpackage.persistence.UserRedPackageMapper;
import com.lw.redpackage.service.IUserRedPackageService;
@Service
public class UserRedPackageServiceImpl extends BaseServiceImpl<UserRedPackage> implements IUserRedPackageService {
// private Logger logger =
// LoggerFactory.getLogger(UserRedPacketServiceImpl.class);
@Autowired
private UserRedPackageMapper userRedPackageMapper;
@Autowired
private RedPackageMapper redPackageMapper;
// 失败
private static final int FAILED = 0;
@Override
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public int grapRedPacket(Long redPacketId, Long userId) {
// 获取红包信息
RedPackage redPacket = redPackageMapper.getRedPacket(redPacketId);
int leftRedPacket = redPacket.getStock();
// 当前小红包库存大于0
if (leftRedPacket > 0) {
redPackageMapper.decreaseRedPacket(redPacketId);
// logger.info("剩余Stock数量:{}", leftRedPacket);
// 生成抢红包信息
UserRedPackage userRedPacket = new UserRedPackage();
userRedPacket.setRedPacketId(redPacketId);
userRedPacket.setUserId(userId);
userRedPacket.setAmount(redPacket.getUnitAmount());
userRedPacket.setNote("redpacket- " + redPacketId);
// 插入抢红包信息
int result = userRedPackageMapper.grapRedPacket(userRedPacket);
return result;
}
// logger.info("没有红包啦.....剩余Stock数量:{}", leftRedPacket);
// 失败返回
return FAILED;
}
}
<file_sep>/src/com/lw/dingtalkmsg/entity/Dingtalkmsg.java
/**
*
*/
package com.lw.dingtalkmsg.entity;
import java.io.Serializable;
/**
* @author CZP
*
* 2018年7月31日
*/
public class Dingtalkmsg implements Serializable{
private int id;
private int errcode;
private String errmsg;
private String send_result;
private String invalid_user_id_list;
private String forbidden_user_id_list;
private String failed_user_id_list;
private String read_user_id_list;
private String unread_user_id_list;
private String invalid_dept_id_list;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getErrcode() {
return errcode;
}
public void setErrcode(int errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
public String getSend_result() {
return send_result;
}
public void setSend_result(String send_result) {
this.send_result = send_result;
}
public String getInvalid_user_id_list() {
return invalid_user_id_list;
}
public void setInvalid_user_id_list(String invalid_user_id_list) {
this.invalid_user_id_list = invalid_user_id_list;
}
public String getForbidden_user_id_list() {
return forbidden_user_id_list;
}
public void setForbidden_user_id_list(String forbidden_user_id_list) {
this.forbidden_user_id_list = forbidden_user_id_list;
}
public String getFailed_user_id_list() {
return failed_user_id_list;
}
public void setFailed_user_id_list(String failed_user_id_list) {
this.failed_user_id_list = failed_user_id_list;
}
public String getRead_user_id_list() {
return read_user_id_list;
}
public void setRead_user_id_list(String read_user_id_list) {
this.read_user_id_list = read_user_id_list;
}
public String getUnread_user_id_list() {
return unread_user_id_list;
}
public void setUnread_user_id_list(String unread_user_id_list) {
this.unread_user_id_list = unread_user_id_list;
}
public String getInvalid_dept_id_list() {
return invalid_dept_id_list;
}
public void setInvalid_dept_id_list(String invalid_dept_id_list) {
this.invalid_dept_id_list = invalid_dept_id_list;
}
}
<file_sep>/src/com/lw/cms/bnmanagerlog/service/IBnManagerLogService.java
/**
*
*/
package com.lw.cms.bnmanagerlog.service;
import com.lw.cms.bnmanagerlog.entity.BnManagerLog;
import com.lw.core.base.service.IBaseService;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:47:25
*/
public interface IBnManagerLogService extends IBaseService<BnManagerLog>{
}
<file_sep>/src/com/lw/traceabilitypoint/service/impl/TraceabilityPointServiceImpl.java
package com.lw.traceabilitypoint.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.core.base.service.impl.BaseServiceImpl;
import com.lw.traceabilitypoint.entity.TraceabilityPoint;
import com.lw.traceabilitypoint.persistence.TraceabilityPointMapper;
import com.lw.traceabilitypoint.service.ITraceabilityPointService;
@Service("TraceabilityPointServiceImpl")
@Transactional
public class TraceabilityPointServiceImpl extends BaseServiceImpl<TraceabilityPoint> implements ITraceabilityPointService{
@Autowired
private TraceabilityPointMapper traceabilityPointMapper;
}
<file_sep>/src/com/lw/cms/bnmanager/persistence/BnManagerMapper.java
/**
*
*/
package com.lw.cms.bnmanager.persistence;
import com.lw.cms.bnmanager.entity.BnManager;
import com.lw.core.base.persistence.BaseMapper;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:46:31
*/
public interface BnManagerMapper extends BaseMapper<BnManager>{
}
<file_sep>/src/com/lw/traceabilitypoint/action/TraceabilityPointAction.java
package com.lw.traceabilitypoint.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
import com.lw.traceabilitypoint.entity.TraceabilityPoint;
import com.lw.traceabilitypoint.service.ITraceabilityPointService;
@Controller("TraceabilityPointAction")
@RequestMapping(value="/traceabilitypoint")
public class TraceabilityPointAction extends BaseAction{
@Autowired
private ITraceabilityPointService traceabilityPointService;
//信息列表
@RequestMapping("")
public String list(){
instantPage(20);
List<TraceabilityPoint> list=traceabilityPointService.getList();
int total=traceabilityPointService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/traceabilitypoint/traceabilitypoint_list";
}
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addtraceabilitypoint(){
return "/WEB-INF/traceabilitypoint/traceabilitypoint_add";
}
//新增信息
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addtraceabilitypoint(TraceabilityPoint traceabilityPoint){
traceabilityPointService.save(traceabilityPoint);
return "redirect:/WEB-INF/traceabilitypoint.html";
}
//删除信息
@RequestMapping(value="/del/{id}")
public String deletetraceabilitypoint(@PathVariable("id")int id,HttpServletResponse response){
traceabilityPointService.del(id);
return "redirect:/WEB-INF/traceabilitypoint.html";
}
//修改信息
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updatetraceabilitypoint(TraceabilityPoint traceabilityPoint,HttpServletResponse response){
traceabilityPointService.edit(traceabilityPoint);
return "redirect:/WEB-INF/traceabilitypoint.html";
}
//编辑前根据id获取信息
@RequestMapping(value="/{id}")
public String viewtraceabilitypoint(@PathVariable("id")int id)
{
TraceabilityPoint traceabilityPoint=traceabilityPointService.get(id);
getRequest().setAttribute("traceabilityPoint",traceabilityPoint);
return "/WEB-INF/traceabilitypoint/traceabilitypoint_detail";
}
}
<file_sep>/src/com/lw/cms/bnlink/service/impl/BnLinkServiceImpl.java
/**
*
*/
package com.lw.cms.bnlink.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.cms.bnlink.entity.BnLink;
import com.lw.cms.bnlink.service.IBnLinkService;
import com.lw.core.base.service.impl.BaseServiceImpl;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:46:52
*/
@Transactional
@Service("BnLinkServiceImpl")
public class BnLinkServiceImpl extends BaseServiceImpl<BnLink> implements IBnLinkService{
}
<file_sep>/src/com/lw/yiminews/action/YimiNewsIndexAction.java
package com.lw.yiminews.action;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
import com.lw.yiminews.entity.YimiNews;
import com.lw.yiminews.service.IYimiNewsService;
@Controller("YimiNewsIndexAction")
@RequestMapping(value="/yiminewsindex")
@SuppressWarnings("all")
public class YimiNewsIndexAction extends BaseAction{
@Autowired
private IYimiNewsService yimiNewsService;
@RequestMapping(value="index")
public String listindex(){
Map map = new HashMap<>();
List<YimiNews> list=yimiNewsService.getList(map);
Pager pager=new Pager();
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/yiminews/yiminews_list";
}
@RequestMapping(value="company_news_brief")
public String list(){
instantPage(5);
Map map = new HashMap<>();
List<YimiNews> list=yimiNewsService.getList(map);
int total=yimiNewsService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/yiminews/company_news_brief";
}
@RequestMapping(value="/detail/{id}")
public String detailyiminews(@PathVariable("id")int id)
{
YimiNews yimiNews=yimiNewsService.get(id);
getRequest().setAttribute("yimiNews",yimiNews);
return "redirect:/yiminews";
}
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String edityiminews(HttpServletResponse response,YimiNews yimiNews)
{
yimiNewsService.edit(yimiNews);
return "redirect:/yiminews";
}
}
<file_sep>/src/com/lw/dingtalkmsg/action/DingtalkmsgAction.java
/**
*
*/
package com.lw.dingtalkmsg.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
import com.lw.dingtalkmsg.entity.Dingtalkmsg;
import com.lw.dingtalkmsg.service.IDingtalkmsgService;
/**
* @author CZP
*
* 2018年7月31日
*/
@Controller("DingtalkmsgAction")
@RequestMapping("dingtalkmsg")
public class DingtalkmsgAction extends BaseAction{
@Autowired
private IDingtalkmsgService dingtalkmsgService;
//信息列表
@RequestMapping("")
public String list(){
instantPage(20);
List<Dingtalkmsg> list=dingtalkmsgService.getList();
int total=dingtalkmsgService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/dingtalkmsg/dingtalkmsg_list";
}
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addDingtalkmsg(){
return "/WEB-INF/dingtalkmsg/dingtalkmsg_add";
}
//新增信息
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addDingtalkmsg(Dingtalkmsg dingtalkmsg){
dingtalkmsgService.save(dingtalkmsg);
return "redirect:dingtalkmsg.html";
}
//删除信息
@RequestMapping(value="/del/{id}")
public String deleteDingtalkmsg(@PathVariable("id")int id,HttpServletResponse response){
dingtalkmsgService.del(id);
return "redirect:dingtalkmsg.html";
}
//修改信息
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updateDingtalkmsg(Dingtalkmsg dingtalkmsg,HttpServletResponse response){
dingtalkmsgService.edit(dingtalkmsg);
return "redirect:dingtalkmsg.html";
}
//编辑前根据id获取信息
@RequestMapping(value="/{id}")
public String viewDingtalkmsg(@PathVariable("id")int id)
{
Dingtalkmsg dingtalkmsg=dingtalkmsgService.get(id);
getRequest().setAttribute("dingtalkmsg",dingtalkmsg);
return "/WEB-INF/dingtalkmsg/dingtalkmsg_detail";
}
}
<file_sep>/src/com/lw/foodsetmealitemtype/action/FoodSetMealItemTypeAction.java
package com.lw.foodsetmealitemtype.action;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
import com.lw.foodsetmealitemtype.entity.FoodSetMealItemType;
import com.lw.foodsetmealitemtype.service.IFoodSetMealItemTypeService;
@Controller("FoodSetMealItemTypeAction")
@RequestMapping(value="/manage/foodsetmealitemtype")
public class FoodSetMealItemTypeAction extends BaseAction{
@Autowired
private IFoodSetMealItemTypeService foodSetMealItemTypeService;
//信息列表
@RequestMapping("")
public String list(ModelMap map){
instantPage(20);
List<FoodSetMealItemType> list=foodSetMealItemTypeService.getList();
int total=foodSetMealItemTypeService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/foodsetmealitemtype/foodsetmealitemtype_list";
}
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addFoodSetMealItemType(){
return "/WEB-INF/foodsetmealitemtype/foodsetmealitemtype_add";
}
//新增信息
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addFoodSetMealItemType(FoodSetMealItemType foodSetMealItemType){
foodSetMealItemTypeService.save(foodSetMealItemType);
return "redirect:/manage/foodsetmealitemtype.html";
}
//删除信息
@RequestMapping(value="/del/{id}")
public String deleteFoodSetMealItemType(@PathVariable("id")int id,HttpServletResponse response){
foodSetMealItemTypeService.del(id);
return "redirect:/manage/foodsetmealitemtype.html";
}
//修改信息
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updateFoodSetMealItemType(FoodSetMealItemType FoodSetMealItemType, HttpServletResponse response){
foodSetMealItemTypeService.edit(FoodSetMealItemType);
return "redirect:/manage/foodsetmealitemtype.html";
}
//编辑前根据id获取信息
@RequestMapping(value="/{id}")
public String viewFoodSetMealItemType(@PathVariable("id")int id)
{
FoodSetMealItemType foodSetMealItemType=foodSetMealItemTypeService.get(id);
getRequest().setAttribute("foodSetMealItemType",foodSetMealItemType);
return "/WEB-INF/foodsetmealitemtype/foodsetmealitemtype_detail";
}
/**
* 新增前根据id获取信息
* @Desc
* @param id
* @return
* @author CZP
*/
@RequestMapping(value="/add/{id}")
public String add(@PathVariable("id")int id)
{
FoodSetMealItemType foodSetMealItemType=foodSetMealItemTypeService.get(id);
getRequest().setAttribute("foodSetMealItemType",foodSetMealItemType);
return "/WEB-INF/foodsetmealitemtype/foodsetmealitemtype_add";
}
}
<file_sep>/src/com/lw/traceabilitytype/entity/TraceabilityType.java
package com.lw.traceabilitytype.entity;
import java.io.Serializable;
public class TraceabilityType implements Serializable{
private int id;
private String name;
private int parent_id;
private Integer point_id;
private Integer type_id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getParent_id() {
return parent_id;
}
public void setParent_id(int parent_id) {
this.parent_id = parent_id;
}
public Integer getPoint_id() {
return point_id;
}
public void setPoint_id(Integer point_id) {
this.point_id = point_id;
}
public Integer getType_id() {
return type_id;
}
public void setType_id(Integer type_id) {
this.type_id = type_id;
}
}
<file_sep>/src/com/lw/cms/bnarticledownload/entity/BnArticleDownload.java
/**
*
*/
/**
* @Desc
* @author CZP
* @Date 2018年10月23日 下午4:04:30
*/
package com.lw.cms.bnarticledownload.entity;
import java.io.Serializable;
public class BnArticleDownload implements Serializable{
private int id;
private int ismsg;
private int isred;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getIsmsg() {
return ismsg;
}
public void setIsmsg(int ismsg) {
this.ismsg = ismsg;
}
public int getIsred() {
return isred;
}
public void setIsred(int isred) {
this.isred = isred;
}
}<file_sep>/src/com/lw/yiminews/action/YimiNewsAction.java
package com.lw.yiminews.action;
import com.lw.acommon.util.Upload;
import com.lw.adpic.entity.Adpic;
import com.lw.adpic.service.IAdpicService;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
import com.lw.yiminews.entity.YimiNews;
import com.lw.yiminews.service.IYimiNewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller("YimiNewsAction")
@RequestMapping(value="/yiminews")
@SuppressWarnings("all")
public class YimiNewsAction extends BaseAction{
@Autowired
private IYimiNewsService yimiNewsService;
@Autowired
private IAdpicService adpicService;
@RequestMapping(value="")
public String list(){
instantPage(20);
Map map = new HashMap<>();
List<YimiNews> list=yimiNewsService.getList(map);
int total=yimiNewsService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/yiminews/yiminews_list";
}
@RequestMapping(value="/company_news_brief")
public String brieflist(){
instantPage(5);
Map map = new HashMap<>();
List<YimiNews> list=yimiNewsService.getList(map);
int total=yimiNewsService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/yiminews/company_news_brief";
}
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addyiminews(){
return "/WEB-INF/yiminews/yiminews_add";
}
//新增信息
@RequestMapping(value="/post",method=RequestMethod.POST)
public String add(@ModelAttribute YimiNews news,@RequestParam(value="image") MultipartFile image,
HttpServletRequest request) throws Exception{
String img = Upload.upload(request, image,null);
news.setImg(img);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date=sdf.format(new Date());
news.setCreatime(date);
news.setContent(news.getContent().replace("\"", ""));
news.setTitle(news.getTitle().replace("\"", ""));
news.setSeoDescribe(news.getSeoDescribe().replace("\"", ""));
news.setSeoKeywords(news.getSeoKeywords().replace("\"", ""));
yimiNewsService.save(news);
return "redirect:/WEB-INF/yiminews.html";
}
//编辑前根据id获取信息
@RequestMapping(value="/{id}")
public String detailyiminews(@PathVariable("id")int id)
{
YimiNews yimiNews=yimiNewsService.get(id);
getRequest().setAttribute("yimiNews",yimiNews);
return "/WEB-INF/yiminews/yiminews_detail";
}
//修改信息
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String edityiminews(HttpServletRequest request,YimiNews yimiNews,
@RequestParam(value="image",required=false) MultipartFile image) throws Exception{
String img=null;
if(image!=null) {
img=Upload.upload(request, image,null);
yimiNews.setImg(img);
}
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date=sdf.format(new Date());
yimiNews.setUptime(date);
yimiNewsService.edit(yimiNews);
return "redirect:/WEB-INF/yiminews.html";
}
@RequestMapping(value="/del/{id}")
public String delyiminews(HttpServletResponse response,@PathVariable("id") int id)
{
yimiNewsService.del(id);
return "redirect:/WEB-INF/yiminews";
}
//官网首页
@RequestMapping(value="/index")
public String index(Model model) {
//图片新闻展示,1代表图片新闻,2代表文字新闻
int type=1;
Map map=new HashMap();
map.put("type", type);
List<YimiNews> imgList=yimiNewsService.getList(map);
model.addAttribute("imgList",imgList);
//上传轮播图,type为11
type=11;//官网首页轮播图
Map param=new HashMap();
param.put("type",type);
List<Adpic> list1=adpicService.getList(param);
model.addAttribute("bannerList",list1);
//上传二图,type为12
type=12;
Adpic list2=adpicService.getByType(type);
model.addAttribute("bannertwo",list2);
//官网首页智能点餐平台一图
type=13;
Adpic list3=adpicService.getByType(type);
model.addAttribute("one",list3);
//官网首页智能点餐平台二图
type=14;
Adpic list4=adpicService.getByType(type);
model.addAttribute("two",list4);
//官网首页智能点餐平台三图
type=15;
Adpic list5=adpicService.getByType(type);
model.addAttribute("three",list5);
return "/WEB-INF/yiminews/index";
}
@RequestMapping(value="/show/{id}")
public String show(@PathVariable("id")int id,Model model) {
YimiNews obj=yimiNewsService.get(id);
model.addAttribute("obj",obj);
return "/WEB-INF/yiminews/show";
}
@RequestMapping(value="/showlist")
public String showlist(Model model) {
instantPage(4);
Map map = new HashMap<>();
List<YimiNews> list=yimiNewsService.getList(map);
int total=yimiNewsService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/yiminews/showlist";
}
@RequestMapping(value="/about")
public String about() {
return "/WEB-INF/yiminews/about";
}
@RequestMapping(value="/head")
public String about1() {
return "/WEB-INF/yiminews/head";
}
@RequestMapping(value="/login")
public String login() {
return "/WEB-INF/yiminews/login";
}
}
<file_sep>/src/com/lw/kitcheninfo/entity/KitchenInfo.java
/**
*
*/
package com.lw.kitcheninfo.entity;
import java.io.Serializable;
import java.util.Date;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:42:58
*/
public class KitchenInfo implements Serializable{
private int id;
private String name;
private String address;
private String phone;
private String logo;
private String longitude;
private String latitude;
private String remark;
private String authorkey;
private String nick_name;
private String user_name;
private String password;
private boolean enable;
private String contacts;
private Date last_login_date;
private String last_login_ip;
private int status;
private Date regist_date;
private String regist_ip;
private String notice;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getAuthorkey() {
return authorkey;
}
public void setAuthorkey(String authorkey) {
this.authorkey = authorkey;
}
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getContacts() {
return contacts;
}
public void setContacts(String contacts) {
this.contacts = contacts;
}
public Date getLast_login_date() {
return last_login_date;
}
public void setLast_login_date(Date last_login_date) {
this.last_login_date = last_login_date;
}
public String getLast_login_ip() {
return last_login_ip;
}
public void setLast_login_ip(String last_login_ip) {
this.last_login_ip = last_login_ip;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getRegist_date() {
return regist_date;
}
public void setRegist_date(Date regist_date) {
this.regist_date = regist_date;
}
public String getRegist_ip() {
return regist_ip;
}
public void setRegist_ip(String regist_ip) {
this.regist_ip = regist_ip;
}
public String getNotice() {
return notice;
}
public void setNotice(String notice) {
this.notice = notice;
}
}<file_sep>/src/com/lw/cms/bnuserloginlog/persistence/BnUserLoginLogMapper.java
/**
*
*/
package com.lw.cms.bnuserloginlog.persistence;
import com.lw.cms.bnuserloginlog.entity.BnUserLoginLog;
import com.lw.core.base.persistence.BaseMapper;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:46:31
*/
public interface BnUserLoginLogMapper extends BaseMapper<BnUserLoginLog>{
}
<file_sep>/src/com/lw/tpartnerbasicinfo/service/impl/TPartnerBasicInfoServiceImpl.java
/**
*
*/
package com.lw.tpartnerbasicinfo.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.core.base.service.impl.BaseServiceImpl;
import com.lw.tpartnerbasicinfo.entity.TPartnerBasicInfo;
import com.lw.tpartnerbasicinfo.service.ITPartnerBasicInfoService;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:46:52
*/
@Transactional
@Service("TPartnerBasicInfoServiceImpl")
public class TPartnerBasicInfoServiceImpl extends BaseServiceImpl<TPartnerBasicInfo> implements ITPartnerBasicInfoService{
}
<file_sep>/src/com/lw/dingtalkmsg/service/impl/DingtalkmsgServiceImpl.java
/**
*
*/
package com.lw.dingtalkmsg.service.impl;
import com.lw.core.base.service.impl.BaseServiceImpl;
import com.lw.dingtalkmsg.entity.Dingtalkmsg;
import com.lw.dingtalkmsg.service.IDingtalkmsgService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author CZP
*
* 2018年7月31日
*/
@Service("DingtalkmsgServiceImpl")
@Transactional
public class DingtalkmsgServiceImpl extends BaseServiceImpl<Dingtalkmsg> implements IDingtalkmsgService{
}
<file_sep>/src/com/lw/aliyunmonitoossinfo/action/AliyunMonitoOssinfoAction.java
package com.lw.aliyunmonitoossinfo.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.aliyunmonitoossinfo.entity.AliyunMonitoOssinfo;
import com.lw.aliyunmonitoossinfo.service.IAliyunMonitoOssinfoService;
import com.lw.common.page.Pager;
import com.lw.core.base.action.BaseAction;
@Controller("AliyunMonitoOssinfoAction")
@RequestMapping(value="/aliyunmonitoossinfo")
public class AliyunMonitoOssinfoAction extends BaseAction{
@Autowired
private IAliyunMonitoOssinfoService aliyunMonitoOssinfoService;
//信息列表
@RequestMapping("")
public String list(){
instantPage(20);
List<AliyunMonitoOssinfo> list=aliyunMonitoOssinfoService.getList();
int total=aliyunMonitoOssinfoService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/aliyunmonitoossinfo/aliyunmonitoossinfo_list";
}
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addAliyunMonitoOssinfo(){
return "/WEB-INF/aliyunmonitoossinfo/aliyunmonitoossinfo_add";
}
//新增信息
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addAliyunMonitoOssinfo(AliyunMonitoOssinfo AliyunMonitoOssinfo){
aliyunMonitoOssinfoService.save(AliyunMonitoOssinfo);
return "redirect:/aliyunmonitoossinfo.html";
}
//删除信息
@RequestMapping(value="/del/{id}")
public String deleteAliyunMonitoOssinfo(@PathVariable("id")int id,HttpServletResponse response){
aliyunMonitoOssinfoService.del(id);
return "redirect:/aliyunmonitoossinfo.html";
}
//修改信息
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updateAliyunMonitoOssinfo(AliyunMonitoOssinfo AliyunMonitoOssinfo,HttpServletResponse response){
aliyunMonitoOssinfoService.edit(AliyunMonitoOssinfo);
return "redirect:/aliyunmonitoossinfo.html";
}
//编辑前根据id获取信息
@RequestMapping(value="/{id}")
public String viewAliyunMonitoOssinfo(@PathVariable("id")int id)
{
AliyunMonitoOssinfo aliyunmonitoossinfo=aliyunMonitoOssinfoService.get(id);
getRequest().setAttribute("aliyunmonitoossinfo",aliyunmonitoossinfo);
return "/WEB-INF/aliyunmonitoossinfo/aliyunmonitoossinfo_detail";
}
}
<file_sep>/src/com/lw/tpartnerbasicinfo/action/TPartnerBasicInfoAction.java
/**
*
*/
package com.lw.tpartnerbasicinfo.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lw.common.page.Pager;
import com.lw.common.util.qrcode.QrcodeUtil;
import com.lw.core.base.action.BaseAction;
import com.lw.tpartnerbasicinfo.entity.TPartnerBasicInfo;
import com.lw.tpartnerbasicinfo.service.ITPartnerBasicInfoService;
/**
* @Desc
* @author CZP
* @Date 2018年10月26日 上午9:41:52
*/
@Controller("TPartnerBasicInfoAction")
@RequestMapping(value="/manage/tpartnerbasicinfo")
public class TPartnerBasicInfoAction extends BaseAction{
@Autowired
private ITPartnerBasicInfoService tPartnerBasicInfoService;
/**
*
* @Desc 信息列表
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:25
*/
@RequestMapping("")
public String list(){
instantPage(20);
List<TPartnerBasicInfo> list=tPartnerBasicInfoService.getList();
int total=tPartnerBasicInfoService.getCount();
Pager pager=new Pager(super.getPage(),super.getRows(),total);
pager.setDatas(list);
getRequest().setAttribute("pager",pager);
return "/WEB-INF/tpartnerbasicinfo/tpartnerbasicinfo_list";
}
/**
*
* @Desc 跳转到新增页面
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:36
*/
@RequestMapping(value="/post",method=RequestMethod.GET)
public String addtpartnerbasicinfo(){
return "/WEB-INF/tpartnerbasicinfo/tpartnerbasicinfo_add";
}
/**
* @Desc 保存数据
* @param tPartnerBasicInfo
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:23
*/
@RequestMapping(value="/post",method=RequestMethod.POST)
public String addAdpic(@ModelAttribute TPartnerBasicInfo tPartnerBasicInfo) throws Exception{
tPartnerBasicInfoService.save(tPartnerBasicInfo);
return "redirect:/manage/tpartnerbasicinfo.html";
}
/**
*
* @Desc 删除信息
* @param id
* @param response
* @return
* @author CZP
* @Date 2018年10月24日 下午3:44:09
*/
@RequestMapping(value="/del/{id}")
public String deletetpartnerbasicinfo(@PathVariable("id")int id,HttpServletResponse response){
tPartnerBasicInfoService.del(id);
return "redirect:/manage/tpartnerbasicinfo.html";
}
/**
* @Desc 修改信息
* @param tPartnerBasicInfo
* @return
* @throws Exception
* @author CZP
* @Date 2018年10月24日 下午3:44:00
*/
@RequestMapping(value="/edit",method=RequestMethod.POST)
public String updatetpartnerbasicinfo(TPartnerBasicInfo tPartnerBasicInfo)throws Exception{
tPartnerBasicInfoService.edit(tPartnerBasicInfo);
return "redirect:/manage/tpartnerbasicinfo.html";
}
/**
*
* @Desc 编辑前根据id获取信息
* @param id
* @return
* @author CZP
* @Date 2018年10月24日 下午3:43:43
*/
@RequestMapping(value="/{id}")
public String viewtpartnerbasicinfo(@PathVariable("id")String id)
{
TPartnerBasicInfo tPartnerBasicInfo=tPartnerBasicInfoService.get(Integer.parseInt(id));
getRequest().setAttribute("tPartnerBasicInfo",tPartnerBasicInfo);
return "/WEB-INF/tpartnerbasicinfo/tpartnerbasicinfo_detail";
}
}
<file_sep>/src/com/lw/aliyunmonitoossinfo/service/impl/AliyunMonitoOssinfoServiceImpl.java
package com.lw.aliyunmonitoossinfo.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.aliyunmonitoossinfo.entity.AliyunMonitoOssinfo;
import com.lw.aliyunmonitoossinfo.service.IAliyunMonitoOssinfoService;
import com.lw.core.base.service.impl.BaseServiceImpl;
@Service("AliyunMonitoOssinfoServiceImpl")
@Transactional
public class AliyunMonitoOssinfoServiceImpl extends BaseServiceImpl<AliyunMonitoOssinfo> implements IAliyunMonitoOssinfoService{
}
| 0397369ae56901759b24277d22e6ee17963a7635 | [
"Java"
] | 65 | Java | DreamFlyC/yimi | 88eec8c3fad8542d4db05dd5d99879bd68eab068 | df5cdafad79e681629362eb35d3f093e22eafdda |
refs/heads/master | <repo_name>liangseven616/vim-config<file_sep>/build.sh
#!/usr/bin/env bash
curl -fLo ~/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
sudo cp -r .vimrc ~/.vimrc
sudo rm -rf ~/.vim
sudo cp -r .vim ~/.vim
curl -LO https://github.com/BurntSushi/ripgrep/releases/download/0.10.0/ripgrep_0.10.0_amd64.deb
sudo dpkg -i ripgrep_0.10.0_amd64.deb
source /etc/os-release
case $ID in
debian|ubuntu|devuan)
echo "Linux : $ID"
sudo apt install ctags global
sudo apt install nodejs
sudo apt install npm
sudo apt install yarn
sudo apt install clang-tools-8
;;
centos|fedora|rhel)
esac
sudo npm i -g bash-language-server
sudo vim -c "CocInstall coc-clangd" -c "q" -c "q"
sudo vim -c "PlugInstall" -c "q" -c "q"
<file_sep>/README.md
# vim-config
1 ,p -> 文件检索
2 c-] -> ctags 查询
3 c-o -> 返回
4 gd ->coc.nvim 找函数定义
5 ,s -> gtags 找标签定义
| 473453ac73bc5fa27e3f0e212e7e387587918cfe | [
"Markdown",
"Shell"
] | 2 | Shell | liangseven616/vim-config | 6ea60bbfb6c2b55390b016ca480b907164e7102b | 6b791b4f744f4f6892e549b10f38c9be6718ee14 |
refs/heads/master | <repo_name>alexvojd/areasTestTask<file_sep>/README.md
# areasTestTask
completed test task
<file_sep>/app/Http/Controllers/AreasListController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
//Radius of Earth in meteres
define('EARTH_RADIUS', 6372795);
class AreasListController extends Controller
{
public function showAreasList(Request $request)
{
$isFiltered=false;
$currArea = "";
$areas = include 'areas.php';
$areasInFilter = array_keys($areas);
asort($areasInFilter);
if (isset($request->area)){
$currArea = $request->area;
$lat1 = $areas[$currArea]['lat'];
$long1 = $areas[$currArea]['long'];
foreach($areas as $area => $coords){
$lat2 = $coords['lat'];
$long2 = $coords['long'];
$distance = $this->calculateTheDistance($lat1, $long1, $lat2, $long2);
$tempArr[$area] = $distance;
}
arsort($tempArr);
$areas = $tempArr;
$isFiltered = true;
}else{
ksort($areas);
}
return view('areaslist', compact('areas', 'isFiltered', 'currArea', 'areasInFilter'));
}
//calculate the distance between 2 points with Earth form as sphere
//returned value rounding to integer
public function calculateTheDistance(float $lat1, float $long1, float $lat2, float $long2): float
{
//coordinates to radians
$radlat1 = $lat1 * M_PI / 180;
$radlat2 = $lat2 * M_PI / 180;
$radlong1 = $long1 * M_PI / 180;
$radlong2 = $long2 * M_PI / 180;
// cos and sin of Latitudes
$coslat1 = cos($radlat1);
$coslat2 = cos($radlat2);
$sinlat1 = sin($radlat1);
$sinlat2 = sin($radlat2);
// Longitude difference
$delta = $radlong2 - $radlong1;
$cosdelta = cos($delta);
$sindelta = sin($delta);
$y = sqrt(pow($coslat2 * $sindelta, 2) + pow($coslat1 * $sinlat2 - $sinlat1 * $coslat2 * $cosdelta, 2));
$x = $sinlat1 * $sinlat2 + $coslat1 * $coslat2 * $cosdelta;
$ad = atan2($y,$x);
$dist = $ad * EARTH_RADIUS / 1000;
return round($dist);
}
}
| 840a1c07d241e490926438e1b6c3ceb9883e8a27 | [
"Markdown",
"PHP"
] | 2 | Markdown | alexvojd/areasTestTask | e5a4e6793043dac40738410a7df803b2ca8d318e | f1371c67350891c148ac6d1f43edf2f835010963 |
refs/heads/master | <file_sep><?php
/**
* The MeetingMinutes extension provides JS and CSS to enable recording meeting
* minutes in SMW. See README.md.
*
* Documentation: https://github.com/enterprisemediawiki/MeetingMinutes
* Support: https://github.com/enterprisemediawiki/MeetingMinutes
* Source code: https://github.com/enterprisemediawiki/MeetingMinutes
*
* @file MeetingMinutes.php
* @addtogroup Extensions
* @author <NAME>
* @copyright © 2014 by <NAME>
* @licence GNU GPL v3+
*/
# Not a valid entry point, skip unless MEDIAWIKI is defined
if ( ! defined( 'MEDIAWIKI' ) ) {
die( 'ParserFunctionHelper extension' );
}
$GLOBALS['wgExtensionCredits']['other'][] = array(
'path' => __FILE__,
'name' => 'Parser Function Helper',
'namemsg' => 'parserfunctionhelper-name',
'url' => 'http://github.com/jamesmontalvo3/ParserFunctionHelper.git',
'author' => '[https://www.mediawiki.org/wiki/User:Jamesmontalvo3 <NAME>]',
'descriptionmsg' => 'parserfunctionhelper-desc',
'version' => '0.1.0'
);
//
$GLOBALS['wgMessagesDirs']['ParserFunctionHelper'] = __DIR__ . '/i18n';
// Autoload
$GLOBALS['wgAutoloadClasses']['ParserFunctionHelper\Setup'] = __DIR__ . '/includes/Setup.php';
$GLOBALS['wgAutoloadClasses']['ParserFunctionHelper\ParserFunctionHelper'] = __DIR__ . '/includes/ParserFunctionHelper.php';
$GLOBALS['wgAutoloadClasses']['ParserFunctionHelper\DummyFunction'] = __DIR__ . '/tests/dummies/DummyFunction.php';
// Setup parser functions
$GLOBALS['wgHooks']['ParserFirstCallInit'][] = 'ParserFunctionHelper\Setup::setupParserFunctions';
// Unit testing
$GLOBALS['wgHooks']['UnitTestsList'][] = 'ParserFunctionHelper\Setup::onUnitTestsList';
// initialize as array
$egParserFunctionHelperClasses = array();
| 7f12e0ae352f9c4fe0f6e3aa95d8a82d64f81d3c | [
"PHP"
] | 1 | PHP | jamesmontalvo3/ParserFunctionHelper | 849c0d03cc56b6eaf890caff32dbe149f92eaa72 | 5df022246b11985dd6190ee0a30948d64bd0ed2f |
refs/heads/master | <file_sep># -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
#
# Copyright (c) 2014 <NAME>/sa (www.noviat.com). All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import xlwt
import time
from datetime import datetime
from openerp.osv import orm
from openerp.report import report_sxw
from openerp.addons.report_xls.report_xls import report_xls
from openerp.addons.report_xls.utils import rowcol_to_cell, _render
from openerp.tools.translate import translate, _
from openerp import pooler
import logging
_logger = logging.getLogger(__name__)
_ir_translation_name = 'chart_dre_line.xls'
class chart_dre_line_xls_parser(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(chart_dre_line_xls_parser, self).__init__(cr, uid, name, context=context)
move_obj = self.pool.get('chart_dre_line')
self.context = context
wanted_list = move_obj._report_xls_fields(cr, uid, context)
template_changes = move_obj._report_xls_template(cr, uid, context)
self.localcontext.update({
'datetime': datetime,
'wanted_list': wanted_list,
'template_changes': template_changes,
'_': self._,
})
def _(self, src):
lang = self.context.get('lang', 'pt_BR')
return translate(self.cr, _ir_translation_name, 'report', lang, src) or src
class chart_dre_line_xls(report_xls):
def __init__(self, name, table, rml=False, parser=False, header=True, store=False):
super(chart_dre_line_xls, self).__init__(name, table, rml, parser, header, store)
# Cell Styles
_xs = self.xls_styles
# header
rh_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rh_cell_style = xlwt.easyxf(rh_cell_format)
self.rh_cell_style_center = xlwt.easyxf(rh_cell_format + _xs['center'])
self.rh_cell_style_right = xlwt.easyxf(rh_cell_format + _xs['right'])
# lines
aml_cell_format = _xs['borders_all']
self.aml_cell_style = xlwt.easyxf(aml_cell_format)
self.aml_cell_style_center = xlwt.easyxf(aml_cell_format + _xs['center'])
self.aml_cell_style_date = xlwt.easyxf(aml_cell_format + _xs['left'], num_format_str=report_xls.date_format)
self.aml_cell_style_decimal = xlwt.easyxf(aml_cell_format + _xs['right'], num_format_str=report_xls.decimal_format)
# totals
rt_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rt_cell_style = xlwt.easyxf(rt_cell_format)
self.rt_cell_style_right = xlwt.easyxf(rt_cell_format + _xs['right'])
self.rt_cell_style_decimal = xlwt.easyxf(rt_cell_format + _xs['right'], num_format_str=report_xls.decimal_format)
# XLS Template
self.col_specs_template = {
'name': {
'header': [1, 42, 'text', _render(u"_('Descrição')")],
'lines': [1, 0, 'text', _render("line.name or ''")],
'totals': [1, 0, 'text', None]},
'code': {
'header': [1, 42, 'text', _render(u"_('Código')")],
'lines': [1, 0, 'text', _render("line.code or ''")],
'totals': [1, 0, 'text', None]},
'period': {
'header': [1, 12, 'text', _render(u"_('Período')")],
'lines': [1, 0, 'text', _render("line.period_id.code or line.period_id.name")],
'totals': [1, 0, 'text', None]},
'parent': {
'header': [1, 12, 'text', _render(u"_('Superior')")],
'lines': [1, 0, 'text', _render("line.parent_id.code or line.parent_id.name")],
'totals': [1, 0, 'text', None]},
'account': {
'header': [1, 36, 'text', _render(u"_('Conta')")],
'lines': [1, 0, 'text', _render("line.account_id.code or line.account_id.name or ''")],
'totals': [1, 0, 'text', None]},
'type': {
'header': [1, 36, 'text', _render(u"_('Tipo')")],
'lines': [1, 0, 'text', _render("line.type")],
'totals': [1, 0, 'text', None]},
'value': {
'header': [1, 18, 'text', _render(u"_('Valor')"), None, self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("line.value"), None, self.aml_cell_style_decimal],
'totals': [1, 0, 'text', None]},
'sum': {
'header': [1, 18, 'text', _render(u"_('Soma')"), None, self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("line.sum"), None, self.aml_cell_style_decimal],
'totals': [1, 0, 'text', None]},
}
def generate_xls_report(self, _p, _xs, data, objects, wb):
wanted_list = _p.wanted_list
self.col_specs_template.update(_p.template_changes)
_ = _p._
sum_pos = 'sum' in wanted_list and wanted_list.index('sum')
if not sum_pos:
raise orm.except_orm(_(u'Erro de Customização!'),
_(u"A coluna 'Soma' é um campo calculado e sua presença é obrigatória!"))
#report_name = objects[0]._description or objects[0]._name
report_name = _(u"DRE do Mês")
ws = wb.add_sheet(report_name[:31])
ws.panes_frozen = True
ws.remove_splits = True
ws.portrait = 0 # Landscape
ws.fit_width_to_pages = 1
row_pos = 0
# set print header/footer
ws.header_str = self.xls_headers['standard']
ws.footer_str = self.xls_footers['standard']
# Title
cell_style = xlwt.easyxf(_xs['xls_title'])
c_specs = [
('report_name', 1, 0, 'text', report_name),
]
row_data = self.xls_row_template(c_specs, ['report_name'])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
row_pos += 1
# Column headers
c_specs = map(lambda x: self.render(x, self.col_specs_template, 'header', render_space={'_': _p._}), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.rh_cell_style, set_column_size=True)
ws.set_horz_split_pos(row_pos)
# account move lines
for line in objects:
c_specs = map(lambda x: self.render(x, self.col_specs_template, 'lines'), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.aml_cell_style)
chart_dre_line_xls('report.chart_dre_line.xls',
'chart_dre_line',
parser=chart_dre_line_xls_parser)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<file_sep># -*- coding: utf-8 -*-
{
"name": "FlowCash",
"version": "0.0.10",
"author": "<NAME>",
"category": "Account",
"website": "http://evoluirinformatica.com.br",
"description": "",
'depends': ['l10n_br_account','report_xls',],
'js': [],
'init_xml': [],
'update_xml': [
'res_company_view.xml',
'account_flow_cash.xml',
'chart_dre_view.xml',
'wizard/create_flow_cash.xml',
'wizard/create_chart_dre.xml',
'report/chart_dre_xls.xml',
],
'demo_xml': [],
'test': [],
'installable': True,
'active': False,
}
<file_sep># -*- coding: utf-8 -*-
import logging
import time
from openerp.osv import fields, osv
from datetime import datetime, date, timedelta
_logger = logging.getLogger(__name__)
class create_flow_cash(osv.osv_memory):
"""
Create Flow Cash
"""
_name = "create.flow_cash"
_description = "Account flow cash"
_columns = {
'date_from': fields.date('Data Inicial', required=True),
'date_to': fields.date('Data Final', required=True),
'date_ger': fields.date('Data Geração'),
'comp_transf': fields.boolean(u'Computa Transferências'),
'target_move': fields.selection([('ok', 'Realizado'),
('pv', 'Previsto'),
('all', 'Realizado e Previsto')
], 'Filtro', required=True),
'journal_id': fields.many2one('account.journal', u'Diário',domain=['|',('type', '=', 'cash'),('type', '=', 'bank')]),
'sintetico': fields.boolean(u'Sintético'),
}
def _get_datefrom(self, cr, uid, ids, context=None):
dt_atual = datetime.today()
dt_new = dt_atual + timedelta(days=-30)
return dt_new.strftime('%Y-%m-%d')
def show_flow_cash(self, cr, uid, ids, context=None):
mod_obj = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
FCa_obj = self.pool.get('account.flow_cash')
today = datetime.today()
if context == None:
context = {}
[wizard] = self.browse(cr, uid, ids)
kwargs={}
if wizard.target_move=='ok':
DataIn = datetime.strptime(wizard.date_from,'%Y-%m-%d')
DataOut = today
kwargs['tipo'] = 'real'
elif wizard.target_move=='pv':
DataIn = today
DataOut = datetime.strptime(wizard.date_to,'%Y-%m-%d')
kwargs['tipo'] = 'prev'
else:
DataIn = datetime.strptime(wizard.date_from,'%Y-%m-%d')
DataOut = datetime.strptime(wizard.date_to,'%Y-%m-%d')
kwargs['tipo'] = 'all'
_logger.info('DataIn = '+str(DataIn))
_logger.info('DataOut = '+str(DataOut))
kwargs['transf'] = wizard.comp_transf
if wizard.journal_id:
kwargs['journal_id'] = wizard.journal_id.id
FlowCashId = FCa_obj.create_flow(cr,uid,DataIn,DataOut,context=context,**kwargs)
result = mod_obj.get_object_reference(cr, uid, 'account_flow_cash', 'action_flow_cash_line_tree')
_logger.info('ID1 = '+str(result))
id = result and result[1] or False
result = act_obj.read(cr, uid, [id], context=context)[0]
result['domain'] = "[('flowcash_id','=',"+str(FlowCashId)+")]"
_logger.info('ID2 = '+str(result))
return result
_defaults = {
'comp_transf': lambda *a: True,
'date_from': _get_datefrom,
'date_to': lambda *a: time.strftime('%Y-%m-%d'),
'date_ger': lambda *a: time.strftime('%Y-%m-%d'),
'target_move': lambda *a: 'all',
'comp_transf': lambda *a: False,
}
create_flow_cash()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<file_sep># -*- coding: utf-8 -*-
import logging
import time
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv
from datetime import datetime
_logger = logging.getLogger(__name__)
TYPE_STATUS = {
'ok': 'OK',
'pv': 'Prev',
'at': 'Atra'
}
TYPE_FILTRO = {
}
class account_flow_cash(osv.osv_memory):
"""
For Flow Cash
"""
_name = "account.flow_cash"
_description = "Account flow cash"
_columns = {
'date_from': fields.date('Data Inicial', readonly=True),
'date_to': fields.date('Data Final', readonly=True),
'date': fields.date('Data Emissão', readonly=True),
'linhas_ids' : fields.one2many('account.flow_cash.line','flowcash_id','Movimento',readonly=True),
'target_move': fields.selection([('all', 'Realizado + Previsto'),
('real', 'Realizado'),
('prev', 'Previsto')
], 'Filtro', required=True,readonly=True),
}
def create_flow(self, cr, uid, DataIn, DataOut, context=None, **kwargs):
_logger.info('Gerando Fluxo de Caixa de '+str(DataIn)+' até '+str(DataOut)+' '+str(kwargs))
if context == None:
context = {}
sintetico = False
account_analitic_id = False
journal_id = False
account_id = False
account_cd = False
tipo = 'all'
transf = False
SaldoAnterior = 0
if kwargs:
if 'transf' in kwargs:
transf = kwargs['transf']
if 'tipo' in kwargs:
tipo = kwargs['tipo']
if 'sintetico' in kwargs:
sintetico = kwargs['sintetico']
if 'account_analitic_id' in kwargs:
account_analitic_id = kwargs['account_analitic_id']
if 'journal_id' in kwargs:
journal_id = kwargs['journal_id']
journal = self.pool.get('account.journal').browse(cr,uid,journal_id,context=None)
account_id = journal.default_debit_account_id.id
account_cd = journal.default_debit_account_id.code
tipo = 'real'
_logger.info('DataIn = '+str(DataIn))
_logger.info('DataOut = '+str(DataOut))
hoje = datetime.today()
dFlow = {
'date_from': DataIn,
'date_to': DataOut,
'date': hoje,
'target_move': tipo,
}
_logger.info('SQL = '+str(dFlow))
FlowCash = self.pool.get('account.flow_cash')
FlowCashLine = self.pool.get('account.flow_cash.line')
idFlowCash = FlowCash.create(cr,uid,dFlow,context)
AccMoveLine = self.pool.get('account.move.line')
sql = "SELECT a.account_id as id, sum(a.credit) as vlcred, sum(a.debit) as vldebit " \
"FROM account_move_line a " \
"JOIN account_account b ON a.account_id = b.id " \
"WHERE CAST(date AS DATE) < '%s'" % datetime.strftime(DataIn,'%Y-%m-%d')+" " \
"AND b.type = 'liquidity' "\
"GROUP BY a.account_id"
#"AND b.code similar to '(1.01.01.)%'"
_logger.info('SQL = {'+sql+'}')
cr.execute(sql)
# res = cr.fetchone()
#
# vlCred = float(res[0] or 0)
# vlDeb = float(res[1] or 0)
vlCred = float(0)
vlDeb = float(0)
vlAcumCr = float(0)
vlAcumDb = float(0)
for r in cr.fetchall():
if account_id:
if int(account_id) == int(r[0]):
vlCred += float(r[1] or 0)
vlDeb += float(r[2] or 0)
_logger.info("Somado no filtro vlCred += "+str(r[1] or 0)+" & vlDeb += "+str(r[2] or 0))
else:
vlCred += float(r[1] or 0)
vlDeb += float(r[2] or 0)
_logger.info("Somado no total vlCred += "+str(r[1] or 0)+" & vlDeb += "+str(r[2] or 0))
_logger.info('Creditos/Debitos = '+str(vlCred)+' / '+str(vlDeb))
vlAcum = vlDeb - vlCred
# if journal_id:
# if account_cd == '1.01.01.02.003':
# vlAcum = vlDeb - (vlCred + 5116.06)
# elif account_cd == '1.01.01.02.004':
# vlAcum = vlDeb - (vlCred + (-11431.33))
# elif account_cd == '1.01.01.02.005':
# vlAcum = vlDeb - (vlCred + 688,24)
# elif account_cd == '1.01.01.02.006':
# vlAcum = vlDeb - (vlCred + 805.95)
# elif account_cd == '1.01.01.02.007':
# vlAcum = vlDeb - (vlCred + 192.81)
# else:
# vlAcum = vlDeb - (vlCred + 4628.27)
dLineFlow = {
'name': 'Saldo Anterior',
'flowcash_id': idFlowCash,
'seq': 0,
'date': DataIn,
'val_sum': vlAcum,
}
LineFlowId = FlowCashLine.create(cr,uid,dLineFlow,context)
Seq = 1
vlSaldo = 0
dtFinal = False
if tipo=='all' or tipo=='real':
_logger.info('realizado: '+tipo) # if journal_id:sql = sql + " AND a.journal_id = %d" % (journal_id,)
#MoveLineIds = AccMoveLine.search(cr, uid, [('date', '>=', DataIn), ('date', '<=', DataOut),('account_id.name', '=like', '%s%%' % '1.01.01.'),], order='date,id')
if account_id:
MoveLineIds = AccMoveLine.search(cr, uid, [('date', '>=', DataIn), ('date', '<=', DataOut),('account_id','=',account_id)], order='date,id')
else:
MoveLineIds = AccMoveLine.search(cr, uid, [('date', '>=', DataIn), ('date', '<=', DataOut),('account_id.type','=','liquidity'),], order='date,id')
for MoveLine in AccMoveLine.browse(cr, uid, MoveLineIds, context):
computa = True
if transf == False:
cre = MoveLine.credit
deb = MoveLine.debit
CPartidaIds = AccMoveLine.search(cr, uid,[('move_id', '=', MoveLine.move_id.id),
('id', '<>', MoveLine.id),
('account_id.type','=','liquidity'),
('credit','=',deb),
('debit','=',cre)],order='date')
if CPartidaIds:
computa = False
if computa:
if MoveLine.credit:
vlCredito = MoveLine.credit
else:
vlCredito = 0
if MoveLine.debit:
vlDebito = MoveLine.debit
else:
vlDebito = 0
vlAcumCr = vlAcumCr + vlCredito
vlAcumDb = vlAcumDb + vlDebito
vlSaldo = vlDebito - vlCredito
vlAcum = vlAcum + vlSaldo
name = MoveLine.ref or MoveLine.name or ''
if MoveLine.partner_id:
if name: name = name + ", "
name = name + MoveLine.partner_id.name
dLineFlow = {
'name': name,
'flowcash_id': idFlowCash,
'seq': Seq,
'date': MoveLine.date,
'val_in': vlDebito,
'val_out': vlCredito,
'val_add': vlSaldo,
'val_sum': vlAcum,
'state': 'ok'
}
LineFlowId = FlowCashLine.create(cr,uid,dLineFlow,context)
Seq = Seq + 1
dtFinal = MoveLine.date
if tipo=='all' or tipo=='prev':
_logger.info('previsto')
#MoveLineIds = AccMoveLine.search(cr, uid, [('date_maturity','<>',False),('date_maturity', '<=', DataOut),('account_id.type', 'in', ['receivable', 'payable']),('reconcile_id', '=', False),], order='date_maturity,id')
MoveLineIds = AccMoveLine.search(cr, uid, [('date_maturity','<>',False),('date_maturity', '<=', DataOut),('account_id.type', 'in', ['receivable', 'payable']),('reconcile_id', '=', False),], order='date_maturity,id')
for MoveLine in AccMoveLine.browse(cr, uid, MoveLineIds, context):
if datetime.strptime(MoveLine.date_maturity,'%Y-%m-%d') < datetime.today():
#DateDue = datetime.today()
DateDue = datetime.strptime(MoveLine.date_maturity,'%Y-%m-%d')
_logger.info(str(DateDue))
Status = 'at'
else:
DateDue = datetime.strptime(MoveLine.date_maturity,'%Y-%m-%d')
Status = 'pv'
if MoveLine.credit > 0:
vlCredito = MoveLine.amount_to_pay
else:
vlCredito = 0
if MoveLine.debit > 0:
vlDebito = MoveLine.amount_to_pay * (-1)
else:
vlDebito = 0
vlAcumCr = vlAcumCr + vlCredito
vlAcumDb = vlAcumDb + vlDebito
vlSaldo = vlDebito - vlCredito
vlAcum = vlAcum + vlSaldo
name = MoveLine.ref or MoveLine.name or ''
if MoveLine.partner_id:
if name: name = name + ", "
name = name + MoveLine.partner_id.name
dLineFlow = {
'name': name,
'flowcash_id': idFlowCash,
'seq': Seq,
'date': DateDue,
'val_in': vlDebito,
'val_out': vlCredito,
'val_add': vlSaldo,
'val_sum': vlAcum,
'state': Status,
}
LineFlowId = FlowCashLine.create(cr,uid,dLineFlow,context)
Seq = Seq + 1
dtFinal = DateDue
if dtFinal:
dLineFlow = {
'name': 'Saldo Final',
'flowcash_id': idFlowCash,
'seq': Seq,
#'date': dtFinal,
'val_in': vlAcumDb,
'val_out': vlAcumCr,
'val_sum': vlAcum,
}
LineFlowId = FlowCashLine.create(cr,uid,dLineFlow,context)
return idFlowCash
account_flow_cash()
class account_flow_cash_line(osv.osv_memory):
"""
For Flow Cash
"""
_name = "account.flow_cash.line"
_description = "Account flow cash line"
_order = "seq asc, id asc"
_columns = {
'name': fields.char(u'Descrição', size=64),
'flowcash_id': fields.many2one('account.flow_cash',u'Fluxo de Caixa'),
'seq': fields.integer(u'Sq'),
'date': fields.date(u'Data'),
'val_in': fields.float(u'Entradas', digits_compute=dp.get_precision('Account')),
'val_out': fields.float(u'Saídas', digits_compute=dp.get_precision('Account')),
'val_add': fields.float(u'Saldo', digits_compute=dp.get_precision('Account')),
'val_sum': fields.float(u'Acumulado', digits_compute=dp.get_precision('Account')),
'state': fields.selection([
('ok','OK'),
('pv','Prev'),
('at','Atra'),
],'St', select=True,),
'journal_id': fields.many2one('account.journal', u'Diário',domain=['|',('type', '=', 'cash'),('type', '=', 'bank')]),
'analytic_account_id': fields.many2one('account.analytic.account', u'Conta Analítica',),
'sintetico': fields.boolean(u'Sintético'),
}
_defaults = {
#'date': lambda *a: time.strftime('%Y-%m-%d'),
#'val_in': lambda *a: 0,
#'val_out': lambda *a: 0,
#'val_add': lambda *a: 0,
#'val_sum': lambda *a: 0,
}
account_flow_cash_line()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<file_sep># -*- coding: utf-8 -*-
import logging
import time
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv
from datetime import datetime
from unittest import result
_logger = logging.getLogger(__name__)
def conta_dot(texto):
i = 0
for caracter in texto:
if caracter == '.':
i = i + 1
_logger.info('caracter = {'+str(caracter)+'}')
return i
class chart_dre(osv.osv):
_name="chart_dre"
_description= u"DRE Extraído do fluxo de caixa"
_columns={
'date': fields.date(u'Data Geração', required=True, readonly=True),
'period_id': fields.many2one('account.period', u'Período', required=True, readonly=True),
'linhas_ids': fields.one2many('chart_dre_line','chart_id',u'Linhas do Gráfico', readonly=True),
}
_defaults = {
'date': lambda *a: time.strftime('%Y-%m-%d'),
}
def cria_dre(self, cr, uid, id_chart, id_periodo):
context = {}
dre = self.browse(cr, uid, id)
obj_dre_line = self.pool.get('chart_dre_line')
obj_account = self.pool.get('account.account')
objPeriodo = self.pool.get('account.period')
objContaTipo = self.pool.get('account.account.type')
objAcMoveLine = self.pool.get('account.move.line')
objPartner = self.pool.get('res.partner')
objCompany = self.pool.get('res.company')
company_id = self.pool.get('res.users').browse(cr, uid, uid, context).company_id.id
bwCompany = objCompany.browse(cr,uid,company_id)
Periodo = objPeriodo.browse(cr,uid,id_periodo)
DataIn = datetime.strptime(Periodo.date_start,'%Y-%m-%d')
DataOut = datetime.strptime(Periodo.date_stop,'%Y-%m-%d')
#_logger.info('Data Inicio = {'+datetime.strftime(DataIn,'%Y-%m-%d')+'} Data Fim = {'+datetime.strftime(DataOut,'%Y-%m-%d')+'}')
#sql = "delete from account_chart_flow_cash where period_id = %s" % str(id_periodo)
sql = "delete from chart_dre_line"
#_logger.info('Delete SQL = {'+sql+'}')
cr.execute(sql)
sql = "delete from chart_dre where id <> %s" % id_chart
#_logger.info('Delete SQL = {'+sql+'}')
cr.execute(sql)
sql = "select id, code, name, parent_id, type, user_type from account_account "\
" where code like '%s' and company_id = %s order by code" % ('3%',str(company_id))
cr.execute(sql)
for rcAccount in cr.fetchall():
vlAcum = 0.0
CtTipo = False
ContaTipo = objContaTipo.browse(cr, uid, rcAccount[5], context).code
if ContaTipo in ['view','income','expense']:
if ContaTipo == 'income':
CtTipo = 'receita'
elif ContaTipo == 'expense':
CtTipo = 'despesa'
elif ContaTipo == 'view':
CtTipo = 'total'
cdParentAccount = obj_account.browse(cr, uid, rcAccount[0], context).parent_id.code
parentid = False
if cdParentAccount:
shIds = obj_dre_line.search(cr, uid,[('code','=',cdParentAccount)])
if shIds:
parentid = shIds[0]
linha = {
'chart_id': id_chart,
'account_id': rcAccount[0],
'code': rcAccount[1],
'name': rcAccount[2],
'period_id': id_periodo,
'parent_id': parentid,
'chart': CtTipo,
'type': 'synthetic',
'value': 0,
}
line_id = obj_dre_line.create(cr,uid,linha,context)
sql1 = "SELECT a.id, a.move_id FROM account_move_line a " + \
"JOIN account_account b ON a.account_id = b.id " + \
"WHERE CAST(a.date AS DATE) >= '%s'" % datetime.strftime(DataIn,'%Y-%m-%d') + \
" and CAST(a.date AS DATE) <= '%s'" % datetime.strftime(DataOut,'%Y-%m-%d') + \
" and b.type = 'liquidity' order by a.date, a.id"
_logger.info(sql1)
cr.execute(sql1)
for mvLiq in cr.fetchall():
lancado = False
_logger.info(str(mvLiq))
sql2 = "select id, date, account_id, name, partner_id, credit, debit, reconcile_id, move_id from account_move_line " + \
"where move_id = %s " % str(mvLiq[1]) + \
" and id <> %s " % str(mvLiq[0]) + \
" order by date, id"
_logger.info(sql2)
cr.execute(sql2)
for mvCP in cr.fetchall():
account = obj_account.browse(cr,uid,mvCP[2],context)
if account.type == 'liquidity':
lancado = True
else:
vlSaldo = float(mvCP[5])-float(mvCP[6])
descricao = '> Em '+str(mvCP[1])
if mvCP[3]:
descricao = descricao + ', '+mvCP[3]
Partner = objPartner.browse(cr,uid,mvCP[4],context)
if Partner:
descricao = descricao + ', parceiro '+Partner.name
descricao = descricao + ' ['+str(mvCP[0])+']'
sql3 = "select id, parent_id from chart_dre_line where chart_id = %s and " % id_chart + \
"account_id = '%s'" % mvCP[2]
cr.execute(sql3)
cl = cr.fetchone()
if cl:
lancado = False
lanca = {
'chart_id': id_chart,
'account_id': False,
'code': str(account.code)+'-%03d' % int(mvCP[0]),
'name': descricao,
'period_id': id_periodo,
'parent_id': cl[0],
'type': 'lancamento',
'value': vlSaldo,
}
_logger.info("Direto: "+str(lanca))
obj_dre_line.create(cr,uid,lanca,context)
lancado = True
else:
if mvCP[7]:
sql3 = "select account_id from account_move_line where move_id = (" + \
"select b.move_id from account_move_line a " + \
"join account_move_line b " + \
"on a.reconcile_id = b.reconcile_id " + \
"where a.id <> b.id and a.id = %s)" % mvCP[0]
_logger.info("SQL3: "+str(sql3))
cr.execute(sql3)
for y in cr.fetchall():
sql4 = "select id, parent_id from chart_dre_line where chart_id = %s and " % id_chart + \
"account_id = '%s'" % y[0]
_logger.info("SQL4: "+str(sql4))
cr.execute(sql4)
cx = cr.fetchone()
if cx:
account2 = obj_account.browse(cr,uid,y[0],context)
lanca = {
'chart_id': id_chart,
'account_id': False,
'code': str(account2.code)+'-%03d' % int(mvCP[0]),
'name': descricao,
'period_id': id_periodo,
'parent_id': cx[0],
'type': 'lancamento',
'value': vlSaldo,
}
_logger.info("Lanca Reconcile: "+str(lanca))
obj_dre_line.create(cr,uid,lanca,context)
lancado = True
break
if not lancado:
account = obj_account.browse(cr,uid,mvCP[2],context)
if vlSaldo > 0:
nw_account_id = bwCompany.account_revenue_id.id
else:
nw_account_id = bwCompany.account_expense_id.id
sql4 = "select id, parent_id from chart_dre_line where chart_id = %s and " % id_chart + \
"account_id = '%s'" % nw_account_id
_logger.info("SQL4: "+str(sql4))
cr.execute(sql4)
cx = cr.fetchone()
if cx:
account2 = obj_account.browse(cr,uid,nw_account_id,context)
lanca = {
'chart_id': id_chart,
'account_id': False,
'code': str(account2.code)+' -%03d' % int(mvCP[0]),
'name': '['+account.code + '] '+descricao,
'period_id': id_periodo,
'parent_id': cx[0],
'type': 'lancamento',
'value': vlSaldo,
}
obj_dre_line.create(cr,uid,lanca,context)
else:
lanca = {
'chart_id': id_chart,
'account_id': False,
'code': '9.' + str(account.code)+'-%03d' % int(mvCP[0]),
'name': descricao,
'period_id': id_periodo,
'parent_id': False,
'type': 'lancamento',
'value': vlSaldo,
}
obj_dre_line.create(cr,uid,lanca,context)
chart_dre()
class chart_dre_line(osv.osv):
_name="chart_dre_line"
_description= u"Linhas do DRE Extraído do fluxo de caixa"
_order = "code,id"
# override list in custom module to add/drop columns or change order
def _report_xls_fields(self, cr, uid, context=None):
return [
'period', 'code', 'name', 'sum',
]
# Change/Add Template entries
def _report_xls_template(self, cr, uid, context=None):
"""
Template updates, e.g.
my_change = {
'move':{
'header': [1, 20, 'text', _('My Move Title')],
'lines': [1, 0, 'text', _render("line.move_id.name or ''")],
'totals': [1, 0, 'text', None]},
}
return my_change
"""
return {}
def _get_child_ids(self, cr, uid, ids, field_name, arg, context=None):
result = {}
for rcLine in self.browse(cr, uid, ids, context=context):
if rcLine.child_parent_ids:
result[rcLine.id] = [x.id for x in rcLine.child_parent_ids]
else:
result[rcLine.id] = []
return result
def _sum_child(self, cr, uid, ids, context=None):
if not context:
context = {}
res = 0.0;
for i in ids:
Dreline = self.browse(cr, uid, i.id, context=context)
if Dreline.type == 'synthetic':
res = res + self._sum_child(cr, uid, Dreline.child_parent_ids, context)
else:
if Dreline.value:
res = res + float(Dreline.value)
return res
def __compute(self, cr, uid, ids, field_names, arg=None, context=None):
res = {}
for id in ids:
chartdreline = self.browse(cr, uid, id, context=context)
if chartdreline.type == 'analytic' or chartdreline.type == 'lancamento':
res[id] = chartdreline.value
else:
res[id] = self._sum_child(cr, uid, chartdreline.child_parent_ids, context)
return res
_columns={
'name': fields.char(u'Descrição', size=256, required=True, select=True),
'code': fields.char(u'Código', size=64, required=True, select=1),
'parent_id': fields.many2one('chart_dre_line', 'Parent', ondelete='cascade'),
'period_id': fields.many2one('account.period', u'Período', required=True),
'account_id': fields.many2one('account.account', 'Account'),
'child_parent_ids': fields.one2many('chart_dre_line','parent_id','Children'),
'child_id': fields.function(_get_child_ids, type='many2many', relation="chart_dre_line", string="Child Accounts"),
'chart_id': fields.many2one('chart_dre', 'chart_flow_cash'),
'type': fields.selection([
('synthetic', u'Sintética'),
('analytic', u'Analítica'),
('other', 'Outra'),
('lancamento', u'Lançamento')], 'Tipo'),
'chart': fields.selection([
('despesa', u'Despesa'),
('receita', u'Receita'),
('total', u'Totalização'),], u'Valorização'),
'value': fields.float(u'Valor', digits_compute=dp.get_precision('Account')),
'sum': fields.function(__compute, type='float',),
}
chart_dre_line()
<file_sep># -*- coding: utf-8 -*-
import logging
import time
from openerp.osv import fields, osv
#from datetime import datetime, date, timedelta
_logger = logging.getLogger(__name__)
class wiz_create_chart_dre(osv.osv_memory):
"""
Assitente para criar o DRE do período
"""
_name = "wiz.create.chart_dre"
_description = ""
_columns = {
'date_ger': fields.date(u'Data Geração'),
'period_from': fields.many2one('account.period', u'Período', required=True),
}
def action_wiz_create_chart_dre(self, cr, uid, ids, context=None):
_logger.info(self._name)
if context == None:
context = {}
[wizard] = self.browse(cr, uid, ids)
mod_obj = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
objChartDRE = self.pool.get('chart_dre')
chart = {
'date': time.strftime('%Y-%m-%d'),
'period_id': wizard.period_from.id,
}
_logger.info(u'Cria Chart: '+str(chart))
idChartDRE = objChartDRE.create(cr,uid,chart,context=None)
#ChartFlowCash = objChartFlowCash.browse(cr,uid,id_ChartFlowCash,context)
objChartDRE.cria_dre(cr,uid,idChartDRE,wizard.period_from.id)
result = mod_obj.get_object_reference(cr, uid, 'account_flow_cash', 'action_chart_dre_line')
_logger.info('ID1 = '+str(result))
id = result and result[1] or False
result = act_obj.read(cr, uid, [id], context=context)[0]
result['domain'] = "[('chart_id','=',"+str(idChartDRE)+")]"
_logger.info('ID2 = '+str(result))
return result
_defaults = {
'date_ger': lambda *a: time.strftime('%Y-%m-%d'),
}
wiz_create_chart_dre()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<file_sep>from openerp.osv import osv, fields
class res_company(osv.osv):
_inherit = 'res.company'
_columns = {
'account_expense_id': fields.many2one('account.account', u'Conta Despesa Padrao',domain="[('type','=','other'),('user_type.code','=','expense')]"),
'account_revenue_id': fields.many2one('account.account', u'Conta Receita Padrao',domain="[('type','=','other'),('user_type.code','=','income')]"),
}
res_company()<file_sep># -*- coding: utf-8 -*-
try:
import res_company
import account_flow_cash
import chart_dre
import wizard
import report
except ImportError:
import logging
logging.getLogger('openerp.module').warning('report_xls not available in addons path. account_financial_report_webkit_xls will not be usable')
| 6b46432c859bbec6a632f8b2d2f346cfaa59509b | [
"Python"
] | 8 | Python | fadeldamen/fluxocaixa | 92f909177f72ead86d4d9b2482986d70f5c230b6 | b0275a585e8c8ea847f20834e691b06510a6c3e4 |
refs/heads/master | <file_sep>// (C) 2016 Mesomorphic Ltd
#include "Towers.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Towers, "Towers" );
<file_sep>[/Script/EngineSettings.GeneralProjectSettings]
ProjectID=4BBF968F48EDD873296061870ED2C72D
CompanyName=Mesomorphic Ltd
Description=Tower Defense - Darkness is the enemy
ProjectName=Nightlands
CopyrightNotice=(C) 2016 Mesomorphic Ltd
<file_sep>// (C) 2016 Mesomorphic Ltd
#pragma once
#include "Components/StaticMeshComponent.h"
#include "Tower_Turret.generated.h"
class UTower_Barrel;
UCLASS(meta = (BlueprintSpawnableComponent))
class TOWERS_API UTower_Turret : public UStaticMeshComponent
{
GENERATED_BODY()
public:
void SetBarrelReference(UTower_Barrel* BarrelToSet);
private:
UTower_Barrel* Barrel = nullptr;
};
<file_sep>// (C) 2016 Mesomorphic Ltd
#pragma once
#include "Engine.h"
<file_sep>// (C) 2016 Mesomorphic Ltd
#include "Towers.h"
#include "SpawnActor.h"
#include "MonsterActor.h"
#include "LevelController.h"
// Sets default values
ASpawnActor::ASpawnActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void ASpawnActor::BeginPlay()
{
Super::BeginPlay();
}
AMonsterActor* ASpawnActor::SpawnMonster()
{
// boring, single monster, once per second (configurable)
AMonsterActor* NewMonster = GetWorld()->SpawnActor<AMonsterActor>( MonsterBlueprint
, GetActorLocation() // TODO - Have this based on Spawner's blueprint pivots
, GetActorRotation()
);
NewMonster->SetTarget(Exit);
if (!Controller) { UE_LOG(LogTemp, Error, TEXT("No controller provided to generator : "), *GetName()) }
else
{ Controller->RegisterMonster(NewMonster);
}
return NewMonster;
}
void ASpawnActor::SpawnWave()
{
if (!Exit) { UE_LOG(LogTemp, Warning, TEXT("ASpawnActor::SpawnWave - No exit spefied for generator: %s"), *GetName()) }
else
{ SpawnMonster();
}
}
// Called every frame
void ASpawnActor::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
if ((LastSpawnTime > SpawnRate) & (NumSpawned < MaxSpawn))
{
SpawnWave();
LastSpawnTime = 0;
NumSpawned++;
}
LastSpawnTime += DeltaTime;
}<file_sep>// (C) 2016 Mesomorphic Ltd
#include "Towers.h"
#include "LevelController.h"
#include "MonsterActor.h"
#include "TowerActor.h"
// LevelController is responsible for:
// - Removing dead monsters
// - Starting/Stopping generators
// - Instructing towers to attack
// Sets default values
ALevelController::ALevelController()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
void ALevelController::SpawnTowers()
{
int i;
for (i=0; i < 3; i++)
{
auto Location = FVector(100*i, 0, 0);
Towers.Add(GetWorld()->SpawnActor<ATowerActor>(TowerBlueprint, Location, FRotator(0)));
Towers[i]->Controller = this;
}
}
// Called when the game starts or when spawned
void ALevelController::BeginPlay()
{
Super::BeginPlay();
SpawnTowers();
}
// Called every frame
void ALevelController::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
for (ATowerActor* Tower : Towers)
{
// UE_LOG(LogTemp, Warning, TEXT("Tower iterator : %s"), *Tower->GetName())
if (!Tower->HasTarget() && (Monsters.Num() > 0))
{ Tower->SetTarget(Monsters[0]);
}
Tower->HurtTarget();
}
}
void ALevelController::RegisterMonster(AMonsterActor* Monster)
{
Monster->Controller = this;
Monsters.Add(Monster);
}
void ALevelController::RemoveMonsterFromGame(AMonsterActor* Monster)
{
// stop any towers that were aiming at it
for (ATowerActor* Tower : Towers)
{
if (Tower->IsTarget(Monster))
{ Tower->SetTarget(nullptr);
}
}
Monsters.Remove(Monster);
Monster->Destroy();
}
// Called by a monster when it reaches its target
void ALevelController::ReachedTarget(AMonsterActor* Monster)
{
RemoveMonsterFromGame(Monster);
}
// Called by a monster when it dies
void ALevelController::Died(AMonsterActor* Monster)
{
RemoveMonsterFromGame(Monster);
}<file_sep>[URL]
[/Script/HardwareTargeting.HardwareTargetingSettings]
TargetedHardwareClass=Desktop
AppliedTargetedHardwareClass=Desktop
DefaultGraphicsPerformance=Maximum
AppliedDefaultGraphicsPerformance=Maximum
[/Script/EngineSettings.GameMapsSettings]
GlobalDefaultGameMode=/Game/TowersGameMode_BP.TowersGameMode_BP_C
EditorStartupMap=/Game/TrainingLevel.TrainingLevel
GameDefaultMap=/Game/IntroScreen_Level.IntroScreen_Level
<file_sep>// (C) 2016 Mesomorphic Ltd
#pragma once
#include "Components/StaticMeshComponent.h"
#include "Tower_Tower.generated.h"
class UTower_Turret;
/**
* Defines the tower portion of the overall tower actor
* TODO De-overload the use of the word 'Tower'
*/
UCLASS(meta = (BlueprintSpawnableComponent))
class TOWERS_API UTower_Tower : public UStaticMeshComponent
{
GENERATED_BODY()
public:
void Rotate(float Difference);
void SetTurretReference(UTower_Turret* TurretToSet);
private:
UTower_Turret* Turret = nullptr;
};
<file_sep>// (C) 2016 Mesomorphic Ltd
#pragma once
#include "Components/ActorComponent.h"
#include "TowerAimingComponent.generated.h"
class UTower_Base;
class UTower_Tower;
class UTower_Turret;
class UTower_Barrel;
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class TOWERS_API UTowerAimingComponent : public UActorComponent
{
GENERATED_BODY()
public:
void SetReferences( UTower_Base* BaseToSet
, UTower_Tower* TowerToSet
, UTower_Turret* TurretToSet
, UTower_Barrel* BarrelToSet
);
// Sets default values for this component's properties
UTowerAimingComponent();
// Called when the game starts
virtual void BeginPlay() override;
// Coordinate the tower to aim at the desired point
virtual void AimAt(FVector TargetLocation);
private:
UTower_Base* Base = nullptr;
UTower_Tower* Tower = nullptr;
UTower_Turret* Turret = nullptr;
UTower_Barrel* Barrel = nullptr;
void RotateBaseTowards(FVector AimDirection);
};
<file_sep>// (C) 2016 Mesomorphic Ltd
#include "Towers.h"
#include "Tower_Barrel.h"
<file_sep>// (C) 2016 Mesomorphic Ltd
#include "Towers.h"
#include "TowerActor.h"
#include "MonsterActor.h"
#include "TowerAimingComponent.h"
#include "LevelController.h"
// Pass on components to aiming system
void ATowerActor::SetReferences(UTower_Base* BaseToSet, UTower_Tower* TowerToSet, UTower_Turret* TurretToSet, UTower_Barrel* BarrelToSet)
{
if (TowerAimingComponent)
{ TowerAimingComponent->SetReferences( BaseToSet
, TowerToSet
, TurretToSet
, BarrelToSet
);
}
else { UE_LOG(LogTemp, Warning, TEXT("No TowerAimingComponent")) }
}
// Sets default values
ATowerActor::ATowerActor()
{
PrimaryActorTick.bCanEverTick = true;
TowerAimingComponent = CreateDefaultSubobject<UTowerAimingComponent>(FName("Aiming Component"));
}
// Receive instructions on which monster to attack
void ATowerActor::SetTarget(AMonsterActor* Monster) { Target = Monster; }
bool ATowerActor::HasTarget( ) { return Target != nullptr; }
bool ATowerActor::IsTarget( AMonsterActor* Monster) { return Monster == Target; }
// Called when the game starts or when spawned
void ATowerActor::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ATowerActor::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
// try to hurt our target
if (Target)
{
TowerAimingComponent->AimAt(Target->GetActorLocation());
}
}
// answers true if the distance between tower centre and monster centre is less than tower range
bool ATowerActor::TargetInRange()
{
if (Target)
{ auto Distance = (GetActorLocation() - Target->GetActorLocation()).Size();
return (Distance < Range);
}
else
{ return false;
}
}
// called by level controller to cause tower to hurt its target
bool ATowerActor::HurtTarget()
{
if (TargetInRange())
{
if ((FPlatformTime::Seconds() - LastFireTime) > ReloadTimeInSeconds)
{
Target->Hurt(Damage); // TODO Parameterise value for different tower types and upgrades
LastFireTime = FPlatformTime::Seconds();
return true;
}
else
{ return false;
}
}
else
{ return false;
}
}
<file_sep>// (C) 2016 Mesomorphic Ltd
#include "Towers.h"
#include "Tower_Base.h"
#include "Tower_Tower.h"
void UTower_Base::SetTowerReference(UTower_Tower* TowerToSet) { Tower = TowerToSet; }
void UTower_Base::Rotate(FVector AimDirection)
{
if (!Tower) { UE_LOG(LogTemp, Warning, TEXT("No tower")) }
else
{ auto DeltaRotator = AimDirection.Rotation() - Tower->GetForwardVector().Rotation();
Tower->Rotate(FMath::Clamp(DeltaRotator.Yaw, -1.0f, 1.0f) * MaxDegreesPerSecond * GetWorld()->DeltaTimeSeconds);
}
}<file_sep>// (C) 2016 Mesomorphic Ltd
#pragma once
// (C) 2016 Mesomorphic Ltd
// TODO Should be called simply Tower, not TowerActor
#include "GameFramework/Actor.h"
#include "TowerActor.generated.h"
class AMonsterActor;
class UTower_Base;
class UTower_Tower;
class UTower_Turret;
class UTower_Barrel;
class UTowerAimingComponent;
class ALevelController;
UCLASS()
class TOWERS_API ATowerActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ATowerActor();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
void SetTarget(AMonsterActor* Monster);
bool IsTarget( AMonsterActor* Monster);
bool HasTarget();
UPROPERTY(EditAnywhere) ALevelController* Controller = nullptr;
UFUNCTION(BlueprintCallable, Category = Setup) void SetReferences( UTower_Base* BaseToSet
, UTower_Tower* TowerToSet
, UTower_Turret* TurretToSet
, UTower_Barrel* BarrelToSet
);
// instruct the tower to hurt the monster, if possible
UFUNCTION(BlueprintCallable, Category = Action) bool HurtTarget();
private:
UPROPERTY(EditDefaultsonly) float LaunchSpeed = 100; // TODO Set sensible default
UPROPERTY(EditDefaultsOnly) float ReloadTimeInSeconds = 2; // TODO Set sensible default
UPROPERTY(EditDefaultsOnly) float Range = 500; // TODO Set sensible default
UPROPERTY(EditDefaultsOnly) float Damage = 10; // TODO Defaults
AMonsterActor* Target = nullptr;
UTowerAimingComponent* TowerAimingComponent = nullptr;
float LastFireTime = 0;
bool TargetInRange();
};
<file_sep>// (C) 2016 Mesomorphic Ltd
#pragma once
#include "GameFramework/Actor.h"
#include "MonsterActor.generated.h"
class ALevelController;
UCLASS()
class TOWERS_API AMonsterActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AMonsterActor();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
// Process the movement of the monster
void Move();
// Receive damage
void Hurt(float damage);
void SetTarget(AActor* inTarget);
UPROPERTY(EditAnywhere) ALevelController* Controller = nullptr;
private:
UPROPERTY(EditAnywhere) AActor* Target = nullptr;
UPROPERTY(EditAnywhere) float Speed = 1;
UPROPERTY(EditAnywhere) float Health = 100;
bool ReachedTarget();
};
<file_sep>// (C) 2016 Mesomorphic Ltd
#pragma once
#include "GameFramework/Actor.h"
#include "SpawnActor.generated.h"
class AMonsterActor;
class ALevelController;
UCLASS()
class TOWERS_API ASpawnActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ASpawnActor();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
void SpawnWave();
private:
UPROPERTY(EditAnywhere, Category = Setup) ALevelController* Controller = nullptr;
UPROPERTY(EditAnywhere, Category = Setup) TSubclassOf<AMonsterActor> MonsterBlueprint = nullptr;
UPROPERTY(EditAnywhere, Category = Setup) AActor* Exit = nullptr;
UPROPERTY(EditAnywhere, Category = Setup) float SpawnRate = 1;
UPROPERTY(EditAnywhere, Category = Setup) int MaxSpawn = 3;
int NumSpawned = 0;
float LastSpawnTime = 0.f;
AMonsterActor* SpawnMonster();
};
<file_sep>// (C) 2016 Mesomorphic Ltd
#include "Towers.h"
#include "ExitActor.h"
// Sets default values
AExitActor::AExitActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AExitActor::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AExitActor::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
}
<file_sep>// (C) 2016 Mesomorphic Ltd
#include "Towers.h"
#include "Tower_Tower.h"
#include "Tower_Turret.h"
void UTower_Tower::SetTurretReference(UTower_Turret* TurretToSet)
{
Turret = TurretToSet;
}
void UTower_Tower::Rotate(float Difference)
{
SetRelativeRotation(FRotator(0, RelativeRotation.Yaw + Difference, 0));
}<file_sep>// (C) 2016 Mesomorphic Ltd
#include "Towers.h"
#include "TowerAimingComponent.h"
#include "Tower_Base.h"
#include "Tower_Tower.h"
#include "Tower_Turret.h"
#include "Tower_Barrel.h"
// Sets default values for this component's properties
UTowerAimingComponent::UTowerAimingComponent()
{
bWantsBeginPlay = true;
PrimaryComponentTick.bCanEverTick = false;
}
// Called when the game starts
void UTowerAimingComponent::BeginPlay()
{
Super::BeginPlay();
}
void UTowerAimingComponent::SetReferences(UTower_Base* BaseToSet, UTower_Tower* TowerToSet, UTower_Turret* TurretToSet, UTower_Barrel* BarrelToSet)
{
Base = BaseToSet;
Tower = TowerToSet; if ( Base) { Base->SetTowerReference( TowerToSet); }
Turret = TurretToSet; if ( Tower) { Tower->SetTurretReference(TurretToSet); }
Barrel = BarrelToSet; if (Turret) { Turret->SetBarrelReference(BarrelToSet); }
}
void UTowerAimingComponent::AimAt(FVector TargetLocation)
{
// rotate tower to face target
RotateBaseTowards(TargetLocation.GetSafeNormal());
}
void UTowerAimingComponent::RotateBaseTowards(FVector AimDirection)
{
if (!Base) { UE_LOG(LogTemp, Warning, TEXT("NO BASE"))
return;
}
else
{ Base->Rotate(AimDirection);
}
}<file_sep># Nightlands
Tower Defense game in Unreal Engine
<file_sep>// (C) 2016 Mesomorphic Ltd
#pragma once
#include "Components/StaticMeshComponent.h"
#include "Tower_Barrel.generated.h"
/**
*
*/
UCLASS(meta = (BlueprintSpawnableComponent))
class TOWERS_API UTower_Barrel : public UStaticMeshComponent
{
GENERATED_BODY()
};
<file_sep>// (C) 2016 Mesomorphic Ltd
#pragma once
#include "GameFramework/Actor.h"
#include "LevelController.generated.h"
class AMonsterActor;
class ATowerActor;
UCLASS()
class TOWERS_API ALevelController : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ALevelController();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
void RegisterMonster(AMonsterActor* Monster); // called by generators when they spawn a new monster, so things are kept track of centrally
void ReachedTarget( AMonsterActor* Monster); // called by monsters when they reach their target
void Died( AMonsterActor* Monster); // called by monsters when they die
bool IsTarget( AMonsterActor* Monster);
private:
TArray<AMonsterActor*> Monsters;
TArray< ATowerActor*> Towers;
// Activate tower spawning for level
void SpawnTowers();
void RemoveMonsterFromGame(AMonsterActor* Monster);
UPROPERTY(EditDefaultsOnly, Category = Setup) TSubclassOf<ATowerActor> TowerBlueprint = nullptr;
};
<file_sep>// (C) 2016 Mesomorphic Ltd
#pragma once
#include "Components/StaticMeshComponent.h"
#include "Tower_Base.generated.h"
class UTower_Tower;
UCLASS(meta = (BlueprintSpawnableComponent))
class TOWERS_API UTower_Base : public UStaticMeshComponent
{
GENERATED_BODY()
public:
void Rotate(FVector Direction);
void SetTowerReference(UTower_Tower* TowerToSet);
private:
UPROPERTY(EditAnywhere, Category = Setup) float MaxDegreesPerSecond = 50;
UTower_Tower* Tower = nullptr;
};
<file_sep>// (C) 2016 Mesomorphic Ltd
#include "Towers.h"
#include "MonsterActor.h"
#include "ExitActor.h"
#include "LevelController.h"
// Sets default values
AMonsterActor::AMonsterActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AMonsterActor::BeginPlay()
{
Super::BeginPlay();
}
void AMonsterActor::Move()
{
if (Target == nullptr) { UE_LOG(LogTemp, Error, TEXT("No target specified")) }
else
{
// Calculate difference between where we are now and the exits and move Speed units towards it
FVector OurLocation = GetActorLocation();
SetActorLocation( OurLocation + (Target->GetActorLocation() - OurLocation).GetSafeNormal() * Speed
, false
);
}
}
void AMonsterActor::SetTarget(AActor* inTarget)
{
Target = inTarget;
}
bool AMonsterActor::ReachedTarget()
{
return (GetActorLocation().Equals(Target->GetActorLocation(), 5.f));
}
// Called every frame
void AMonsterActor::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
Move();
if (ReachedTarget())
{
// call out to controller
if (Controller) { Controller->ReachedTarget(this); }
else { UE_LOG(LogTemp, Error, TEXT("No controller")) }
}
}
void AMonsterActor::Hurt(float damage)
{
Health -= damage;
UE_LOG(LogTemp, Warning, TEXT("Ow! %s"), *GetName())
if (Health < 0)
{ Controller->Died(this); // call out to controller to let it know we died
}
}<file_sep>// (C) 2016 Mesomorphic Ltd
#include "Towers.h"
#include "Tower_Turret.h"
void UTower_Turret::SetBarrelReference(UTower_Barrel* BarrelToSet)
{
Barrel = BarrelToSet;
}
| e8d41e6c547e5fa00400539c1514f0d6ecc7a0fe | [
"Markdown",
"C",
"C++",
"INI"
] | 24 | C++ | Fjool/Nightlands | 0f21c3675f026a7438e140212495615c63ed53eb | 63e9c73dd4035828606aaa4fb892f750b0e22d40 |
refs/heads/master | <repo_name>eestivill/prueba-atoda<file_sep>/utils/mocks/estadosPedidos.js
const estadosPedidos = require("../schemas/estadosPedidos");
const estadosPedidosMock = [{
"IdEstadoPedido": "JZKM",
"Nombre": "Gabtune",
"Activo": 1
}, {
"IdEstadoPedido": "TXQS",
"Nombre": "Oodoo",
"Activo": 1
}, {
"IdEstadoPedido": "LRYB",
"Nombre": "Voonyx",
"Activo": 1
}];
function filteredEstadosPedidosMock(tag) {
return estadosPedidosMock.filter(estadoPedido => estadoPedido.Nombre.includes(tag));
}
class EstadosPedidosServiceMock {
getEstadosPedidos = function(callback) {
callback(null, estadosPedidosMock);
}
createEstadoPedido() {
return estadosPedidosMock[0];
}
}
module.exports = {
estadosPedidosMock,
filteredEstadosPedidosMock,
EstadosPedidosServiceMock
};
<file_sep>/lib/mysqlPool.js
const mysql = require('mysql');
const { config } = require("../config");
const configDB = {
host: 'localhost',//config.dbHost,
database: 'atodaco_beta', //config.dbName,
user: 'atodaco_beta', //config.dbUser,
password: '<PASSWORD>' //config.dbPassword
};
//const mysqlPool = mysql.createPool(config);
const mysqlPool = mysql.createConnection(config);
mysqlPool.connect(error => {
if (error) throw error;
console.log("Successfully connected to the database.");
});
module.exports = mysqlPool;
<file_sep>/test/utils.buildMessage.test.js
const assert = require("assert");
const buildMessage = require("../utils/buildMessage");
describe("utils - buildMessage", function () {
describe("when receives an entity an a action", function () {
it("should return the respective message", function () {
const result = buildMessage("EstadosPedidos", "create");
const expect = "EstadosPedidos create";
assert.strictEqual(result, expect);
});
});
describe("when receives an entity an a action and is a list", function () {
it("should return the respective message with the entity in plural", function () {
const result = buildMessage("EstadosPedidos", "list");
const expect = "EstadosPedidos list";
assert.strictEqual(result, expect);
});
});
});
<file_sep>/routes/estadosPedidos.js
const express = require('express');
const EstadosPedidosService = require('../services/estadosPedidos');
const {
idEstadoPedidoSchema,
createEstadoPedidoSchema,
updateEstadoPedidoSchema
} = require('../utils/schemas/estadosPedidos');
const validationHandler = require('../utils/middleware/validationHandler');
const cacheResponse = require('../utils/cacheResponse');
const { FIVE_MINUTES_IN_SECONDS, SIXTY_MINUTES_IN_SECONDS } = require('../utils/time');
const { cache } = require('@hapi/joi');
function estadosPedidosApi(app) {
const router = express.Router();
app.use('/api/estadospedidos', router);
const estadosPedidosService = new EstadosPedidosService();
router.get('/', function(req, res, next) {
cacheResponse(res, SIXTY_MINUTES_IN_SECONDS);
try {
estadosPedidosService.getEstadosPedidos(function(error, estadosPedidos) {
res.status(200).json({
data: estadosPedidos,
message: 'Listados todos los EstadosPedidos'
});
});
} catch(err) {
next(err);
}
});
router.get('/:IdEstadoPedido', validationHandler({ IdEstadoPedido: idEstadoPedidoSchema }, 'params'), function(req, res, next) {
cacheResponse(res, SIXTY_MINUTES_IN_SECONDS);
const idEstadoPedido = req.params.IdEstadoPedido;
try {
estadosPedidosService.getEstadoPedido(idEstadoPedido , function(error, estadoPedido) {
if (typeof estadoPedido !== 'undefined' && estadoPedido.length > 0) {
res.status(200).json({
data: estadoPedido,
message: 'Devuelto registro de EstadosPedidos'
});
} else {
res.status(404).json({
data: idEstadoPedido,
message: 'No existe el registro en EstadosPedidos'
});
}
});
} catch(err) {
next(err);
}
});
router.post('/', validationHandler(createEstadoPedidoSchema), function(req, res, next) {
const estadoPedido = {
idEstadoPedido : req.body.IdEstadoPedido,
nombre : req.body.Nombre,
activo : req.body.Activo
};
try {
estadosPedidosService.createEstadoPedido(estadoPedido, function(error, datos) {
if (datos) {
res.status(200).json({
data: estadoPedido.idEstadoPedido,
message: 'Insertado registro en EstadosPedidos'
});
} else {
res.status(500).json({
data: estadoPedido.idEstadoPedido,
message: 'Error al insertar en EstadosPedidos'
});
}
});
} catch(err) {
next(err);
}
});
router.put('/:IdEstadoPedido', validationHandler({ IdEstadoPedido: idEstadoPedidoSchema }, 'params'), validationHandler(updateEstadoPedidoSchema), function(req, res, next) {
const idEstadoPedido = req.params.IdEstadoPedido;
const estadoPedido = {
nombre : req.body.Nombre,
activo : req.body.Activo
};
try {
estadosPedidosService.updatePedido(idEstadoPedido, estadoPedido, function(error, estadoPedido) {
res.status(200).json({
data: idEstadoPedido,
message: 'Modificado registro de EstadosPedidos'
});
});
} catch(err) {
next(err);
}
});
router.delete('/:IdEstadoPedido', validationHandler({ IdEstadoPedido: idEstadoPedidoSchema }, 'params'), function(req, res, next) {
const idEstadoPedido = req.params.IdEstadoPedido;
try {
estadosPedidosService.deleteEstadoPedido(idEstadoPedido , function(error, estadoPedido) {
res.status(200).json({
data: idEstadoPedido,
message: "Borrado registro de EstadosPedidos"
});
});
} catch(err) {
next(err);
}
});
}
module.exports = estadosPedidosApi;
<file_sep>/utils/mocks/mysqlLib.js
const sinon = require('sinon');
const { estadosPedidosMock, filteredEstadosPedidosMock } = require('./estadosPedidos');
const getAllStub = sinon.stub();
getAllStub.withArgs('EstadosPedidos').returns(estadosPedidosMock);
const tagQuery = { tgas: { $in: ["Rhycero"] } };
getAllStub.withArgs('EstadosPedidos', tagQuery).resolves(filteredEstadosPedidosMock("Rhycero"));
const createStub = sinon.stub().resolves(estadosPedidosMock[0].IdEstadoPedido);
class MysqlLibMock {
getAll = function(collection, callback) {
callback(null, getAllStub(collection));
}
create(collection, data) {
return createStub(collection, data);
}
}
module.exports = {
getAllStub,
createStub,
MysqlLibMock
}
<file_sep>/utils/schemas/estadosPedidos.js
const joi = require('@hapi/joi');
const idEstadoPedidoSchema = joi.number().min(1).max(9999);
const nombreSchema = joi.string().max(50);
const activoSchema = joi.number().min(0).max(1);
const createEstadoPedidoSchema = {
IdEstadoPedido: idEstadoPedidoSchema.required(),
Nombre: nombreSchema.required(),
Activo: activoSchema.required()
}
const updateEstadoPedidoSchema = {
Nombre: nombreSchema.required(),
Activo: activoSchema.required()
}
module.exports = {
idEstadoPedidoSchema,
createEstadoPedidoSchema,
updateEstadoPedidoSchema
};
<file_sep>/utils/buildMessage.js
function buildMessage(entity, action) {
return `${entity} ${action}`;
}
module.exports = buildMessage;
<file_sep>/index.js
const express = require('express');
const app = express();
const { config } = require('./config/index');
const estadosPedidosApi = require('./routes/estadosPedidos.js');
const { logErrors, wrapErrors, errorHandler } = require('./utils/middleware/errorHandlers.js');
const notFoundHandler = require('./utils/middleware/notFoundHandler');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
// Middleware - Body parser
app.use(express.json());
// Routes
estadosPedidosApi(app);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// Catch 404
app.use(notFoundHandler);
// Manejadores de errores del middleware
app.use(logErrors);
app.use(wrapErrors);
app.use(errorHandler);
app.listen(config.port, function() {
console.log(`Listening http://localhost:${config.port}`);
});
| 53f368bc61734f83b665baa0bf9c9277bde50092 | [
"JavaScript"
] | 8 | JavaScript | eestivill/prueba-atoda | 5ddd6c78f639dcc3c89eca76d114c7f1a5b5b08b | 30191229dcd08a52c6bfdbb561e390fc272ad89a |
refs/heads/main | <file_sep>#pragma once
#include <wx/wx.h>
class CShape
{
public:
virtual void draw(wxPaintDC *dc) = 0;
virtual ~CShape() {}
};
<file_sep>#pragma once
#include "cshape.hpp"
class CTriangle : public CShape
{
wxCoord m_x1, m_y1, m_x2, m_y2, m_x3, m_y3;
public:
CTriangle(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, wxCoord x3, wxCoord y3)
: m_x1(x1), m_y1(y1), m_x2(x2), m_y2(y2), m_x3(x3), m_y3(y3)
{}
virtual ~CTriangle()
{}
void draw(wxPaintDC *dc) override
{
dc->DrawLine(m_x1, m_y1, m_x2, m_y2);
dc->DrawLine(m_x2, m_y2, m_x3, m_y3);
dc->DrawLine(m_x1, m_y1, m_x3, m_y3);
}
};
<file_sep>#include "MainFrame.h"
#include "ctriangle.hpp"
#include "crectangle.hpp"
#include "ccircle.hpp"
#include <wx/aboutdlg.h>
#include <wx/msgdlg.h>
MainFrame::MainFrame(wxWindow* parent)
: MainFrameBaseClass(parent)
{
srand(time(NULL));
this->Connect(wxEVT_PAINT, wxPaintEventHandler(MainFrame::OnPaint));
this->Centre();
}
MainFrame::~MainFrame()
{
}
void MainFrame::OnPaint(wxPaintEvent& event)
{
wxPaintDC dc(this);
for (auto it = m_shapes.begin(); it != m_shapes.end(); it++)
{
(*it)->draw(&dc);
}
}
void MainFrame::OnExit(wxCommandEvent& event)
{
wxUnusedVar(event);
Close();
}
void MainFrame::OnAbout(wxCommandEvent& event)
{
wxUnusedVar(event);
wxAboutDialogInfo info;
info.SetCopyright(_("My MainFrame"));
info.SetLicence(_("GPL v2 or later"));
info.SetDescription(_("Short description goes here"));
::wxAboutBox(info);
}
void MainFrame::OnMainpanelPaint(wxPaintEvent& event)
{
}
void MainFrame::OnMenuitemcreatetriangleMenuSelected(wxCommandEvent& event)
{
int w, h;
GetSize(&w, &h);
int x1 = rand() % w;
int y1 = rand() % h;
int x2 = rand() % w;
int y2 = rand() % h;
int x3 = rand() % w;
int y3 = rand() % h;
m_shapes.emplace_back(std::make_unique<CTriangle>(x1, y1, x2, y2, x3, y3));
Refresh();
}
void MainFrame::OnMenuitemcreatecircleMenuSelected(wxCommandEvent& event)
{
int w, h;
GetSize(&w, &h);
int x = rand() % w;
int y = rand() % h;
int radius = rand() % ((w + h) / 8);
m_shapes.emplace_back(std::make_unique<CCircle>(x, y, radius));
Refresh();
}
void MainFrame::OnMenuitemcreaterectangleMenuSelected(wxCommandEvent& event)
{
int w, h;
GetSize(&w, &h);
int x1 = rand() % w;
int y1 = rand() % h;
int x2 = rand() % w;
int y2 = rand() % h;
m_shapes.emplace_back(std::make_unique<CRectangle>(x1, y1, x2, y2));
Refresh();
}
<file_sep>#pragma once
#include "cshape.hpp"
class CCircle : public CShape
{
wxCoord m_x, m_y;
wxCoord m_radius;
public:
CCircle(wxCoord x, wxCoord y, wxCoord radius)
: m_x(x), m_y(y), m_radius(radius)
{}
virtual ~CCircle()
{}
void draw(wxPaintDC *dc) override
{
dc->DrawCircle(m_x, m_y, m_radius);
}
};
<file_sep>#pragma once
#include "cshape.hpp"
class CRectangle : public CShape
{
wxCoord m_x1, m_y1, m_x2, m_y2;
public:
CRectangle(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)
: m_x1(x1), m_y1(y1), m_x2(x2), m_y2(y2)
{}
virtual ~CRectangle()
{}
void draw(wxPaintDC *dc) override
{
dc->DrawRectangle(m_x1, m_y1, m_x2 - m_x1, m_y2 - m_y1);
}
};
<file_sep>#ifndef MAINFRAME_H
#define MAINFRAME_H
#include "wxcrafter.h"
#include "cshape.hpp"
#include <wx/wx.h>
#include <memory>
#include <vector>
class MainFrame : public MainFrameBaseClass
{
std::vector<std::unique_ptr<CShape>> m_shapes;
public:
MainFrame(wxWindow* parent);
virtual ~MainFrame();
void OnExit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
void OnPaint(wxPaintEvent& event);
protected:
virtual void OnMenuitemcreatecircleMenuSelected(wxCommandEvent& event);
virtual void OnMenuitemcreaterectangleMenuSelected(wxCommandEvent& event);
virtual void OnMenuitemcreatetriangleMenuSelected(wxCommandEvent& event);
virtual void OnMainpanelPaint(wxPaintEvent& event);
};
#endif // MAINFRAME_H
| 32eb710edae62ecde84bdc3cffdd7cc5654370bd | [
"C++"
] | 6 | C++ | beneG/TopSystemsTest | 89abd168150e45737619b8fc9ca735d7d2bf2b7a | 873ec170549053855d89eb4ff7e9794856277baa |
refs/heads/master | <file_sep># dev-setup
updated<file_sep>#!/usr/bin/env bash
# ~/osx.sh — Originally from https://mths.be/osx
# Ask for the administrator password upfront
sudo -v
# Keep-alive: update existing `sudo` time stamp until `osx.sh` has finished
while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &
###############################################################################
# uninstall vs extention #
###############################################################################
rm -rf ~/.vscode/extensions
###############################################################################
# install vs extention #
###############################################################################
code --install-extension esbenp.prettier-vscode
code --install-extension eamodio.gitlens
code --install-extension techer.open-in-browser
code --install-extension wayou.vscode-todo-highlight
code --install-extension streetsidesoftware.code-spell-checker
code --install-extension ms-vscode.vscode-typescript-tslint-plugin
code --install-extension dbaeumer.vscode-eslint
code --install-extension coenraads.bracket-pair-colorizer-2
| ac14c7e2cfdd0cc95ed713770bb2e1a7874ba7d3 | [
"Markdown",
"Shell"
] | 2 | Markdown | trtquan/dev-setup | 5284b2a522e3c1c00ac3ab6777c19a2a6c051bbd | 678438fe11e8a0ddf0799efb4f46e5b21358754e |
refs/heads/master | <repo_name>f0ursecond/loginapp<file_sep>/settings.gradle
rootProject.name = "loginapp"
include ':app'
<file_sep>/app/src/main/java/com/example/loginapp/MainActivity3.java
package com.example.loginapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity3 extends AppCompatActivity {
private Button btn_masuk;
private ImageButton btn_login;
private EditText emailbang;
private EditText pwBang;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
btn_masuk = findViewById(R.id.btn_masuk);
btn_login = findViewById(R.id.btn_login);
emailbang = findViewById(R.id.emailbang);
pwBang = findViewById(R.id.pwBang);
btn_masuk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent ganti = new Intent(MainActivity3.this, MainActivity4.class);
startActivity(ganti);
}
});
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (emailbang.getText().toString().equals("azulfanur") && pwBang.getText().toString().equals("root")){
//Correct
Toast.makeText(MainActivity3.this,"Login Succses",Toast.LENGTH_SHORT).show();
Intent login = new Intent(MainActivity3.this, MainActivity5.class);
startActivity(login);
} else if (emailbang.getText().toString().equals("") && pwBang.getText().toString().equals("")){
//Error
Toast.makeText(MainActivity3.this,"Enter Username & Password",Toast.LENGTH_LONG).show();
} else if (emailbang.getText().toString().equals("azulfanur") && pwBang.getText().toString().equals("")) {
//Username Only
Toast.makeText(MainActivity3.this,"Enter your Password",Toast.LENGTH_LONG).show();
} else if (emailbang.getText().toString().equals("") && pwBang.getText().toString().equals("root")) {
//Password Only
Toast.makeText(MainActivity3.this,"Enter your Username",Toast.LENGTH_SHORT).show();
} else {
//Incorrect
Toast.makeText(MainActivity3.this,"Password & Username Incorrect",Toast.LENGTH_SHORT).show();
}
}
});
}
}<file_sep>/app/src/main/java/com/example/loginapp/MainActivity2.java
package com.example.loginapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity2 extends AppCompatActivity {
private EditText texttinggi;
private EditText textalas;
private Button hitungcuy;
private TextView hasilcuy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
texttinggi = findViewById(R.id.texttinggi);
textalas = findViewById(R.id.textalas);
hitungcuy = findViewById(R.id.hitungcuy);
hasilcuy = findViewById(R.id.hasilcuy);
hitungcuy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int a = Integer.parseInt(texttinggi.getText().toString());
int b = Integer.parseInt(textalas.getText().toString());
float hasil = a*b/2;
hasilcuy.setText("Luas segitiga adalah = " + String.valueOf(hasil) + ("cm"));
}
});
}
}<file_sep>/app/src/main/java/com/example/loginapp/MainActivity.java
package com.example.loginapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.loginapp.MainActivity2;
public class MainActivity extends AppCompatActivity {
private Button btnlogin;
private Button btnpencet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlogin = findViewById(R.id.btn_login);
btnpencet = findViewById(R.id.btn_pencet);
btnlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent pindah = new Intent(MainActivity.this, MainActivity2.class);
startActivity(pindah);
}
});
btnpencet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent ganti = new Intent(MainActivity.this, MainActivity3.class);
startActivity(ganti);
}
});
}
} | 2310a1768638f06ad162d549584308647b025b05 | [
"Java",
"Gradle"
] | 4 | Gradle | f0ursecond/loginapp | 314625d9aae509b143a06236d8c4cf7cc95248df | 46c8b8289c548c8021f20d55e830ca38f1336608 |
refs/heads/master | <repo_name>Tai7sy/zstack<file_sep>/core/src/main/java/org/zstack/core/notification/APIQueryNotificationMsg.java
package org.zstack.core.notification;
import org.springframework.http.HttpMethod;
import org.zstack.header.query.APIQueryMessage;
import org.zstack.header.query.AutoQuery;
import org.zstack.header.rest.RestRequest;
/**
* Created by xing5 on 2017/3/18.
*/
@RestRequest(
path = "/notifications",
optionalPaths = {"/notifications/{uuid}"},
method = HttpMethod.GET,
responseClass = APIQueryNotificationReply.class
)
@AutoQuery(replyClass = APIQueryNotificationReply.class, inventoryClass = NotificationInventory.class)
public class APIQueryNotificationMsg extends APIQueryMessage {
}
| 619d5e62d537733538feffd4de74343802011122 | [
"Java"
] | 1 | Java | Tai7sy/zstack | 2fd07736ae707439e40eaf15058f5bef4ae7b2e9 | 9da5cacaafaf094af108ff2de89082a38702d265 |
refs/heads/master | <file_sep>Luwak
======
A static blog generator built with python.
Visit the [official site](http://luwak.preommr.com) for more information.
<file_sep>#!/home/preom/Workarea/projects/luwak_env/bin/python
from luwak.settings import Settings
from luwak.generate import *
from luwak.pagination import *
from luwak.taggint import *
from luwak.templating import TemplateCombinator
from luwak.db import DatabaseManager
import argparse
import sys
import os
import shutil
import sqlite3
import logging
import time
from pygments.formatters import HtmlFormatter
def process_start(*args, **kwargs):
CONFIG_FILENAME = Settings.CONFIG_FILENAME
params = vars(args[0])
def make_directory(dirname):
os.mkdir(dirname)
if params['is_verbose']:
print "Directory made: " + dirname
if params['is_verbose']:
print "VARS:" + str(vars(args[0]))
if params['destination'] is not None:
os.chdir(params['destination'])
if params['is_verbose']:
print "Path set to: " + os.getcwd();
# Make root project folder
make_directory(params['project_name'])
os.chdir(params['project_name'])
# Make database
dbDir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'db')
with open(os.path.join(dbDir, 'main.sql'), 'r') as f:
sqlScript = f.read()
make_directory('db')
oldDir = os.getcwd()
os.chdir('db')
conn = sqlite3.connect(Settings.default_data['db_name'])
cursor = conn.cursor()
cursor.executescript(sqlScript)
conn.commit()
os.chdir(oldDir)
# Make output
output_dir = Settings.default_data['output_dir']
make_directory(output_dir)
# Make tags directory
oldDir = os.getcwd()
os.chdir(output_dir)
tags_dir = Settings.default_data['tags_dir']
make_directory(tags_dir)
os.chdir(oldDir)
# copy start template
startTemplateDir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templating', 'templates', 'start')
for src in [os.path.join(startTemplateDir, i) for i in os.listdir(startTemplateDir)]:
if os.path.isfile(src):
shutil.copy(src, output_dir)
else:
print os.path.join(os.path.join(output_dir, os.path.basename(src)))
shutil.copytree(src, os.path.join(output_dir, os.path.basename(src)))
with open(os.path.join(output_dir, 'css', 'pygments.css'), 'w') as f:
f.write(HtmlFormatter(style='monokai').get_style_defs('.codehilite'))
# Make content directory
source_dir = Settings.default_data['source_dir']
make_directory(source_dir)
olddir = os.getcwd()
os.chdir(source_dir)
testFilesDirPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tests')
for i in os.listdir(testFilesDirPath):
pth = os.path.join(testFilesDirPath, i)
if os.path.isfile(pth):
shutil.copy(pth, '.')
os.chdir(olddir)
# Make config file
Settings.generate_default_settings_file()
def process_generate(*args, **kwargs):
startTime = time.time()
CONFIG_FILENAME = Settings.CONFIG_FILENAME
params = vars(args[0])
if 'project_path' not in params:
params['project_path'] = os.getcwd()
proj_settings = GenerationComponent.load_project_file(params['project_path'])
iterativeBuidler = IterativeBuilder(proj_settings)
dbManager = DatabaseManager(proj_settings)
content_loader = ContentLoader(proj_settings)
contentReader = ContentReader(proj_settings)
templater = TemplateCombinator(proj_settings)
contentWriter = ContentWriter(proj_settings)
contentFiles = content_loader.get_content_paths()
if params['do_flush']:
conn = sqlite3.connect(dbManager.dbFilePath)
cursor = conn.cursor()
cursor.execute('delete from records')
cursor.execute('delete from meta')
conn.commit()
contentFiles = iterativeBuidler.content_filter(contentFiles)
postList = []
metaList = []
conn = sqlite3.connect(dbManager.dbFilePath)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
toUpdateList = [] #TODO change name from toUpdateList
sourceDir = os.path.join(proj_settings['project_path'], proj_settings['source_dir'])
for fpath in contentFiles:
relativeFname = os.path.relpath(fpath, sourceDir)
cursor.execute('select * from meta where filename=?', (relativeFname,))
row = cursor.fetchone()
meta = contentReader.generate_meta(fpath)
meta['modtime'] = os.path.getmtime(fpath)
category = meta.get('category', [None])[0]
if row:
if 'category' in row.keys():
storedCategory = row['category']
else:
storedCategory = None
if storedCategory != category:
toUpdateList.append((relativeFname, meta, 'update')),
else:
toUpdateList.append((relativeFname, meta, 'add'))
# Set meta data
for relativeFname, meta, status in toUpdateList:
category = meta.get('category', [None])[0]
title = meta['title'][0]
try:
metaDate = datetime.datetime.strptime(meta['date'][0], '%Y-%m-%d')
except ValueError:
print '>>--------------------------------------------------------<<'
print '>>----------------------- Error --------------------------<<'
print '>>--------------------------------------------------------<<'
print ''
print "File: ", relativeFname
print "Mandatory meta date could not be parsed"
print "Make sure that it is in the correct format."
print "Either `YYYY-MM-DD` (e.g. 2015-07-04)"
#print "Or `MONTHNAME MM, YYYY` (e.g. July 04, 2015)"
print ""
print "Found: ", meta['date']
print ""
print '>>--------------------------------------------------------<<'
print ""
raise
dbManager.update_tags(relativeFname, meta.get('tags', []))
# Important: date value in db must be unique for article navigation linking to work (correct row number);
# content file doesn't specify hour, minute, etc. therefore combined with last modifed
date = datetime.datetime.fromtimestamp(meta['modtime'])
date = date.replace(year=metaDate.year, month=metaDate.month, day=metaDate.day)
if status == 'add':
cursor.execute('insert into meta (filename, category, title, created) values(?, ?, ?, ?)', (relativeFname, category, title, date))
conn.commit()
cursor.execute('select count(*) from meta where category=? and title<?', (category, title))
rowCount = cursor.fetchone()[0]
# SKIP NULL VALUES:
if category is None:
continue
if rowCount <= 0:
cursor.execute('select * from meta where category=? order by category, title limit 2 offset ?', (category, rowCount))
results = cursor.fetchall()
prev = None
current = results[0]
if len(results) > 1:
next = results[1]
else:
next = None
else:
cursor.execute('select * from meta where category=? order by category, title limit 3 offset ?', (category, rowCount - 1))
results = cursor.fetchall()
while (len(results) < 3):
results.append(None)
prev, current, next = results
# Link Next
if next:
cursorArgs = (next['filename'], current['filename'])
cursor.execute('update meta set nextFilename=? where filename=?', cursorArgs)
cursorArgs = (current['filename'], next['filename'])
cursor.execute('update meta set prevFilename=? where filename=?', cursorArgs)
# Link previous
if prev:
cursorArgs = (prev['filename'], current['filename'])
cursor.execute('update meta set prevFilename=? where filename=?', cursorArgs)
cursorArgs = (current['filename'], prev['filename'])
cursor.execute('update meta set nextFilename=? where filename=?', cursorArgs)
conn.commit()
# Write content
for fpath in contentFiles:
fname = os.path.basename(fpath)
htmlContent = contentReader.generate_html(fpath)
metaContent = contentReader.generate_meta(fpath)
relativeFname = os.path.relpath(fpath, sourceDir)
cursor.execute('select * from meta where filename=?', (relativeFname,))
row = cursor.fetchone()
# transform from source filename to output filename
if row['prevFilename']:
metaContent['prev'] = [contentWriter.generate_name(row['prevFilename'])]
if row['nextFilename']:
metaContent['next'] = [contentWriter.generate_name(row['nextFilename'])]
html = templater.combine_html_wrapper(htmlContent, fname=fname, meta=metaContent)
href = contentWriter.output(html, fname)
postList.append((metaContent['title'][0], href))
# Generate tag pages
tagGenerator = CategoryGenerator(proj_settings)
tags = [t['tag'] for t in tagGenerator.get_tags()]
tags = [(t, '/tags/{}.html'.format(t)) for t in tags]
ctx = {'items': tags, 'title': 'Tags'}
print tags
html = templater.combine(ctx, templateType="list")
contentWriter.output_specific(html, 'index.html', 'tags')
for tag, tagLink in tags:
articles = []
for row in tagGenerator.get_fnames_from_tag(tag):
fname = os.path.basename(row['filename'])
fname = '/' + contentWriter.generate_name(fname)
articles.append((row['title'], fname))
ctx = {'items': articles, 'title': tag}
html = templater.combine(ctx, templateType="list")
contentWriter.output_specific(html, '{}.html'.format(tag), 'tags')
# Generate Index pages
pgDSource = PaginationDbDataSource(dbManager.dbFilePath)
paginator = Paginator(pgDSource)
for pageInfo in paginator.get_generator():
index_html = templater.combine_index_wrapper(pageInfo)
contentWriter.output(index_html, pageInfo['currentPage'][1])
elapsedTime = time.time() - startTime
print ">> -- Time: {:.4f} -- <<".format(elapsedTime)
if __name__ == "__main__":
# root parser
parser = argparse.ArgumentParser(description='cli for luwak')
subparsers = parser.add_subparsers(title='Subcommands',
description='List of subcommands')
# 'startproject' parser
parser_start = subparsers.add_parser('startproject', help='Creates a new luwak project')
parser_start.add_argument('project_name', help='project name')
parser_start.add_argument('-d', '--destination', help='Where to startproject', dest='destination')
parser_start.add_argument('-v', '--verbose', help='verbose', dest='is_verbose', action='store_true')
parser_start.set_defaults(func=process_start)
# 'generate' parser
parser_generate = subparsers.add_parser('generate', help='Generates luwak project content')
parser_generate.add_argument('-p', '--path', help='Path to root luwak project (where the config file is)', dest='project_path')
parser_generate.add_argument('-f', '--flush', help='', dest='do_flush', action='store_true')
parser_generate.set_defaults(func=process_generate)
args = parser.parse_args()
args.func(args)
<file_sep>#!/usr/bin/python
import json
import unittest
import os
import sys
import logging
logger = logging.getLogger('settingsLogger')
CONFIG_FILENAME = 'luwak.rc'
default_data = {
'output_dir': 'output',
'source_dir': 'content',
'tags_dir': 'tags',
'project_path': '',
'db_name': 'main_db.sqlite3'
}
def generate_default_settings_file(dir_path=None):
if not dir_path:
dir_path = os.getcwd()
file_path = os.path.join(dir_path, CONFIG_FILENAME)
with open(file_path, 'w') as f:
settings = default_data
settings['project_path'] = os.path.abspath(dir_path)
f.write(json.dumps(default_data,
sort_keys=True,
indent=4,
separators=(',', ': ')))
def validate(dirPath, fixErrors=True):
""" Validate a settings file.
Attributes:
dirPath (str): Absolute path to the root of the project directory.
fixErrors (bool): Try and fix any erros found. Defaults to True.
Returns:
bool: True if everything is ok, False otherwise.
"""
settings = get_settings_file(dirPath)
errors = False
msgPreamble = "Settings Validation: \n"
msg = "{preamble}{reason}\n"
if settings['project_path'] != dirPath:
errors = True
msgReason = 'Wrong project path - fixing to correct path.'
logger.info(msg.format(preamble=msgPreamble, reason=msgReason))
settings['project_path'] = dirPath
if errors and fixErrors:
update_settings_file(dirPath, settings)
def get_settings_file(dirPath):
""" Return a json settings file.
"""
file_path = get_settings_filepath(dirPath)
try:
with open(file_path, 'r') as f:
return json.loads(f.read())
except IOError:
config_access_error()
def config_access_error():
print ''
print " >>> ----------------------------- <<< "
print " >>> Error loading the config file <<< "
print " >>> ----------------------------- <<< "
sys.exit(0)
def get_settings_filepath(dirPath):
""" Return the settings filepath.
"""
return os.path.join(dirPath, CONFIG_FILENAME)
def update_settings_file(dirPath, contents):
""" Update a json settings file.
Attributes:
contents (dict): Settings file.
"""
file_path = get_settings_filepath(dirPath)
try:
with open(file_path, 'w') as f:
f.write(json.dumps(contents,
sort_keys=True,
indent=4,
separators=(',', ': ')))
except IOError:
config_access_error()
def load_project_file(dirPath=None):
""" Load settings object from filepath using the Settings module.
If path is not given, use the current working directory.
Attributes:
dirPath (str): absolute path to the project directory containing
the settigs file.
Returns:
An instance of the Settings class.
"""
if not dirPath:
dirPath = '.'
if not os.path.isdir(dirPath):
raise ValueError('Not a directory', dirPath)
settings = get_settings_file(dirPath)
return settings
<file_sep>DROP TABLE IF EXISTS records;
CREATE TABLE records(filename text not null unique,
modified timestamp not null,
FOREIGN KEY(filename) REFERENCES meta(filename));
DROP TABLE IF EXISTS meta;
CREATE TABLE meta(filename text not null unique,
title text not null unique,
nextFilename text,
prevFilename text,
category text,
created timestamp not null,
PRIMARY KEY(filename));
DROP TABLE IF EXISTS tags;
CREATE TABLE tags (id INTEGER,
filename text,
tag text not null,
PRIMARY KEY(id),
FOREIGN KEY(filename) references meta(filename));
select * from records;
<file_sep>from luwak import GenerationComponent
from luwak.generate import *
class DatabaseManager(GenerationComponent):
""" Abstraction for db operations. """
def __init__(self, settings):
super(DatabaseManager, self).__init__(settings)
self.dbFilePath = os.path.join(self.settings['project_path'], 'db', self.settings['db_name'])
def get_conn(self):
""" Get sql connection and cursor.
Returns:
tuple: (cursor, connection) from sqlite3 module.
"""
conn = sqlite3.connect(self.dbFilePath, detect_types=sqlite3.PARSE_DECLTYPES)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
return (conn, cursor)
def get_list(self, table, col, distinct=False):
""" Return a list of row objects.
Attributes:
table: Table name.
col: Column name; defaults to '*'.
distinct: If select operation should be distinct. Defaults to False.
Returns:
[Row]: A list of row objects where the row factory is sqlite3.Row.
Meaning that column values can be accessed using the column
name as the key. For example: rowObject['column_name'].
"""
conn, cursor = self.get_conn()
if col is None:
col = '*'
if distinct:
distinct = "distinct"
else:
distinct = ''
sqlString = "SELECT {distinct} {col} from {table}".format(table=table, col=col, distinct=distinct)
cursor.execute(sqlString)
return cursor.fetchall()
def fname_formatter(self, absFPath):
""" Formats an absolute filepath to the format used as a key in the db.
Attributes:
absFPath: Absolute path to the file to format.
Returns:
str: filepath relative to the output directory.
"""
sourceDir = os.path.join(self.settings['project_path'], self.settings['source_dir'])
relativeFname = os.path.relpath(fpath, sourceDir)
return relativeFname
def update_tags(self, fnameKey, tags):
""" Update the tags for a given filename.
Attributes:
fnameKey: Filename that's used as a key. Use fname_formatter to make
sure that the filename is the standard form used in the db.
tags: List of new tags for the article.
"""
conn, cursor = self.get_conn()
cursor.execute('select tag from tags where filename=?', (fnameKey,))
tagSet = set(tags)
dbTagSet = set([row['tag'] for row in cursor.fetchall()])
toDelete = dbTagSet - tagSet
toAdd = tagSet - dbTagSet
for tagName in toAdd:
cursor.execute('Insert into tags (filename, tag) values (?, ?)', (fnameKey, tagName))
for tagName in toDelete:
cursor.execute('Delete from tags where filename=? and tag=?', (fnameKey, tagName))
conn.commit()
conn.close()
<file_sep>from luwak import settings as Settings
class GenerationComponent(object):
""" Base class for components part of the content processing pipeline """
def __init__(self, settings):
"""
Attributes:
settings: path to a directory containing settings file, or instance of Settings dict data.
"""
if type(settings) == str:
settings = Settings.load_project_file(settings)
self.settings = settings
<file_sep>Title: My title
Subtitle: My subtitle
Summary: A cool Summary
Date: 1923-05-31
Tags: first
second
last
# Loreim Impsum
## Lorem Ipsum borem dorst
### Lorem Ipsum borem dorst
#### Beldosr venuor belisk
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
````python
class Animal(object):
def __init__(self):
self.sound = ''
def speak(self):
print self.sound
class Cat(Animal):
def __init__(self):
super(Cat, self).__init__()
self.sound = 'Meow'
````
### Lorem Ipsum borem dorst
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tincidunt neque nec magna tincidunt volutpat. Etiam condimentum purus tellus, sollicitudin vulputate tortor mattis eget. Sed sit amet molestie neque, non imperdiet purus. Etiam sit amet fringilla purus. Maecenas ac lorem erat. Mauris sed massa nisl. Ut sagittis pulvinar nulla, quis rutrum lectus dignissim ac.
Donec vestibulum diam nec velit hendrerit scelerisque. Morbi sit amet nulla libero. Aliquam id tristique sem. Fusce iaculis tristique consequat. Fusce ullamcorper sem sed posuere sodales. Mauris bibendum consectetur mauris ac iaculis. Nam sollicitudin convallis tortor, eget eleifend neque convallis vel. Nullam accumsan enim nec nisi laoreet finibus. Quisque mollis velit mauris, eget dapibus nunc vulputate in. Donec et ligula magna. Vestibulum a lacus in libero elementum tincidunt. Vivamus enim felis, gravida in mollis nec, placerat eu ex.
Ut varius faucibus turpis vitae varius. Phasellus erat nulla, elementum nec ante sit amet, imperdiet vehicula risus. Integer et egestas enim. Aenean a fringilla urna. Nulla facilisi. Donec sodales porttitor nunc, sit amet ornare odio feugiat et. Praesent facilisis est in libero ornare dapibus. Suspendisse id velit augue. Sed pellentesque tellus orci, ac consectetur justo laoreet non. Integer tincidunt, lectus id dictum finibus, lacus odio efficitur magna, sit amet maximus est lacus non quam. Aenean tempus, ante pretium ultricies condimentum, tortor orci volutpat nisi, in imperdiet ipsum lectus sit amet metus. Sed in nisl interdum, tincidunt justo in, pharetra leo. Mauris a consectetur arcu. Quisque viverra arcu felis, a semper libero consectetur id.
Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam blandit pellentesque aliquet. Aenean in sem viverra, feugiat lectus at, hendrerit elit. Vivamus sapien metus, lacinia nec tellus eget, consectetur vehicula nisl. Integer accumsan et risus a fermentum. Nam ac molestie ante. Praesent facilisis pretium urna ac aliquam. Aenean eleifend dui ligula, vitae posuere dolor posuere nec. Praesent facilisis egestas felis ac vulputate. Donec quis felis in dolor vehicula viverra. Integer sed velit nec augue hendrerit consequat vitae at justo.
<file_sep>import json
import os
import markdown
from luwak import settings as Settings
from luwak import GenerationComponent
from luwak.db import DatabaseManager
import sys
import pdb
import datetime
import sqlite3
class ContentLoader(GenerationComponent):
""" Responsible for finding potential content files """
def __init__(self, settings):
super(ContentLoader, self).__init__(settings)
def get_content_paths(self):
""" Get paths to all potential source files to be processed using the
settings attribute.
Returns:
list of absolute filepaths.
"""
settings_source = self.settings['source_dir']
sources = []
files = []
oldpath = os.getcwd()
# json source can be a list or string
if type(settings_source) == str or type(settings_source) == unicode:
sources.append(settings_source)
else:
sources.extend(settings_source)
os.chdir(self.settings['project_path'])
def walkerror(oserr):
print "ERR: " + oserr.filename
def make_abspath(fname):
if os.path.isabs(fname):
return fname
else:
return os.path.abspath(fname)
sources = map(make_abspath, sources)
for src in sources:
for dirpath, dirname, filenames in os.walk(src, onerror=walkerror):
files.extend([os.path.join(dirpath, filename) for filename in filenames])
files = filter(self.file_filter_func, files)
os.chdir(oldpath)
return files
@staticmethod
def file_filter_func(filename):
""" Filters the content files based .
Use this function to filter by things such as file extension.
Returns:
bool: True if file is valid, False otherwise.
"""
valid_extensions = ['.md']
result = False
for extension in valid_extensions:
if filename.endswith(extension):
result = True
break
return result
class ContentReader(GenerationComponent):
""" Parse the contents of a source file.
Assume that the content file is markdown and process using the python
markdown module.
Note:
Default markdown extensions for meta and syntax highlitng are also used.
"""
def __init__(self, settings):
super(ContentReader, self).__init__(settings)
def generate_html(self, fpath):
""" Transform contents of a source file into html.
Attributes:
fpath: Absolute filepath to the file to transform.
Returns:
str: html string
"""
html = ''
sourceContents = ''
with open(fpath, 'r') as f:
sourceContents = f.read()
if fpath.endswith('.md'):
md = markdown.Markdown(extensions=[
'markdown.extensions.meta',
'markdown.extensions.fenced_code',
'markdown.extensions.codehilite'])
html = md.convert(sourceContents)
else:
raise Exception("No reader known for: " + fpath)
if not html:
print 'Err: empty content file: ' + os.path.basename(fpath)
return html
def generate_meta(self, fpath):
""" Gather any meta data related to the filepath given.
Use the markdown extension to gather meta information.
Attributes:
fpath: absolute filepath to the filename.
Returns:
dict: dict of meta values.
TODO:
- Use a separate file as a source for meta information based on filename
"""
meta = {}
if fpath.endswith('.md'):
md = markdown.Markdown(extensions=['markdown.extensions.meta'])
with open(fpath,'r') as f:
md.convert(f.read())
for k, v in md.Meta.items():
meta[k] = v
return meta
class ContentWriter(GenerationComponent):
""" Use to write contents to a file. """
def __init__(self, settings):
super(ContentWriter, self).__init__(settings)
def generate_name(self, fname):
""" Take a filename (not path) and return a canonical filename """
if not fname:
raise ValueError("Expected a valid filename")
root, ext = os.path.splitext(fname)
newName = root + '.html'
return newName
def generate_dir(self, dirType):
""" Generate the directory to be used based on dirType.
Use to control the structure of luwak project directories by
establishing a specific structure.
Attributes:
dirType (str): Directory type; valid types are: 'tags'.
Returns:
str: Absolute path to directory in the luwak project.
Todo:
rename method since it implies that it actually generates a
directory and not a directory name.
"""
validDirTypes = ['tags']
settingsValues = ['tags_dir']
lookup = dict(zip(validDirTypes, settingsValues))
if dirType not in validDirTypes:
raise ValueError("")
outputDir = os.path.join(self.settings['project_path'], self.settings['output_dir'], self.settings[lookup[dirType]])
return outputDir
def output(self, html, fname=None, dirPath=None):
""" Writes html code to a file.
Use to output final versions of processed content to the output
directory.
Attributes:
html: Content to be written (assumed to be html code).
fname: Related filename (e.g. filename of the original source file).
Defaults to None.
dirPath: Absolute directory path to place the file in. Defaults to None.
Returns:
str: Filename relative to the output directory.
Note:
Instead of using the dirPath attribute, use output_specific to
output to specific directories in the output directory.
"""
if dirPath is None:
output_dir = self.settings['output_dir']
else:
output_dir = dirPath
project_path = self.settings['project_path']
newName = ''
newName = self.generate_name(fname)
oldDir = os.getcwd()
os.chdir(project_path)
os.chdir(output_dir)
with open(newName, 'w') as f:
f.write(html)
os.chdir(oldDir)
return newName
def output_specific(self, html, fname, dirType):
""" Wrapper for output method with a specific directory type.
Use to output to specific directory categories in the output directory
such as the 'tags' directory. Refer to the generate_dir method used
to see what valid directories exist and where they are in the output
directory.
Notes:
Bulk of code logic moved to self.generate_dir
"""
return self.output(html, fname, dirPath=self.generate_dir(dirType))
class IterativeBuilder(GenerationComponent):
""" Use to implement iterative builds. """
def __init__(self, settings):
super(IterativeBuilder, self).__init__(settings)
def content_filter(self, contentList):
""" Filter files that haven't been updated.
Check files against the database, return those that have been recently
modified and update db. If the file isn't found in database, add it.
Attributes:
contentList: List of absolute filepaths to be filtered.
Returns:
List of filepaths that have been updated that are a subset of
contentList.
"""
dbManager = DatabaseManager(self.settings)
dbPath = dbManager.dbFilePath
conn = sqlite3.connect(dbPath, detect_types=sqlite3.PARSE_DECLTYPES)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
sourceDir = os.path.join(self.settings['project_path'], self.settings['source_dir'])
resultList = []
for fpath in contentList:
relativeFname = os.path.relpath(fpath, sourceDir)
modtime = datetime.datetime.fromtimestamp(os.stat(fpath).st_mtime)
cursor.execute('select * from records where filename=?', (relativeFname,))
row = cursor.fetchone()
if row is None:
cursor.execute('insert into records values(?, ?)', (relativeFname, modtime))
conn.commit()
else:
dbModtime = row['modified']
if (modtime > dbModtime): # check if updated
#TODO Delete this
cursor.execute('update records set modified=? where filename=?', (modtime, relativeFname))
conn.commit()
else:
continue
resultList.append(fpath)
if len(resultList) == 0:
print ">>>----------------<<<"
print ">>> All up to date <<<"
print ">>>----------------<<<"
return resultList
def update(self, contentList):
""" Updates files.
Attributes:
contentList: list of filenames to update in database.
"""
pass
class DefaultGenerator(GenerationComponent):
""" Wrapper for the content processing pipeline.
Use all the derived GenerationComponent classes to provide an interface
to process source content.
Note:
Currently not implemented.
"""
def __init__(self, settings):
super(DefaultGenerator, self).__init__(settings)
self.content_loader = ContentLoader(self.settings)
self.content_reader = ContentReader(self.settings)
self.template = TemplateCombinator(self.settings)
self.content_writer = ContentWriter(self.settings)
def generate(self):
pass
<file_sep>import os
import json
import datetime
import logging
from luwak.generate import GenerationComponent
from bs4 import BeautifulSoup
from jinja2 import FileSystemLoader, Environment
TEMPLATE_RC_NAME = 'luwak_template.rc'
# Returns path to template config file so far, useless
# TODO change to using local template folder
def load_template_file(settings=None):
""" Load absolute path to luwak template config file.
Get the correct template config file using the settings file and returning the
correct defualt template. If not settings object is given, use the first template
found in the default templates directory (uses os.listdir which has an arbitrary
order).
Note:
Default templates can be created using the templates folder in the
luwak source directory.
Attributes:
settings: Instance of a settings object.
Returns:
str: absolute file path.
"""
templateFilename = 'luwak_template.rc'
defaultTemplatesPath = os.path.join(os.path.dirname(__file__), 'templates')
defaultTemplates = os.listdir(defaultTemplatesPath)
if settings and hasattr(self.settings, 'template'):
template = self.settings.template
else:
template = defaultTemplates[0]
if template in defaultTemplates:
return os.path.join(defaultTemplatesPath, template, templateFilename)
else:
return ValueError("not implemented yet...")
class CombinatorBase(object):
def __init__(self, templateSettings, templateDirPath):
"""
templateDirPath is specified because templates are meant to be mobile.
Attributes:
templateSettings (dict): template settings.
"""
self.templateSettings = templateSettings
self.templateDirPath = templateDirPath
def combine(self, template, context, templateType):
pass
def load_template(self, templateType):
pass
def _load_template_name(self, templateType=None):
if templateType is None:
templateType = 'default'
try:
return self.templateSettings[templateType]
except KeyError:
errorMsg = """
Template doesn't have that kind of file. If this is a custom
template, make sure the correct type is added."""
print templateType
print errorMsg
# class Bs4Combinator(CombinatorBase):
# def combine(self, type) :
# if type is None or type == 'default':
# templateHtml = self.get_template()
# templateSoup = BeautifulSoup(templateHtml)
# htmlSoup = BeautifulSoup(html)
# tag = templateSoup.find(class_='luwak-content')
# tag.insert(1, htmlSoup)
# templateSoup = BeautifulSoup(templateSoup.encode_contents())
# def cleanup():
# """ Return a cleaned version of a beautifulsoup object.
# BeautifulSoup has a bug that prevents finding tags correctly
# after inserting a soup object. Use this function to decod the
# template soup into text and then parse that string into a
# BeautifulSoup object again.
# """
# return BeautifulSoup(templateSoup.encode_contents())
# # Formatters for the data to be injected
# def date_formatter(metaDate):
# date = datetime.datetime.strptime(metaDate[0], '%Y-%m-%d')
# return date.strftime('%B %d, %Y')
# def tag_formatter(metaTags):
# tagString = "<span class='tag label label-default'> <span class='glyphicon glyphicon-tag'></span> {}</span>"
# tagHtml = ''.join([tagString.format(tag) for tag in meta['tags']])
# def prev_formatter(metaPrev):
# tagString = '<a href=\'{}\'><span aria-hidden="true" class="glyphicon glyphicon-menu-left"></span> Prev </a>'
# return tagString.format(metaPrev[0])
# def next_formatter(metaNext):
# tagString = '<a href=\'{}\'>Next <span aria-hidden="true" class="glyphicon glyphicon-menu-right"></span></a>'
# return tagString.format(metaNext[0])
# metaTags = ['date', 'tags', 'title', 'prev', 'next']
# formatters = [date_formatter, tag_formatter, None, prev_formatter, next_formatter]
# template_class = ['luwak-date', 'luwak-tags', 'luwak-title', 'luwak-prev', 'luwak-next']
# assert(len(metaTags) == len(formatters) == len(template_class))
# for mTag, frmt, cls in zip(metaTags, formatters, template_class):
# if mTag in meta:
# tag = templateSoup.find(class_=cls)
# if frmt:
# tagContent = frmt(meta[mTag])
# else:
# tagContent = meta[mTag][0]
# if tagContent:
# soup = BeautifulSoup(tagContent, 'html.parser')
# else:
# continue
# try:
# tag.append(soup)
# except:
# print "Error with parsing " + mTag
# templateSoup = cleanup()
# #TODO Fix this arbitrary piece of code
# if len(templateSoup) < 3000:
# tag = templateSoup.find(class_='to-top')
# if tag:
# tag['class'].append('hidden')
# endProduct = templateSoup.prettify()
# return endProduct
# elif type == 'list':
# templateHtml = self.get_template('list')
# def a_formatter(title, href):
# if not href:
# href = ''
# return "<a href='{1}'>{0}</a>".format(title, href)
# linksHtml = ''.join([a_formatter(title, href) for title, href in links])
# linksSoup = BeautifulSoup(linksHtml)
# templateSoup = BeautifulSoup(templateHtml)
# tag = templateSoup.find(class_='luwak-list')
# tag.append(linksSoup)
# if listTitle:
# tag = templateSoup.find(class_='luwak-list-title')
# tag.string.replace_with(listTitle)
# return templateSoup.prettify()
# elif type == 'index':
# def a_formatter(title, href):
# return "<a href='{1}'>{0}</a>".format(title, href)
# templateHtml = self.get_template('index')
# postListHtml = []
# for title, href, article in pageInfo['postList']:
# aHtml = '<a href=\'{1}\'>{0}</a>'.format(title.title(), href)
# dateHtml = '<span>{}</span>'.format(article['created'].strftime("%b %d, %y"))
# postStr = """
# <div class=\'index-post\'>
# <div class=\'post-title\'>{aHtml}</div>
# <div class=\'post-date\'>{dateHtml}</div>
# </div>
# """
# postListHtml.append(postStr.format(aHtml=aHtml,dateHtml=dateHtml))
# listSoup = BeautifulSoup('<hr>'.join(postListHtml))
# templateSoup = BeautifulSoup(templateHtml)
# tag = templateSoup.find(class_='luwak-index')
# paginationTag = templateSoup.find(class_='luwak-pagination')
# if not tag:
# raise ValueError('No luwak-index in index template')
# else:
# tag.append(listSoup)
# leftAdjacent = [a_formatter(title, href) for title, href in pageInfo['leftAdjacentPages']]
# rightAdjacent = [a_formatter(title, href) for title, href in pageInfo['rightAdjacentPages']]
# currentpage = a_formatter(pageInfo['currentPage'][0], pageInfo['currentPage'][1])
# page_list = leftAdjacent + [currentpage] + rightAdjacent
# for ind, val in enumerate(page_list):
# if val == currentpage:
# cls = 'active'
# else:
# cls = ''
# page_list[ind] = "<li class='{}'>{}</li>".format(cls, val)
# page_list = ['<ul class="pagination pull-right">'] + page_list + ['</ul>']
# paginationSoup = BeautifulSoup(''.join(page_list))
# tag = templateSoup.find(class_='luwak-pagination')
# if paginationTag:
# paginationTag.append(paginationSoup)
# else:
# print "WARNING: no page index"
# return templateSoup.prettify()
class Bs4Combinator(CombinatorBase):
pass
class JinjaCombinator(CombinatorBase):
def __init__(self, *args):
super(JinjaCombinator, self).__init__(*args)
self.env = Environment(loader=FileSystemLoader(self.templateDirPath))
def defaultDateFilter(datetimeObj):
return datetimeObj.strftime("%B %-d, %Y")
self.env.filters['defaultDate'] = defaultDateFilter
def combine(self, context, templateType=None):
template = self.load_template(templateType)
return template.render(context)
def load_template(self, templateType):
templateName = self._load_template_name(templateType)
return self.env.get_template(templateName)
class TemplateLoader(object):
pass
def get_combinator(settings):
""" Get combinator based on template settings type. """
class TemplateCombinator(GenerationComponent):
""" Insert values into a template """
def __init__(self, settings):
super(TemplateCombinator, self).__init__(settings)
self.combinator = get_combinator(settings)
def _get_template_dir(self):
""" Get template directory
"""
defaultTemplatesDir = os.path.join(os.path.dirname(__file__), 'templates')
defaultTemplates = os.listdir(defaultTemplatesDir)
defaultTemplate = 'default'
try:
localTemplatesDir = os.path.join(self.settings['project_path'], 'templates')
foundTemplates = os.listdir(localTemplatesDir)
except:
logging.warning('No local templates directory found.')
foundTemplates = []
if 'template' not in self.settings:
return os.path.join(defaultTemplatesDir, 'default')
elif os.path.isdir(self.settings['template']):
return self.settings['template']
elif self.settings['template'] in foundTemplates:
return os.path.join(localTemplatesDir, self.settings['template'])
else:
raise ValueError("Couldn't find specified template: " + self.settings['template'])
def combine(self, ctx, templateType=None):
"""Injects values into a html template.
Use for standard type article i.e. with a title, content, tags, etc.
Returns:
str: html code with given values inserted.
"""
templateDir = self._get_template_dir()
templateRcPath = os.path.join(templateDir, TEMPLATE_RC_NAME)
try:
with open(templateRcPath) as f:
templateRc = json.loads(f.read())
except ValueError:
print "Is rc file a valid JSON file?"
raise
except IOError:
print "Couldn't load template rc folder... Is it a valid template?"
raise
if 'loader_type' not in templateRc:
logging.error("template should have a type")
elif templateRc['loader_type'] == 'default':
pass
elif templateRc['loader_type'] == 'jinja':
combinator = JinjaCombinator(templateRc, templateDir)
else:
ValueError('Not a valid option for template rc.')
output = combinator.combine(ctx, templateType=templateType)
return output
def combine_html_wrapper(self, html='', fname=None, meta=dict()):
context = meta
context['main_content'] = html
context['fname'] = html
return self.combine(context)
def combine_index_wrapper(self, pageInfo):
context = pageInfo
return self.combine(context, templateType='index')
if __name__ == '__main__':
pass
<file_sep>beautifulsoup4==4.3.2
cffi==1.1.2
cryptography==0.9.1
enum34==1.0.4
idna==2.0
ipaddress==1.0.7
Markdown==2.6.2
ndg-httpsclient==0.4.0
pyasn1==0.1.7
pycparser==2.14
pyOpenSSL==0.15.1
requests==2.7.0
six==1.9.0
wheel==0.24.0
<file_sep>import sqlite3
from luwak.db import DatabaseManager
class PaginationDataSource(object):
""" Adapter between data and Pagination class.
"""
def __init__(self, pageSize=10):
self.pageSize = pageSize
def get_generator(self):
""" Returns a iterable generator
Note: Low memory usage, but slower
"""
pass
class PaginationDbDataSource(PaginationDataSource):
""" Uses a db source e.g. sqlite3 as a data source.
Note:
page index begins at 1
"""
def __init__(self, dbfilepath=None):
super(PaginationDbDataSource, self).__init__()
if not dbfilepath:
raise ValueError("PaginationDbDataSource requires a path to a database")
self.conn = sqlite3.connect(dbfilepath, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
self.conn.row_factory = sqlite3.Row
self.cursor = self.conn.cursor()
self.table = 'meta'
self.cursor.execute('select count(*) as total from {}'.format(self.table))
self.totalCount = self.cursor.fetchone()['total']
self.pageCount = self.totalCount/self.pageSize
def get_generator(self):
""" Return a generator that produces index pages.
Note:
function shouldn't make any writes to db
"""
cursor = self.cursor
for pageIndex in range(0, self.pageCount + 1):
limit = self.pageSize
offset = (pageIndex) * limit
cursor.execute('select * from {} limit ? offset ?'.format(self.table), (limit, offset))
page = cursor.fetchall()
yield (pageIndex + 1, page)
class Paginator(object):
""" Takes a data source and outputs a nested data structure.
TODO:
Add start page number
"""
def __init__(self, paginationDataSource):
self.paginationDataSource = paginationDataSource
self.pagePreviewSize = 4
self.outputString = 'index{}.html'
def indexHrefFormatter(self, pagenum):
if pagenum == 1:
pagenum = ""
return self.outputString.format(pagenum)
def get_generator(self):
""" Returns a generator that procues page index info.
"""
for pageIndex, page in self.paginationDataSource.get_generator():
pageInfo = dict()
postList = []
for article in page:
# load from row object to dict
title = article['title']
filename = article['filename']
created = article['created']
#TODO: load from db instead to presrve data integrity
newName = ''.join(filename.split('.')[:-1]+['.html'])
href = newName
postList.append((title, href, article))
pageInfo['postList'] = postList
pageInfo['currentPage'] = pageIndex
pageInfo['leftAdjacentPages'] = \
[i for i in range(max(pageIndex-self.pagePreviewSize, 1), pageIndex)]
if 1 in pageInfo['leftAdjacentPages']:
pageInfo['firstPage'] = None
else:
pageInfo['firstPage'] = 1
pageInfo['rightAdjacentPages'] = \
[i for i in range(pageIndex+1, min(pageIndex+self.pagePreviewSize, self.paginationDataSource.pageCount) + 1)]
if self.paginationDataSource.pageCount in pageInfo['rightAdjacentPages']:
pageInfo['lastPage'] = None
else:
pageInfo['lastPage'] = self.paginationDataSource.pageCount
for l in [pageInfo['leftAdjacentPages'], pageInfo['rightAdjacentPages']]:
l[:] = [(i, self.indexHrefFormatter(i)) for i in l]
for l in ['firstPage', 'lastPage', 'currentPage']:
# pageInfo[l] can evaluate to False if index is 0
if pageInfo[l] is not None:
pageInfo[l] = (pageInfo[l], self.indexHrefFormatter(pageInfo[l]))
yield pageInfo
<file_sep>from generate import GenerationComponent
from luwak.db import DatabaseManager
class CategoryGenerator(GenerationComponent):
def __init__(self, settings):
super(CategoryGenerator, self).__init__(settings)
def get_tags(self, fname=None):
""" Get a list of all the tags in the database as a row object.
Attributes:
fname: Standardized form of the filename stored in the database.
Returns:
[str]: list of tags.
"""
dbManager = DatabaseManager(self.settings)
conn, cursor = dbManager.get_conn()
sqlString = 'Select distinct tag from tags order by tag'
cursor.execute(sqlString)
return cursor.fetchall()
def get_fnames_from_tag(self, tagName):
""" Get filenames with a tag matching tagName. """
dbManager = DatabaseManager(self.settings)
conn, cursor = dbManager.get_conn()
sqlString = 'Select tags.filename, title from tags left join meta on tags.filename=meta.filename where tags.tag="{}"'.format(tagName)
cursor.execute(sqlString)
return cursor.fetchall()
def tag_page(self, tagName):
""" Return the links to posts that use 'tagName' """
pass
| 93a019dcd93ec2e54bb2b1bfb95d8821816be716 | [
"Markdown",
"SQL",
"Python",
"Text"
] | 12 | Markdown | preom/luwak | 9197a28bdb1f92fc46a1c361f5e1c70834621005 | 65d7e8347edaa5437b8e75ed8241b196cf4b0107 |
refs/heads/master | <repo_name>hienbv/vagrant-ubuntu1604<file_sep>/scripts/ubuntu1604/04-setup-mysql57.sh
#!/bin/bash
# ******************************************
# Developer: HienBV(<NAME>)
# Email:<EMAIL>
# Date: 08-11-2017
# ******************************************
# MYSQL
#config_mysql_root_password=<PASSWORD>
sudo echo "mysql-server-5.7 mysql-server/root_password password $config_mysql_root_password" | sudo debconf-set-selections;
sudo echo "mysql-server-5.7 mysql-server/root_password_again password $config_mysql_root_password" | sudo debconf-set-selections;
sudo apt-get install -y mysql-server php-mysql;
# Change MySQL Listening IP Address from local 127.0.0.1 to All IPs 0.0.0.0
sudo sed -i 's/127\.0\.0\.1/0\.0\.0\.0/g' /etc/mysql/mysql.conf.d/mysqld.cnf;
# Update mysql Table root record to accept incoming remote connections
sudo mysql -uroot --password=$config_mysql_root_password -e 'USE mysql; UPDATE `user` SET `Host`="%" WHERE `User`="root" AND `Host`="localhost"; DELETE FROM `user` WHERE `Host` != "%" AND `User`="root"; FLUSH PRIVILEGES;';
# Restart MySQL Service
sudo service mysql restart;
echo "04-setup-mysql57: Done!!!!!";
<file_sep>/scripts/ubuntu1604/05-setup-phpmyadmin.sh
#!/bin/bash
# ******************************************
# Developer: HienBV(<NAME>)
# Email:<EMAIL>
# Date: 08-11-2017
# ******************************************
# PHPMYADMIN
sudo echo "phpmyadmin phpmyadmin/dbconfig-install boolean true" | sudo debconf-set-selections;
sudo echo "phpmyadmin phpmyadmin/app-password-confirm password $config_mysql_root_password" | sudo debconf-set-selections;
sudo echo "phpmyadmin phpmyadmin/mysql/admin-pass password $config_mysql_root_password" | sudo debconf-set-selections;
sudo echo "phpmyadmin phpmyadmin/mysql/app-pass password $config_mysql_root_password" | sudo debconf-set-selections;
sudo echo "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2" | sudo debconf-set-selections;
sudo apt-get install -y phpmyadmin;
echo "04-setup-phpmyadmin: Done!!!!!";
<file_sep>/scripts/ubuntu1604/02-setup-apache2.sh
#!/bin/bash
# ******************************************
# Developer: HienBV(<NAME>)
# Email:<EMAIL>
# Date: 08-11-2017
# ******************************************
# Install Apache
sudo apt-get install -y apache2 apache2-utils;
sudo a2enmod rewrite;
sudo sed -i "s/export APACHE_RUN_USER=www-data$/export APACHE_RUN_USER=ubuntu/" /etc/apache2/envvars;
sudo sed -i "s/export APACHE_RUN_GROUP=www-data$/export APACHE_RUN_GROUP=ubuntu/" /etc/apache2/envvars;
echo "02-setup-apache2: Done!!!!!";
<file_sep>/scripts/ubuntu1604/03-setup-php70.sh
#!/bin/bash
# ******************************************
# Developer: HienBV(<NAME>)
# Email:<EMAIL>
# Date: 08-11-2017
# ******************************************
# Install PHP7
sudo apt-get install -y;
# Install module of PHP7
sudo apt-get install -y libapache2-mod-php php php-mcrypt php-curl php-intl;
sudo phpenmod mcrypt;
# /etc/apache2/mods-enabled/dir.conf
sudo sed -i "s/DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm$/DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm/" /etc/apache2/mods-enabled/dir.conf;
# Update the /etc/php/7.0/apache2/php.ini file.
sudo sed -i "s/post_max_size = 8M$/post_max_size = 1024M/" /etc/php/7.0/apache2/php.ini;
sudo sed -i "s/upload_max_filesize = 2M$/upload_max_filesize = 1024M/" /etc/php/7.0/apache2/php.ini;
sudo sed -i "s/;date\.timezone =$/date\.timezone = Asia\/Tokyo/" /etc/php/7.0/apache2/php.ini;
sudo sed -i "s/; max_input_vars = 1000$/max_input_vars = 10000/" /etc/php/7.0/apache2/php.ini;
sudo sed -i "s/session\.gc_maxlifetime = 1440$/session\.gc_maxlifetime = 56700/" /etc/php/7.0/apache2/php.ini;
echo "03-setup-php70: Done!!!!!";
<file_sep>/scripts/ubuntu1604/auto_install.sh
#!/bin/bash
# ******************************************
# Program: LAMP, Git, Composer, phpmyadmin
# Developer: HienBV(<NAME>)
# Email:<EMAIL>
# Date: 08-11-2017
# Last Updated: 05-10-2016
# ******************************************
DBPASSWD=<PASSWORD>
echo "Begin install";
if [ "`lsb_release -is`" == "Ubuntu" ] || [ "`lsb_release -is`" == "Debian" ]
then
sudo apt-get update;
sudo apt-get upgrade -y;
sudo apt-get autoremove;
# Install CURL
sudo apt-get install -y curl;
# GIT
sudo apt-get install -y git;
# Install Apache
sudo apt-get install -y apache2 apache2-utils;
sudo a2enmod rewrite;
sudo sed -i "s/export APACHE_RUN_USER=www-data$/export APACHE_RUN_USER=ubuntu/" /etc/apache2/envvars;
sudo sed -i "s/export APACHE_RUN_GROUP=www-data$/export APACHE_RUN_GROUP=ubuntu/" /etc/apache2/envvars;
# Install PHP7
sudo apt-get install -y
# Install module of PHP7
sudo apt-get install -y libapache2-mod-php php php-mcrypt php-curl php-intl php-mysql;
sudo php5enmod mcrypt;
# /etc/apache2/mods-enabled/dir.conf
sudo sed -i "s/DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm$/DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm/" /etc/apache2/mods-enabled/dir.conf;
# Update the /etc/php/7.0/apache2/php.ini file.
sudo sed -i "s/post_max_size = 8M$/post_max_size = 1024M/" /etc/php/7.0/apache2/php.ini;
sudo sed -i "s/upload_max_filesize = 2M$/upload_max_filesize = 1024M/" /etc/php/7.0/apache2/php.ini;
sudo sed -i "s/;date\.timezone =$/date\.timezone = Asia\/Tokyo/" /etc/php/7.0/apache2/php.ini;
sudo sed -i "s/; max_input_vars = 1000$/max_input_vars = 10000/" /etc/php/7.0/apache2/php.ini;
sudo sed -i "s/session\.gc_maxlifetime = 1440$/session\.gc_maxlifetime = 56700/" /etc/php/7.0/apache2/php.ini;
# MYSQL
sudo echo "mysql-server-5.7 mysql-server/root_password password $<PASSWORD>" | sudo debconf-set-selections;
sudo echo "mysql-server-5.7 mysql-server/root_password_again password $<PASSWORD>" | sudo debconf-set-selections;
sudo apt-get install -y mysql-server;
# Change MySQL Listening IP Address from local 127.0.0.1 to All IPs 0.0.0.0
sudo sed -i 's/127\.0\.0\.1/0\.0\.0\.0/g' /etc/mysql/mysql.conf.d/mysqld.cnf;
# Update mysql Table root record to accept incoming remote connections
sudo mysql -uroot -p$<PASSWORD>WD -e 'USE mysql; UPDATE `user` SET `Host`="%" WHERE `User`="root" AND `Host`="localhost"; DELETE FROM `user` WHERE `Host` != "%" AND `User`="root"; FLUSH PRIVILEGES;';
# Restart MySQL Service
service mysql restart
# PHPMYADMIN
sudo echo "phpmyadmin phpmyadmin/dbconfig-install boolean true" | sudo debconf-set-selections;
sudo echo "phpmyadmin phpmyadmin/app-password-confirm password $DB<PASSWORD>" | sudo debconf-set-selections;
sudo echo "phpmyadmin phpmyadmin/mysql/admin-pass password $<PASSWORD>" | sudo debconf-set-selections;
sudo echo "phpmyadmin phpmyadmin/mysql/app-pass password $<PASSWORD>" | sudo debconf-set-selections;
sudo echo "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2" | sudo debconf-set-selections;
sudo apt-get install -y phpmyadmin;
echo "Include /etc/phpmyadmin/apache.conf" | sudo tee -a /etc/apache2/apache2.conf;
# Copy apache2 config
sudo rm /etc/apache2/apache2.conf;
sudo rm /etc/apache2/sites-available/papps.conf;
sudo cp /apache_config/apache2.conf /etc/apache2/apache2.conf;
sudo cp /apache_config/papps.conf /etc/apache2/sites-available/papps.conf;
sudo a2ensite papps.conf;
sudo systemctl restart apache2;
elif [ "`lsb_release -is`" == "CentOS" ] || [ "`lsb_release -is`" == "RedHat" ]
then
# TODO
echo "CentOS - RedHat";
else
echo "Unsupported Operating System";
fi
# Install Composer
EXPECTED_SIGNATURE=$(wget https://composer.github.io/installer.sig -O - -q);
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');";
ACTUAL_SIGNATURE=$(php -r "echo hash_file('SHA384', 'composer-setup.php');");
if [ "$EXPECTED_SIGNATURE" = "$ACTUAL_SIGNATURE" ]
then
php composer-setup.php --quiet;
RESULT=$?;
rm composer-setup.php;
mv composer.phar /usr/local/bin/composer;
else
>&2 echo 'ERROR: Invalid installer signature';
rm composer-setup.php;
fi
# Symlink web directory into vagrant direcotry
if ! [ -L /var/www/html ]; then
rm -rf /var/www/html
ln -fs /vagrant /var/www/html
fi
echo "End install";
<file_sep>/README.md
## Nội dung ##
### [Vagrant](https://www.vagrantup.com/) là gì? ###
Create and configure lightweight, reproducible, and portable development environments.
### Tại sao sử dụng vagrant? ###
Vagrant là một công cụ tiện lợi, giúp bạn có thể tạo ra môi trường phát triển cho team phát triển một cách nhanh chóng và tiện lợi.
Hướng dẫn này sẽ giúp bạn có thể tạo môi trường phát triển trên ubuntu có cài đặt LAMP + Git và phpmyadmin.
## Yêu cầu phần mềm ##
Trước khi bắt đầu học vagrant thì chúng ta cần phải cài đặt một số phần mềm sau:
- Máy ảo [virtualbox](https://www.virtualbox.org/wiki/Downloads)
- Phiên bản [Vagrant](https://www.vagrantup.com/downloads.html) mới nhất.
- Terminal [Xshell](https://www.netsarang.com/products/xsh_overview.html) bạn có thể sử dụng terminal của [git for window](https://git-for-windows.github.io/)
Sau khi hoàn thành xong cài đặt phần mềm, chúng ta sẽ bắt đầu tạo máy ảo.
## Cài đặt máy ảo ubuntu + LAMP + phpmyadmin + Git ##
Sau khi đã hoàn thành việc cài đặt các phần mềm cần thiết. Bạn có thể mở terminal nên, tạo một thư mục cho vagrant:
> $ mkdir vagrant_dir
Sau khi tạo thành công thư mục hãy copy toàn bộ thư mục con trong thư mục ubuntu vào thư mục vagrant_dir vừa tạo.
Di chuyển vào thư mục vagrant_dir bằng terminal:
> $ cd vagrant_dir
Cuối cùng là bạn gõ lệnh sau để hoàn thành việc thiết lập môi trường phát triển
> $ vagrant up
Công việc còn lại của bạn là ngồi chờ kết quả cuối cùng. Sẽ mất thời gian cho lần chạy đầu tiên vì vagrant sẽ phải download box từ [HashiCorp](https://atlas.hashicorp.com/boxes/search), sau đó mới tiến hành build máy ảo trên virtualbox cho bạn.
Làm sao để biết mình đã hoàn thành tạo máy ảo thành công. Rất đơn giản, bạn có thể gõ vào lệnh sau:
> $ vagrant ssh
Hoặc bạn gõ vào trình duyệt url [http//:192.168.56.56/phpinfo.php](http//:192.168.56.56/phpinfo.php)
Cuối cùng là hãy chiêm ngưỡng kết quả đạt được!
## Thông tin tác giả ##
- Author: HienBV
- Email: [<EMAIL>](<EMAIL>)<file_sep>/scripts/install.sh
#!/bin/sh
# include parse_yaml function
. $SETUP_SCRIPT/parse_yaml.sh
SETUP_SCRIPT="$config_os_setup_path"
OS=ubuntu1604;
# SETUP
. $SETUP_SCRIPT/$OS/00-beforeSetup.sh
. $SETUP_SCRIPT/$OS/01-common.sh
. $SETUP_SCRIPT/$OS/02-setup-apache2.sh
. $SETUP_SCRIPT/$OS/03-setup-php70.sh
. $SETUP_SCRIPT/$OS/04-setup-mysql57.sh
. $SETUP_SCRIPT/$OS/05-setup-phpmyadmin.sh
. $SETUP_SCRIPT/$OS/06-sites.sh
. $SETUP_SCRIPT/$OS/08-setup-nodejs-8x.sh
<file_sep>/scripts/ubuntu1604/01-common.sh
#!/bin/bash
# ******************************************
# Developer: HienBV(<NAME>)
# Email:<EMAIL>
# Date: 08-11-2017
# ******************************************
# Install CURL
sudo apt-get install -y curl;
# Install GIT
sudo apt-get install -y git;
# Install Composer
sudo wget https://getcomposer.org/composer.phar
sudo mv composer.phar /usr/local/bin/composer;
echo "01-common.sh: Done!!!!!";
<file_sep>/scripts/ubuntu1604/08-setup-nodejs-8x.sh
#!/bin/bash
# ******************************************
# Developer: HienBV(<NAME>)
# Email:<EMAIL>
# Date: 09-11-2017
# ******************************************
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs;
sudo apt-get install -y build-essential;
echo "08-setup-nodejs-8x.sh: Done!!!!!";<file_sep>/scripts/ubuntu1604/00-beforeSetup.sh
#!/bin/bash
# ******************************************
# Developer: HienBV(<NAME>)
# Email:<EMAIL>
# Date: 08-11-2017
# ******************************************
# Update package
sudo apt update;
# sudo apt upgrade -y;
sudo apt autoremove;
echo "00-beforeSetup.sh: Done!!!!!";
| 0b14344ba9ac7620b0348e8b7a42e3400b903ec4 | [
"Markdown",
"Shell"
] | 10 | Shell | hienbv/vagrant-ubuntu1604 | 5f0c36556be459b1c1a19861962b52360120e91f | 25f0172a62bb424e6f453bebc97e9a975addcc8b |
refs/heads/master | <file_sep>class Ingredient < ApplicationRecord
has_many :doses, dependent: :restrict_with_exception
has_many :cocktails, through: :doses
validates :name, presence: true
validates :name, uniqueness: { case_sensitive: false,
message: "This ingredient already exists" }
end
| 1c1a5a3faa4df739e82c17e0db59f8461bf657bb | [
"Ruby"
] | 1 | Ruby | BlancSasha/rails-mister-cocktail | 4d84b910c6ac5e4170335cf83bc95cccc8132efe | 33c2e397f9e6f4eabc7fb9e6d9d7eec0f77a3142 |
refs/heads/master | <repo_name>Owned-by-MR/calcsf<file_sep>/src/AppBundle/Entity/Operation/Orr.php
<?php
namespace AppBundle\Entity\Operation;
class Orr implements OperationInterface
{
public function runCalculation($firstNumber, $secondNumber)
{
$a = print_r($firstNumber | $secondNumber, TRUE);
return $a;
}
}
<file_sep>/src/AppBundle/Entity/Operation/Andd.php
<?php
namespace AppBundle\Entity\Operation;
class Andd implements OperationInterface
{
public function runCalculation($firstNumber, $secondNumber)
{ // echo 'Bitwise result is: ';
$a=print_r($firstNumber & $secondNumber, TRUE);
return $a;
}
} | 17a2032ab25ab4fd5a4317f76c4f1205bf22cf18 | [
"PHP"
] | 2 | PHP | Owned-by-MR/calcsf | 3e54256e87096d4671d1891015dba6b3e687c0b5 | 1268b3b52a02382c91ebe37233287fff219636fa |
refs/heads/master | <file_sep>//=============================================================================
// Drill_MiniPlateForEvent.js
//=============================================================================
/*:
* @plugindesc [v1.4] 鼠标 - 事件说明窗口
* @author Drill_up
*
* @param ---窗口---
* @default
*
* @param 布局模式
* @parent ---窗口---
* @type select
* @option 默认窗口布局
* @value 默认窗口布局
* @option 黑底布局
* @value 黑底布局
* @option 系统窗口布局
* @value 系统窗口布局
* @option 图片窗口布局
* @value 图片窗口布局
* @desc 窗口背景布局的模式。
* @default 黑底布局
*
* @param 布局透明度
* @parent 布局模式
* @type number
* @min 0
* @max 255
* @desc 布局的透明度,0为完全透明,255为完全不透明。
* @default 255
*
* @param 资源-系统窗口布局
* @parent 布局模式
* @desc 配置该资源,可以使得该窗口有与默认不同的系统窗口。
* @default Window
* @require 1
* @dir img/system/
* @type file
*
* @param 资源-图片窗口布局
* @parent 布局模式
* @desc 背景图片布局的资源。
* @default
* @require 1
* @dir img/system/
* @type file
*
* @param 平移-图片窗口布局 X
* @parent 布局模式
* @desc 修正图片的偏移用。以窗口的点为基准,x轴方向平移,单位像素。(可为负数)
* @default 0
*
* @param 平移-图片窗口布局 Y
* @parent 布局模式
* @desc 修正图片的偏移用。以窗口的点为基准,y轴方向平移,单位像素。(可为负数)
* @default 0
*
* @param 是否锁定窗口位置
* @parent ---窗口---
* @type boolean
* @on 锁定
* @off 关闭
* @desc true - 锁定,false - 关闭,将面板锁定在一个固定的地方,而不是跟随鼠标位置走。
* @default false
*
* @param 平移-锁定位置 X
* @parent 是否锁定窗口位置
* @desc 将面板锁定在一个固定的地方,而不是跟随鼠标位置走。x轴方向平移,单位像素,0为贴在最左边。
* @default 0
*
* @param 平移-锁定位置 Y
* @parent 是否锁定窗口位置
* @desc 将面板锁定在一个固定的地方,而不是跟随鼠标位置走。y轴方向平移,单位像素,0为贴在最上面。
* @default 0
*
* @param 窗口行间距
* @parent ---窗口---
* @type number
* @min 0
* @desc 窗口内容之间的行间距。(rmmv默认标准:36)
* @default 10
*
* @param 窗口内边距
* @parent ---窗口---
* @type number
* @min 0
* @desc 窗口内容与窗口外框的内边距。(rmmv默认标准:18)
* @default 10
*
* @param 窗口字体大小
* @parent ---窗口---
* @type number
* @min 1
* @desc 窗口的字体大小。注意图标无法根据字体大小变化。(rmmv默认标准:28)
* @default 22
*
* @param 窗口附加宽度
* @parent ---窗口---
* @desc 在当前自适应的基础上,再额外增加的宽度。可为负数。
* @default 0
*
* @param 窗口附加高度
* @parent ---窗口---
* @desc 在当前自适应的基础上,再额外增加的高度。可为负数。
* @default 0
*
*
* @help
* =============================================================================
* +++ Drill_MiniPlateForEvent +++
* 作者:Drill_up
* 如果你有兴趣,也可以来看看更多我写的drill插件哦ヽ(*。>Д<)o゜
* https://rpg.blue/thread-409713-1-1.html
* =============================================================================
* 你可以使得鼠标靠近事件时,可以显示窗口说明。
* 关于窗口的配置介绍,去看看"窗口与布局.docx"。
* ★★必须放在所有"基于"的插件后面★★
*
* -----------------------------------------------------------------------------
* ----插件扩展
* 该插件 不能 单独使用,必须拥有下面插件作为基础,才能运行:
* 基于:
* - Drill_CoreOfInput 系统 - 输入设备核心
*
* -----------------------------------------------------------------------------
* ----设定注意事项
* 1.插件的作用域:地图界面。
* 作用于事件的行走图。
* 单独对鼠标有效。另支持触屏按住。
* 结构:
* (1.由于该窗口的大小是变化的,所以布局可以设定四种。
* 如果是触屏情况,可能需要将窗口锁定在一个固定位置,方便查看信息。
* (2.一个事件只能对应一个鼠标触发窗口方式,设置多个没有效果。
* 内容:
* (1.如果说明中没有任何字符,将不显示这个状态的说明内容。
* (2.写了一个"=>事件说明窗口"后,后面可以跟非常多的"=:"内容。
* (3.你可以设置"附加宽度高度"来适应被遮住的文字,但是不要加太多。
* 刷新:
* (1.插件不会主动刷新内容。
* (2.如果你想改变事件的内容信息,首先需要改变第二页的事件注释,
* 并且,你需要确保第一页和第二页的行走图不同即可。
* 只改变行走图朝向不会刷新。
* (3.你也可以使用插件指令强制刷新。
* 但是注意,强制刷新时,如果事件所处的事件页没有写注释,则没有任何效果。
* 接触面:
* (1.面板接触显示的触发范围与行走图大小相关,行走图资源越大,接触范围越大。
* 同一张行走图情况下,考虑到优化,鼠标范围默认不刷新。所以需要换图来触发刷新。
*
* -----------------------------------------------------------------------------
* ----关联文件
* 资源路径:img/system
* 先确保项目img文件夹下是否有system文件夹。
* 要查看所有关联资源文件的插件,可以去看看"插件清单.xlsx"。
* 如果没有,需要自己建立。需要配置资源文件:
*
* 资源-系统窗口布局
* 资源-图片窗口布局
*
* 系统窗口与rmmv默认的window.png图片一样,可设置为不同的皮肤。
* 图片布局不能根据窗口内容自适应,你需要合理控制的设置的说明文字。
*
* -----------------------------------------------------------------------------
* ----激活条件
* 你可以通过插件指令手动控制类型情况:
* (第一个冒号两边都有一个空格,=:后面的文字表示一行的内容。)
*
* 事件注释:=>事件说明窗口 : 鼠标接近 : 显示下列说明
* =:第一行内容
* =:第二行内容
* 事件注释:=>事件说明窗口 : 鼠标左键按下[持续] : 显示下列说明
* 事件注释:=>事件说明窗口 : 鼠标滚轮按下[持续] : 显示下列说明
* 事件注释:=>事件说明窗口 : 鼠标右键按下[持续] : 显示下列说明
* 事件注释:=>事件说明窗口 : 触屏按下[持续] : 显示下列说明
*
* 注意,一条注释最多能填入六行,如果你要设置更多内容,多加几个注释即可。
*
* -----------------------------------------------------------------------------
* ----可选设定
* 你可以通过插件指令,临时显示/隐藏窗口设置。
* (注意,冒号后面有两个空格。)
*
* 插件指令:>事件说明窗口 : 本事件 : 隐藏说明
* 插件指令:>事件说明窗口 : 本事件 : 显示说明
* 插件指令:>事件说明窗口 : 本事件 : 强制刷新说明
* 插件指令:>事件说明窗口 : 事件[2] : 隐藏说明
* 插件指令:>事件说明窗口 : 事件[3] : 显示说明
* 插件指令:>事件说明窗口 : 事件[3] : 强制刷新说明
*
* 1.数字对应的事件的id。
* 隐藏是暂时性的,切换了地图或者改变了事件的图像,就会失效。
* 2.使用"强制刷新说明"时,事件所处的事件页没有写注释,则没有任何效果。
*
* -----------------------------------------------------------------------------
* ----插件性能
* 测试仪器: 4G 内存,Intel Core i5-2520M CPU 2.5GHz 处理器
* Intel(R) HD Graphics 3000 集显 的垃圾笔记本
* (笔记本的3dmark综合分:571,鲁大师综合分:48456)
* 总时段: 20000.00ms左右
* 对照表: 0.00ms - 40.00ms (几乎无消耗)
* 40.00ms - 80.00ms (低消耗)
* 80.00ms - 120.00ms(中消耗)
* 120.00ms以上 (高消耗)
* 工作类型: 持续执行
* 时间复杂度: o(n^2) + o(图像处理) 每帧
* 测试方法: 指定地图中放置10个带有说明窗口的事件,测试触发情况。
* 测试结果: 200个事件的地图中,平均消耗为:【32.18ms】
* 100个事件的地图中,平均消耗为:【30.09ms】
* 50个事件的地图中,平均消耗为:【22.95ms】
*
* 1.插件只在自己作用域下工作消耗性能,在其它作用域下是不工作的。
* 测试结果并不是精确值,范围在给定值的10ms范围内波动。
* 更多了解插件性能,可以去看看"关于插件性能.docx"。
* 2.目前并没有设置大量含说明窗口的事件进行测试。
*
* -----------------------------------------------------------------------------
* ----更新日志
* [v1.0]
* 完成插件ヽ(*。>Д<)o゜
* [v1.1]
* 添加了附加宽度附加高度设置。
* [v1.2]
* 优化了窗口层级的位置。
* [v1.3]
* 分离了核心,优化了插件性能。添加了锁定功能。
* [v1.4]
* 修改了内部结构,添加了强制刷新插件指令。
*/
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// 插件简称: MPFE (Mini_Plate_For_Event)
// 临时全局变量 DrillUp.g_MPFE_xxx
// 临时局部变量 this._drill_MPFE_xxx
// 存储数据变量 无
// 全局存储变量 无
// 覆盖重写方法 无
//
// 工作类型 持续执行
// 时间复杂度 o(n^2) + o(图像处理) 每帧
// 性能测试因素 鼠标乱晃
// 性能测试消耗 30.09ms
// 最坏情况 当前视角,存在大批说明窗口的事件,并且玩家的鼠标乱晃。
// (该插件目前没有对最坏情况进行实测。)
//
//插件记录:
// ★大体框架与功能如下:
// 事件说明窗口:
// ->显示隐藏
// ->鼠标事件
// ->多行内容
// ->内容转义
// ->窗口皮肤
//
// ★必要注意事项:
// 1.插件的面板画在ui层。
//
// ★其它说明细节:
// 1.该插件原理为 鼠标触发事件 和 状态和buff说明窗口 的组合效果。
// 实际上结合后,改动非常大,结构已经截然不同了。
// 2.地图界面最容易造成卡顿问题,稍不注意,计算量就暴涨,一定要加约束。
// (窗口的宽高不要轻易修改,每次修改都会重画)
// 3. 2020/9/13:
// 这个插件给我的印象一点都不好,糟透了。刷新文本非常困难。
// 由于之前加锁加的太死了,结构环环相扣,修改内容后,仍然不变,就很头疼。
// 从原理上,这里分成了三个管理体系:
// 窗口与鼠标(难点在鼠标悬停、鼠标离开)
// 事件页与文本内容(难点在文本变化时机、行走图变化时机)
// 事件贴图触发范围(难点在获取事件的位置、贴图触发区)
// 这三个结构纠缠在一起,难以分离。
// 并且,我还没有找到很好的方法将它们独立开来。
// 可能还需要花时间建立 特殊的核心 或 对象捕获体系。
//
// ★存在的问题:
// 暂无
//
//=============================================================================
// ** 变量获取
//=============================================================================
var Imported = Imported || {};
Imported.Drill_MiniPlateForEvent = true;
var DrillUp = DrillUp || {};
DrillUp.parameters = PluginManager.parameters('Drill_MiniPlateForEvent');
DrillUp.g_MPFE_layout_type = String(DrillUp.parameters["布局模式"] || "黑底布局");
DrillUp.g_MPFE_opacity = Number(DrillUp.parameters["布局透明度"] || 255);
DrillUp.g_MPFE_layout_window = String(DrillUp.parameters["资源-系统窗口布局"] );
DrillUp.g_MPFE_layout_pic = String(DrillUp.parameters["资源-图片窗口布局"] );
DrillUp.g_MPFE_layout_pic_x = Number(DrillUp.parameters["平移-图片窗口布局 X"] );
DrillUp.g_MPFE_layout_pic_y = Number(DrillUp.parameters["平移-图片窗口布局 Y"] );
DrillUp.g_MPFE_lock_enable = String(DrillUp.parameters["是否锁定窗口位置"] || "false") === "true";
DrillUp.g_MPFE_lock_x = Number(DrillUp.parameters["平移-锁定位置 X"] || 0);
DrillUp.g_MPFE_lock_y = Number(DrillUp.parameters["平移-锁定位置 Y"] || 0);
DrillUp.g_MPFE_lineheight = Number(DrillUp.parameters["窗口行间距"] || 10);
DrillUp.g_MPFE_padding = Number(DrillUp.parameters["窗口内边距"] || 18);
DrillUp.g_MPFE_fontsize = Number(DrillUp.parameters["窗口字体大小"] || 22);
DrillUp.g_MPFE_ex_width = Number(DrillUp.parameters["窗口附加宽度"] || 0);
DrillUp.g_MPFE_ex_height = Number(DrillUp.parameters["窗口附加高度"] || 0);
//=============================================================================
// * >>>>基于插件检测>>>>
//=============================================================================
if( Imported.Drill_CoreOfInput ){
//=============================================================================
// ** 插件指令
//=============================================================================
var _drill_MPFE_pluginCommand = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
_drill_MPFE_pluginCommand.call(this, command, args);
if( command === ">事件说明窗口" ){ // >事件说明窗口 : A : 隐藏说明
if(args.length == 4){
var temp1 = String(args[1]);
var type = String(args[3]);
if( type == "隐藏说明" ){
var e_id = 0;
if( temp1 == "本事件" ){
e_id = this._eventId;
}else if( temp1.indexOf("事件[") != -1 ){
temp1 = temp1.replace("事件[","");
temp1 = temp1.replace("]","");
e_id = Number(temp1);
}else{
e_id = Number(temp1);
}
if( $gameMap.drill_MPFE_isEventExist( e_id ) == false ){ return; }
$gameMap.drill_MPFE_setDataVisible( e_id , false );
}
if( type == "显示说明" ){
var e_id = 0;
if( temp1 == "本事件" ){
e_id = this._eventId;
}else if( temp1.indexOf("事件[") != -1 ){
temp1 = temp1.replace("事件[","");
temp1 = temp1.replace("]","");
e_id = Number(temp1);
}else{
e_id = Number(temp1);
}
if( $gameMap.drill_MPFE_isEventExist( e_id ) == false ){ return; }
$gameMap.drill_MPFE_setDataVisible( e_id , true );
}
if( type == "强制刷新说明" ){
var e_id = 0;
if( temp1 == "本事件" ){
e_id = this._eventId;
}else if( temp1.indexOf("事件[") != -1 ){
temp1 = temp1.replace("事件[","");
temp1 = temp1.replace("]","");
e_id = Number(temp1);
}else{
e_id = Number(temp1);
}
if( $gameMap.drill_MPFE_isEventExist( e_id ) == false ){ return; }
$gameMap.event( e_id )._drill_MPFE_eventNeedRefresh = true;
}
}
}
};
//==============================
// ** 插件指令 - 事件检查
//==============================
Game_Map.prototype.drill_MPFE_isEventExist = function( e_id ){
if( e_id == 0 ){ return false; }
var e = this.event( e_id );
if( e == undefined ){
alert( "【Drill_MiniPlateForEvent.js 鼠标 - 事件说明窗口】\n" +
"插件指令错误,当前地图并不存在id为"+e_id+"的事件。");
return false;
}
return true;
}
//=============================================================================
// ** 事件贴图
//=============================================================================
//==============================
// * 事件贴图 - 初始化
//==============================
//var _drill_MPFE_setCharacter = Sprite_Character.prototype.setCharacter;
//Sprite_Character.prototype.setCharacter = function( character ){ //图像改变,范围就改变
// _drill_MPFE_setCharacter.call(this,character);
// this.drill_MPFE_refreshTrigger();
//};
//==============================
// * 事件贴图 - 刷新内容
//==============================
Sprite_Character.prototype.drill_MPFE_refreshTrigger = function() {
if(!this._character ){ return; }
if( this._character.constructor.name !== "Game_Event" ){ return; }
var page = this._character.page();
if(!page ){ return; }
var temp_list = this._character.list();
var temp_context = [];
var start_count = false; //多行注释索引
var type = "";
for(var i=0; i < temp_list.length; i++){
var l = temp_list[i];
if( l.code === 108 || l.code === 408 ){
var row = l.parameters[0];
var args = l.parameters[0].split(' ');
var command = args.shift();
if( command == "=>事件说明窗口" ){ //=>事件说明窗口 : 鼠标滚轮按下[持续] : 显示下列说明 =:xxxx =:xxx
if(args.length >= 2){
if(args[1]){ type = String(args[1]); }
if(args[3]){ var temp1 = String(args[3]); }
if( temp1 == "显示下列说明" ){
start_count = true;
continue;
}
}
};
if( start_count == true ){
if(row.contains("=:")){
temp_context.push(row.replace("=:",""));
}else{
start_count = false;
}
}
};
};
if( temp_context.length != 0 ){ //添加多条内容
var obj = {};
obj._event_id = this._character._eventId; //只能存数据,不能存对象指针
obj._event_pageIndex = this._character._pageIndex;
obj._type = type;
obj._context = temp_context;
obj._enable = true;
$gameMap.drill_MPFE_pushData(obj);
}
};
//==============================
// * 事件贴图 - 刷新内容
//==============================
var _drill_MPFE_spriteUpdate = Sprite_Character.prototype.update;
Sprite_Character.prototype.update = function() {
// > 切换图片时变化
if( this.isImageChanged() ){
this.drill_MPFE_refreshTrigger();
}
// > 原函数
_drill_MPFE_spriteUpdate.call( this );
// > 强制刷新
if(!this._character ){ return; }
if( this._character.constructor.name !== "Game_Event" ){ return; }
if( this._character._drill_MPFE_eventNeedRefresh == true ){
this._character._drill_MPFE_eventNeedRefresh = false;
this.drill_MPFE_refreshTrigger();
}
}
//=============================================================================
// ** 数据刷新
//=============================================================================
//==============================
// * 地图 - 初始化
//==============================
var _drill_MPFE_gmap_initialize = Game_Map.prototype.initialize;
Game_Map.prototype.initialize = function() {
_drill_MPFE_gmap_initialize.call(this);
this._drill_MPFE_data = [];
};
//==============================
// * 地图 - 切换地图
//==============================
var _drill_MPFE_gmap_setup = Game_Map.prototype.setup;
Game_Map.prototype.setup = function(mapId) {
_drill_MPFE_gmap_setup.call(this,mapId);
this._drill_MPFE_data = [];
}
//==============================
// * 地图 - 添加条件
//==============================
Game_Map.prototype.drill_MPFE_pushData = function( obj ){
for(var i=0; i<this._drill_MPFE_data.length; i++){
var temp_obj = this._drill_MPFE_data[i];
if( temp_obj._event_id == obj._event_id &&
temp_obj._type == obj._type ){
// > 重复的不插入
if( temp_obj._event_pageIndex == obj._event_pageIndex ){ return ;}
// > 事件页不同的,覆盖
this._drill_MPFE_data[i] = obj;
return;
}
}
this._drill_MPFE_data.push(obj);
};
//==============================
// * 地图 - 去除条件
//==============================
Game_Map.prototype.drill_MPFE_setDataVisible = function(event_id,v) {
for(var i = this._drill_MPFE_data.length-1; i >= 0; i--){
var temp_obj = this._drill_MPFE_data[i];
if( temp_obj._event_id == event_id ){
temp_obj._enable = v;
}
}
}
//=============================================================================
// ** 地图场景中 说明面板实例
//=============================================================================
//==============================
// * 实例 - 创建面板(ui层)
//==============================
var _drill_MPFE_Scene_createSpriteset = Scene_Map.prototype.createSpriteset;
Scene_Map.prototype.createSpriteset = function() {
_drill_MPFE_Scene_createSpriteset.call(this);
if (!this._drill_map_ui_board) {
this._drill_map_ui_board = new Sprite();
this.addChild(this._drill_map_ui_board);
};
if( !this._drill_mini_event_plate ){ //只建立一个窗口
this._drill_mini_event_plate = new Drill_MiniPlateForEvent_Window();
this._drill_mini_event_plate.zIndex = 1;
this._drill_map_ui_board.addChild(this._drill_mini_event_plate);
}
};
//==============================
// * 实例 - 帧刷新
//==============================
var _drill_MPFE_smap_update = Scene_Map.prototype.updateScene;
Scene_Map.prototype.updateScene = function() {
_drill_MPFE_smap_update.call(this);
this._drill_MPFE_updateMiniPlate();
}
Scene_Map.prototype._drill_MPFE_updateMiniPlate = function() {
// > 从地图贴图找起 >> 找到含event的Sprite_Character >> 刷新事件的注释
var char_sprites = this._spriteset._characterSprites;
for(var i=0; i< char_sprites.length; i++){
var temp_sprite = char_sprites[i];
if(!temp_sprite ){ continue; }
var temp_character = temp_sprite._character;
if(!temp_character ){ continue; }
if( temp_character.constructor.name !== "Game_Event" ){ continue; }
for( var j = 0; j< $gameMap._drill_MPFE_data.length; j++ ){
var temp_obj = $gameMap._drill_MPFE_data[j];
if( temp_character._eventId == temp_obj._event_id ){
//刷新事件注释不需要找父类,因为这个函数就在Scene_Map中
var cw = temp_sprite.patternWidth() ;
var ch = temp_sprite.patternHeight() ;
var check = {
'x': temp_sprite.x - cw*temp_sprite.anchor.x,
'y': temp_sprite.y - ch*temp_sprite.anchor.y,
'w': cw,
'h': ch,
't': temp_obj._context,
'id': temp_character._eventId,
'type': temp_obj._type,
'enable': temp_obj._enable
}
this._drill_mini_event_plate.drill_pushChecks(check);
}
}
}
};
//=============================================================================
// * Drill_MiniPlateForEvent_Window 说明面板(整个场景只有一个该窗口)
// (该面板 与 Drill_MiniPlateForState_Window 结构一模一样)
//=============================================================================
//==============================
// * 说明面板 - 定义
//==============================
function Drill_MiniPlateForEvent_Window() {
this.initialize.apply(this, arguments);
};
Drill_MiniPlateForEvent_Window.prototype = Object.create(Window_Base.prototype);
Drill_MiniPlateForEvent_Window.prototype.constructor = Drill_MiniPlateForEvent_Window;
//==============================
// * 说明面板 - 初始化
//==============================
Drill_MiniPlateForEvent_Window.prototype.initialize = function() {
Window_Base.prototype.initialize.call(this, 0, 0, 0, 0);
this._drill_data = {};
this.drill_initData(); //初始化数据
this.drill_initSprite(); //初始化对象
};
//==============================
// * 说明面板 - 帧刷新
//==============================
Drill_MiniPlateForEvent_Window.prototype.update = function() {
Window_Base.prototype.update.call(this);
this.drill_updateChecks(); //判断条件
this.drill_updatePosition(); //刷新位置
}
//==============================
// * 说明面板 - 窗口属性
//==============================
Drill_MiniPlateForEvent_Window.prototype.standardFontSize = function() {
return DrillUp.g_MPFE_fontsize;
};
Drill_MiniPlateForEvent_Window.prototype.standardPadding = function() {
return DrillUp.g_MPFE_padding;
};
//==============================
// * 接口 - 添加内容判断
//==============================
Drill_MiniPlateForEvent_Window.prototype.drill_pushChecks = function(c) {
if( this._drill_check_tank.length < 1000){ //防止卡顿造成的过度积压
this._drill_check_tank.push(c);
}
}
//==============================
// * 初始化 - 数据
//==============================
Drill_MiniPlateForEvent_Window.prototype.drill_initData = function() {
var data = this._drill_data;
data['layout_type'] = DrillUp.g_MPFE_layout_type;
data['opacity'] = DrillUp.g_MPFE_opacity;
data['pic_x'] = DrillUp.g_MPFE_layout_pic_x;
data['pic_y'] = DrillUp.g_MPFE_layout_pic_y;
// > 私有属性初始化
this._drill_winSkin_bitmap = ImageManager.loadSystem(DrillUp.g_MPFE_layout_window);
this._drill_pic_bitmap = ImageManager.loadSystem(DrillUp.g_MPFE_layout_pic);
this._drill_width = 0;
this._drill_height = 0;
this._drill_visible = false;
this._drill_check_tank = []; //条件缓冲器(帧刷新会不断加入,窗口内会去重复)
this._drill_curEventId = 0; //当前指向事件
this._drill_curContext = null; //当前指向内容(传的是指针)
// > 窗口属性
this.createContents();
this.contents.clear();
this._windowBackSprite.zIndex = 2;
this._windowFrameSprite.zIndex = 3;
}
//==============================
// * 初始化 - 对象
//==============================
Drill_MiniPlateForEvent_Window.prototype.drill_initSprite = function() {
this.drill_createBackground(); //创建背景
this.drill_sortBottomByZIndex(); //底层层级排序
}
//==============================
// * 创建 - 背景
//==============================
Drill_MiniPlateForEvent_Window.prototype.drill_createBackground = function() {
var data = this._drill_data;
this._drill_background = new Sprite();
this._drill_background.zIndex = 1;
this._drill_background.opacity = data['opacity'];
this._windowBackSprite.opacity = 0;
this._windowFrameSprite.opacity = 0;
if( data['layout_type'] == "图片窗口布局" ){
this._drill_background.bitmap = this._drill_pic_bitmap;
this._drill_background.x = data['pic_x'];
this._drill_background.y = data['pic_y'];
}else if( data['layout_type'] == "系统窗口布局" ){
this.windowskin = this._drill_winSkin_bitmap;
this._windowBackSprite.opacity = data['opacity'];
this._windowFrameSprite.opacity = data['opacity'];
}else if( data['layout_type'] == "默认窗口布局" ){
this.opacity = data['opacity'];
this._windowBackSprite.opacity = data['opacity'];
this._windowFrameSprite.opacity = data['opacity'];
}
this._windowSpriteContainer.addChild(this._drill_background);
//_windowSpriteContainer为窗口的最底层贴图
}
//==============================
// ** 底层层级排序
//==============================
Drill_MiniPlateForEvent_Window.prototype.drill_sortBottomByZIndex = function() {
this._windowSpriteContainer.children.sort(function(a, b){return a.zIndex-b.zIndex}); //比较器
};
//==============================
// * 帧刷新 - 刷新位置
//==============================
Drill_MiniPlateForEvent_Window.prototype.drill_updatePosition = function() {
var data = this._drill_data;
var cal_x = _drill_mouse_x;
var cal_y = _drill_mouse_y;
if( cal_x + this._drill_width > Graphics.boxWidth ){ //横向贴边控制
cal_x = Graphics.boxWidth - this._drill_width;
}
if( cal_y + this._drill_height > Graphics.boxHeight ){ //纵向贴边控制
cal_y = Graphics.boxHeight - this._drill_height;
}
if( DrillUp.g_MPFE_lock_enable == true ){ //锁定位置
cal_x = DrillUp.g_MPFE_lock_x;
cal_y = DrillUp.g_MPFE_lock_y;
}
this.x = cal_x;
this.y = cal_y;
}
//==============================
// * 帧刷新 - 判断条件
//==============================
Drill_MiniPlateForEvent_Window.prototype.drill_updateChecks = function() {
var data = this._drill_data;
if( !this._drill_check_tank ){ this.visible = false ; return ;}
var is_visible = false;
var check_obj = null;
for(var i=0; i<this._drill_check_tank.length; i++){
var temp_check = this._drill_check_tank[i];
if ( this.drill_checkCondition(temp_check) ) {
is_visible = true;
check_obj = temp_check;
break;
}
}
//这里有三道锁,看起来会比较乱
//(check.enable显示/隐藏 锁 ,this._drill_visible 接近/离开 锁,this._drill_curEventId 落在不同事件上的锁)
if( check_obj && check_obj.enable == true ){
if ( this._drill_visible == true ) {
if( is_visible == true ){
//显示中
if( this._drill_curEventId != check_obj.id ||
this._drill_curContext != check_obj.t ){
this._drill_curEventId = check_obj.id;
this._drill_curContext = check_obj.t;
this.drill_reflashTextMassage(check_obj.t);
}
}else{
//显示中断
this._drill_visible = false;
this._drill_width = 0;
this._drill_height = 0;
}
}else{
if( is_visible == true ){
//激活显示
//this.drill_reflashTextMassage(check_obj.t);
//this._drill_curEventId = check_obj.id ;
this._drill_visible = true;
}else{
//隐藏中,不操作
}
}
}else{
this._drill_visible = false;
}
//(宽高不要轻易修改)
this.visible = this._drill_visible;
this._drill_check_tank = [];
}
//==============================
// * 激活 - 显示条件
//==============================
Drill_MiniPlateForEvent_Window.prototype.drill_checkCondition = function( check ){
var _x = _drill_mouse_x;
var _y = _drill_mouse_y;
if(check.type == "触屏按下[持续]"){
var _x = TouchInput.x;
var _y = TouchInput.y;
}
if(_x > check.x + check.w){ return false;}
if(_x < check.x + 0){ return false;}
if(_y > check.y + check.h){ return false;}
if(_y < check.y + 0 ){ return false;}
if(check.type == "鼠标左键按下[持续]"){
if( TouchInput.drill_isLeftPressed() ){ return true; }else{ return false; }
}else if(check.type == "鼠标滚轮按下[持续]"){
if( TouchInput.drill_isMiddlePressed() ){ return true; }else{ return false; }
}else if(check.type == "鼠标右键按下[持续]"){
if( TouchInput.drill_isRightPressed() ){ return true; }else{ return false; }
}else if(check.type == "触屏按下[持续]"){
if( TouchInput.isPressed() ){ return true; }else{ return false; }
}
return true;
}
//==============================
// * 激活 - 刷新内容
//==============================
Drill_MiniPlateForEvent_Window.prototype.drill_reflashTextMassage = function( contexts ){
if(contexts.length == 0){ return }
var data = this._drill_data;
//1.内容获取
var tar_width = 0;
//2.长度判定(必须在绘制前)
for (var i=0; i< contexts.length; i++) {
var ic = 0; //icon字符大小
var temp = contexts[i];
var temp_s = temp.concat();
temp_s = temp_s.replace(/\\C\[\d+\]/gi,'');
temp_s = temp_s.replace(/\\I\[\d+\]/gi,function(){
ic+=1;
return '';
}.bind(this));
var temp_w = this.textWidth(temp_s) + ic * (this.standardFontSize() + 8);
if( temp_w > tar_width ){
tar_width = temp_w;
}
}
this._drill_width = tar_width;
this._drill_height = contexts.length * ( this.standardFontSize() + DrillUp.g_MPFE_lineheight);
this._drill_width += this.standardPadding() * 2;
this._drill_height += this.standardPadding() * 2;
this._drill_width += DrillUp.g_MPFE_ex_width;
this._drill_height += DrillUp.g_MPFE_ex_height;
if( contexts.length == 0){
this._drill_width = 0;
this._drill_height = 0;
}
this.width = this._drill_width;
this.height = this._drill_height;
//3.绘制内容
this.createContents();
this.contents.clear();
for (var i=0; i< contexts.length; i++) {
var x = 0;
var y = 0 + i*( this.standardFontSize() + DrillUp.g_MPFE_lineheight);
var temp = contexts[i];
this.drawTextEx(temp,x,y);
}
//if(contexts.length >= 1){
// alert(contexts);
// alert(this._drill_width);
// alert(this._drill_height);
//}
if( data['layout_type'] == "黑底布局" ){
this._drill_background_bitmap = new Bitmap(this._drill_width, this._drill_height);
this._drill_background_bitmap.fillRect(0, 0 , this._drill_width, this._drill_height, "#000000");//背景黑框
this._drill_background.bitmap = this._drill_background_bitmap;
}
}
//=============================================================================
// * <<<<基于插件检测<<<<
//=============================================================================
}else{
Imported.Drill_MiniPlateForEvent = false;
alert(
"【Drill_MiniPlateForEvent.js 鼠标 - 事件说明窗口】\n缺少基础插件,去看看下列插件是不是 未添加 / 被关闭 / 顺序不对:"+
"\n- Drill_CoreOfInput 系统-输入设备核心"
);
}
<file_sep>//=============================================================================
// Yanfly Engine Plugins - Slippery Tiles
// YEP_SlipperyTiles.js
//=============================================================================
var Imported = Imported || {};
Imported.YEP_SlipperyTiles = true;
var Yanfly = Yanfly || {};
Yanfly.Slip = Yanfly.Slip || {};
Yanfly.Slip.version = 1.05
//=============================================================================
/*:
* @plugindesc v1.05 [v1.4] 互动 - 光滑图块
* @author Yanfly Engine Plugins (drill_up翻译+优化)
*
* @param 滑行动作
* @type number
* @min 0
* @desc 滑行时角色的行走动作。根据当前角色的行走图的位置开始,0-左,1-中,2-右,>2会选择往右的其它行走图。
* @default 2
*
* @param 光滑区域
* @type number
* @min 0
* @max 255
* @desc 填入R区域的ID,地图中设置的R区域将会变为光滑区域,0表示没有区域。
* @default 0
*
* @param 滑行速度
* @type number
* @min 0
* @desc 玩家滑行时会改变到指定速度,填入1-6,4为标准速度,0表示速度不变。
* @default 0
*
* @param 斜向滑行是否穿透两边阻碍
* @type boolean
* @on 穿透
* @off 不穿透
* @desc 假设向左上方滑行,左上方可以通行,但是左方和上方两处都有阻碍,设置不穿透则会被阻挡。
* @default true
*
* @help
* ============================================================================
* 插件介绍
* ============================================================================
* 能使得地图中指定的区域或者图块表面完全光滑,玩家走在上面会一直滑行,
* 滑行过程不能改变方向。
* 更多详细的介绍,去看看"关于光滑图块.docx"。
*
* ============================================================================
* 设定注意事项
* ============================================================================
* 1.插件的作用域:地图界面。
* 只对玩家有效,NPC不能滑行。
* 2.如果滑行时需要强制转向,需要使用插件指令。
* (rmmv事件的转向会让角色暂停滑行,如果玩家一直按住方向键,会无视强制转向。)
* 3.玩家可以举着花盆滑行
* 4.玩家可以在滑行时跳跃
* 5.斜向滑行时,可以设置是否穿透对角两边的阻碍。
*
* ============================================================================
* 可选设定 - 滑行转向
* ============================================================================
* 你可以通过插件指令临时控制滑行的方向:
*
* 插件指令: >光滑图块 : 转向上方
* 插件指令: >光滑图块 : 转向下方
* 插件指令: >光滑图块 : 转向左方
* 插件指令: >光滑图块 : 转向右方
*
* 插件指令: >光滑图块 : 转向左上方
* 插件指令: >光滑图块 : 转向左下方
* 插件指令: >光滑图块 : 转向右上方
* 插件指令: >光滑图块 : 转向右下方
*
* ============================================================================
* 可选设定 - 图块注释
* ============================================================================
* 除了指定R区域为光滑的表面,你可以直接在图块中设置指定的图块为光滑表面。
*
* 图块注释: <Slippery Tile: x>
* 图块注释: <Slippery Tile: x, x, x>
*
* 参数x:
* 指定参数对应的图块ID将为光滑表面。
* (图块ID,指的是地形标志,默认0,你可以设置0-7。)
*
* ============================================================================
* ----插件性能
* ============================================================================
* 测试仪器: 4G 内存,Intel Core i5-2520M CPU 2.5GHz 处理器
* Intel(R) HD Graphics 3000 集显 的垃圾笔记本
* (笔记本的3dmark综合分:571,鲁大师综合分:48456)
* 总时段: 20000.00ms左右
* 对照表: 0.00ms - 40.00ms (几乎无消耗)
* 40.00ms - 80.00ms (低消耗)
* 80.00ms - 120.00ms(中消耗)
* 120.00ms以上 (高消耗)
* 工作类型: 持续执行
* 时间复杂度: o(n)*o(玩家动作) 每帧
* 测试方法: 去物体管理层、地理管理层、鼠标管理层转一圈测试就可以了。
* 测试结果: 200个事件的地图中,消耗为:【48.42ms】
* 100个事件的地图中,消耗为:【40.19ms】
* 50个事件的地图中,消耗为:【63.58ms】
* 光滑图块设计地图中,消耗为:【20.95ms】
*
* 1.插件只在自己作用域下工作消耗性能,在其它作用域下是不工作的。
* 测试结果并不是精确值,范围在给定值的10ms范围内波动。
* 更多了解插件性能,可以去看看"关于插件性能.docx"。
* 2.插件实际测试中的值不是很稳定。虽然插件只对玩家起效,但是有时候会在
* 某些时刻飙升到81.81ms,而有时候又低落到20.95ms。目前原因不明。
*
* ============================================================================
* 关于Drill_up优化:
* ============================================================================
* [v1.1]
* 添加了转向插件指令功能,并且使得可以斜向滑行。
* [v1.2]
* 修复了转向地毯撞墙时,会一直卡住的bug。并且添加了斜向滑行的穿透阻碍设置。
* [v1.3]
* 修改了插件分类。
* [v1.4]
* 添加了插件性能测试说明。
*
* ============================================================================
* 版本更新日志
* ============================================================================
*
* Version 1.05:
* - Updated for RPG Maker MV version 1.5.0.
*
* Version 1.04:
* - Added 'Slippery Speed' plugin parameter to var you change the speed of
* a character when its on a slippery tile.
*
* Version 1.03:
* - Added anti-crash for switch checks from battle tests.
*
* Version 1.02:
* - Updated for RPG Maker MV version 1.1.0.
*
* Version 1.01:
* - Added failsafe for people who aren't using tilesets
*
* Version 1.00:
* - Finished Plugin!
*/
//=============================================================================
//=============================================================================
// Parameter Variables
//=============================================================================
Yanfly.Parameters = PluginManager.parameters('YEP_SlipperyTiles');
Yanfly.Param = Yanfly.Param || {};
Yanfly.Param.SlipRegion = Number(Yanfly.Parameters['光滑区域']);
Yanfly.Param.SlipFrame = Number(Yanfly.Parameters['滑行动作']);
Yanfly.Param.SlipSpeed = Number(Yanfly.Parameters['滑行速度']);
Yanfly.Param.SlipDiagonallyThrough = String(Yanfly.Parameters['斜向滑行是否穿透两边阻碍'] || "true") == "true";
//=============================================================================
// 插件指令
//=============================================================================
var _drill_yep_SlipperyTiles_pluginCommand = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
_drill_yep_SlipperyTiles_pluginCommand.call(this, command, args);
if (command === '>光滑图块') {
if(args.length == 2){
var type = String(args[1]);
if (type === '转向上方') {
$gameSystem._drill_yep_SlipperyTiles_direction = 8;
}
if (type === '转向下方') {
$gameSystem._drill_yep_SlipperyTiles_direction = 2;
}
if (type === '转向左方') {
$gameSystem._drill_yep_SlipperyTiles_direction = 4;
}
if (type === '转向右方') {
$gameSystem._drill_yep_SlipperyTiles_direction = 6;
}
if (type === '转向左上方') {
$gameSystem._drill_yep_SlipperyTiles_direction = 48;
}
if (type === '转向左下方') {
$gameSystem._drill_yep_SlipperyTiles_direction = 42;
}
if (type === '转向右上方') {
$gameSystem._drill_yep_SlipperyTiles_direction = 68;
}
if (type === '转向右下方') {
$gameSystem._drill_yep_SlipperyTiles_direction = 62;
}
}
}
};
//=============================================================================
// DataManager
//=============================================================================
Yanfly.Slip.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded;
DataManager.isDatabaseLoaded = function() {
if (!Yanfly.Slip.DataManager_isDatabaseLoaded.call(this)) return false;
if (!Yanfly._loaded_YEP_SlipperyTiles) {
this.processSlipNotetags($dataTilesets);
Yanfly._loaded_YEP_SlipperyTiles = true;
}
return true;
};
DataManager.processSlipNotetags = function(group) {
var regexp1 = /<(?:SLIPPERY|slippery tile):[ ]*(\d+(?:\s*,\s*\d+)*)>/i;
for (var n = 1; n < group.length; n++) {
var obj = group[n];
var notedata = obj.note.split(/[\r\n]+/);
obj.slippery = [];
for (var i = 0; i < notedata.length; i++) {
var line = notedata[i];
if (line.match(regexp1)) {
var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']');
obj.slippery = obj.slippery.concat(array);
}
}
}
};
//=============================================================================
// Game_Map
//=============================================================================
Game_Map.prototype.isSlippery = function(mx, my) {
if ($gameParty.inBattle()) return false;
if (this.isValid(mx, my) && this.tileset()) {
if (Yanfly.Param.SlipRegion !== 0 &&
this.regionId(mx, my) === Yanfly.Param.SlipRegion) return true;
var tagId = this.terrainTag(mx, my);
var slipTiles = this.tileset().slippery;
return slipTiles.contains(tagId);
}
return false;
};
//=============================================================================
// Game_CharacterBase
//=============================================================================
Game_CharacterBase.prototype.onSlipperyFloor = function() {
return $gameMap.isSlippery(this._x, this._y);
};
Game_CharacterBase.prototype.slipperyPose = function() {
if (!this.onSlipperyFloor()) return false;
if (this._stepAnime) return false;
return true;
};
Yanfly.Slip.Game_CharacterBase_pattern = Game_CharacterBase.prototype.pattern;
Game_CharacterBase.prototype.pattern = function() {
if (this.slipperyPose()) return Yanfly.Param.SlipFrame;
return Yanfly.Slip.Game_CharacterBase_pattern.call(this);
};
Yanfly.Slip.Game_CharacterBase_realMoveSpeed = Game_CharacterBase.prototype.realMoveSpeed;
Game_CharacterBase.prototype.realMoveSpeed = function() {
if (this.onSlipperyFloor() && Yanfly.Param.SlipSpeed > 0) {
return Yanfly.Param.SlipSpeed;
}
return Yanfly.Slip.Game_CharacterBase_realMoveSpeed.call(this);
};
//=============================================================================
// Game_Player
//=============================================================================
Yanfly.Slip.Game_Player_isDashing = Game_Player.prototype.isDashing;
Game_Player.prototype.isDashing = function() {
if (this.onSlipperyFloor()) return false;
return Yanfly.Slip.Game_Player_isDashing.call(this);
};
Yanfly.Slip.Game_Player_update = Game_Player.prototype.update;
Game_Player.prototype.update = function(sceneActive) {
Yanfly.Slip.Game_Player_update.call(this, sceneActive);
this.updateSlippery();
};
Yanfly.Slip.Game_Player_moveByInput = Game_Player.prototype.moveByInput;
Game_Player.prototype.moveByInput = function() {
if($gameSystem._drill_yep_SlipperyTiles_direction ){
if( this.isMovementSucceeded() ){
}else{
$gameSystem._drill_yep_SlipperyTiles_direction = null; //移动失败(撞墙)立即停止滑行
}
}else{
Yanfly.Slip.Game_Player_moveByInput.call(this);
}
};
Game_Player.prototype.updateSlippery = function() {
if ($gameMap.isEventRunning()) return;
if (this.onSlipperyFloor() && !this.isMoving()) {
$gameTemp.clearDestination();
if($gameSystem._drill_yep_SlipperyTiles_direction != undefined){
if($gameSystem._drill_yep_SlipperyTiles_direction < 10){
this.moveStraight($gameSystem._drill_yep_SlipperyTiles_direction);
}else if($gameSystem._drill_yep_SlipperyTiles_direction == 42){
this.moveDiagonally(4, 2);
}else if($gameSystem._drill_yep_SlipperyTiles_direction == 62){
this.moveDiagonally(6, 2);
}else if($gameSystem._drill_yep_SlipperyTiles_direction == 48){
this.moveDiagonally(4, 8);
}else if($gameSystem._drill_yep_SlipperyTiles_direction == 68){
this.moveDiagonally(6, 8);
}
}else{
if(this.isMovementSucceeded()){ //斜向滑行被阻止后,关闭向前滑行
this.moveStraight(this._direction);
}
}
}
if(!this.onSlipperyFloor()){
$gameSystem._drill_yep_SlipperyTiles_direction = null;
}
};
//==============================
// * 穿透判断斜向可通行区域
//==============================
var _drill_yep_SlipperyTiles_canPassDiagonally = Game_CharacterBase.prototype.canPassDiagonally;
Game_CharacterBase.prototype.canPassDiagonally = function(x, y, horz, vert) {
if( $gameSystem._drill_yep_SlipperyTiles_direction != null && Yanfly.Param.SlipDiagonallyThrough == true ){ //滑行中时设置斜向判断
var x2 = $gameMap.roundXWithDirection(x, horz);
var y2 = $gameMap.roundYWithDirection(y, vert);
return $gameMap.drill_yepST_isAnyPassable(x2, y2);
}else{
return _drill_yep_SlipperyTiles_canPassDiagonally.call(this,x, y, horz, vert);
}
};
//==============================
// * 判断图块可通行情况(isPassable需要指定方向是否可通行,这里任意一个方向可通行则返回true)
//==============================
Game_Map.prototype.drill_yepST_isAnyPassable = function( x, y ) {
return this.isPassable(x, y, 2)||this.isPassable(x, y, 4)||this.isPassable(x, y, 6)||this.isPassable(x, y, 8);
}
//=============================================================================
// End of File
//=============================================================================
<file_sep>//=============================================================================
// Drill_CoreOfEventTags.js
//=============================================================================
/*:
* @plugindesc [v1.0] 物体 - 事件标签核心
* @author Drill_up
*
*
* @help
* =============================================================================
* +++ Drill_CoreOfEventTags +++
* 作者:Drill_up
* 如果你有兴趣,也可以来看看更多我写的drill插件哦ヽ(*。>Д<)o゜
* https://rpg.blue/thread-409713-1-1.html
* =============================================================================
* 该插件为基础核心。可以单独使用。
* 给指定事件添加各种标签,用于子插件捕获使用。
*
* -----------------------------------------------------------------------------
* ----插件扩展
* 该插件为基础核心,是以下插件的依赖。
* 可作用于:
* - Drill_CoreOfEventTags 物体触发 - 固定区域核心
* 插件的筛选器可以支持"必须含指定标签的事件"的捕获。
*
* -----------------------------------------------------------------------------
* ----设定注意事项
* 1.插件的作用域:地图界面。
* 只作用于事件。
* 标签与筛选器:
* (1.标签属于辅助性功能,用于区分不同事件的特殊属性。
* (2.标签可以与固定区域核心的筛选器一起使用,
* 实现某些特定标签免疫特定的攻击,或者遭受特定的弱点打击。
* 你需要留意 标签 与 被触发条件 之间的关系。
* 获取事件id:
* (1.你可以根据 事件名、标签 ,获取到事件id。
* 只对当前地图的所有事件有效,如果没有找到,会赋值 -1 。
* (2.如果你想获取 复制的新事件 中符合标签/事件名的事件id,
* 需要用 "获取事件id(最后)" ,因为新事件的id都是最大值。
*
* -----------------------------------------------------------------------------
* ----激活条件
* 如果你需要设置标签,使用下面事件注释或插件指令:
* (注意,冒号左右有空格)
*
* 事件注释:=>标签核心 : 添加标签 : 被动技_躲避斩击
*
* 插件指令:>标签核心 : 本事件 : 添加标签 : 被动技_躲避斩击
* 插件指令:>标签核心 : 事件[10] : 添加标签 : 被动技_躲避斩击
* 插件指令:>标签核心 : 事件变量[10] : 添加标签 : 被动技_躲避斩击
* 插件指令:>标签核心 : 批量事件[10,11,12] : 添加标签 : 被动技_躲避斩击
*
* 插件指令:>标签核心 : 本事件 : 添加标签 : 被动技_躲避斩击
* 插件指令:>标签核心 : 本事件 : 去除标签 : 被动技_躲避斩击
* 插件指令:>标签核心 : 本事件 : 去除全部标签
*
* 1."被动技_躲避斩击"是可以完全自定义的字符串。
* 之所以叫做"躲避斩击",是因为该标签可以避免筛选器捕获到该事件。
* 但并不代表免疫触发,如果要免疫触发,需要关掉 被触发 条件。
* 你需要留意 标签 与 被触发条件 之间的关系。
*
* -----------------------------------------------------------------------------
* ----可选设定
* 你可以根据事件名、标签来获取到事件的id:
*
* 插件指令:>标签核心 : 获取事件id : 根据事件名 : 小爱丽丝 : 变量[21]
* 插件指令:>标签核心 : 获取事件id(最后) : 根据事件名 : 小爱丽丝 : 变量[21]
* 插件指令:>标签核心 : 获取事件id(随机) : 根据事件名 : 小爱丽丝 : 变量[21]
*
* 插件指令:>标签核心 : 获取事件id : 根据标签 : 被动技_躲避斩击 : 变量[21]
* 插件指令:>标签核心 : 获取事件id(最后) : 根据标签 : 被动技_躲避斩击 : 变量[21]
* 插件指令:>标签核心 : 获取事件id(随机) : 根据标签 : 被动技_躲避斩击 : 变量[21]
*
* 1.如果有多个事件名相同的的事件,或者标签相同的事件,
* "获取事件id" 获取到的是事件id最小的那个;
* "获取事件id(最后)" 获取的是id最大的那个;
* "获取事件id(随机)" 获取的是其中任意一个。
* 只对当前地图的所有事件有效,如果没有找到,会赋值 -1 。
* 2.如果你想获取 复制的新事件 中符合标签/事件名的事件id,
* 需要用 "获取事件id(最后)" ,因为新事件的id都是最大值。
*
* -----------------------------------------------------------------------------
* ----插件性能
* 测试仪器: 4G 内存,Intel Core i5-2520M CPU 2.5GHz 处理器
* Intel(R) HD Graphics 3000 集显 的垃圾笔记本
* (笔记本的3dmark综合分:571,鲁大师综合分:48456)
* 总时段: 20000.00ms左右
* 对照表: 0.00ms - 40.00ms (几乎无消耗)
* 40.00ms - 80.00ms (低消耗)
* 80.00ms - 120.00ms(中消耗)
* 120.00ms以上 (高消耗)
* 工作类型: 单次执行
* 时间复杂度: o(n)
* 测试方法: 去各个管理层跑一圈,测试性能。
* 测试结果: 200个事件的地图中,平均消耗为:【5ms以下】
* 100个事件的地图中,平均消耗为:【5ms以下】
* 50个事件的地图中,平均消耗为:【5ms以下】
*
* 1.插件只在自己作用域下工作消耗性能,在其它作用域下是不工作的。
* 测试结果并不是精确值,范围在给定值的10ms范围内波动。
* 更多了解插件性能,可以去看看"关于插件性能.docx"。
* 2.标签只是附加在事件身上的一个属性,如果没有子插件反复使用这个
* 属性,插件是不会出现任何多余计算量的。
*
* -----------------------------------------------------------------------------
* ----更新日志
* [v1.0]
* 完成插件ヽ(*。>Д<)o゜
*
*
*/
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// 插件简称 COET(Core_Of_Event_Tags)
// 临时全局变量 无
// 临时局部变量 this._drill_COET_tag
// 存储数据变量 无
// 全局存储变量 无
// 覆盖重写方法 无
//
// 工作类型 单次执行
// 时间复杂度 o(n)
// 性能测试因素 到处跑
// 性能测试消耗 消耗列表中找不到
// 最坏情况 无
//
//插件记录:
// ★大体框架与功能如下:
// 事件标签核心:
// ->设置标签
// ->获取事件(根据标签)
// ->获取事件(根据事件名)
//
// ★必要注意事项:
// 暂无
//
// ★其它说明细节:
// 1.这里只是提供了一系列"通过标签"快速筛选的功能和方法。
// 需要持续与子插件进行配合。
//
// ★核心接口说明:
// 1.该插件准确地说,【不是一个标准的核心】。
// 没有对外接口。
//
// ★存在的问题:
// 暂无
//
//=============================================================================
// ** 变量获取
//=============================================================================
var Imported = Imported || {};
Imported.Drill_CoreOfEventTags = true;
var DrillUp = DrillUp || {};
DrillUp.parameters = PluginManager.parameters('Drill_CoreOfEventTags');
//=============================================================================
// * 插件指令
//=============================================================================
var _drill_COET_pluginCommand = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
_drill_COET_pluginCommand.call(this, command, args);
if (command === ">标签核心") {
/*-----------------设置标签------------------*/
var e_ids = null;
if(args.length >= 2){
var unit = String(args[1]);
if( unit == "本事件" ){
e_ids = [ this._eventId ];
}
if( unit.indexOf("批量事件[") != -1 ){
unit = unit.replace("批量事件[","");
unit = unit.replace("]","");
e_ids = [];
var temp_arr = unit.split(/[,,]/);
for( var k=0; k < temp_arr.length; k++ ){
e_ids.push( Number(temp_arr[k]) );
}
}
if( unit.indexOf("事件变量[") != -1 ){
unit = unit.replace("事件变量[","");
unit = unit.replace("]","");
e_ids = [ $gameVariables.value(Number(unit)) ];
}
if( unit.indexOf("事件[") != -1 ){
unit = unit.replace("事件[","");
unit = unit.replace("]","");
e_ids = [ Number(unit) ];
}
}
if( e_ids && args.length == 4){
var type = String(args[3]);
if( type == "去除全部标签" ){
for( var k=0; k < e_ids.length; k++ ){
var e_id = e_ids[k];
if( $gameMap.drill_COET_isEventExist( e_id ) == false ){ continue; }
var e = $gameMap.event( e_id );
e.drill_COET_removeAllTag();
}
}
}
if( e_ids && args.length == 6){
var type = String(args[3]);
var temp2 = String(args[5]);
if( type == "去除标签" ){
for( var k=0; k < e_ids.length; k++ ){
var e_id = e_ids[k];
if( $gameMap.drill_COET_isEventExist( e_id ) == false ){ continue; }
var e = $gameMap.event( e_id );
e.drill_COET_removeTag(temp2);
}
}
if( type == "添加标签" ){
for( var k=0; k < e_ids.length; k++ ){
var e_id = e_ids[k];
if( $gameMap.drill_COET_isEventExist( e_id ) == false ){ continue; }
var e = $gameMap.event( e_id );
e.drill_COET_addTag(temp2);
}
}
}
/*-----------------获取事件id------------------*/
if(args.length == 8){ //>标签核心 : 获取事件id : 根据事件名 : 小爱丽丝 : 变量[21]
var temp1 = String(args[1]);
var type = String(args[3]);
var temp2 = String(args[5]);
var temp3 = String(args[7]);
temp3 = temp3.replace("变量[","");
temp3 = temp3.replace("]","");
if( type == "根据事件名" ){
var events = $gameMap.drill_COET_getEventsByName(temp2);
if( events.length > 0 ){
if( temp1 == "获取事件id" ){
$gameVariables.setValue( Number(temp3), events[0]._eventId );
}
if( temp1 == "获取事件id(最后)" ){
$gameVariables.setValue( Number(temp3), events[ events.length-1 ]._eventId );
}
if( temp1 == "获取事件id(随机)" ){
$gameVariables.setValue( Number(temp3), events[ Math.floor( Math.random()*events.length ) ]._eventId );
}
}else{
$gameVariables.setValue( Number(temp3), -1 );
}
}
if( type == "根据标签" ){
var events = $gameMap.drill_COET_getEventsByTag(temp2);
if( events.length > 0 ){
if( temp1 == "获取事件id" ){
$gameVariables.setValue( Number(temp3), events[0]._eventId );
}
if( temp1 == "获取事件id(最后)" ){
$gameVariables.setValue( Number(temp3), events[ events.length-1 ]._eventId );
}
if( temp1 == "获取事件id(随机)" ){
$gameVariables.setValue( Number(temp3), events[ Math.floor( Math.random()*events.length ) ]._eventId );
}
}else{
$gameVariables.setValue( Number(temp3), -1 );
}
}
}
}
}
//==============================
// ** 插件指令 - 事件检查
//==============================
Game_Map.prototype.drill_COET_isEventExist = function( e_id ){
if( e_id == 0 ){ return false; }
var e = this.event( e_id );
if( e == undefined ){
alert( "【Drill_CoreOfEventTags.js 物体 - 事件标签核心】\n" +
"插件指令错误,当前地图并不存在id为"+e_id+"的事件。");
return false;
}
return true;
};
//==============================
// * 注释初始化
//==============================
var _drill_COET_event_setupPage = Game_Event.prototype.setupPage;
Game_Event.prototype.setupPage = function() {
_drill_COET_event_setupPage.call(this);
this.drill_COET_setupPage();
};
Game_Event.prototype.drill_COET_setupPage = function() {
if (!this._erased && this.page()) {this.list().forEach(function(l) {
if (l.code === 108) {
var args = l.parameters[0].split(' ');
var command = args.shift();
if (command == "=>标签核心"){ //=>标签核心 : 添加标签 : 斩击躲避
if(args.length == 4){
var temp1 = String(args[1]);
var temp2 = String(args[3]);
if( temp1 == "添加标签" ){
this.drill_COET_addTag(temp2);
}
}
};
};
}, this);};
};
//=============================================================================
// * 事件
//=============================================================================
//==============================
// * 事件 - 初始化
//==============================
var _drill_COET_e_initMembers = Game_Event.prototype.initMembers;
Game_Event.prototype.initMembers = function() {
this._drill_COET_tag = [];
_drill_COET_e_initMembers.call(this);
}
//==============================
// * 事件 - 含指定标签
//==============================
Game_Event.prototype.drill_COET_hasTag = function(tag) {
return this._drill_COET_tag.indexOf(tag) != -1 ;
}
//==============================
// * 事件 - 含指定标签组任意一个
//==============================
Game_Event.prototype.drill_COET_hasAnyTag = function( tag_list ) {
for(var i=0; i < tag_list.length; i++){
if( this.drill_COET_hasTag( tag_list[i] ) ){
return true;
}
}
return false;
}
//==============================
// * 事件 - 添加标签
//==============================
Game_Event.prototype.drill_COET_addTag = function(tag) {
if( this.drill_COET_hasTag(tag) == false ){
this._drill_COET_tag.push(tag);
}
}
//==============================
// * 事件 - 去除标签
//==============================
Game_Event.prototype.drill_COET_removeTag = function(tag) {
if( this.drill_COET_hasTag(tag) == true ){
var index = this._drill_COET_tag.indexOf(tag);
this._drill_COET_tag.splice(index,1);
}
}
//==============================
// * 事件 - 去除全部标签
//==============================
Game_Event.prototype.drill_COET_removeAllTag = function() {
this._drill_COET_tag = [];
}
//=============================================================================
// * 地图
//=============================================================================
//==============================
// * 地图 - 获取事件(根据单标签)
//==============================
Game_Map.prototype.drill_COET_getEventsByTag = function( tag ) {
var result = [];
var events = this.events();
for (var i = 0; i < events.length ; i++) {
if( events[i].drill_COET_hasTag(tag) ){
result.push(events[i]);
}
}
return result;
}
//==============================
// * 地图 - 获取事件(根据多个标签)
//==============================
Game_Map.prototype.drill_COET_getEventsByTaglist = function( tag_list ) {
var result = [];
var events = this.events();
for (var i = 0; i < events.length ; i++) {
if( events[i].drill_COET_hasAnyTag(tag_list) ){
result.push(events[i]);
}
}
return result;
}
//==============================
// * 地图 - 筛选事件(根据多个标签)
//==============================
Game_Map.prototype.drill_COET_selectEventsByTaglist = function( event_list, tag_list ) {
var result = [];
for (var i = 0; i < event_list.length ; i++) {
if( event_list[i].drill_COET_hasAnyTag(tag_list) ){
result.push(event_list[i]);
}
}
return result;
}
//==============================
// * 地图 - 获取事件(根据事件名)
//==============================
Game_Map.prototype.drill_COET_getEventsByName = function( name ) {
var result = [];
var events = this.events();
for (var i = 0; i < events.length ; i++) {
if( events[i].event().name == name ){
result.push(events[i]);
}
}
return result;
}
| 4d6b7add78be4070f3227b72ff3031e4ea18bd44 | [
"JavaScript"
] | 3 | JavaScript | wx7614140/drill_plugins | b2737630d1f4b31f361c57e588b7676a089eb0b0 | f7ebba218c26dcf8e137ba39c81bc886a9e32a9e |
refs/heads/master | <file_sep>__author__ = 'liwang'
<file_sep># Source: http://neuralnetworksanddeeplearning.com/chap1.html
# You need only train and test sets. Simply disregard the validation set.
import numpy as np
import cPickle
import gzip
import datetime
def load_data():
file_location = '../mnist.pkl.gz'
f = gzip.open(file_location, 'rb')
training_data, validation_data, test_data = cPickle.load(f)
f.close()
return training_data, validation_data, test_data
def load_data_wrapper():
tr_d, va_d, te_d = load_data()
# normalize the training data
norm_tr_d = ([t / np.reshape(np.linalg.norm(t), (-1, 1))
for t in tr_d[0]], tr_d[1])
# normalize the test data
norm_te_d = ([v / np.reshape(np.linalg.norm(v), (-1, 1))
for v in te_d[0]], te_d[1])
# array to store successful results
succ_list = []
# array to store failure results
fail_list = []
start_time = datetime.datetime.now()
# outer loop is for each data in test dataset
for d in xrange(len(norm_te_d[0])):
if d % 100 == 0:
print(datetime.datetime.now())
print(len(succ_list))
print(len(fail_list))
# variable to store information for each test data,
# the first element is the max dot value,
# the second element is the corresponding estimated result
nearest = (0, 0)
# inner loop is for each data in training dataset
for k in xrange(len(norm_tr_d[0])):
# compute dot value
# always put the pair with the larger dot value into nearest
dot = np.dot(norm_te_d[0][d][0], norm_tr_d[0][k][0])
if nearest[0] < dot:
nearest = (dot, norm_tr_d[1][k])
# compare the estimated value and the true value
if nearest[1] == norm_te_d[1][d]:
succ_list.append((nearest, norm_te_d[1][d]))
else:
fail_list.append((nearest, norm_te_d[1][d]))
end_time = datetime.datetime.now()
print(end_time - start_time)
print("succ:", len(succ_list))
print("fail:", len(fail_list))
return succ_list, fail_list
# here we compute confusion matrix
def compute_matrix(succ, fail):
matrix = [[0 for x in xrange(11)] for x in xrange(11)]
for s in succ:
# true value and estimated value are the same
matrix[s[1]][s[1]] += 1
for f in fail:
# put true value in row and estimated value in column
matrix[f[1]][f[0][1]] += 1
# calculate the precision and recall
correct_count = 0
for i in xrange(10):
matrix[i][10] = round(float(matrix[i][i]) / sum(matrix[i]), 3)
matrix[10][i] = round(float(matrix[i][i]) / sum((zip(*matrix)[i])), 3)
correct_count += matrix[i][i]
accuracy = float(correct_count)/10000
print("accuracy=", accuracy)
for e in matrix:
print ('|'.join(['%5s' % (e[n]) for n in xrange(len(e))]))
if __name__ == "__main__":
load=False
if load:
load_data_wrapper()
else:
succfileloc = '../succ_list'
failfileloc = '../fail_list'
f1 = open(succfileloc, 'rb')
f2 = open(failfileloc, 'rb')
succ = cPickle.load(f1)
fail = cPickle.load(f2)
f1.close()
f2.close()
if succ is None or fail is None:
succ, fail = load_data_wrapper()
f1 = open(succfileloc, 'wb')
f2 = open(failfileloc, 'wb')
cPickle.dump(succ, f1)
cPickle.dump(fail, f2)
f1.close()
f2.close()
compute_matrix(succ, fail)<file_sep># mnist
assignment from data mining, basicly using NN to test some dataset, recognize numbers from pictures.
| 2d71b8478e04089fb2f38d843feb088e8c6f59e2 | [
"Markdown",
"Python"
] | 3 | Python | realyasswl/mnist | 138b3d9d62e90a7f0c13cf944c1cc2f44b1e1d96 | 0b31774e3a2200529c6934b0a9b3ba7cebf39023 |
refs/heads/master | <file_sep>package payrollCalculation.service;
import payrollCalculation.model.ActualWorkingHoursByUsers;
import java.util.List;
public interface ActualWorkingHoursByUserService {
List<ActualWorkingHoursByUsers> findAllByUserId(long userId);
void setByUser(ActualWorkingHoursByUsers actualWorkingHoursByUser);
ActualWorkingHoursByUsers getByUserIdAndDate(long userId, int year, int month, int day);
void updateByUserIdAndDate(long userId, int year, int month, int day, int workingHoursOfFirstPartOfAMonth,
int workingHoursOfSecondPartOfAMonth);
void deleteByUserIdAndDate(long userId, int year, int month, int day);
}
<file_sep>package payrollCalculation.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import payrollCalculation.model.CKUsersIdAndDate;
import payrollCalculation.model.StdPayrollOfUser;
import java.util.List;
public interface StdPayrollOfUserRepository
extends JpaRepository<StdPayrollOfUser, CKUsersIdAndDate> {
List<StdPayrollOfUser> findById_UserId(long userId);
}
<file_sep>package payrollCalculation.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private long id;
@Column(name = "user_name")
private String name;
public User() {
}
public User(String name) {
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
if (getId() != user.getId()) return false;
return getName().equals(user.getName());
}
@Override
public int hashCode() {
int result = (int) (getId() ^ (getId() >>> 32));
result = 31 * result + getName().hashCode();
return result;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
<file_sep>package payrollCalculation.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlGroup;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import payrollCalculation.model.User;
import javax.annotation.Resource;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/ApplicationContext.xml")
@SqlGroup({
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = "/sqlScriptsForTesting/before_run_test_UserServiceImpl")
})
public class UserServiceImplTest {
@Resource
UserService userService;
@Test
public void set() throws Exception {
userService.set(new User("John"));
assertEquals("John", userService.get(1).getName());
}
@Test
public void get() throws Exception {
userService.set(new User("Jane"));
assertEquals("Jane", userService.get(1).getName());
}
@Test
public void updateUserName() throws Exception {
userService.set(new User("Jake"));
userService.updateUserName(1, "Nick");
assertEquals("Nick", userService.get(1).getName());
}
@Test
public void delete() throws Exception {
userService.set(new User("Jim"));
userService.delete(1);
User user = userService.get(1);
assertNull(user);
}
@Test
public void getAllUsers() throws Exception {
userService.set(new User("Bobby"));
userService.set(new User("Mike"));
userService.set(new User("Bill"));
List<User> userList = userService.getAllUsers();
assertEquals(3, userList.size());
}
@Test
public void findByName() throws Exception {
userService.set(new User("Bobby"));
userService.set(new User("Mike"));
userService.set(new User("Bill"));
userService.set(new User("Bill"));
userService.set(new User("Billy"));
List<User> userList = userService.findByName("Bill");
assertEquals(2, userList.size());
}
@Test
public void findByNameContains() throws Exception{
userService.set(new User("Bobby"));
userService.set(new User("Mike"));
userService.set(new User("Bill"));
userService.set(new User("Bill"));
userService.set(new User("Billy"));
List<User> userList = userService.findByNameContains("Bill");
assertEquals(3, userList.size());
}
}<file_sep>package payrollCalculation.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import payrollCalculation.model.StdWorkingHours;
import java.time.LocalDate;
import java.util.List;
public interface StdWorkingHoursRepository extends JpaRepository<StdWorkingHours, LocalDate> {
@Query("select s from StdWorkingHours s where function('year', s.date)= :year")
List<StdWorkingHours> getByYear(@Param("year") int year);
}
<file_sep>package payrollCalculation.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import payrollCalculation.model.StdTaxes;
import payrollCalculation.repository.StdTaxesRepository;
import java.time.LocalDate;
import java.util.List;
@Service
public class StdTaxesServiceImpl implements StdTaxesService {
@Autowired
private StdTaxesRepository stdTaxesRepository;
@Override
public List<StdTaxes> getByYear(int year) {
List<StdTaxes> stdTaxesList = stdTaxesRepository.getByYear(year);
return stdTaxesList;
}
@Override
public void set(StdTaxes stdTaxes) {
stdTaxesRepository.saveAndFlush(stdTaxes);
}
@Override
public StdTaxes get(int year, int month, int day) {
return stdTaxesRepository.findOne(LocalDate.of(year, month, day));
}
@Override
public void update(int year, int month, int day, double personalIncomeTax, double militaryTax) {
stdTaxesRepository.saveAndFlush(new StdTaxes(year, month, day, personalIncomeTax, militaryTax));
}
@Override
public void delete(int year, int month, int day) {
stdTaxesRepository.delete(LocalDate.of(year, month, day));
}
}
<file_sep>package payrollCalculation.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlGroup;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import payrollCalculation.model.StdWorkingHours;
import javax.annotation.Resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/ApplicationContext.xml")
@SqlGroup({
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = "/sqlScriptsForTesting/before_run_test_StdWorkingHoursService")
})
public class StdWorkingHoursServiceImplTest {
@Resource
StdWorkingHoursService stdWorkingHoursService;
@Test
public void set() throws Exception {
stdWorkingHoursService.set(new StdWorkingHours(2017, 5, 1, 63, 96));
stdWorkingHoursService.set(new StdWorkingHours(2017, 6, 1, 80, 79));
assertEquals(63, stdWorkingHoursService.get(2017, 5, 1).getStdWorkingHoursOfFirstPartOfAMonth());
assertEquals(79, stdWorkingHoursService.get(2017, 6, 1).getStdWorkingHoursOfSecondPartOfAMonth());
}
@Test
public void get() throws Exception {
stdWorkingHoursService.set(new StdWorkingHours(2017, 7, 1, 80, 88));
assertEquals(88, stdWorkingHoursService.get(2017, 7, 1).getStdWorkingHoursOfSecondPartOfAMonth());
}
@Test
public void update() throws Exception {
stdWorkingHoursService.set(new StdWorkingHours(2017, 8, 1, 88, 87));
assertEquals(87, stdWorkingHoursService.get(2017, 8, 1).getStdWorkingHoursOfSecondPartOfAMonth());
stdWorkingHoursService.update(2017, 8, 1, 88, 88);
assertEquals(88, stdWorkingHoursService.get(2017, 8, 1).getStdWorkingHoursOfSecondPartOfAMonth());
}
@Test
public void delete() throws Exception {
stdWorkingHoursService.set(new StdWorkingHours(2017, 9, 1, 88, 80));
assertEquals(80, stdWorkingHoursService.get(2017, 9, 1).getStdWorkingHoursOfSecondPartOfAMonth());
stdWorkingHoursService.delete(2017, 9, 1);
assertNull(stdWorkingHoursService.get(2017, 9, 1));
}
@Test
public void getByYear() throws Exception {
stdWorkingHoursService.set(new StdWorkingHours(2016, 1, 1, 88, 88));
stdWorkingHoursService.set(new StdWorkingHours(2017, 10, 1, 80, 87));
stdWorkingHoursService.set(new StdWorkingHours(2017, 11, 1, 88, 88));
stdWorkingHoursService.set(new StdWorkingHours(2017, 12, 1, 88, 80));
assertEquals(3, stdWorkingHoursService.getByYear(2017).size());
}
}<file_sep>package payrollCalculation.service;
import payrollCalculation.model.StdPayrollOfUser;
import java.util.List;
public interface StdPayrollOfUserService {
List<StdPayrollOfUser> findAllByUserId(long userId);
void setByUser(StdPayrollOfUser stdPayrollOfUser);
StdPayrollOfUser getByUserAndDate(long id, int year, int month, int day);
void update(long id, int year, int month, int day, double grossSalary, double percentOfBonus);
void deleteByUserAndDate(long id, int year, int month, int day);
}
<file_sep>package payrollCalculation.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDate;
@Entity
@Table(name = "stdworkinghours")
public class StdWorkingHours {
@Id
@Column(name = "period")
private LocalDate date;
@Column(name = "stdWorkingHoursOfFirstPartOfAMonth")
private int stdWorkingHoursOfFirstPartOfAMonth;
@Column(name = "stdWorkingHoursOfSecondPartOfAMonth")
private int stdWorkingHoursOfSecondPartOfAMonth;
@Column(name = "stdWorkingHoursOfAMonth")
private int stdWorkingHoursOfAMonth;
public StdWorkingHours() {
}
public StdWorkingHours(int year, int month, int day, int stdWorkingHoursOfFirstPartOfAMonth,
int stdWorkingHoursOfSecondPartOfAMonth) {
this.date = LocalDate.of(year, month, day);
this.stdWorkingHoursOfFirstPartOfAMonth = stdWorkingHoursOfFirstPartOfAMonth;
this.stdWorkingHoursOfSecondPartOfAMonth = stdWorkingHoursOfSecondPartOfAMonth;
this.stdWorkingHoursOfAMonth = stdWorkingHoursOfFirstPartOfAMonth + stdWorkingHoursOfSecondPartOfAMonth;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public int getStdWorkingHoursOfFirstPartOfAMonth() {
return stdWorkingHoursOfFirstPartOfAMonth;
}
public void setStdWorkingHoursOfFirstPartOfAMonth(int stdWorkingHoursOfFirstPartOfAMonth) {
this.stdWorkingHoursOfFirstPartOfAMonth = stdWorkingHoursOfFirstPartOfAMonth;
}
public int getStdWorkingHoursOfSecondPartOfAMonth() {
return stdWorkingHoursOfSecondPartOfAMonth;
}
public void setStdWorkingHoursOfSecondPartOfAMonth(int stdWorkingHoursOfSecondPartOfAMonth) {
this.stdWorkingHoursOfSecondPartOfAMonth = stdWorkingHoursOfSecondPartOfAMonth;
}
public int getStdWorkingHoursOfAMonth() {
return stdWorkingHoursOfAMonth;
}
public void setStdWorkingHoursOfAMonth(int stdWorkingHoursOfAMonth) {
this.stdWorkingHoursOfAMonth = stdWorkingHoursOfAMonth;
}
@Override
public String toString() {
return "StdWorkingHours{" +
"date=" + date +
", stdWorkingHoursOfFirstPartOfAMonth=" + stdWorkingHoursOfFirstPartOfAMonth +
", stdWorkingHoursOfSecondPartOfAMonth=" + stdWorkingHoursOfSecondPartOfAMonth +
", stdWorkingHoursOfAMonth=" + stdWorkingHoursOfAMonth +
'}';
}
}
<file_sep>package payrollCalculation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import payrollCalculation.service.ActualWorkingHoursByUserService;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
ActualWorkingHoursByUserService actualWorkingHoursByUserService = applicationContext.getBean(ActualWorkingHoursByUserService.class);
System.out.println(actualWorkingHoursByUserService.getByUserIdAndDate(5L, 2017,6,1));
}
}
| dd4ee6f5830a011bd4b5819f29a3ee6a28d4d680 | [
"Java"
] | 10 | Java | oleksiizykin/payroll-calc | ea535fec1ed4e35aaf5ce983333f0e191b16c7b1 | a449acb5216c881b7c77a58470ebfc7bb1c09ca1 |
refs/heads/master | <file_sep>import numpy as np
import matplotlib.pyplot as plt
from PyATMM.uniaxialTransferMatrix import *
from PyATMM.isotropicTransferMatrix import *
from PyATMM.transferMatrix import solve_transfer_matrix
__author__ = '<NAME>'
#
# Setup
#
c = 299792458 # m/c
w = 500 * 10 **12
l = 2*np.pi*c / w
angle = np.linspace(0, 90, 500, endpoint=False)
ran_kx = (w/c) * np.sin(np.deg2rad(angle))
n_g = 1.5
eps_g = n_g**2
n_ord = 1
eps_ord = n_ord**2
n_ex = 1.2
eps_ex = n_ex**2
ky = 0
a_refl_pp = []
a_refl_ss = []
a_refl_ps = []
a_refl_sp = []
for kx in ran_kx:
D_0 = build_isotropic_dynamic_matrix(eps_g, w, n_g*kx, ky)
D_1 = build_uniaxial_dynamic_matrix(eps_ord, eps_ex, w, n_g*kx, ky, opticAxis=([0, 1./np.sqrt(2), 1./np.sqrt(2)]))
D = np.dot(np.linalg.inv(D_0), D_1)
r_ss, r_sp, r_ps, r_pp, t_ss, t_sp, t_ps, t_pp = solve_transfer_matrix(D)
a_refl_pp.append(np.abs(r_pp**2))
a_refl_ss.append(np.abs(r_ss**2))
a_refl_sp.append(np.abs(r_sp**2))
a_refl_ps.append(np.abs(r_ps**2))
#PyATMM
#TE
plt.plot(angle, a_refl_ss)
plt.plot(angle, a_refl_sp)
plt.plot(angle, numpy.add(a_refl_ss, a_refl_sp))
plt.legend(['SS', 'SP', 'Sum'], loc='best')
#TM
#plt.plot(angle, a_refl_pp)
#plt.plot(angle, a_refl_ps)
#plt.plot(angle, numpy.add(a_refl_pp, a_refl_ps))
#plt.legend(['PP', 'PS', 'Sum'], loc='best')
plt.xlabel("angle, degrees")
plt.ylabel("Reflectance")
plt.title("Uniaxial total internal reflection")
plt.show(block=True)<file_sep>__author__ = '<NAME>'
import numpy
import numpy.linalg
def build_isotropic_layer_matrix(eps, w, kx, ky, d):
D = build_isotropic_bounding_layer_matrix(eps, w, kx, ky)
P = build_isotropic_propagation_matrix(eps, w, kx, ky, d)
LayerMatrix = numpy.dot(D, numpy.dot(P, numpy.linalg.inv(D)))
return LayerMatrix
def build_isotropic_bounding_layer_matrix(eps, w, kx, ky):
#
# Build boundary transition matrix
#
D_0 = build_isotropic_dynamic_matrix(1, w, kx, ky)
D = build_isotropic_dynamic_matrix(eps, w, kx, ky)
return numpy.dot(numpy.linalg.inv(D_0), D)
#
# Building blocks
#
def build_isotropic_propagation_matrix(eps, w, kx, ky, d):
mu = 1.
c = 299792458. # m/c
mod_kz = numpy.sqrt(eps*(w/c)**2 - kx**2 - ky**2, dtype=numpy.complex128)
gamma = [mod_kz, -mod_kz, mod_kz, -mod_kz]
P = numpy.asarray(
[
[numpy.exp(-1j*gamma[0]*d), 0, 0, 0],
[0, numpy.exp(-1j*gamma[1]*d), 0, 0],
[0, 0, numpy.exp(-1j*gamma[2]*d), 0],
[0, 0, 0, numpy.exp(-1j*gamma[3]*d)]
], dtype=numpy.complex128
)
return P
def build_isotropic_dynamic_matrix(eps, w, kx, ky):
mu = 1.
c = 299792458. # m/c
mod_kz = numpy.sqrt(eps*(w/c)**2 - kx**2 - ky**2, dtype=numpy.complex128)
gamma = [mod_kz, -mod_kz, mod_kz, -mod_kz]
k = [numpy.asarray([kx, ky, g]) for g in gamma]
#
# Build polarization vectors
#
p = isotropic_polarizations(w, eps, kx, ky, gamma)
q = [(c/(w*mu))*numpy.cross(ki, pi) for ki, pi in zip(k, p)]
#
# Build boundary transition matrix
#
D = numpy.asarray(
[
[p[0][0], p[1][0], p[2][0], p[3][0]],
[q[0][1], q[1][1], q[2][1], q[3][1]],
[p[0][1], p[1][1], p[2][1], p[3][1]],
[q[0][0], q[1][0], q[2][0], q[3][0]]
], dtype=numpy.complex128
)
return D
def isotropic_polarizations(w, eps, kx, ky, kz):
k = [[kx, ky, ki] for ki in kz]
# TODO
# K-vector aligned
# k = [kx, ky, kz]
#
if not numpy.isclose(kx, 0) or not numpy.isclose(ky, 0):
p_3 = numpy.cross(k[2], [-kx, -ky, kz[2]])
p_4 = numpy.cross(k[3], [-kx, -ky, kz[3]])
p_1 = numpy.cross(k[0], [-kx, -ky, kz[0]])
p_1 = numpy.cross(k[0], p_1)
p_2 = numpy.cross(k[1], [-kx, -ky, kz[1]])
p_2 = numpy.cross(k[1], p_2)
else:
# Axially aligned
p_1 = [-kz[0], 0, kx]
p_2 = [-kz[1], 0, kx]
p_3 = [0, -kz[2], ky]
p_4 = [0, -kz[3], ky]
# p_1 = [-kz[0], 0, kx]
# p_2 = [-kz[1], 0, kx]
# p_3 = [0, -kz[2], ky]
# p_4 = [0, -kz[3], ky]
p = [p_1, p_2, p_3, p_4]
p = [numpy.divide(pi, numpy.sqrt(numpy.dot(pi, pi))) for pi in p]
if not numpy.isclose(numpy.dot(p[0], k[0]), 0 + 0j) \
or not numpy.isclose(numpy.dot(p[1], k[1]), 0 + 0j) \
or not numpy.isclose(numpy.dot(p[2], k[2]), 0 + 0j) \
or not numpy.isclose(numpy.dot(p[3], k[3]), 0 + 0j):
print("polarization not normal to k-vector")
#assert numpy.isclose(numpy.dot(p[0], k[0]), 0+0j)
#assert numpy.isclose(numpy.dot(p[1], k[1]), 0+0j)
#assert numpy.isclose(numpy.dot(p[2], k[2]), 0+0j)
#assert numpy.isclose(numpy.dot(p[3], k[3]), 0+0j)
return p
<file_sep>import numpy as np
import matplotlib.pyplot as plt
import scipy.linalg
import PyTMM.transferMatrix as tm
from PyATMM.isotropicTransferMatrix import *
from PyATMM.transferMatrix import solve_transfer_matrix
__author__ = '<NAME>'
#
# Setup
#
c = 299792458 # m/c
w = 500 * 10 **12
l = 2*np.pi*c / w
angle = np.linspace(0, 90, 200, endpoint=False)
ran_kx = (w/c) * np.sin(np.deg2rad(angle))
eps_1 = 6.7
n_1 = np.sqrt(eps_1)
eps_2 = 4.41
n_2 = np.sqrt(eps_2)
ky = 0
#
# PyTMM
#
refl_p = []
refl_s = []
for kx in ran_kx:
B = tm.TransferMatrix.boundingLayer(n_1, n_2, np.arcsin(kx*c/w), tm.Polarization.s)
C = tm.TransferMatrix.boundingLayer(n_1, n_2, np.arcsin(kx*c/w), tm.Polarization.p)
#a.appendRight(b)
M = scipy.linalg.block_diag(B.matrix, C.matrix)
r_ss, r_sp, r_ps, r_pp, t_ss, t_sp, t_ps, t_pp = solve_transfer_matrix(M)
refl_p.append(np.abs(r_pp**2))
refl_s.append(np.abs(r_ss**2))
#
# PyATMM
#
a_refl_p = []
a_refl_s = []
for kx in ran_kx:
D_0 = build_isotropic_dynamic_matrix(eps_1, w, n_1*kx, ky)
D_1 = build_isotropic_dynamic_matrix(eps_2, w, n_1*kx, ky)
D = np.dot(np.linalg.inv(D_0), D_1)
r_ss, r_sp, r_ps, r_pp, t_ss, t_sp, t_ps, t_pp = solve_transfer_matrix(D)
a_refl_p.append(np.abs(r_pp**2))
a_refl_s.append(np.abs(r_ss**2))
#PyTMM
plt.plot(angle, refl_p, '+')
plt.plot(angle, refl_s, '+')
#PyATMM
plt.plot(angle, a_refl_p)
plt.plot(angle, a_refl_s)
plt.xlabel("angle, degrees")
plt.ylabel("Reflectance")
plt.title("Total internal reflection")
plt.legend(['PP', 'SS', 'P', 'S'], loc='best')
plt.show(block=True)<file_sep>"""
Python implementation of the generalized TMM
"""
__author__ = "<NAME>"
__version__ = "1.0.0-a0"<file_sep>__author__ = '<NAME>'
import numpy
import numpy.linalg
import PyATMM.isotropicTransferMatrix as isotropicTransferMatrix
def build_uniaxial_layer_matrix(e_o, e_e, w, kx, ky, d, opticAxis=([0., 1., 0.])):
D = build_uniaxial_bounding_layer_matrix(e_o, e_e, w, kx, ky, opticAxis=opticAxis)
P = build_uniaxial_propagation_matrix(e_o, e_e, w, kx, ky, d, opticAxis=opticAxis)
LayerMatrix = numpy.dot(D, numpy.dot(P, numpy.linalg.inv(D)))
return LayerMatrix
def build_uniaxial_bounding_layer_matrix(e_o, e_e, w, kx, ky, opticAxis=([0., 1., 0.])):
D_0 = isotropicTransferMatrix.build_isotropic_dynamic_matrix(1, w, kx, ky)
D = build_uniaxial_dynamic_matrix(e_o, e_e, w, kx, ky, opticAxis=opticAxis)
return numpy.dot(numpy.linalg.inv(D_0), D)
#
# Building blocks
#
def build_uniaxial_propagation_matrix(e_o, e_e, w, kx, ky, d, opticAxis=([0., 1., 0.])):
gamma = build_uniaxial_transmitted_wavevectors(e_o, e_e, w, kx, ky, opticAxis)
P = numpy.asarray(
[
[numpy.exp(-1j*gamma[0]*d), 0, 0, 0],
[0, numpy.exp(-1j*gamma[1]*d), 0, 0],
[0, 0, numpy.exp(-1j*gamma[2]*d), 0],
[0, 0, 0, numpy.exp(-1j*gamma[3]*d)]
], dtype=numpy.complex128
)
return P
def build_uniaxial_dynamic_matrix(e_o, e_e, w, kx, ky, opticAxis=([0., 1., 0.])):
mu = 1.
c = 299792458. # m/c
gamma = build_uniaxial_transmitted_wavevectors(e_o, e_e, w, kx, ky, opticAxis)
k = [[kx, ky, g] for g in gamma]
p = axially_aligned_uniaxial_polarizations(e_o, e_e, w, kx, ky, gamma, opticAxis)
q = [(c/(w*mu))*numpy.cross(ki, pi) for ki, pi in zip(k, p)]
D = numpy.asarray(
[
[p[0][0], p[1][0], p[2][0], p[3][0]],
[q[0][1], q[1][1], q[2][1], q[3][1]],
[p[0][1], p[1][1], p[2][1], p[3][1]],
[q[0][0], q[1][0], q[2][0], q[3][0]]
], dtype=numpy.complex128
)
return D
def axially_aligned_uniaxial_polarizations(e_o, e_e, w, kx, ky, kz, opticAxis):
# For now optic axis should be aligned to main axes
#assert numpy.allclose(opticAxis, [0, 0, 1]) \
# or numpy.allclose(opticAxis, [0, 1, 0]) \
# or numpy.allclose(opticAxis, [1, 0, 0])
# In general, as long as k-vector and optic axis are not colinear, this should work
assert all(not numpy.allclose(opticAxis, [kx, ky, numpy.abs(g)]) for g in kz)
assert numpy.isclose(numpy.dot(opticAxis, opticAxis), 1.)
nu = (e_e - e_o) / e_o
kap = [numpy.asarray([kx, ky, g]) for g in kz]
kap = [numpy.divide(kap_i, numpy.sqrt(numpy.dot(kap_i, kap_i))) for kap_i in kap]
ka = [numpy.dot(opticAxis, kap_i) for kap_i in kap]
p_1 = numpy.cross(opticAxis, kap[0])
p_2 = numpy.cross(opticAxis, kap[1])
p_3 = numpy.subtract(opticAxis, ((1 + nu)/(1+nu*ka[2]**2))*ka[2] * kap[2])
p_4 = numpy.subtract(opticAxis, ((1 + nu)/(1+nu*ka[3]**2))*ka[3] * kap[3])
p = [p_1, p_2, p_3, p_4]
p = [numpy.divide(pi, numpy.sqrt(numpy.dot(pi, pi))) for pi in p]
return p
def build_uniaxial_transmitted_wavevectors(e_o, e_e, w, kx, ky, opticAxis=([0., 1., 0.])):
mu = 1.
c = 299792458. # m/c
nu = (e_e - e_o) / e_o
k_par = numpy.sqrt(kx**2 + ky**2)
k_0 = w/c
n = [0, 0, 1]
if not numpy.isclose(k_par, 0):
l = [kx/k_par, ky/k_par, 0]
assert numpy.isclose(numpy.dot(l, l), 1)
else:
l = [0, 0, 0]
na = numpy.dot(n, opticAxis)
la = numpy.dot(l, opticAxis)
mod_kz_ord = numpy.sqrt(e_o * k_0**2 - k_par**2, dtype=numpy.complex128)
mod_kz_extraord = (1 / (1 + nu * na**2)) * (-nu * k_par * na*la
+ numpy.sqrt(e_o * k_0**2 * (1 + nu) * (1 + nu * na**2)
- k_par**2 * (1 + nu * (la**2 + na**2)),
dtype=numpy.complex128)
)
k_z1 = mod_kz_ord
k_z2 = -mod_kz_ord
k_z3 = mod_kz_extraord
k_z4 = -mod_kz_extraord
return [k_z1, k_z2, k_z3, k_z4]
<file_sep>import numpy as np
import matplotlib.pyplot as plt
from PyATMM.uniaxialTransferMatrix import *
from PyATMM.isotropicTransferMatrix import *
from PyATMM.transferMatrix import solve_transfer_matrix
__author__ = '<NAME>'
#
# Setup
#
c = 299792458. # m/c
w = c
#
# Theta sweep
#
theta = np.linspace(54.20, 54.22, 50, endpoint=True)
#
# Start layer, ZnSe
#
eps_ZnSe = 6.6995
ran_kx = np.sqrt(eps_ZnSe) * (w/c) * np.sin(np.deg2rad(theta))
ky = 0
#
# Second layer, Ta_2O_5
#
eps_Ta2O5 = 4.41
ran_d = np.linspace(5, 0, 50, endpoint=True)
#
# Anisotropic layer, YV04
#
eps_YVO4_per = 3.9733
eps_YVO4_par = 4.898
phi = np.deg2rad(46.25)
a_refl_pp = []
a_refl_ss = []
a_refl_ps = []
a_refl_sp = []
for d in ran_d:
a_refl_pp_ = []
a_refl_ss_ = []
a_refl_ps_ = []
a_refl_sp_ = []
d *= 2.*np.pi
for kx in ran_kx:
# Layer 0
D_ZnSe = build_isotropic_dynamic_matrix(eps_ZnSe, w, kx, ky)
# Layer 1
D_Ta2O5 = build_isotropic_dynamic_matrix(eps_Ta2O5, w, kx, ky)
D_Ta2O5_p = build_isotropic_propagation_matrix(eps_Ta2O5, w, kx, ky, d)
# Layer 2
D_YVo4 = build_uniaxial_dynamic_matrix(eps_YVO4_per, eps_YVO4_par, w, kx, ky, opticAxis=[np.cos(phi), np.sin(phi), 0])
# Multiply Matricies
D = np.dot(np.dot(np.dot(np.linalg.inv(D_ZnSe), D_Ta2O5), D_Ta2O5_p), np.dot(np.linalg.inv(D_Ta2O5), D_YVo4))
# Solve Matrix
r_ss, r_sp, r_ps, r_pp, t_ss, t_sp, t_ps, t_pp = solve_transfer_matrix(D)
a_refl_pp_.append(np.abs(r_pp**2))
a_refl_ss_.append(np.abs(r_ss**2))
a_refl_sp_.append(np.abs(r_sp**2))
a_refl_ps_.append(np.abs(r_ps**2))
a_refl_pp.append(a_refl_pp_)
a_refl_ss.append(a_refl_ss_)
a_refl_sp.append(a_refl_sp_)
a_refl_ps.append(a_refl_ps_)
plt.figure(figsize=(9, 6))
plt.imshow(a_refl_ps, interpolation='none', extent=[np.min(theta), np.max(theta), np.min(ran_d), np.max(ran_d)],
aspect="auto", cmap=plt.get_cmap("jet"))
plt.colorbar()
plt.xlabel("$\Theta$, degrees")
plt.xticks([54.20, 54.205, 54.21, 54.215, 54.22])
plt.ticklabel_format(style = 'sci', useOffset=False)
plt.ylabel("$\Delta / \lambda$")
plt.title("R_ps")
plt.show(block=True)
<file_sep>import PyATMM
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the RpythonEADME file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='PyATMM',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version=PyATMM.__version__,
description='Implementation of the transfer matrix method',
long_description=long_description,
url='https://github.com/kitchenknif/PyTMM',
author=PyATMM.__author__,
author_email='<EMAIL>',
# license=PyATMM.__license__,
classifiers=[
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Physics',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=['numpy', 'scipy'],
extras_require={},
package_data={},
data_files=[],
entry_points={},
)<file_sep>import numpy as np
import matplotlib.pyplot as plt
import scipy.linalg
import PyTMM.transferMatrix as tm
from PyATMM.uniaxialTransferMatrix import *
from PyATMM.transferMatrix import solve_transfer_matrix
__author__ = '<NAME>'
#
# Setup
#
c = 299792458 # m/c
ran_w = np.linspace(50, 1200, 100, endpoint=False)
ran_w = np.multiply(ran_w, 10 ** 12) # (1/(2*np.pi))*
ran_l = np.divide(c*(2*np.pi), ran_w)
eps_1 = 2
eps_2 = 2.25
n_1 = np.sqrt(eps_1)
n_2 = np.sqrt(eps_2)
kx = 0
ky = 0
d_nm = 2000
d_m = d_nm * 10**-9
#
# PyTMM
#
refl_p = []
refl_s = []
for i in ran_l:
B = tm.TransferMatrix.layer(n_1, d_nm, i*10**9, 0, tm.Polarization.s)
C = tm.TransferMatrix.layer(n_2, d_nm, i*10**9, 0, tm.Polarization.p)
M = scipy.linalg.block_diag(B.matrix, C.matrix)
r_ss, r_sp, r_ps, r_pp, t_ss, t_sp, t_ps, t_pp = solve_transfer_matrix(M)
refl_p.append(np.abs(r_pp**2))
refl_s.append(np.abs(r_ss**2))
#
# PyATMM
#
a_refl_p = []
a_refl_s = []
for w in ran_w:
D = build_uniaxial_layer_matrix(eps_1, eps_2, w, kx, ky, d_m, opticAxis=([0., 1., 0.]))
r_ss, r_sp, r_ps, r_pp, t_ss, t_sp, t_ps, t_pp = solve_transfer_matrix(D)
a_refl_p.append(np.abs(r_pp**2))
a_refl_s.append(np.abs(r_ss**2))
#PyATMM
plt.plot(ran_l*10**9, a_refl_p)
plt.plot(ran_l*10**9, a_refl_s)
#PyTMM
plt.plot(ran_l*10**9, refl_p, 'o')
plt.plot(ran_l*10**9, refl_s, 'o')
plt.xlabel("Wavelength, nm")
plt.ylabel("Reflectance")
plt.title("Reflectance uniaxial crystal")
plt.legend(['PP', 'SS'], loc='best')
plt.show(block=True)<file_sep># PyATMM: Generalized transfer matrix method
## Citing
[](https://zenodo.org/badge/latestdoi/44310723)
## Documentation
Hosted on Github pages: [PyATMM](https://kitchenknif.github.io/PyATMM)
## References
Based on papers by
- <NAME> 1980 - [doi:10.1016/0039-6028(80)90293-9](https://dx.doi.org/10.1016/0039-6028%2880%2990293-9)
- <NAME> 2012 - [doi:10.3367/UFNe.0182.201207f.0759](https://dx.doi.org/10.3367/UFNe.0182.201207f.0759)
<file_sep>import numpy as np
import matplotlib.pyplot as plt
from PyATMM.uniaxialTransferMatrix import *
from PyATMM.isotropicTransferMatrix import *
from PyATMM.transferMatrix import solve_transfer_matrix
__author__ = '<NAME>'
c = 299792458. # m/c
w = c
# w = 2*np.pi * 500. * 10 **12
#
# Sweep parameters
#
aoi = np.linspace(66, 63, 200, endpoint=True)
k_par_angles = np.linspace(np.deg2rad(40), np.deg2rad(50), 200)
#
# Layer 0, "prism"
#
n_prism = 1.77862
eps_prism = n_prism**2
k_par = np.sqrt(eps_prism) * (w/c) * np.sin(np.deg2rad(aoi))
#
# Layer 1, unixaial, E7
#
n_o = 1.520
n_e = 1.725
eps_o = n_o**2
eps_e = n_e**2
axis_1 = [1., 0., 0.]
d = 2*np.pi * 4
#
# Layer 2, uniaxial, E7
#
axis_2 = [0., 1., 0.]
#
# Layer 4, "prism"
#
a_refl_pp = []
a_refl_ss = []
a_refl_ps = []
a_refl_sp = []
for k in k_par:
a_refl_pp_ = []
a_refl_ss_ = []
a_refl_ps_ = []
a_refl_sp_ = []
for o in k_par_angles:
kx = np.cos(o) * k
ky = np.sin(o) * k
# 0
D_prism = build_isotropic_dynamic_matrix(eps_prism, w, kx, ky)
# 1
D_E7_1 = build_uniaxial_dynamic_matrix(eps_o, eps_e, w, kx, ky,
opticAxis=axis_1)
D_E7_1p = build_uniaxial_propagation_matrix(eps_o, eps_e, w, kx, ky, d,
opticAxis=axis_1)
D_1 = np.dot(np.dot(np.linalg.inv(D_prism), D_E7_1), D_E7_1p)
# 2
D_E7_2 = build_uniaxial_dynamic_matrix(eps_o, eps_e, w, kx, ky,
opticAxis=axis_2)
D_E7_2p = build_uniaxial_propagation_matrix(eps_o, eps_e, w, kx, ky, d,
opticAxis=axis_2)
D_2 = np.dot(np.dot(np.linalg.inv(D_E7_1), D_E7_2), D_E7_2p)
# 3
D_prism_2 = np.dot(np.linalg.inv(D_E7_2), D_prism)
D = np.dot(D_1, np.dot(D_2, D_prism_2))
r_ss, r_sp, r_ps, r_pp, \
t_ss, t_sp, t_ps, t_pp = solve_transfer_matrix(D)
a_refl_pp_.append(np.abs(r_pp**2))
a_refl_ss_.append(np.abs(r_ss**2))
a_refl_sp_.append(np.abs(r_sp**2))
a_refl_ps_.append(np.abs(r_ps**2))
a_refl_pp.append(a_refl_pp_)
a_refl_ss.append(a_refl_ss_)
a_refl_sp.append(a_refl_sp_)
a_refl_ps.append(a_refl_ps_)
plt.figure(figsize=(9, 6))
plt.imshow(a_refl_ss, interpolation='none',
extent=[np.min(k_par_angles), np.max(k_par_angles),
np.min(aoi), np.max(aoi)],
aspect="auto", cmap=plt.get_cmap("afmhot"))
plt.colorbar()
plt.xlabel("K$_{par}$ Angle, radians")
plt.ticklabel_format(style='sci', useOffset=False)
plt.ylabel("AOI, degrees")
plt.title("R_ps")
# plt.suptitle("Otto Geometry test", fontsize=40)
# plt.savefig("otto_test.pdf", bbox_inches='tight')
plt.show()
<file_sep>__author__ = '<NAME>'
import numpy
import numpy.linalg
def build_anisotropic_permittivity(e1, e2, e3):
eps = numpy.zeros([3, 3], dtype=numpy.complex128)
eps[0, 0] = e1
eps[1, 1] = e2
eps[2, 2] = e3
return eps
def build_rotation_matrix(theta, phi, psi):
R = numpy.asarray([
[numpy.cos(psi)*numpy.cos(phi) - numpy.cos(theta)*numpy.sin(phi)*numpy.sin(psi),
-numpy.sin(psi)*numpy.cos(phi) - numpy.cos(theta)*numpy.sin(phi)*numpy.cos(psi),
numpy.sin(theta)*numpy.sin(phi)],
[numpy.cos(psi)*numpy.sin(phi) + numpy.cos(theta)*numpy.cos(phi)*numpy.sin(psi),
- numpy.sin(psi)*numpy.sin(phi) + numpy.cos(theta)*numpy.cos(phi)*numpy.cos(psi),
-numpy.sin(theta)*numpy.cos(phi)],
[numpy.sin(theta)*numpy.sin(psi), numpy.sin(theta)*numpy.cos(psi), numpy.cos(theta)]
], dtype=numpy.float64)
return R
def build_general_permittivity_matrix(e1, e2, e3, theta, phi, psi):
E = build_anisotropic_permittivity(e1, e2, e3)
R = build_rotation_matrix(theta, phi, psi)
Eps = numpy.dot(R, numpy.dot(E, numpy.linalg.inv(R)))
assert numpy.isclose(Eps[1, 0], Eps[0, 1])
assert numpy.isclose(Eps[2, 0], Eps[0, 2])
assert numpy.isclose(Eps[1, 2], Eps[2, 1])
return Eps
def solve_transfer_matrix(M):
#
# Components 3,4 - S
# Components 1,2 - P Was mixed up until 11.08.2016 (switched s and p)
#
r_pp = (M[1, 0]*M[2, 2] - M[1, 2]*M[2, 0]) / (M[0, 0]*M[2, 2] - M[0, 2]*M[2, 0])
r_ps = (M[3, 0]*M[2, 2] - M[3, 2]*M[2, 0]) / (M[0, 0]*M[2, 2] - M[0, 2]*M[2, 0])
r_sp = (M[0, 0]*M[1, 2] - M[1, 0]*M[0, 2]) / (M[0, 0]*M[2, 2] - M[0, 2]*M[2, 0])
r_ss = (M[0, 0]*M[3, 2] - M[3, 0]*M[0, 2]) / (M[0, 0]*M[2, 2] - M[0, 2]*M[2, 0])
t_pp = M[2, 2] / (M[0, 0]*M[2, 2] - M[0, 2]*M[2, 0])
t_ps = -M[2, 0] / (M[0, 0]*M[2, 2] - M[0, 2]*M[2, 0])
t_sp = -M[0, 2] / (M[0, 0]*M[2, 2] - M[0, 2]*M[2, 0])
t_ss = M[0, 0] / (M[0, 0]*M[2, 2] - M[0, 2]*M[2, 0])
return r_ss, r_sp, r_ps, r_pp, t_ss, t_sp, t_ps, t_pp
| 23937e167d8544cb7115171e528f1b8d28062334 | [
"Markdown",
"Python"
] | 11 | Python | SalahuddinNur/PyATMM | 6439ecd90719c43d04b3d41e47f66306ea9fb13e | a721126b581a13028807548daf0d86b8170311dc |
refs/heads/master | <repo_name>Husnain19/FYP3<file_sep>/AutomotiveSols.BLL/ViewModels/ServiceCartVM.cs
using AutomotiveSols.BLL.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.ViewModels
{
public class ServiceCartVM
{
public List<Services> Services { get; set; }
public Appointments Appointments { get; set; }
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/OrderController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using AspNetCore.Reporting;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.BLL.ViewModels;
using AutomotiveSols.Data;
using AutomotiveSols.Models;
using AutomotiveSols.ServicesReport;
using AutomotiveSols.Static;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Stripe;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize]
public class OrderController : Controller
{
private readonly ApplicationDbContext _db;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly OrderHistoryService orderService = new OrderHistoryService();
private readonly UserManager<ApplicationUser> _userManager;
[BindProperty]
public OrderVM OrderVM { get; set; }
public OrderController(ApplicationDbContext db, UserManager<ApplicationUser> userManager,IWebHostEnvironment
webHostEnvironment)
{
_db = db;
_userManager = userManager;
_webHostEnvironment = webHostEnvironment;
}
public async Task<IActionResult> Index(string status = "")
{
var applicationUser = await _userManager.GetUserAsync(User);
var part = _db.AutoParts.Where(x => x.ApplicationUser.Id == applicationUser.Id).FirstOrDefault();
IEnumerable<OrderHeader> orderHeaderList;
if (User.IsInRole(StaticDetails.Role_Admin))
{
orderHeaderList = _db.OrderHeaders.Include(x => x.ApplicationUser).ToList();
}
else if (User.IsInRole(StaticDetails.Role_Vendor))
{
orderHeaderList = _db.OrderHeaders.Include(x => x.ApplicationUser)
.Where(x=>part.ApplicationUserId == applicationUser.Id).ToList();
}
else
{
orderHeaderList = _db.OrderHeaders.Include(x => x.ApplicationUser)
.Where(x => x.ApplicationUserId == applicationUser.Id).ToList();
}
switch (status)
{
case "pending":
orderHeaderList = orderHeaderList.Where(o => o.PaymentStatus == StaticDetails.PaymentStatusDelayedPayment);
break;
case "inprocess":
orderHeaderList = orderHeaderList.Where(o => o.OrderStatus == StaticDetails.StatusApproved ||
o.OrderStatus == StaticDetails.StatusInProcess ||
o.OrderStatus == StaticDetails.StatusPending);
break;
case "completed":
orderHeaderList = orderHeaderList.Where(o => o.OrderStatus == StaticDetails.StatusShipped);
break;
case "rejected":
orderHeaderList = orderHeaderList.Where(o => o.OrderStatus == StaticDetails.StatusCancelled ||
o.OrderStatus == StaticDetails.StatusRefunded ||
o.OrderStatus == StaticDetails.PaymentStatusRejected);
break;
default:
break;
}
return View( orderHeaderList );
}
public IActionResult OrderHistory()
{
var dt = new DataTable();
dt = orderService.GetOrders();
string mimtype = "";
int extension = 1;
var path = $"{this._webHostEnvironment.WebRootPath}\\Reports\\Report4.rdlc";
Dictionary<string, string> parameters = new Dictionary<string, string>();
LocalReport localReport = new LocalReport(path);
localReport.AddDataSource("DataSet2", dt);
var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimtype);
return File(result.MainStream, "application/pdf");
}
public IActionResult OrdersPending()
{
var dt = new DataTable();
dt = orderService.GetOrdersPending();
string mimtype = "";
int extension = 1;
var path = $"{this._webHostEnvironment.WebRootPath}\\Reports\\PendingOrders.rdlc";
Dictionary<string, string> parameters = new Dictionary<string, string>();
LocalReport localReport = new LocalReport(path);
localReport.AddDataSource("PendingOrders", dt);
var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimtype);
return File(result.MainStream, "application/pdf");
}
public IActionResult OrdersApproved()
{
var dt = new DataTable();
dt = orderService.GetOrdersApproved();
string mimtype = "";
int extension = 1;
var path = $"{this._webHostEnvironment.WebRootPath}\\Reports\\ApprovedOrders.rdlc";
Dictionary<string, string> parameters = new Dictionary<string, string>();
LocalReport localReport = new LocalReport(path);
localReport.AddDataSource("ApprovedOrders", dt);
var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimtype);
return File(result.MainStream, "application/pdf");
}
public IActionResult Invoice(int id)
{
OrderVM OrderVM = new OrderVM()
{
OrderHeader = _db.OrderHeaders.Include(x => x.ApplicationUser).FirstOrDefault(u => u.Id == id),
OrderDetails = _db.OrderDetails.Include(x => x.AutoPart).Where(o => o.OrderId == id).ToList()
};
string mimtype = "";
int extension = 1;
var path = $"{this._webHostEnvironment.WebRootPath}\\Reports\\Report2.rdlc";
Dictionary<string, string> parameters = new Dictionary<string, string>();
int count = OrderVM.OrderDetails.Count();
int p = 1;
while (count > 0)
{
foreach (var item in OrderVM.OrderDetails)
{
parameters.Add("rp"+p.ToString(), item.AutoPart.Name);
p = p + 1;
parameters.Add("rp"+p.ToString(), item.AutoPart.Price.ToString());
p = p + 1;
count = count - 1;
}
}
parameters.Add("rp5", OrderVM.OrderHeader.ApplicationUser.Name);
parameters.Add("rp6", OrderVM.OrderHeader.ApplicationUser.Email);
parameters.Add("rp7", OrderVM.OrderHeader.PhoneNumber);
parameters.Add("rp9", OrderVM.OrderHeader.PostalCode);
parameters.Add("rp10", OrderVM.OrderHeader.State);
parameters.Add("rp11", OrderVM.OrderHeader.City);
parameters.Add("rp12", OrderVM.OrderHeader.StreetAddress);
parameters.Add("rp13", OrderVM.OrderHeader.ShippingDate.ToString());
parameters.Add("rp14", OrderVM.OrderHeader.TrackingNumber);
parameters.Add("rp15", OrderVM.OrderHeader.TransactionId);
//parameters.Add("rp16", OrderVM.OrderHeader.CouponCode);
parameters.Add("rp17", OrderVM.OrderHeader.Carrier);
parameters.Add("rp18", OrderVM.OrderHeader.OrderDate.ToString());
parameters.Add("rp19", OrderVM.OrderHeader.OrderTotalOriginal.ToString());
parameters.Add("rp20", OrderVM.OrderHeader.PaymentStatus);
LocalReport localReport = new LocalReport(path);
var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimtype);
return File(result.MainStream, "application/pdf");
}
public IActionResult Details(int id)
{
OrderVM OrderVM = new OrderVM()
{
OrderHeader = _db.OrderHeaders.Include(x=>x.ApplicationUser).FirstOrDefault(u => u.Id == id),
OrderDetails = _db.OrderDetails.Include(x=>x.AutoPart).Where(o => o.OrderId == id).ToList()
};
return View(OrderVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("Details")]
public IActionResult Details(string stripeToken)
{
OrderHeader orderHeader = _db.OrderHeaders.Include(x => x.ApplicationUser).FirstOrDefault(u => u.Id == OrderVM.OrderHeader.Id);
if (stripeToken != null)
{
//process the payment
var options = new ChargeCreateOptions
{
Amount = Convert.ToInt32(orderHeader.OrderTotal * 100),
Currency = "usd",
Description = "Order ID : " + orderHeader.Id,
Source = stripeToken
};
var service = new ChargeService();
Charge charge = service.Create(options);
if (charge.Id == null)
{
orderHeader.PaymentStatus = StaticDetails.PaymentStatusRejected;
}
else
{
orderHeader.TransactionId = charge.Id;
}
if (charge.Status.ToLower() == "succeeded")
{
orderHeader.PaymentStatus = StaticDetails.PaymentStatusApproved;
orderHeader.PaymentDate = DateTime.Now;
}
_db.SaveChanges();
}
return RedirectToAction("Details", "Order", new { id = orderHeader.Id });
}
[Authorize(Roles = StaticDetails.Role_Admin + "," + StaticDetails.Role_Vendor)]
public IActionResult StartProcessing(int id)
{
OrderHeader orderHeader = _db.OrderHeaders.FirstOrDefault(u => u.Id == id);
orderHeader.OrderStatus = StaticDetails.StatusInProcess;
_db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
[Authorize(Roles = StaticDetails.Role_Admin + "," + StaticDetails.Role_Vendor)]
public IActionResult ShipOrder()
{
OrderHeader orderHeader = _db.OrderHeaders.FirstOrDefault(u => u.Id == OrderVM.OrderHeader.Id);
orderHeader.TrackingNumber = OrderVM.OrderHeader.TrackingNumber;
orderHeader.Carrier = OrderVM.OrderHeader.Carrier;
orderHeader.OrderStatus = StaticDetails.StatusShipped;
orderHeader.ShippingDate = DateTime.Now;
_db.SaveChanges();
return RedirectToAction("Index");
}
[Authorize(Roles = StaticDetails.Role_Admin + "," + StaticDetails.Role_Vendor)]
public IActionResult CancelOrder(int id)
{
OrderHeader orderHeader = _db.OrderHeaders.FirstOrDefault(u => u.Id == id);
if (orderHeader.PaymentStatus == StaticDetails.StatusApproved)
{
var options = new RefundCreateOptions
{
Amount = Convert.ToInt32(orderHeader.OrderTotal * 100),
Reason = RefundReasons.RequestedByCustomer,
Charge = orderHeader.TransactionId
};
var service = new RefundService();
Refund refund = service.Create(options);
orderHeader.OrderStatus = StaticDetails.StatusRefunded;
orderHeader.PaymentStatus = StaticDetails.StatusRefunded;
}
else
{
orderHeader.OrderStatus = StaticDetails.StatusCancelled;
orderHeader.PaymentStatus = StaticDetails.StatusCancelled;
}
_db.SaveChanges();
return RedirectToAction("Index");
}
public IActionResult UpdateOrderDetails()
{
var orderHEaderFromDb = _db.OrderHeaders.FirstOrDefault(u => u.Id == OrderVM.OrderHeader.Id);
orderHEaderFromDb.Name = OrderVM.OrderHeader.Name;
orderHEaderFromDb.PhoneNumber = OrderVM.OrderHeader.PhoneNumber;
orderHEaderFromDb.StreetAddress = OrderVM.OrderHeader.StreetAddress;
orderHEaderFromDb.City = OrderVM.OrderHeader.City;
orderHEaderFromDb.State = OrderVM.OrderHeader.State;
orderHEaderFromDb.PostalCode = OrderVM.OrderHeader.PostalCode;
if (OrderVM.OrderHeader.Carrier != null)
{
orderHEaderFromDb.Carrier = OrderVM.OrderHeader.Carrier;
}
if (OrderVM.OrderHeader.TrackingNumber != null)
{
orderHEaderFromDb.TrackingNumber = OrderVM.OrderHeader.TrackingNumber;
}
_db.SaveChanges();
TempData["Error"] = "Order Details Updated Successfully.";
return RedirectToAction("Details", "Order", new { id = orderHEaderFromDb.Id });
}
public IActionResult Print()
{
var orderData = _db.OrderHeaders.Where(x => x.OrderDate <= OrderVM.OrderHeader.OrderDate
&& x.OrderDate >= OrderVM.OrderHeader.OrderDate).ToList();
return View(orderData);
}
}
}
<file_sep>/AutomotiveSols.BLL/Models/Appointments.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace AutomotiveSols.BLL.Models
{
public class Appointments
{
public int Id { get; set; }
public string SalesPersonId { get; set; }
public ApplicationUser SalesPerson { get; set; }
public DateTime AppointmentDate { get; set; }
[NotMapped]
public DateTime AppointmentTime { get; set; }
public string CustomerName { get; set; }
public string CustomerPhoneNumber { get; set; }
public string CustomerEmail { get; set; }
public bool isConfirmed { get; set; }
public bool? isCar { get; set; }
public bool? isService { get; set; }
public List<ServicesAppointment> ServicesAppointments { get; set; }
public List<CarAppointment> CarAppointments { get; set; }
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210626104735_addCarTableToDb.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class addCarTableToDb : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "BranId",
table: "Car",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "MileageId",
table: "Car",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "ModelId",
table: "Car",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "RegistrationCityId",
table: "Car",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "TransmissionId",
table: "Car",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "TrimId",
table: "Car",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "YearId",
table: "Car",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateTable(
name: "Brand",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Brand", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Features",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false),
Description = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Features", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Mileage",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
NumberKm = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Mileage", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Model",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Model", x => x.Id);
});
migrationBuilder.CreateTable(
name: "RegistrationCity",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RegistrationCity", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Transmissions",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Transmissions", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Trim",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Trim", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Year",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SolarYear = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Year", x => x.Id);
});
migrationBuilder.CreateTable(
name: "CarFeature",
columns: table => new
{
Id = table.Column<int>(nullable: false),
FeatureId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CarFeature", x => new { x.FeatureId, x.Id });
table.ForeignKey(
name: "FK_CarFeature_Features_FeatureId",
column: x => x.FeatureId,
principalTable: "Features",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_CarFeature_Car_Id",
column: x => x.Id,
principalTable: "Car",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Car_BranId",
table: "Car",
column: "BranId");
migrationBuilder.CreateIndex(
name: "IX_Car_MileageId",
table: "Car",
column: "MileageId");
migrationBuilder.CreateIndex(
name: "IX_Car_ModelId",
table: "Car",
column: "ModelId");
migrationBuilder.CreateIndex(
name: "IX_Car_RegistrationCityId",
table: "Car",
column: "RegistrationCityId");
migrationBuilder.CreateIndex(
name: "IX_Car_TransmissionId",
table: "Car",
column: "TransmissionId");
migrationBuilder.CreateIndex(
name: "IX_Car_TrimId",
table: "Car",
column: "TrimId");
migrationBuilder.CreateIndex(
name: "IX_Car_YearId",
table: "Car",
column: "YearId");
migrationBuilder.CreateIndex(
name: "IX_CarFeature_Id",
table: "CarFeature",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_Car_Brand_BranId",
table: "Car",
column: "BranId",
principalTable: "Brand",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_Mileage_MileageId",
table: "Car",
column: "MileageId",
principalTable: "Mileage",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_Model_ModelId",
table: "Car",
column: "ModelId",
principalTable: "Model",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_RegistrationCity_RegistrationCityId",
table: "Car",
column: "RegistrationCityId",
principalTable: "RegistrationCity",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_Transmissions_TransmissionId",
table: "Car",
column: "TransmissionId",
principalTable: "Transmissions",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_Trim_TrimId",
table: "Car",
column: "TrimId",
principalTable: "Trim",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_Year_YearId",
table: "Car",
column: "YearId",
principalTable: "Year",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Car_Brand_BranId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_Mileage_MileageId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_Model_ModelId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_RegistrationCity_RegistrationCityId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_Transmissions_TransmissionId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_Trim_TrimId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_Year_YearId",
table: "Car");
migrationBuilder.DropTable(
name: "Brand");
migrationBuilder.DropTable(
name: "CarFeature");
migrationBuilder.DropTable(
name: "Mileage");
migrationBuilder.DropTable(
name: "Model");
migrationBuilder.DropTable(
name: "RegistrationCity");
migrationBuilder.DropTable(
name: "Transmissions");
migrationBuilder.DropTable(
name: "Trim");
migrationBuilder.DropTable(
name: "Year");
migrationBuilder.DropTable(
name: "Features");
migrationBuilder.DropIndex(
name: "IX_Car_BranId",
table: "Car");
migrationBuilder.DropIndex(
name: "IX_Car_MileageId",
table: "Car");
migrationBuilder.DropIndex(
name: "IX_Car_ModelId",
table: "Car");
migrationBuilder.DropIndex(
name: "IX_Car_RegistrationCityId",
table: "Car");
migrationBuilder.DropIndex(
name: "IX_Car_TransmissionId",
table: "Car");
migrationBuilder.DropIndex(
name: "IX_Car_TrimId",
table: "Car");
migrationBuilder.DropIndex(
name: "IX_Car_YearId",
table: "Car");
migrationBuilder.DropColumn(
name: "BranId",
table: "Car");
migrationBuilder.DropColumn(
name: "MileageId",
table: "Car");
migrationBuilder.DropColumn(
name: "ModelId",
table: "Car");
migrationBuilder.DropColumn(
name: "RegistrationCityId",
table: "Car");
migrationBuilder.DropColumn(
name: "TransmissionId",
table: "Car");
migrationBuilder.DropColumn(
name: "TrimId",
table: "Car");
migrationBuilder.DropColumn(
name: "YearId",
table: "Car");
}
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210505094557_changenames.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class changenames : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_AspNetUsers_Organization_OrganizationId",
table: "AspNetUsers");
migrationBuilder.DropForeignKey(
name: "FK_AutoPart_AspNetUsers_ApplicationUserId",
table: "AutoPart");
migrationBuilder.DropForeignKey(
name: "FK_AutoPart_Categories_CategoryId",
table: "AutoPart");
migrationBuilder.DropForeignKey(
name: "FK_AutoPart_SubCategories_SubCategoryId",
table: "AutoPart");
migrationBuilder.DropPrimaryKey(
name: "PK_Organization",
table: "Organization");
migrationBuilder.DropPrimaryKey(
name: "PK_AutoPart",
table: "AutoPart");
migrationBuilder.RenameTable(
name: "Organization",
newName: "Organizations");
migrationBuilder.RenameTable(
name: "AutoPart",
newName: "AutoParts");
migrationBuilder.RenameIndex(
name: "IX_AutoPart_SubCategoryId",
table: "AutoParts",
newName: "IX_AutoParts_SubCategoryId");
migrationBuilder.RenameIndex(
name: "IX_AutoPart_CategoryId",
table: "AutoParts",
newName: "IX_AutoParts_CategoryId");
migrationBuilder.RenameIndex(
name: "IX_AutoPart_ApplicationUserId",
table: "AutoParts",
newName: "IX_AutoParts_ApplicationUserId");
migrationBuilder.AddPrimaryKey(
name: "PK_Organizations",
table: "Organizations",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_AutoParts",
table: "AutoParts",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_AspNetUsers_Organizations_OrganizationId",
table: "AspNetUsers",
column: "OrganizationId",
principalTable: "Organizations",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AutoParts_AspNetUsers_ApplicationUserId",
table: "AutoParts",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AutoParts_Categories_CategoryId",
table: "AutoParts",
column: "CategoryId",
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
migrationBuilder.AddForeignKey(
name: "FK_AutoParts_SubCategories_SubCategoryId",
table: "AutoParts",
column: "SubCategoryId",
principalTable: "SubCategories",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_AspNetUsers_Organizations_OrganizationId",
table: "AspNetUsers");
migrationBuilder.DropForeignKey(
name: "FK_AutoParts_AspNetUsers_ApplicationUserId",
table: "AutoParts");
migrationBuilder.DropForeignKey(
name: "FK_AutoParts_Categories_CategoryId",
table: "AutoParts");
migrationBuilder.DropForeignKey(
name: "FK_AutoParts_SubCategories_SubCategoryId",
table: "AutoParts");
migrationBuilder.DropPrimaryKey(
name: "PK_Organizations",
table: "Organizations");
migrationBuilder.DropPrimaryKey(
name: "PK_AutoParts",
table: "AutoParts");
migrationBuilder.RenameTable(
name: "Organizations",
newName: "Organization");
migrationBuilder.RenameTable(
name: "AutoParts",
newName: "AutoPart");
migrationBuilder.RenameIndex(
name: "IX_AutoParts_SubCategoryId",
table: "AutoPart",
newName: "IX_AutoPart_SubCategoryId");
migrationBuilder.RenameIndex(
name: "IX_AutoParts_CategoryId",
table: "AutoPart",
newName: "IX_AutoPart_CategoryId");
migrationBuilder.RenameIndex(
name: "IX_AutoParts_ApplicationUserId",
table: "AutoPart",
newName: "IX_AutoPart_ApplicationUserId");
migrationBuilder.AddPrimaryKey(
name: "PK_Organization",
table: "Organization",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_AutoPart",
table: "AutoPart",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_AspNetUsers_Organization_OrganizationId",
table: "AspNetUsers",
column: "OrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AutoPart_AspNetUsers_ApplicationUserId",
table: "AutoPart",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AutoPart_Categories_CategoryId",
table: "AutoPart",
column: "CategoryId",
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AutoPart_SubCategories_SubCategoryId",
table: "AutoPart",
column: "SubCategoryId",
principalTable: "SubCategories",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}
<file_sep>/AutomotiveSols/Areas/Customer/Controllers/TempCartController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.BLL.ViewModels;
using AutomotiveSols.Data;
using AutomotiveSols.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace AutomotiveSols.Areas.Customer.Controllers
{
[Area("Customer")]
public class TempCartController : Controller
{
private readonly ApplicationDbContext _db;
[BindProperty]
public ServiceCartVM ServiceCartVM { get; set; }
public TempCartController(ApplicationDbContext db)
{
_db = db;
ServiceCartVM = new ServiceCartVM()
{
Services = new List<AutomotiveSols.BLL.Models.Services>()
};
}
public async Task<IActionResult> Index()
{
List<int> tempCart = HttpContext.Session.Get<List<int>>("tempCart");
if (tempCart.Count > 0)
{
foreach (int cartItem in tempCart)
{
Services service = await _db.Services.Include(p => p.ServiceType).Where(p => p.Id == cartItem).FirstOrDefaultAsync();
ServiceCartVM.Services.Add(service);
}
}
return View(ServiceCartVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("Index")]
public IActionResult IndexPost()
{
List<int> lstCartItems = HttpContext.Session.Get<List<int>>("tempCart");
ServiceCartVM.Appointments.AppointmentDate = ServiceCartVM.Appointments.AppointmentDate
.AddHours(ServiceCartVM.Appointments.AppointmentTime.Hour)
.AddMinutes(ServiceCartVM.Appointments.AppointmentTime.Minute);
Appointments appointments = ServiceCartVM.Appointments;
appointments.isCar = false;
appointments.isService = true;
_db.Appointments.Add(appointments);
_db.SaveChanges();
int appointmentId = appointments.Id;
foreach (int productId in lstCartItems)
{
ServicesAppointment productsSelectedForAppointment = new ServicesAppointment()
{
AppointmentId = appointmentId,
ServiceId = productId
};
_db.ServicesAppointments.Add(productsSelectedForAppointment);
}
_db.SaveChanges();
lstCartItems = new List<int>();
HttpContext.Session.Set("tempCart", lstCartItems);
return RedirectToAction("AppointmentConfirmation", "TempCart", new { Id = appointmentId });
}
public IActionResult Remove(int id)
{
List<int> lstCartItems = HttpContext.Session.Get<List<int>>("tempCart");
if (lstCartItems.Count > 0)
{
if (lstCartItems.Contains(id))
{
lstCartItems.Remove(id);
}
}
HttpContext.Session.Set("tempCart", lstCartItems);
return RedirectToAction(nameof(Index));
}
public IActionResult AppointmentConfirmation(int id)
{
ServiceCartVM.Appointments = _db.Appointments.Where(a => a.Id == id).FirstOrDefault();
List<ServicesAppointment> objServicesList = _db.ServicesAppointments.Where(p => p.AppointmentId == id).ToList();
foreach (ServicesAppointment serviceAptObj in objServicesList)
{
ServiceCartVM.Services.Add(_db.Services.Include(p => p.ServiceType).Where(p => p.Id == serviceAptObj.ServiceId).FirstOrDefault());
}
return View(ServiceCartVM);
}
}
}<file_sep>/AutomotiveSols.BLL/Models/Services.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.Models
{
public class Services
{
public int Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
public string ImageUrl { get; set; }
public string SellerComments { get; set; }
public string Description { get; set; }
public bool Status { get; set; }
public int ServiceTypeId { get; set; }
public ServiceType ServiceType { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public List<ServicesAppointment> ServicesAppointments { get; set; }
}
}
<file_sep>/AutomotiveSols.BLL/ViewModels/OrderVM.cs
using AutomotiveSols.BLL.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.ViewModels
{
public class OrderVM
{
public OrderHeader OrderHeader { get; set; }
public IEnumerable<OrderDetails> OrderDetails { get; set; }
}
}
<file_sep>/AutomotiveSols.BLL/ViewModels/ServiceVM.cs
using AutomotiveSols.BLL.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
namespace AutomotiveSols.BLL.ViewModels
{
public class ServiceVM
{
public Services Services { get; set; }
public int Id { get; set; }
public string Name { get; set; }
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210524085828_addservicestable.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class addservicestable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Services",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(maxLength: 100, nullable: false),
Price = table.Column<decimal>(nullable: false),
ImageUrl = table.Column<string>(nullable: false),
SellerComments = table.Column<string>(maxLength: 300, nullable: false),
Description = table.Column<string>(maxLength: 300, nullable: false),
ServiceTypeId = table.Column<int>(nullable: false),
ApplicationUserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Services", x => x.Id);
table.ForeignKey(
name: "FK_Services_AspNetUsers_ApplicationUserId",
column: x => x.ApplicationUserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Services_ServiceTypes_ServiceTypeId",
column: x => x.ServiceTypeId,
principalTable: "ServiceTypes",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Services_ApplicationUserId",
table: "Services",
column: "ApplicationUserId");
migrationBuilder.CreateIndex(
name: "IX_Services_ServiceTypeId",
table: "Services",
column: "ServiceTypeId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Services");
}
}
}
<file_sep>/AutomotiveSols.BLL/Models/ServicesAppointment.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.Models
{
public class ServicesAppointment
{
public int Id { get; set; }
public int AppointmentId { get; set; }
public Appointments Appointments { get; set; }
public int ServiceId { get; set; }
public Services Service { get; set; }
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210629114821_addCarAppointment.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class addCarAppointment : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "Status",
table: "Cars",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "CarAppointments",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
AppointmentId = table.Column<int>(nullable: false),
CarId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CarAppointments", x => x.Id);
table.ForeignKey(
name: "FK_CarAppointments_Appointments_AppointmentId",
column: x => x.AppointmentId,
principalTable: "Appointments",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_CarAppointments_Cars_CarId",
column: x => x.CarId,
principalTable: "Cars",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_CarAppointments_AppointmentId",
table: "CarAppointments",
column: "AppointmentId");
migrationBuilder.CreateIndex(
name: "IX_CarAppointments_CarId",
table: "CarAppointments",
column: "CarId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CarAppointments");
migrationBuilder.DropColumn(
name: "Status",
table: "Cars");
}
}
}
<file_sep>/AutomotiveSols/Areas/Customer/Controllers/CarCartController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.BLL.ViewModels;
using AutomotiveSols.Data;
using AutomotiveSols.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace AutomotiveSols.Areas.Customer.Controllers
{
[Area("Customer")]
public class CarCartController : Controller
{
private readonly ApplicationDbContext _db;
[BindProperty]
public CarAppointmentVM CarAppointmentVM { get; set; }
public CarCartController(ApplicationDbContext db)
{
_db = db;
CarAppointmentVM = new CarAppointmentVM()
{
Cars = new List<AutomotiveSols.BLL.Models.Car>()
};
}
public async Task<IActionResult> Index()
{
List<int> carCart = HttpContext.Session.Get<List<int>>("carCart");
if (carCart.Count > 0)
{
foreach (int cartItem in carCart)
{
Car car = await _db.Cars.Include(x => x.Brand)
.Include(x => x.Model)
.Include(x => x.Mileage)
.Include(x => x.Transmission)
.Include(x => x.Trim)
.Include(x => x.RegistrationCity)
.Include(x => x.Year)
.Where(p => p.Id == cartItem).FirstOrDefaultAsync();
CarAppointmentVM.Cars.Add(car);
}
}
else
{
CarAppointmentVM carAppointmentVM = new CarAppointmentVM()
{
Cars = new List<AutomotiveSols.BLL.Models.Car>()
};
return View(carAppointmentVM);
}
return View(CarAppointmentVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("Index")]
public IActionResult IndexPost()
{
List<int> lstCartItems = HttpContext.Session.Get<List<int>>("carCart");
CarAppointmentVM.Appointments.AppointmentDate = CarAppointmentVM.Appointments.AppointmentDate
.AddHours(CarAppointmentVM.Appointments.AppointmentTime.Hour)
.AddMinutes(CarAppointmentVM.Appointments.AppointmentTime.Minute);
Appointments appointments = CarAppointmentVM.Appointments;
appointments.isCar = true;
appointments.isService = false;
_db.Appointments.Add(appointments);
_db.SaveChanges();
int appointmentId = appointments.Id;
foreach (int carId in lstCartItems)
{
CarAppointment carsSelectedForAppointment = new CarAppointment()
{
AppointmentId = appointmentId,
CarId = carId
};
_db.CarAppointments.Add(carsSelectedForAppointment);
}
_db.SaveChanges();
lstCartItems = new List<int>();
HttpContext.Session.Set("carCart", lstCartItems);
return RedirectToAction("AppointmentConfirmation", "CarCart", new { Id = appointmentId });
}
public IActionResult Remove(int id)
{
List<int> lstCartItems = HttpContext.Session.Get<List<int>>("carCart");
if (lstCartItems.Count > 0)
{
if (lstCartItems.Contains(id))
{
lstCartItems.Remove(id);
}
}
HttpContext.Session.Set("carCart", lstCartItems);
return RedirectToAction(nameof(Index));
}
public IActionResult AppointmentConfirmation(int id)
{
CarAppointmentVM.Appointments = _db.Appointments.Where(a => a.Id == id).FirstOrDefault();
List<CarAppointment> objCarsList = _db.CarAppointments.Where(p => p.AppointmentId == id).ToList();
foreach (CarAppointment carAptObj in objCarsList)
{
CarAppointmentVM.Cars.Add(_db.Cars.Include(x => x.Brand)
.Include(x => x.Model)
.Include(x => x.Mileage)
.Include(x => x.Transmission)
.Include(x => x.Trim)
.Include(x => x.RegistrationCity)
.Include(x => x.Year)
.Where(p => p.Id == carAptObj.CarId).FirstOrDefault());
}
return View(CarAppointmentVM);
}
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/ModelController.cs
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 AutomotiveSols.BLL.Models;
using AutomotiveSols.Data;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class ModelController : Controller
{
private readonly ApplicationDbContext _context;
public ModelController(ApplicationDbContext context)
{
_context = context;
}
// GET: Admin/Model
public async Task<IActionResult> Index()
{
return View(await _context.Models.Include(x=>x.Brand).ToListAsync());
}
[ActionName("GetModels")]
public async Task<IActionResult> GetModels(int id)
{
List<Model> models = new List<Model>();
models = await (from model in _context.Models
where model.BrandId== id
select model).ToListAsync();
return Json(new SelectList(models, "Id", "Name"));
}
// GET: Admin/Model/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var model = await _context.Models
.FirstOrDefaultAsync(m => m.Id == id);
if (model == null)
{
return NotFound();
}
return View(model);
}
// GET: Admin/Model/Create
public IActionResult Create()
{
ViewBag.BrandList = new SelectList(_context.Brands.ToList(), "Id", "Name");
return View();
}
// POST: Admin/Model/Create
// To protect from overposting attacks, 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(Model model)
{
ViewBag.BrandList = new SelectList(_context.Brands.ToList(), "Id", "Name");
if (ModelState.IsValid)
{
_context.Add(model);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(model);
}
// GET: Admin/Model/Edit/5
public async Task<IActionResult> Edit(int? id)
{
ViewBag.BrandList = new SelectList(_context.Brands.ToList(), "Id", "Name");
if (id == null)
{
return NotFound();
}
var model = await _context.Models.FindAsync(id);
if (model == null)
{
return NotFound();
}
return View(model);
}
// POST: Admin/Model/Edit/5
// To protect from overposting attacks, 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(int id, Model model)
{
if (id != model.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(model);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ModelExists(model.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(model);
}
// GET: Admin/Model/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var model = await _context.Models
.FirstOrDefaultAsync(m => m.Id == id);
if (model == null)
{
return NotFound();
}
return View(model);
}
// POST: Admin/Model/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var model = await _context.Models.FindAsync(id);
_context.Models.Remove(model);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool ModelExists(int id)
{
return _context.Models.Any(e => e.Id == id);
}
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/SubCategoryController.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class SubCategoryController : Controller
{
private readonly ApplicationDbContext _db;
public SubCategoryController(ApplicationDbContext db)
{
_db = db;
}
public async Task<IActionResult> Index()
{
return View ( await _db.SubCategories.Include(x=>x.Category).ToListAsync());
}
[HttpGet]
public IActionResult Create()
{
ViewBag.CategoryList = new SelectList(_db.Categories.ToList(), "Id", "Name");
return View();
}
[HttpPost]
public async Task<IActionResult> Create(SubCategory subCategory)
{
ViewBag.CategoryList = new SelectList(_db.Categories.ToList(), "Id", "Name");
if (ModelState.IsValid)
{
await _db.SubCategories.AddAsync(subCategory);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(subCategory);
}
[HttpGet]
public IActionResult Edit(int id)
{
SubCategory subCategory = new SubCategory();
subCategory = _db.SubCategories.Find(id);
if (subCategory == null)
{
return NotFound();
}
ViewBag.CategoryList = new SelectList(_db.Categories.ToList(), "Id", "Name");
return View(subCategory);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, SubCategory subcategory)
{
if (id != subcategory.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
_db.Update(subcategory);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(subcategory);
}
[ActionName("GetSubCategory")]
public async Task<IActionResult> GetSubCategory(int id)
{
List<SubCategory> subCategories = new List<SubCategory>();
subCategories = await (from subCategory in _db.SubCategories
where subCategory.CategoryId == id
select subCategory).ToListAsync();
return Json(new SelectList(subCategories, "Id", "Name"));
}
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var subcategory = await _db.SubCategories.Include(x=>x.Category).Where(x=>x.Id==id).FirstOrDefaultAsync();
if (subcategory == null)
{
return NotFound();
}
return View(subcategory);
}
//POST Delete for the better security
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var subcategory = await _db.SubCategories.FindAsync(id);
_db.SubCategories.Remove(subcategory);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}
<file_sep>/AutomotiveSols.BLL/Models/AutoPart.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace AutomotiveSols.BLL.Models
{
public class AutoPart
{
public int Id { get; set; }
public string Name { get; set; }
[Required]
[Range(1, 10000)]
public int ListPrice { get; set; }
[Required]
[Range(1, 10000)]
public int Price { get; set; }
// [Required]
[Range(1, 10000)]
public int Price50 { get; set; }
// [Required]
[Range(1, 10000)]
public int Price100 { get; set; }
// [Required]
public int CategoryId { get; set; }
//[ForeignKey("CategoryId")]
public Category Category { get; set; }
[Required]
public int SubCategoryId { get; set; }
// [ForeignKey("SubCategoryId")]
public SubCategory SubCategory { get; set; }
public string Description { get; set; }
public string SellerComments { get; set; }
public string MainImageUrl { get; set; }
public DateTime? CreatedOn { get; set; }
public DateTime? UpdatedOn { get; set; }
public bool Status { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public List<ShoppingCart> ShoppingCarts { get; set; }
public List<OrderDetails> OrderDetails { get; set; }
public List<PartGallery> PartGalleries { get; set; }
// public ICollection<PartGallery> PartGallery { get; set; }
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/AutoPartController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.BLL.ViewModels;
using AutomotiveSols.Data;
using AutomotiveSols.Static;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class AutoPartController : Controller
{
private readonly ApplicationDbContext _db;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly UserManager<ApplicationUser> _userManager;
public AutoPartController(ApplicationDbContext db,IWebHostEnvironment webHostEnvironment,
UserManager<ApplicationUser> userManager)
{
_db = db;
_webHostEnvironment = webHostEnvironment;
_userManager = userManager;
}
public IActionResult Index()
{
return View(_db.AutoParts.Include(x=>x.Category)
.Include(x=>x.SubCategory)
.Include(x=>x.ApplicationUser)
.Include(x=>x.PartGalleries).ToList());
}
public IActionResult Edit(int id)
{
ViewBag.CategoryList = new SelectList(_db.Categories.ToList(), "Id", "Name");
ViewBag.SubCategoryList = new SelectList(_db.SubCategories.ToList(), "Id", "Name");
var data = _db.AutoParts.Include(x => x.Category).Include(x => x.SubCategory).Include(x => x.PartGalleries)
.Where(x => x.Id == id).FirstOrDefault();
AutoPart autoPart = new AutoPart()
{
Id =data.Id,
Name =data.Name,
ListPrice = data.ListPrice,
Price =data.Price,
Price50 =data.Price50,
Price100 =data.Price100,
CategoryId = data.CategoryId,
SubCategoryId = data.SubCategoryId,
MainImageUrl = data.MainImageUrl,
Description =data.Description,
SellerComments =data.SellerComments,
CreatedOn = data.CreatedOn,
UpdatedOn = data.UpdatedOn,
ApplicationUserId = data.ApplicationUserId
};
return View(autoPart);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, AutoPart autoPart)
{
ViewBag.CategoryList = new SelectList(_db.Categories.ToList(), "Id", "Name");
ViewBag.SubCategoryList = new SelectList(_db.SubCategories.ToList(), "Id", "Name");
if (ModelState.IsValid)
{
string webRootPath = _webHostEnvironment.WebRootPath;
var files = HttpContext.Request.Form.Files;
var applicationUser = await _userManager.GetUserAsync(User);
var serviceFromDb = _db.AutoParts.Where(m => m.Id == autoPart.Id).FirstOrDefault();
if (files.Count > 0 && files[0] != null)
{
//if user uploads a new image
var uploads = Path.Combine(webRootPath, StaticDetails.partsimage);
var new_extension = Path.GetExtension(files[0].FileName);
var old_extension = Path.GetExtension(serviceFromDb.MainImageUrl);
if (System.IO.File.Exists(Path.Combine(uploads, autoPart.Id + old_extension)))
{
System.IO.File.Delete(Path.Combine(uploads, autoPart.Id + old_extension));
}
using (var filestream = new FileStream(Path.Combine(uploads, autoPart.Id + new_extension), FileMode.Create))
{
files[0].CopyTo(filestream);
}
autoPart.MainImageUrl = @"\" + StaticDetails.ImageFolder + @"\" + autoPart.Id + new_extension;
}
if (autoPart.MainImageUrl != null)
{
serviceFromDb.MainImageUrl = autoPart.MainImageUrl;
}
serviceFromDb.Name = autoPart.Name;
serviceFromDb.ListPrice = autoPart.ListPrice;
serviceFromDb.Price = autoPart.Price;
serviceFromDb.Price50 = autoPart.Price50;
serviceFromDb.Price100 = autoPart.Price100;
serviceFromDb.Description = autoPart.Description;
serviceFromDb.SellerComments = autoPart.SellerComments;
serviceFromDb.MainImageUrl = autoPart.MainImageUrl;
serviceFromDb.UpdatedOn = DateTime.UtcNow;
serviceFromDb.CategoryId = autoPart.CategoryId;
serviceFromDb.SubCategoryId = autoPart.SubCategoryId;
serviceFromDb.ApplicationUserId = applicationUser.Id;
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(autoPart);
}
//[HttpPost]
//public async Task<IActionResult> Edit( AutoPart partModel)
//{
// //ViewBag.CategoryList = new SelectList(_db.Categories.ToList(), "Id", "Name");
// //ViewBag.SubCategoryList = new SelectList(_db.SubCategories.ToList(), "Id", "Name");
// //var applicationUser = await _userManager.GetUserAsync(User);
// //if (id != partModel.Id)
// //{
// // return NotFound();
// //}
// //if (ModelState.IsValid)
// //{
// // _db.Update(partModel);
// // await _db.SaveChangesAsync();
// // return RedirectToAction(nameof(GetPart), new { id = id });
// //}
// //return View(partModel);
// if (ModelState.IsValid)
// {
// string webRootPath = _webHostEnvironment.WebRootPath;
// var files = HttpContext.Request.Form.Files;
// if (files.Count > 0)
// {
// string fileName = Guid.NewGuid().ToString();
// var uploads = Path.Combine(webRootPath, @"parts\cover");
// var extenstion = Path.GetExtension(files[0].FileName);
// if (partModel.MainImageUrl != null)
// {
// //this is an edit and we need to remove old image
// var imagePath = Path.Combine(webRootPath, partModel.MainImageUrl.TrimStart('\\'));
// if (System.IO.File.Exists(imagePath))
// {
// System.IO.File.Delete(imagePath);
// }
// }
// using (var filesStreams = new FileStream(Path.Combine(uploads, fileName + extenstion), FileMode.Create))
// {
// files[0].CopyTo(filesStreams);
// }
// partModel.MainImageUrl = @"\parts\cover\" + fileName + extenstion;
// }
// else
// {
// //update when they do not change the image
// if (partModel.Id != 0)
// {
// AutoPart objFromDb = _db.AutoParts.Where(x => x.Id == partModel.Id).FirstOrDefault();
// partModel.MainImageUrl = objFromDb.MainImageUrl;
// }
// }
// if (partModel.Id == 0)
// {
// _db.AutoParts.Add(partModel);
// }
// else
// {
// _db.AutoParts.Update(partModel);
// }
// _db.SaveChanges();
// return RedirectToAction(nameof(Index));
// }
// else
// {
// ViewBag.CategoryList = new SelectList(_db.Categories.ToList(), "Id", "Name");
// ViewBag.SubCategoryList = new SelectList(_db.SubCategories.ToList(), "Id", "Name");
// if (partModel.Id != 0)
// {
// partModel = _db.AutoParts.Where(x => x.Id == partModel.Id).FirstOrDefault();
// }
// }
// return View(partModel);
//}
public IActionResult AddNewPart(bool isSuccess = false, int partId = 0)
{
ViewBag.CategoryList = new SelectList(_db.Categories.ToList(), "Id", "Name");
ViewBag.SubCategoryList = new SelectList(_db.SubCategories.ToList(), "Id", "Name");
AutoPartViewModel autoPartViewModel = new AutoPartViewModel();
var model = autoPartViewModel;
ViewBag.IsSuccess = isSuccess;
ViewBag.PartId = partId;
return View(model);
}
[HttpPost]
public async Task<IActionResult> AddNewPart(AutoPartViewModel partModel)
{
ViewBag.CategoryList = new SelectList(_db.Categories.ToList(), "Id", "Name");
ViewBag.SubCategoryList = new SelectList(_db.SubCategories.ToList(), "Id", "Name");
var applicationUser = await _userManager.GetUserAsync(User);
partModel.autoPart.Status = false;
if (ModelState.IsValid)
{
//if (partModel.CoverPhoto != null)
//{
// string folder = "parts/cover/";
// //partModel.CoverImageUrl = await UploadImage(partModel, partModel.CoverPhoto);
//}
if (partModel.GalleryFiles != null)
{
string folder = "parts/gallery/";
partModel.Gallery = new List<GalleryModel>();
foreach (var file in partModel.GalleryFiles)
{
var gallery = new GalleryModel()
{
Name = file.FileName,
URL = await UploadImageGallery(folder, file)
};
partModel.Gallery.Add(gallery);
}
}
// var newPart = new AutoPart()
// {
// Name = partModel.autoPart.Name,
// ListPrice = partModel.autoPart.ListPrice,
// Price = partModel.autoPart.Price,
// Price50 = partModel.autoPart.Price50,
// Price100 = partModel.autoPart.Price100,
// Description = partModel.autoPart.Description,
// SellerComments = partModel.autoPart.SellerComments,
// // MainImageUrl = partModel.CoverImageUrl,
// CreatedOn = DateTime.UtcNow,
// CategoryId = partModel.autoPart.CategoryId,
// SubCategoryId = partModel.autoPart.SubCategoryId,
// ApplicationUserId = applicationUser.Id
//};
partModel.autoPart.CreatedOn = DateTime.Now;
partModel.autoPart.ApplicationUserId = applicationUser.Id;
partModel.autoPart.PartGalleries = new List<PartGallery>();
foreach (var file in partModel.Gallery)
{
partModel.autoPart.PartGalleries.Add(new PartGallery()
{
Name = file.Name,
URL = file.URL
});
}
await _db.AutoParts.AddAsync(partModel.autoPart);
await _db.SaveChangesAsync();
string webRootPath = _webHostEnvironment.WebRootPath;
var files = HttpContext.Request.Form.Files;
var serviceFromDb = _db.AutoParts.Find(partModel.autoPart.Id);
if (files.Count != 0)
{
//Image has been uploaded
var uploads = Path.Combine(webRootPath, StaticDetails.partsimage);
var extension = Path.GetExtension(files[0].FileName);
using (var filestream = new FileStream(Path.Combine(uploads, partModel.autoPart.Id + extension), FileMode.Create))
{
files[0].CopyTo(filestream);
}
serviceFromDb.MainImageUrl = @"\" + StaticDetails.partsimage + @"\" + partModel.autoPart.Id + extension;
}
else
{
//when user does not upload image
var uploads = Path.Combine(webRootPath, StaticDetails.partsimage + @"\" + StaticDetails.DefaultProductImage);
System.IO.File.Copy(uploads, webRootPath + @"\" + StaticDetails.partsimage + @"\" + partModel.autoPart.Id + ".png");
serviceFromDb.MainImageUrl = @"\" + StaticDetails.partsimage + @"\" + partModel.autoPart.Id + ".png";
}
await _db.SaveChangesAsync();
int id = partModel.autoPart.Id;
if (id > 0)
{
return RedirectToAction(nameof(AddNewPart), new { isSuccess = true, bookId = id });
}
}
return View(partModel);
}
public async Task<ViewResult> GetPart(int id)
{
var data = await _db.AutoParts.Include(x => x.Category).Include(x => x.SubCategory).Include(x => x.PartGalleries)
.Where(x => x.Id == id).FirstOrDefaultAsync();
var autopartViewModel = new AutoPartViewModel()
{
autoPart = data,
CoverImageUrl = data.MainImageUrl,
Gallery = data.PartGalleries .Select(g => new GalleryModel()
{
Id = g.Id,
Name = g.Name,
URL = g.URL
}).ToList(),
};
return View(autopartViewModel);
}
//private async Task<string> UploadImage(string folderPath, IFormFile file)
//{
// folderPath += Guid.NewGuid().ToString() + "_" + file.FileName;
// string serverFolder = Path.Combine(_webHostEnvironment.WebRootPath, folderPath );
// await file.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
// return "/" + folderPath;
//}
private async Task<string> UploadImage(string folderPath, IFormFile file)
{
folderPath += Guid.NewGuid().ToString() + "_" + file.FileName;
string serverFolder = Path.Combine(_webHostEnvironment.WebRootPath, folderPath);
await file.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
return "/" + folderPath;
}
private async Task<string> UploadImageGallery(string folderPath, IFormFile file)
{
// folderPath += Guid.NewGuid().ToString() + "_" + file.FileName;
folderPath += file.FileName;
string serverFolder = Path.Combine(_webHostEnvironment.WebRootPath, folderPath);
await file.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
return "/" + folderPath;
}
[HttpGet]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var model = new AutoPart();
ViewBag.CategoryList = new SelectList(_db.Categories.ToList(), "Id", "Name");
ViewBag.SubCategoryList = new SelectList(_db.SubCategories.ToList(), "Id", "Name");
model = await _db.AutoParts.Include(x => x.PartGalleries).SingleOrDefaultAsync(m => m.Id == id);
if (model == null)
{
return NotFound();
}
return View(model);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
string webRootPath = _webHostEnvironment.WebRootPath;
AutoPart autoPart = await _db.AutoParts.FindAsync(id);
if (autoPart == null)
{
return NotFound();
}
else
{
var uploads = Path.Combine(webRootPath, StaticDetails.partsimage);
var extension = Path.GetExtension(autoPart.MainImageUrl);
if (System.IO.File.Exists(Path.Combine(uploads, autoPart.Id + extension)))
{
System.IO.File.Delete(Path.Combine(uploads, autoPart.Id + extension));
}
_db.AutoParts.Remove(autoPart);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}
}
<file_sep>/AutomotiveSols/OrderService.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace AutomotiveSols.ServicesReport
{
public class OrderServiceFromDB
{
string constr = "Data Source=(localdb)\\mssqllocaldb;Database=aspnet-AutomotiveSols-103ECA17-1716-4B1D-9297-9171642A1348;Trusted_Connection=True;MultipleActiveResultSets=true";
public DataTable GetOrders()
{
var dt = new DataTable();
using(SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("SPGetOrders", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
}
return dt;
}
}
}
<file_sep>/AutomotiveSols.BLL/Models/Car.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.Models
{
public class Car
{
public int Id { get; set; }
public int Price { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
public string MainImage { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public int TransmissionId { get; set; }
//[ForeignKey("CategoryId")]
public Transmission Transmission { get; set; }
public int BranId { get; set; }
public Brand Brand { get; set; }
public int MileageId { get; set; }
public Mileage Mileage { get; set; }
public int ModelId { get; set; }
public Model Model { get; set; }
public int RegistrationCityId { get; set; }
public RegistrationCity RegistrationCity { get; set; }
public bool Status { get; set; }
public int TrimId { get; set; }
public Trim Trim { get; set; }
public bool? isVerified { get; set; }
public bool? isFeatured { get; set; }
public int YearId { get; set; }
public Year Year { get; set; }
public int? ShowroomId { get; set; }
public Showroom Showroom { get; set; }
public IList<CarFeature> GetCarFeatures { get; set; }
public List<CarGallery> CarGalleries { get; set; }
public List<CarAppointment> CarAppointments { get; set; }
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210925174254_ondelecasonorderdetail2.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class ondelecasonorderdetail2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_OrderHeaders_AspNetUsers_ApplicationUserId",
table: "OrderHeaders");
migrationBuilder.AddForeignKey(
name: "FK_OrderHeaders_AspNetUsers_ApplicationUserId",
table: "OrderHeaders",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_OrderHeaders_AspNetUsers_ApplicationUserId",
table: "OrderHeaders");
migrationBuilder.AddForeignKey(
name: "FK_OrderHeaders_AspNetUsers_ApplicationUserId",
table: "OrderHeaders",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}
<file_sep>/AutomotiveSols/EmailServices/MessageService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
namespace AutomotiveSols.EmailServices
{
public class AuthMessageSender : IEmailSender
{
public async Task SendEmailAsync(string email, string subject, string message)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("<EMAIL>");
//From Address
string FromAddress = "<EMAIL>";
string FromAddressPassword = "<PASSWORD>";
string FromAdressTitle = "Confirm Your Account";
mail.To.Add(email);
mail.Subject = "Microsoft ASP.NET Core";
mail.IsBodyHtml = true;
mail.Body = message;
using (SmtpClient client = new SmtpClient("smtp.gmail.com",587))
{
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(FromAddress, FromAddressPassword);
client.EnableSsl = true;
client.Send(mail);
}
////To Address
//string ToAddress = email;
//string ToAdressTitle = "Microsoft ASP.NET Core";
//string Subject = subject;
//string BodyContent = message;
////Smtp Server
//string SmtpServer = "smtp.gmail.com ";
////Smtp Port Number
//int SmtpPortNumber = 587;
//var mimeMessage = new MimeMessage();
//mimeMessage.From.Add(new MailboxAddress
// (FromAdressTitle,
// FromAddress
// ));
//mimeMessage.To.Add(new MailboxAddress
// (ToAdressTitle,
// ToAddress
// ));
//mimeMessage.Subject = Subject; //Subject
//mimeMessage.Body = new TextPart("plain")
//{
// Text = BodyContent
//};
//using (var client = new SmtpClient())
//{
// client.Connect(SmtpServer, SmtpPortNumber, true);
// client.Authenticate(
// "<EMAIL>",
// "<PASSWORD>"
// );
// await client.SendAsync(mimeMessage);
// Console.WriteLine("The mail has been sent successfully !!");
// Console.ReadLine();
// await client.DisconnectAsync(true);
//}
}
catch (Exception ex)
{
throw ex;
}
}
}
}<file_sep>/AutomotiveSols/Source/DataSet2.cs
namespace AutomotiveSols.Source
{
}
namespace AutomotiveSols.Source
{
}<file_sep>/AutomotiveSols.BLL/ViewModels/FeatureAssignedToCar.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.ViewModels
{
public class FeatureAssignedToCar
{
public int FeatureId { get; set; }
public string FeatureName { get; set; }
public bool Assigned { get; set; }
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/PartGalleriesController.cs
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 AutomotiveSols.BLL.Models;
using AutomotiveSols.Data;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using AutomotiveSols.Static;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class PartGalleriesController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IWebHostEnvironment _webHostEnvironment;
public PartGalleriesController(ApplicationDbContext context,IWebHostEnvironment webHostEnvironment)
{
_context = context;
_webHostEnvironment = webHostEnvironment;
}
// GET: Admin/PartGalleries
public async Task<IActionResult> Index() {
//{
// PartGallery partGallery = new PartGallery();
// var displayImg = Path.Combine(_webHostEnvironment.WebRootPath, "parts/gallery");
// DirectoryInfo directoryInfo = new DirectoryInfo(displayImg);
// FileInfo[] fileInfos = directoryInfo.GetFiles();
// partGallery.
var applicationDbContext = _context.PartGalleries.Include(p => p.AutoPart);
return View(await applicationDbContext.ToListAsync());
}
// GET: Admin/PartGalleries/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var partGallery = await _context.PartGalleries
.Include(p => p.AutoPart)
.FirstOrDefaultAsync(m => m.Id == id);
if (partGallery == null)
{
return NotFound();
}
return View(partGallery);
}
// GET: Admin/PartGalleries/Create
public IActionResult Create()
{
ViewData["AutoPartId"] = new SelectList(_context.AutoParts, "Id", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,AutoPartId,Name,URL")] PartGallery partGallery)
{
if (ModelState.IsValid)
{
_context.Add(partGallery);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["AutoPartId"] = new SelectList(_context.AutoParts, "Id", "Name", partGallery.AutoPartId);
return View(partGallery);
}
// GET: Admin/PartGalleries/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var partGallery = await _context.PartGalleries.Include(x => x.AutoPart)
.Where(x => x.AutoPartId == id).ToListAsync();
if (partGallery == null)
{
return NotFound();
}
ViewData["AutoPartId"] = new SelectList(_context.AutoParts, "Id", "Name");
return View(partGallery);
}
// POST: Admin/PartGalleries/Edit/5
// To protect from overposting attacks, 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(int id, [Bind("Id,AutoPartId,Name,URL")] PartGallery partGallery)
{
if (id != partGallery.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(partGallery);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PartGalleryExists(partGallery.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["AutoPartId"] = new SelectList(_context.AutoParts, "Id", "Name", partGallery.AutoPartId);
return View(partGallery);
}
// GET: Admin/PartGalleries/Delete/5
//public async Task<IActionResult> Delete(int? id)
//{
// if (id == null)
// {
// return NotFound();
// }
// var partGallery = await _context.PartGalleries
// .Include(p => p.AutoPart)
// .FirstOrDefaultAsync(m => m.Id == id);
// if (partGallery == null)
// {
// return NotFound();
// }
// return View(partGallery);
//}
public IActionResult Delete(string imgdel)
{
string webRootPath = _webHostEnvironment.WebRootPath;
var partGallery = _context.PartGalleries
.Include(p => p.AutoPart)
.FirstOrDefault(m => m.Name == imgdel);
imgdel = Path.Combine(_webHostEnvironment.WebRootPath, "parts/gallery/", imgdel);
FileInfo fi = new FileInfo(imgdel);
if (fi != null)
{
System.IO.File.Delete(imgdel);
fi.Delete();
}
_context.PartGalleries.Remove(partGallery);
_context.SaveChanges();
return RedirectToAction("Index");
}
// POST: Admin/PartGalleries/Delete/5
//[HttpPost, ActionName("Delete")]
//[ValidateAntiForgeryToken]
//public async Task<IActionResult> DeleteConfirmed(int id)
//{
// var partGallery = await _context.PartGalleries.FindAsync(id);
// string webRootPath = _webHostEnvironment.WebRootPath;
// var imagePath = Path.Combine(webRootPath, partGallery.URL.TrimStart('\\'));
// if (System.IO.File.Exists(imagePath))
// {
// System.IO.File.Delete(imagePath);
// }
// _context.PartGalleries.Remove(partGallery);
// await _context.SaveChangesAsync();
// return RedirectToAction(nameof(Index));
// }
private bool PartGalleryExists(int id)
{
return _context.PartGalleries.Any(e => e.Id == id);
}
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210925175825_ondelecasonorderdetail4.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class ondelecasonorderdetail4 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_OrderDetails_AutoParts_AutoPartId",
table: "OrderDetails");
migrationBuilder.DropIndex(
name: "IX_OrderDetails_OrderId",
table: "OrderDetails");
migrationBuilder.CreateIndex(
name: "IX_OrderDetails_OrderId",
table: "OrderDetails",
column: "OrderId");
migrationBuilder.AddForeignKey(
name: "FK_OrderDetails_AutoParts_AutoPartId",
table: "OrderDetails",
column: "AutoPartId",
principalTable: "AutoParts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_OrderDetails_AutoParts_AutoPartId",
table: "OrderDetails");
migrationBuilder.DropIndex(
name: "IX_OrderDetails_OrderId",
table: "OrderDetails");
migrationBuilder.CreateIndex(
name: "IX_OrderDetails_OrderId",
table: "OrderDetails",
column: "OrderId",
unique: true);
migrationBuilder.AddForeignKey(
name: "FK_OrderDetails_AutoParts_AutoPartId",
table: "OrderDetails",
column: "AutoPartId",
principalTable: "AutoParts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210518134400_addservicetypetodb.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class addservicetypetodb : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_AspNetUsers_Organizations_OrganizationId",
table: "AspNetUsers");
migrationBuilder.DropTable(
name: "Organizations");
migrationBuilder.DropIndex(
name: "IX_AspNetUsers_OrganizationId",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "OrganizationId",
table: "AspNetUsers");
migrationBuilder.CreateTable(
name: "Car",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Price = table.Column<decimal>(nullable: false),
CreatedOn = table.Column<DateTime>(nullable: false),
UpdatedOn = table.Column<DateTime>(nullable: false),
MainImage = table.Column<string>(nullable: true),
ApplicationUserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Car", x => x.Id);
table.ForeignKey(
name: "FK_Car_AspNetUsers_ApplicationUserId",
column: x => x.ApplicationUserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "ServiceTypes",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ServiceTypes", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Car_ApplicationUserId",
table: "Car",
column: "ApplicationUserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Car");
migrationBuilder.DropTable(
name: "ServiceTypes");
migrationBuilder.AddColumn<int>(
name: "OrganizationId",
table: "AspNetUsers",
type: "int",
nullable: true);
migrationBuilder.CreateTable(
name: "Organizations",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
City = table.Column<string>(type: "nvarchar(max)", nullable: false),
IsAuthorizedCompany = table.Column<bool>(type: "bit", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
PhoneNumber = table.Column<string>(type: "nvarchar(max)", nullable: false),
PostalCode = table.Column<string>(type: "nvarchar(max)", nullable: false),
State = table.Column<string>(type: "nvarchar(max)", nullable: false),
StreetAddress = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Organizations", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetUsers_OrganizationId",
table: "AspNetUsers",
column: "OrganizationId");
migrationBuilder.AddForeignKey(
name: "FK_AspNetUsers_Organizations_OrganizationId",
table: "AspNetUsers",
column: "OrganizationId",
principalTable: "Organizations",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
<file_sep>/AutomotiveSols.BLL/ViewModels/IndexViewModel.cs
using AutomotiveSols.BLL.Models;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Web.Mvc;
namespace AutomotiveSols.BLL.ViewModels
{
public class IndexViewModel
{
[Display(Name = "Cars")]
public int TotalCars { get; set; }
[Display(Name = "Services")]
public int TotalServices { get; set; }
[Display(Name = "Spare Parts")]
public int TotalSpareParts { get; set; }
[Display(Name = "Application Users")]
public int TotalUsers { get; set; }
public IEnumerable<Category> CategoryList { get; set; }
public IEnumerable<Brand> Brands { get; set; }
public IEnumerable<AutoPart> AutoPartList { get; set; }
public IEnumerable<ServiceType> ServiceTypes { get; set; }
public IEnumerable<Services> Services { get; set; }
public IEnumerable<Car> Cars { get; set; }
/// <summary>
///
/// </summary>
public Car Car { get; set; }
public List<FeatureAssignedToCar> FeatureAssignedToCar { get; set; }
public IEnumerable<SelectListItem> BrandList { get; set; }
public IEnumerable<SelectListItem> ModelList { get; set; }
public IEnumerable<SelectListItem> MileageList { get; set; }
public IEnumerable<SelectListItem> RegistrationCityList { get; set; }
public IEnumerable<SelectListItem> TransmissionList { get; set; }
public IEnumerable<SelectListItem> TrimList { get; set; }
public IEnumerable<SelectListItem> YearList { get; set; }
public IFormFile CoverPhoto { get; set; }
public string CoverImageUrl { get; set; }
[Display(Name = "Choose the gallery images of your Spare-part")]
public IFormFileCollection GalleryFiles { get; set; }
public List<GalleryModel> Gallery { get; set; }
public DecisionVM DecisionVM { get; set; }
}
}
<file_sep>/AutomotiveSols.BLL/ViewModels/AppointmentDetailsVM.cs
using AutomotiveSols.BLL.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.ViewModels
{
public class AppointmentDetailsVM
{
public Appointments Appointments { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public List<Services> Services { get; set; }
public List<Car> Cars { get; set; }
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210912110826_CarsDBChanges.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class CarsDBChanges : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "TrimId",
table: "Years",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "ModelId",
table: "Trims",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "TransmissionId",
table: "Trims",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "YearId",
table: "Trims",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "TrimId",
table: "Transmissions",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "BrandId",
table: "Models",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateIndex(
name: "IX_Years_TrimId",
table: "Years",
column: "TrimId");
migrationBuilder.CreateIndex(
name: "IX_Trims_ModelId",
table: "Trims",
column: "ModelId");
migrationBuilder.CreateIndex(
name: "IX_Trims_TransmissionId",
table: "Trims",
column: "TransmissionId");
migrationBuilder.CreateIndex(
name: "IX_Trims_YearId",
table: "Trims",
column: "YearId");
migrationBuilder.CreateIndex(
name: "IX_Transmissions_TrimId",
table: "Transmissions",
column: "TrimId");
migrationBuilder.CreateIndex(
name: "IX_Models_BrandId",
table: "Models",
column: "BrandId");
migrationBuilder.AddForeignKey(
name: "FK_Models_Brands_BrandId",
table: "Models",
column: "BrandId",
principalTable: "Brands",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
migrationBuilder.AddForeignKey(
name: "FK_Transmissions_Trims_TrimId",
table: "Transmissions",
column: "TrimId",
principalTable: "Trims",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
migrationBuilder.AddForeignKey(
name: "FK_Trims_Models_ModelId",
table: "Trims",
column: "ModelId",
principalTable: "Models",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
migrationBuilder.AddForeignKey(
name: "FK_Trims_Transmissions_TransmissionId",
table: "Trims",
column: "TransmissionId",
principalTable: "Transmissions",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
migrationBuilder.AddForeignKey(
name: "FK_Trims_Years_YearId",
table: "Trims",
column: "YearId",
principalTable: "Years",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
migrationBuilder.AddForeignKey(
name: "FK_Years_Trims_TrimId",
table: "Years",
column: "TrimId",
principalTable: "Trims",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Models_Brands_BrandId",
table: "Models");
migrationBuilder.DropForeignKey(
name: "FK_Transmissions_Trims_TrimId",
table: "Transmissions");
migrationBuilder.DropForeignKey(
name: "FK_Trims_Models_ModelId",
table: "Trims");
migrationBuilder.DropForeignKey(
name: "FK_Trims_Transmissions_TransmissionId",
table: "Trims");
migrationBuilder.DropForeignKey(
name: "FK_Trims_Years_YearId",
table: "Trims");
migrationBuilder.DropForeignKey(
name: "FK_Years_Trims_TrimId",
table: "Years");
migrationBuilder.DropIndex(
name: "IX_Years_TrimId",
table: "Years");
migrationBuilder.DropIndex(
name: "IX_Trims_ModelId",
table: "Trims");
migrationBuilder.DropIndex(
name: "IX_Trims_TransmissionId",
table: "Trims");
migrationBuilder.DropIndex(
name: "IX_Trims_YearId",
table: "Trims");
migrationBuilder.DropIndex(
name: "IX_Transmissions_TrimId",
table: "Transmissions");
migrationBuilder.DropIndex(
name: "IX_Models_BrandId",
table: "Models");
migrationBuilder.DropColumn(
name: "TrimId",
table: "Years");
migrationBuilder.DropColumn(
name: "ModelId",
table: "Trims");
migrationBuilder.DropColumn(
name: "TransmissionId",
table: "Trims");
migrationBuilder.DropColumn(
name: "YearId",
table: "Trims");
migrationBuilder.DropColumn(
name: "TrimId",
table: "Transmissions");
migrationBuilder.DropColumn(
name: "BrandId",
table: "Models");
}
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210926110308_pricedatatypechange.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class pricedatatypechange : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "Price",
table: "Services",
nullable: false,
oldClrType: typeof(decimal),
oldType: "decimal(18,2)");
migrationBuilder.AlterColumn<int>(
name: "Price",
table: "Cars",
nullable: false,
oldClrType: typeof(decimal),
oldType: "decimal(18,2)");
migrationBuilder.AlterColumn<int>(
name: "Price50",
table: "AutoParts",
nullable: true,
oldClrType: typeof(double),
oldType: "float");
migrationBuilder.AlterColumn<int>(
name: "Price100",
table: "AutoParts",
nullable: true,
oldClrType: typeof(double),
oldType: "float");
migrationBuilder.AlterColumn<int>(
name: "Price",
table: "AutoParts",
nullable: false,
oldClrType: typeof(double),
oldType: "float");
migrationBuilder.AlterColumn<int>(
name: "ListPrice",
table: "AutoParts",
nullable: true,
oldClrType: typeof(double),
oldType: "float");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<decimal>(
name: "Price",
table: "Services",
type: "decimal(18,2)",
nullable: false,
oldClrType: typeof(int));
migrationBuilder.AlterColumn<decimal>(
name: "Price",
table: "Cars",
type: "decimal(18,2)",
nullable: false,
oldClrType: typeof(int));
migrationBuilder.AlterColumn<double>(
name: "Price50",
table: "AutoParts",
type: "float",
nullable: false,
oldClrType: typeof(int));
migrationBuilder.AlterColumn<double>(
name: "Price100",
table: "AutoParts",
type: "float",
nullable: false,
oldClrType: typeof(int));
migrationBuilder.AlterColumn<double>(
name: "Price",
table: "AutoParts",
type: "float",
nullable: false,
oldClrType: typeof(int));
migrationBuilder.AlterColumn<double>(
name: "ListPrice",
table: "AutoParts",
type: "float",
nullable: false,
oldClrType: typeof(int));
}
}
}
<file_sep>/AutomotiveSols.BLL/ViewModels/CarAppointmentVM.cs
using AutomotiveSols.BLL.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.ViewModels
{
public class CarAppointmentVM
{
public List<Car> Cars { get; set; }
public Appointments Appointments { get; set; }
}
}
<file_sep>/AutomotiveSols.DAL/Data/ApplicationDbContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutomotiveSols.BLL.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace AutomotiveSols.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Category> Categories { get; set; }
public DbSet<SubCategory> SubCategories { get; set; }
public DbSet<AutoPart> AutoParts { get; set; }
public DbSet<PartGallery> PartGalleries { get; set; }
public DbSet<ApplicationUser > ApplicationUsers { get; set; }
// public DbSet<Organization> Organizations { get; set; }
public DbSet<ShoppingCart> ShoppingCarts { get; set; }
public DbSet<OrderHeader> OrderHeaders { get; set; }
public DbSet<Coupon> Coupons { get; set; }
public DbSet<OrderDetails> OrderDetails { get; set; }
public DbSet<ServiceType> ServiceTypes { get; set; }
public DbSet<Services> Services { get; set; }
public DbSet<Appointments> Appointments { get; set; }
public DbSet<Transmission> Transmissions { get; set; }
public DbSet<Brand> Brands { get; set; }
public DbSet<Trim> Trims { get; set; }
public DbSet<Year> Years { get; set; }
public DbSet<RegistrationCity> RegistrationCities { get; set; }
public DbSet<Model> Models { get; set; }
public DbSet<Mileage> Mileages { get; set; }
public DbSet<Features> Features { get; set; }
public DbSet<Car> Cars { get; set; }
public DbSet<Showroom> Showrooms { get; set; }
public DbSet<CarAppointment> CarAppointments { get; set; }
public DbSet<CarFeature> CarFeatures { get; set; }
public DbSet<ServicesAppointment> ServicesAppointments { get; set; }
public DbSet<QR> QRs { get; set; }
public DbSet<Payment> Payments { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
foreach (var foreignKey in builder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
foreignKey.DeleteBehavior = DeleteBehavior.Restrict;
}
builder.Entity<Category>().HasKey(a => a.Id);
builder.Entity<Category>().Property(a => a.Name).IsRequired();
builder.Entity<Category>().Property(a => a.DisplayOrder).IsRequired();
builder.Entity<SubCategory>().HasKey(k => k.Id);
builder.Entity<SubCategory>().Property(k => k.Name).IsRequired();
builder.Entity<SubCategory>().HasOne(k => k.Category)
.WithMany(k => k.SubCategories).HasForeignKey(k => k.CategoryId);
builder.Entity<Transmission>().HasKey(k => k.Id);
builder.Entity<Transmission>().Property(k => k.Name).IsRequired();
//builder.Entity<Transmission>().HasOne(k => k.Trim)
// .WithMany(k => k.Transmissions).HasForeignKey(k => k.TrimId);
builder.Entity<Trim>().HasKey(k => k.Id);
builder.Entity<Trim>().Property(k => k.Name).IsRequired();
builder.Entity<Trim>().HasOne(k => k.Model)
.WithMany(k => k.Trims).HasForeignKey(k => k.ModelId);
builder.Entity<Year>().HasKey(k => k.Id);
builder.Entity<Year>().Property(k => k.SolarYear).IsRequired();
//builder.Entity<Year>().HasOne(k => k.Trim)
// .WithMany(k => k.Years).HasForeignKey(k => k.TrimId);
builder.Entity<RegistrationCity>().HasKey(k => k.Id);
builder.Entity<RegistrationCity>().Property(k => k.Name).IsRequired();
builder.Entity<Model>().HasKey(k => k.Id);
builder.Entity<Model>().Property(k => k.Name).IsRequired();
builder.Entity<Model>().HasOne(k => k.Brand)
.WithMany(k => k.Models).HasForeignKey(k => k.BrandId);
builder.Entity<Mileage>().HasKey(k => k.Id);
builder.Entity<Mileage>().Property(k => k.NumberKm).IsRequired();
builder.Entity<Brand>().HasKey(k => k.Id);
builder.Entity<Brand>().Property(k => k.Name).IsRequired();
builder.Entity<Car>().HasKey(k => k.Id);
builder.Entity<Car>().Property(k => k.Price).IsRequired();
builder.Entity<Car>().Property(k => k.Price).IsRequired();
builder.Entity<Car>().Property(k => k.CreatedOn);
builder.Entity<Car>().Property(k => k.UpdatedOn);
builder.Entity<Car>().Property(k => k.Status);
builder.Entity<Car>().HasOne(k => k.ApplicationUser)
.WithMany(k => k.Cars).HasForeignKey(k => k.ApplicationUserId);
builder.Entity<Car>().HasOne(k => k.Transmission)
.WithMany(k => k.Cars).HasForeignKey(k => k.TransmissionId);
builder.Entity<Car>().HasOne(k => k.Trim)
.WithMany(k => k.Cars).HasForeignKey(k => k.TrimId);
builder.Entity<Car>().HasOne(k => k.Year)
.WithMany(k => k.Cars).HasForeignKey(k => k.YearId);
builder.Entity<Car>().HasOne(k => k.RegistrationCity)
.WithMany(k => k.Cars).HasForeignKey(k => k.RegistrationCityId);
builder.Entity<Car>().HasOne(k => k.Model)
.WithMany(k => k.Cars).HasForeignKey(k => k.ModelId);
builder.Entity<Car>().HasOne(k => k.Mileage)
.WithMany(k => k.Cars).HasForeignKey(k => k.MileageId);
builder.Entity<Car>().HasOne(k => k.Brand)
.WithMany(k => k.Cars).HasForeignKey(k => k.BranId);
builder.Entity<Car>().HasOne(k => k.Showroom)
.WithMany(k => k.Cars).HasForeignKey(k => k.ShowroomId);
builder.Entity<Features>().HasKey(k => k.Id);
builder.Entity<Features>().Property(k => k.Name).IsRequired();
builder.Entity<Features>().Property(k => k.Description);
builder.Entity<CarFeature>().HasKey(k => new { k.FeatureId, CarId = k.Id });
builder.Entity<CarFeature>().HasOne(k => k.Car)
.WithMany(k => k.GetCarFeatures).HasForeignKey(k => k.Id);
builder.Entity<CarFeature>().HasOne(k => k.Features)
.WithMany(k => k.GetCarFeatures).HasForeignKey(k => k.FeatureId);
builder.Entity<CarAppointment>().HasKey(k => k.Id);
builder.Entity<CarAppointment>().HasOne(k => k.Appointments)
.WithMany(k => k.CarAppointments).HasForeignKey(k => k.AppointmentId);
builder.Entity<CarAppointment>().HasOne(k => k.Car)
.WithMany(k => k.CarAppointments).HasForeignKey(k => k.CarId);
builder.Entity<Appointments>().HasKey(a => a.Id);
builder.Entity<Appointments>().Property(k => k.AppointmentDate).IsRequired();
builder.Entity<Appointments>().Property(k => k.CustomerEmail).IsRequired();
builder.Entity<Appointments>().Property(k => k.CustomerName).IsRequired();
builder.Entity<Appointments>().Property(k => k.CustomerPhoneNumber).IsRequired();
builder.Entity<Appointments>().Property(k => k.isConfirmed);
builder.Entity<Appointments>().Property(k => k.isService);
builder.Entity<Appointments>().Property(k => k.isCar);
builder.Entity<Appointments>().HasOne(k => k.SalesPerson)
.WithMany(k => k.Appointments).HasForeignKey(k => k.SalesPersonId);
builder.Entity<ServicesAppointment>().HasKey(k => k.Id);
builder.Entity<ServicesAppointment>().HasOne(k => k.Appointments)
.WithMany(k => k.ServicesAppointments).HasForeignKey(k => k.AppointmentId);
builder.Entity<ServicesAppointment>().HasOne(k => k.Service)
.WithMany(k => k.ServicesAppointments).HasForeignKey(k => k.ServiceId);
builder.Entity<ServiceType>().HasKey(k => k.Id);
builder.Entity<ServiceType>().Property(k => k.Name).IsRequired();
builder.Entity<Services>().HasKey(k => k.Id);
builder.Entity<Services>().Property(k => k.Name).IsRequired().HasMaxLength(100);
builder.Entity<Services>().Property(k => k.Price).IsRequired();
builder.Entity<Services>().Property(k => k.ImageUrl);
builder.Entity<Services>().Property(k => k.SellerComments).IsRequired().HasMaxLength(300);
builder.Entity<Services>().Property(k => k.Description).IsRequired().HasMaxLength(300);
builder.Entity<Services>().Property(k => k.Status);
builder.Entity<Services>().HasOne(k => k.ServiceType)
.WithMany(k => k.Services).HasForeignKey(k => k.ServiceTypeId);
builder.Entity<Services>().HasOne(k => k.ApplicationUser)
.WithMany(k => k.Services).HasForeignKey(l => l.ApplicationUserId);
builder.Entity<AutoPart>().HasKey(k => k.Id);
builder.Entity<AutoPart>().Property(k => k.Name).IsRequired();
builder.Entity<AutoPart>().Property(k => k.ListPrice);
builder.Entity<AutoPart>().Property(k => k.Price);
builder.Entity<AutoPart>().Property(k => k.Price50);
builder.Entity<AutoPart>().Property(k => k.Price100);
builder.Entity<AutoPart>().Property(k => k.Description).IsRequired().HasMaxLength(300);
builder.Entity<AutoPart>().Property(k => k.SellerComments).IsRequired().HasMaxLength(200);
builder.Entity<AutoPart>().Property(k => k.MainImageUrl);
builder.Entity<AutoPart>().Property(k => k.CreatedOn);
builder.Entity<AutoPart>().Property(k => k.UpdatedOn);
builder.Entity<AutoPart>().Property(k => k.Status);
builder.Entity<AutoPart>().HasOne(k => k.Category).WithMany(k => k.AutoParts).HasForeignKey(m => m.CategoryId);
builder.Entity<AutoPart>().HasOne(k => k.SubCategory).WithMany(k => k.AutoParts).HasForeignKey(m => m.SubCategoryId);
builder.Entity<AutoPart>().HasOne(m => m.ApplicationUser).WithMany(m => m.AutoParts).HasForeignKey(m => m.ApplicationUserId);
builder.Entity<PartGallery>().HasKey(s => s.Id);
builder.Entity<PartGallery>().Property(s => s.Name);
builder.Entity<PartGallery>().Property(s => s.URL);
builder.Entity<PartGallery>().HasOne(k => k.AutoPart).WithMany(k => k.PartGalleries).HasForeignKey(s => s.AutoPartId);
builder.Entity<CarGallery>().HasKey(s => s.Id);
builder.Entity<CarGallery>().Property(s => s.Name);
builder.Entity<CarGallery>().Property(s => s.URL);
builder.Entity<CarGallery>().HasOne(k => k.Car).WithMany(k => k.CarGalleries).HasForeignKey(s => s.CarId);
//builder.Entity<Organization>().HasKey(m => m.Id);
//builder.Entity<Organization>().Property(m => m.Name).IsRequired();
//builder.Entity<Organization>().Property(m => m.StreetAddress).IsRequired();
//builder.Entity<Organization>().Property(m => m.PhoneNumber).IsRequired();
//builder.Entity<Organization>().Property(m => m.PostalCode).IsRequired();
//builder.Entity<Organization>().Property(m => m.State).IsRequired();
//builder.Entity<Organization>().Property(m => m.City).IsRequired();
//builder.Entity<Organization>().Property(m => m.IsAuthorizedCompany).IsRequired();
// builder.Entity<ShoppingCart>().HasKey(m => m.Id);
builder.Entity<ShoppingCart>().Property(m => m.Count);
//builder.Entity<OrderHeader>().HasKey(m => m.Id);
//builder.Entity<OrderHeader>().Property(g => g.OrderDate);
//builder.Entity<OrderHeader>().Property(g => g.ShippingDate);
//builder.Entity<OrderHeader>().Property(g => g.OrderTotalOriginal);
//builder.Entity<OrderHeader>().Property(g => g.OrderTotal);
//builder.Entity<OrderHeader>().Property(g => g.CouponCode);
//builder.Entity<OrderHeader>().Property(g => g.CouponCodeDiscount);
//builder.Entity<OrderHeader>().Property(g => g.TrackingNumber);
//builder.Entity<OrderHeader>().Property(g => g.Carrier);
//builder.Entity<OrderHeader>().Property(g => g.OrderStatus);
//builder.Entity<OrderHeader>().Property(g => g.PaymentStatus);
//builder.Entity<OrderHeader>().Property(g => g.PaymentDate);
//builder.Entity<OrderHeader>().Property(g => g.PaymentDueDate);
//builder.Entity<OrderHeader>().Property(g => g.TransactionId);
//builder.Entity<OrderHeader>().Property(g => g.PhoneNumber);
//builder.Entity<OrderHeader>().Property(g => g.CashonDelivery);
//builder.Entity<OrderHeader>().Property(g => g.StreetAddress);
//builder.Entity<OrderHeader>().Property(g => g.City);
//builder.Entity<OrderHeader>().Property(g => g.State);
//builder.Entity<OrderHeader>().Property(g => g.PostalCode);
//builder.Entity<OrderHeader>().Property(g => g.Name);
//builder.Entity<OrderHeader>().HasOne(m => m.ApplicationUser).WithMany(m => m.OrderHeaders)
// .HasForeignKey(m => m.ApplicationUserId).OnDelete(DeleteBehavior.Restrict);
//builder.Entity<OrderDetails>().HasKey(y => y.Id);
//builder.Entity<OrderDetails>().Property(y => y.Count);
//builder.Entity<OrderDetails>().Property(y => y.Price);
//builder.Entity<OrderDetails>().HasOne(y => y.OrderHeader)
// .WithOne(y => y.OrderDetails).HasForeignKey<OrderDetails>(y => y.OrderId).OnDelete(DeleteBehavior.Restrict);
//builder.Entity<OrderDetails>().HasOne(y => y.AutoPart).WithMany
// (y => y.OrderDetails).HasForeignKey(y => y.AutoPartId).OnDelete(DeleteBehavior.Cascade);
builder.Entity<Coupon>().HasKey(y => y.Id);
builder.Entity<Coupon>().Property(y => y.Name);
builder.Entity<Coupon>().Property(y => y.CouponType);
builder.Entity<Coupon>().Property(y => y.Discount);
builder.Entity<Coupon>().Property(y => y.MinimumAmount);
builder.Entity<Coupon>().Property(y => y.Picture);
builder.Entity<Coupon>().Property(y => y.IsActive);
builder.Entity<Showroom>().HasKey(y => y.Id);
builder.Entity<Showroom>().Property(y => y.Name);
builder.Entity<Showroom>().Property(y => y.StreetAddress);
builder.Entity<Showroom>().Property(y => y.City);
builder.Entity<Showroom>().Property(y => y.State);
builder.Entity<Showroom>().Property(y => y.PhoneNumber);
builder.Entity<Showroom>().Property(y => y.PostalCode);
builder.Entity<Showroom>().Property(y => y.IsAuthorizedCompany);
}
}
}
<file_sep>/AutomotiveSols.BLL/ViewModels/DecisionVM.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace AutomotiveSols.BLL.ViewModels
{
public class DecisionVM
{
[Display(Name = "Allow Us To Sale For You")]
public bool SaleOwn { get; set; }
[Display(Name = "I will Manage On My Own")]
public bool SaleUs { get; set; }
}
}
<file_sep>/AutomotiveSols.BLL/Models/CarAppointment.cs
namespace AutomotiveSols.BLL.Models
{
public class CarAppointment
{
public int Id { get; set; }
public int AppointmentId { get; set; }
public Appointments Appointments { get; set; }
public int CarId { get; set; }
public Car Car { get; set; }
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/CarController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.BLL.ViewModels;
using AutomotiveSols.Data;
using AutomotiveSols.EmailServices;
using AutomotiveSols.Static;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class CarController : Controller
{
private readonly ApplicationDbContext _db;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IEmailSender _emailSender;
public CarController(ApplicationDbContext db, IWebHostEnvironment webHostEnvironment,
UserManager<ApplicationUser> userManager,
IEmailSender emailSender)
{
_db = db;
_webHostEnvironment = webHostEnvironment;
_userManager = userManager;
_emailSender = emailSender;
}
public IActionResult Index()
{
return View(_db.Cars.Include(x=>x.Brand)
.Include(x=>x.Transmission)
.Include(x=>x.Trim)
.Include(x=>x.RegistrationCity)
.Include(x=>x.Year)
.Include(x=>x.Model)
.Include(x=>x.CarGalleries)
.Include(x=>x.GetCarFeatures).Include(x=>x.ApplicationUser)
.ToList());
}
public async Task<IActionResult> CarAd()
{
var applicationUser = await _userManager.GetUserAsync(User);
return View(_db.Cars.Include(x => x.Brand)
.Include(x => x.Transmission)
.Include(x => x.Trim)
.Include(x => x.RegistrationCity)
.Include(x => x.Year)
.Include(x => x.Model)
.Include(x => x.CarGalleries)
.Include(x => x.GetCarFeatures).Include(x => x.ApplicationUser).
Where(x=>x.ApplicationUserId==applicationUser.Id && x.Status == false).ToList());
}
[HttpGet]
public IActionResult AddNewCar(bool isSuccess = false, int carId = 0)
{
ViewBag.BrandList = new SelectList(_db.Brands.ToList(), "Id", "Name");
ViewBag.ModelList = new SelectList(_db.Models.ToList(), "Id", "Name");
ViewBag.MileageList = new SelectList(_db.Mileages.ToList(), "Id", "NumberKm");
ViewBag.RegistrationCityList = new SelectList(_db.RegistrationCities.ToList(), "Id", "Name");
ViewBag.TransmissionList = new SelectList(_db.Transmissions.ToList(), "Id", "Name");
ViewBag.TrimList = new SelectList(_db.Trims.ToList(), "Id", "Name");
ViewBag.YearList = new SelectList(_db.Years.ToList(), "Id", "SolarYear");
ViewBag.ShowroomList = new SelectList(_db.Showrooms.ToList(), "Id", "Name");
var features = _db.Features.ToList();
CarViewModel carViewModel = new CarViewModel()
{
FeatureAssignedToCar = features.Select(s => new FeatureAssignedToCar()
{
FeatureId = s.Id,
FeatureName = s.Name,
Assigned = false
}).ToList()
};
var model = carViewModel;
ViewBag.IsSuccess = isSuccess;
ViewBag.CarId = carId;
return View(model);
}
[HttpPost]
public async Task<IActionResult> AddNewCar(CarViewModel carModel)
{
ViewBag.BrandList = new SelectList(_db.Brands.ToList(), "Id", "Name");
ViewBag.ModelList = new SelectList(_db.Models.ToList(), "Id", "Name");
ViewBag.MileageList = new SelectList(_db.Mileages.ToList(), "Id", "NumberKm");
ViewBag.RegistrationCityList = new SelectList(_db.RegistrationCities.ToList(), "Id", "Name");
ViewBag.TransmissionList = new SelectList(_db.Transmissions.ToList(), "Id", "Name");
ViewBag.TrimList = new SelectList(_db.Trims.ToList(), "Id", "Name");
ViewBag.YearList = new SelectList(_db.Years.ToList(), "Id", "SolarYear");
ViewBag.ShowroomList = new SelectList(_db.Showrooms.ToList(), "Id", "Name");
var applicationUser = await _userManager.GetUserAsync(User);
//carModel.autoPart.Status = false;
if (ModelState.IsValid)
{
//if (partModel.CoverPhoto != null)
//{
// string folder = "parts/cover/";
// //partModel.CoverImageUrl = await UploadImage(partModel, partModel.CoverPhoto);
//}
if (carModel.GalleryFiles != null)
{
string folder = "cars/gallery/";
carModel.Gallery = new List<GalleryModel>();
foreach (var file in carModel.GalleryFiles)
{
var gallery = new GalleryModel()
{
Name = file.FileName,
URL = await UploadImageGallery(folder, file)
};
carModel.Gallery.Add(gallery);
}
}
carModel.Car.ApplicationUserId = applicationUser.Id;
//carModel.Car.ShowroomId =
carModel.Car.CarGalleries = new List<CarGallery>();
foreach (var file in carModel.Gallery)
{
carModel.Car.CarGalleries.Add(new CarGallery()
{
Name = file.Name,
URL = file.URL
});
}
await _db.Cars.AddAsync(carModel.Car);
await _db.SaveChangesAsync();
var carId = carModel.Car.Id;
var carFeatures = new List<CarFeature>();
if (carModel.FeatureAssignedToCar != null)
{
foreach (var data in carModel.FeatureAssignedToCar)
{
if (data.Assigned)
{
//courseAssignment.Add(new CourseAssignment(){CourseId = data.CourseId,InstructorId = instructorId});
_db.CarFeatures.Add(new CarFeature()
{ FeatureId = data.FeatureId, Id = carId });
}
}
}
string webRootPath = _webHostEnvironment.WebRootPath;
var files = HttpContext.Request.Form.Files;
var carFromDb = _db.Cars.Find(carModel.Car.Id);
if (files.Count != 0)
{
//Image has been uploaded
var uploads = Path.Combine(webRootPath, StaticDetails.carimage);
var extension = Path.GetExtension(files[0].FileName);
using (var filestream = new FileStream(Path.Combine(uploads, carModel.Car.Id + extension), FileMode.Create))
{
files[0].CopyTo(filestream);
}
carFromDb.MainImage = @"\" + StaticDetails.carimage + @"\" + carModel.Car.Id + extension;
}
else
{
//when user does not upload image
var uploads = Path.Combine(webRootPath, StaticDetails.carimage + @"\" + StaticDetails.DefaultProductImage);
System.IO.File.Copy(uploads, webRootPath + @"\" + StaticDetails.carimage + @"\" + carModel.Car.Id + ".png");
carFromDb.MainImage = @"\" + StaticDetails.carimage + @"\" + carModel.Car.Id + ".png";
}
await _db.SaveChangesAsync();
int id = carModel.Car.Id;
if (id > 0)
{
return RedirectToAction(nameof(AddNewCar), new { isSuccess = true, bookId = id });
}
}
return View(carModel);
}
[HttpGet]
public IActionResult Edit(int id)
{
var data = _db.Cars.Include(x => x.Brand)
.Include(x => x.Transmission)
.Include(x=>x.Showroom)
.Include(x => x.Trim)
.Include(x => x.RegistrationCity)
.Include(x => x.Year)
.Include(x => x.Model)
.Include(x => x.CarGalleries)
.Include(x => x.GetCarFeatures).FirstOrDefault(x=>x.Id==id);
//Car car = new Car()
//{
// Id = data.Id,
// Price = data.Price,
// MainImage = data.MainImage,
// BranId = data.BranId,
// ModelId= data.ModelId,
// MileageId = data.MileageId,
// RegistrationCityId = data.RegistrationCityId,
// TransmissionId = data.TransmissionId,
// TrimId = data.TrimId,
// YearId= data.YearId
//};
IEnumerable<Brand> brands = _db.Brands.ToList();
IEnumerable<Model> models = _db.Models.ToList();
IEnumerable<Mileage> mileage = _db.Mileages.ToList();
IEnumerable<RegistrationCity> registrationCities = _db.RegistrationCities.ToList();
IEnumerable<Transmission> transmissions = _db.Transmissions.ToList();
IEnumerable<Trim> trim = _db.Trims.ToList();
IEnumerable<Year> year = _db.Years.ToList();
IEnumerable<Showroom> showroom = _db.Showrooms.ToList();
var features = _db.Features.ToList();
var featureSelected = _db.CarFeatures.Include(x => x.Features).Where(x => x.Id == data.Id).ToList();
var model = new CarViewModel()
{
Car = data,
BrandList = brands.Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
}),
ShowroomList = showroom.Select(i=>new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
}),
ModelList = models.Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
}),
MileageList = mileage.Select(i => new SelectListItem
{
Text = i.NumberKm,
Value = i.Id.ToString()
}),
RegistrationCityList=registrationCities.Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
}),
TransmissionList = transmissions.Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
}),
TrimList = trim.Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
}),
YearList = year.Select(i => new SelectListItem
{
Text = i.SolarYear,
Value = i.Id.ToString()
}),
FeatureAssignedToCar = features.Select(s => new FeatureAssignedToCar()
{
FeatureId = s.Id,
FeatureName =s.Name,
Assigned =featureSelected.Exists(f=>f.Features.Id==s.Id)
}).OrderBy(x=>x.FeatureName).ToList()
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, CarViewModel carViewModel)
{
if (ModelState.IsValid)
{
string webRootPath = _webHostEnvironment.WebRootPath;
var files = HttpContext.Request.Form.Files;
var applicationUser = await _userManager.GetUserAsync(User);
var serviceFromDb = _db.Cars.Where(m => m.Id == carViewModel.Car.Id).FirstOrDefault();
ViewBag.ShowroomList = new SelectList(_db.Showrooms.ToList(), "Id", "Name");
if (files.Count > 0 && files[0] != null)
{
//if user uploads a new image
var uploads = Path.Combine(webRootPath, StaticDetails.carimage);
var new_extension = Path.GetExtension(files[0].FileName);
var old_extension = Path.GetExtension(serviceFromDb.MainImage);
if (System.IO.File.Exists(Path.Combine(uploads, carViewModel.Car.Id + old_extension)))
{
System.IO.File.Delete(Path.Combine(uploads, carViewModel.Car.Id + old_extension));
}
using (var filestream = new FileStream(Path.Combine(uploads, carViewModel.Car.Id + new_extension), FileMode.Create))
{
files[0].CopyTo(filestream);
}
carViewModel.Car.MainImage = @"\" + StaticDetails.carimage + @"\" + carViewModel.Car.Id + new_extension;
}
if (carViewModel.Car.MainImage != null)
{
serviceFromDb.MainImage = carViewModel.Car.MainImage;
}
serviceFromDb.Price = carViewModel.Car.Price;
serviceFromDb.MainImage = carViewModel.Car.MainImage;
serviceFromDb.UpdatedOn = DateTime.UtcNow;
serviceFromDb.BranId = carViewModel.Car.BranId;
serviceFromDb.ModelId = carViewModel.Car.ModelId;
serviceFromDb.MileageId = carViewModel.Car.MileageId;
serviceFromDb.TrimId = carViewModel.Car.TrimId;
serviceFromDb.ShowroomId = carViewModel.Car.ShowroomId;
serviceFromDb.TransmissionId = carViewModel.Car.TransmissionId;
serviceFromDb.RegistrationCityId = carViewModel.Car.RegistrationCityId;
serviceFromDb.YearId = carViewModel.Car.YearId;
serviceFromDb.ApplicationUserId = applicationUser.Id;
await _db.SaveChangesAsync();
var carId = carViewModel.Car.Id;
if (carViewModel.FeatureAssignedToCar != null)
{
foreach (var data in carViewModel.FeatureAssignedToCar)
{
if (data.Assigned)
{
var isExist = IsExist(_db.CarFeatures.ToList(), carId, data.FeatureId);
if (!isExist)
{
_db.CarFeatures.Add(new CarFeature()
{ FeatureId = data.FeatureId, Id = carId });
}
_db.SaveChanges();
}
else
{
var isExist = IsExist(_db.CarFeatures.ToList(), carId, data.FeatureId);
if (isExist)
{
var filter = GetByFiler(x => x.FeatureId == data.FeatureId && x.Id == carId)
.FirstOrDefault();
_db.CarFeatures.Remove(filter);
}
_db.SaveChanges();
}
}
return RedirectToAction(nameof(Index));
}
else
{
carViewModel.BrandList = _db.Brands.ToList().Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
});
carViewModel.ShowroomList = _db.Showrooms.ToList().Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
});
carViewModel.ModelList = _db.Models.ToList().Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
});
carViewModel.MileageList = _db.Mileages.ToList().Select(i => new SelectListItem
{
Text = i.NumberKm,
Value = i.Id.ToString()
});
carViewModel.RegistrationCityList = _db.RegistrationCities.ToList().Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
});
carViewModel.TransmissionList = _db.Transmissions.ToList().Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
});
carViewModel.TrimList = _db.Trims.ToList().Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
});
carViewModel.YearList = _db.Years.ToList().Select(i => new SelectListItem
{
Text = i.SolarYear,
Value = i.Id.ToString()
});
if (carViewModel.Car.Id != 0)
{
carViewModel.Car = _db.Cars.FirstOrDefault(x => x.Id == carViewModel.Car.Id);
}
}
}
return View(carViewModel);
}
public async Task<IActionResult> GetCar(int id)
{
var applicationUser = await _userManager.GetUserAsync(User);
return View(_db.Cars.Include(x => x.Brand)
.Include(x=>x.Showroom)
.Include(x => x.Transmission)
.Include(x => x.Trim)
.Include(x => x.RegistrationCity)
.Include(x => x.Year)
.Include(x => x.Model)
.Include(x => x.CarGalleries)
.Include(x => x.GetCarFeatures).Include(x => x.ApplicationUser).
Where(x => x.ApplicationUserId == applicationUser.Id && x.Id == id && x.Status ==false).FirstOrDefault());
}
public IActionResult DeleteStatus(int id)
{
Car car = _db.Cars.FirstOrDefault(x=>x.Id==id);
car.Status = true;
_db.Cars.Update(car);
_db.SaveChanges();
return View(RedirectToAction(nameof(GetCar)));
}
private bool IsExist(IEnumerable<CarFeature> source, int carId, int featureId)
{
return source.Where(x => x.Id == carId).Any(c => c.FeatureId == featureId);
}
public IEnumerable<CarFeature> GetByFiler(Func<CarFeature, bool> predicate)
{
return _db.Set<CarFeature>().Where(predicate).ToList();
}
[HttpGet]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var model = new Car();
model = await _db.Cars.Include(x => x.CarGalleries)
.Include(x=>x.ApplicationUser)
.Include(x=>x.Brand)
.Include(x=>x.Model)
.Include(x=>x.Mileage)
.Include(x=>x.RegistrationCity)
.Include(x=>x.Transmission)
.Include(x=>x.Trim).SingleOrDefaultAsync(m => m.Id == id);
if (model == null)
{
return NotFound();
}
return View(model);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
string webRootPath = _webHostEnvironment.WebRootPath;
Car car = await _db.Cars.FindAsync(id);
if (car == null)
{
return NotFound();
}
else
{
var uploads = Path.Combine(webRootPath, StaticDetails.carimage);
var extension = Path.GetExtension(car.MainImage);
if (System.IO.File.Exists(Path.Combine(uploads, car.Id + extension)))
{
System.IO.File.Delete(Path.Combine(uploads, car.Id + extension));
}
_db.Cars.Remove(car);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
private async Task<string> UploadImageGallery(string folderPath, IFormFile file)
{
// folderPath += Guid.NewGuid().ToString() + "_" + file.FileName;
folderPath += file.FileName;
string serverFolder = Path.Combine(_webHostEnvironment.WebRootPath, folderPath);
await file.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
return "/" + folderPath;
}
public IActionResult Request(bool isSuccess = false ,bool isReject = false)
{
var payments = _db.Payments.Include(x=>x.Car)
.Include(x=>x.ApplicationUser)
.ToList();
ViewBag.isSuccess = false;
ViewBag.isReject = false;
return View(payments);
}
public async Task<IActionResult> Approve(int id)
{
var applicationUser = await _userManager.GetUserAsync(User);
var payment = _db.Payments.Where(x => x.Id == id).FirstOrDefault();
payment.Status = true;
_db.Update(payment);
_db.SaveChanges();
string email = _db.ApplicationUsers.Where(x => x.Id == payment.ApplicationUserId).Select(x => x.Email).FirstOrDefault();
string name = _db.ApplicationUsers.Where(x => x.Id == payment.ApplicationUserId).Select(x => x.Name).FirstOrDefault();
await _emailSender.SendEmailAsync(email, "Your invoice is verified",
$"Mr/Miss '{name}'.Please your ad by clicking this link: <a href='https://localhost:44363/Customer/Home/UserAdFeature'>link</a>");
return RedirectToAction(nameof(Request), new
{
isSuccess = true , isRject = false
});
}
public async Task<IActionResult> Reject(int id)
{
var applicationUser = await _userManager.GetUserAsync(User);
var payment = _db.Payments.Where(x => x.Id == id).FirstOrDefault();
payment.Status = false;
_db.Update(payment);
_db.SaveChanges();
string email = _db.ApplicationUsers.Where(x => x.Id == payment.ApplicationUserId).Select(x => x.Email).FirstOrDefault();
string name = _db.ApplicationUsers.Where(x => x.Id == payment.ApplicationUserId).Select(x => x.Name).FirstOrDefault();
await _emailSender.SendEmailAsync(email, "Your invoice is verified",
$"Mr/Miss '{name}'. Please upload the valid payment invoice");
return RedirectToAction(nameof(Request), new
{
isSuccess = false,
isReject = true
});
}
}
}
<file_sep>/AutomotiveSols.BLL/ViewModels/QRVM.cs
using AutomotiveSols.BLL.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.ViewModels
{
public class QRVM
{
public QR QR { get; set; }
public Car Car { get; set; }
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/PaymentController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.Data;
using AutomotiveSols.EmailServices;
using AutomotiveSols.Static;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class PaymentController : Controller
{
private readonly IWebHostEnvironment _hostEnvironment;
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _db;
private readonly IEmailSender _emailSender;
public PaymentController(IWebHostEnvironment _hostEnvironment, UserManager<ApplicationUser> _userManager,
ApplicationDbContext _db,
IEmailSender emailSender)
{
this._hostEnvironment = _hostEnvironment;
this._userManager = _userManager;
this._db = _db;
_emailSender = emailSender;
}
public IActionResult Index()
{
var qrs = _db.Payments.ToList();
return View(qrs);
}
[HttpGet]
public IActionResult Create(bool isSuccess = false)
{
var model = new Payment();
ViewBag.IsSuccess = isSuccess;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Payment payment)
{
var applicationUser = await _userManager.GetUserAsync(User);
if (!ModelState.IsValid)
{
return View(payment);
}
else
{
payment.ApplicationUserId = applicationUser.Id;
_db.Payments.Add(payment);
await _db.SaveChangesAsync();
//Image being saved
string webRootPath = _hostEnvironment.WebRootPath;
var files = HttpContext.Request.Form.Files;
var qrFromDb = _db.Payments.Find(payment.Id);
if (files.Count != 0)
{
//Image has been uploaded
var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolderPayment);
var extension = Path.GetExtension(files[0].FileName);
using (var filestream = new FileStream(Path.Combine(uploads, payment.Id + extension), FileMode.Create))
{
files[0].CopyTo(filestream);
}
qrFromDb.PaymentImage = @"\" + StaticDetails.ImageFolderPayment + @"\" + payment.Id + extension;
await _emailSender.SendEmailAsync(applicationUser.Email, "Status: Pending",
$"Your request is forward to the team, Please wait we will let you through email.");
await _emailSender.SendEmailAsync("<EMAIL>", "Confirm the transaction",
$"Mr/Miss '{applicationUser.Name}' has uploaded the payment slip/invoice . Please review and verify.Please confirm your account by clicking this link: <a href='https://localhost:44363/Admin/Car/Requests'>link</a>");
}
else
{
//when user does not upload image
var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolderPayment + @"\" + StaticDetails.DefaultProductImage);
System.IO.File.Copy(uploads, webRootPath + @"\" + StaticDetails.ImageFolderPayment + @"\" + payment.Id + ".png");
qrFromDb.PaymentImage = @"\" + StaticDetails.ImageFolderPayment + @"\" + payment.Id + ".png";
}
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Create), new
{
IsSuccess = true
});
}
}
}
}<file_sep>/AutomotiveSols/Areas/Admin/Controllers/AccountController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.BLL.ViewModels;
using AutomotiveSols.EmailServices;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
using AutomotiveSols.Data;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> userManager;
private readonly SignInManager<ApplicationUser> signInManager;
private readonly RoleManager<IdentityRole> roleManager;
private readonly IEmailSender _emailSender;
private readonly ApplicationDbContext _db;
public AccountController(UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager, RoleManager<IdentityRole> roleManager,
IEmailSender emailSender,
ApplicationDbContext db)
{
this.userManager = userManager;
this.signInManager = signInManager;
this.roleManager = roleManager;
_emailSender = emailSender;
_db = db;
}
[HttpGet]
public IActionResult Register()
{
ViewBag.ShowroomList = new SelectList(_db.Showrooms.ToList(), "Id", "Name");
return View();
}
[HttpPost]
public async Task<IActionResult> Register(RegisterVM model)
{
ViewBag.ShowroomList = new SelectList(_db.Showrooms.ToList(), "Id", "Name");
if (ModelState.IsValid)
{
// Map data from RegisterViewModel to IdentityUser
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
Name = model.Name,
PhoneNumber = model.PhoneNumber,
StreetAddress = model.StreetAddress,
State = model.State,
PostalCode = model.PostalCode,
ShowroomId = model.ShowroomId
};
// Store the user in AspNetUsers database table
var result = await userManager.CreateAsync(user, model.Password);
Random r = new Random();
int num = r.Next();
// If user is successfully created, sign-in the user using
// SignInManager and redirect to index action of HomeController
if (result.Succeeded)
{
var code = await userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account",
new { userId = user.Id, token = code }, protocol: HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
$"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a> {num.ToString()}");
TempData["Message"] = "Confirmation Email has been send to your email. Please check email.";
TempData["MessageValue"] = "1";
if (signInManager.IsSignedIn(User) && User.IsInRole("Admin"))
{
return RedirectToAction("ListUsers", "Account");
}
ViewBag.ErrorTitle = "Registration successful";
ViewBag.ErrorMessage = "Before you can Login, please confirm your " +
"email, by clicking on the confirmation link we have emailed you";
return View("Error");
// await signInManager.SignInAsync(user, isPersistent: false);
//return RedirectToAction("index", "home","customer");
// return RedirectToAction("index", "home", new { area = "customer" });
}
// If there are any errors, add them to the ModelState object
// which will be displayed by the validation summary tag helper
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return View(model);
}
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string token)
{
if (userId == null || token == null)
{
return RedirectToAction("index", "home", new { area = "customer" });
}
var user = await userManager.FindByIdAsync(userId);
if (user == null)
{
ViewBag.ErrorMessage = $"The User ID {userId} is invalid";
return View("NotFound");
}
var result = await userManager.ConfirmEmailAsync(user, token);
if (result.Succeeded)
{
return View();
}
ViewBag.ErrorTitle = "Email cannot be confirmed";
return View("Error");
}
[HttpPost]
public async Task<IActionResult> Logout()
{
await signInManager.SignOutAsync();
return RedirectToAction("index", "home", new { area = "customer" });
}
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login(LoginVM model, string returnUrl)
{
//model.ExternalLogins =(await signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = await userManager.FindByEmailAsync(model.Email);
if (user != null && !user.EmailConfirmed &&
(await userManager.CheckPasswordAsync(user, model.Password)))
{
ModelState.AddModelError(string.Empty, "Email not confirmed yet");
return View(model);
}
var result = await signInManager.PasswordSignInAsync(
model.Email, model.Password, model.RememberMe, false);
if (result.Succeeded)
{
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("index", "home", new { area = "customer" });
}
}
ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
}
return View(model);
}
//Get method for the Create Role
[HttpGet]
public IActionResult CreateRole()
{
return View();
}
[HttpPost]
public async Task<IActionResult> CreateRole(CreateRoleVM model)
{
if (ModelState.IsValid)
{
// We just need to specify a unique role name to create a new role
IdentityRole identityRole = new IdentityRole
{
Name = model.RoleName
};
// Saves the role in the underlying AspNetRoles table
IdentityResult result = await roleManager.CreateAsync(identityRole);
if (result.Succeeded)
{
return RedirectToAction("ListRoles", "Account", new { area = "Admin" });
}
foreach (IdentityError error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
return View(model);
}
//Get The Roles Present In Database
[HttpGet]
public IActionResult ListRoles()
{
//Roles Property will have the Names of the Roles
var roles = roleManager.Roles;
return View(roles);
}
// Id is passed from the Url to the Action method to get the Role details
[HttpGet]
public async Task<IActionResult> EditRole(string id)
{
// Find the role by Role ID
var role = await roleManager.FindByIdAsync(id);
if (role == null)
{
ViewBag.ErrorMessage = $"Role with Id = {id} cannot be found";
return View("NotFound");
}
var model = new EditRoleVM
{
Id = role.Id,
RoleName = role.Name
};
// Retrieve all the Users
foreach (var user in userManager.Users)
{
// If the user is in this role, add the username to
// Users property of EditRoleViewModel. This model
// object is then passed to the view for display
if (await userManager.IsInRoleAsync(user, role.Name))
{
model.Users.Add(user.UserName);
}
}
return View(model);
}
// This action responds to HttpPost and receives EditRoleViewModel
[HttpPost]
public async Task<IActionResult> EditRole(EditRoleVM model)
{
var role = await roleManager.FindByIdAsync(model.Id);
if (role == null)
{
ViewBag.ErrorMessage = $"Role with Id = {model.Id} cannot be found";
return View("NotFound");
}
else
{
role.Name = model.RoleName;
// Update the Role using UpdateAsync
var result = await roleManager.UpdateAsync(role);
if (result.Succeeded)
{
return RedirectToAction("ListRoles");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
return View(model);
}
}
[HttpGet]
public async Task<IActionResult> EditUsersInRole(string roleId)
{
ViewBag.roleId = roleId;
//find the role by built in method , by passing the roleId
var role = await roleManager.FindByIdAsync(roleId);
if (role == null)//if the role not present display the error
{
ViewBag.ErrorMessage = $"Role with Id = {roleId} is not present";
return View("NotFound");
}
var model = new List<UserRoleVM>();
//retrive the users present in that role
foreach (var user in userManager.Users)
{
var userRoleViewModel = new UserRoleVM
{
UserId = user.Id,
UserName = user.UserName
};
//if the user is present then check the checkboxes
if (await userManager.IsInRoleAsync(user, role.Name))
{
userRoleViewModel.IsSelected = true;
}
else // otherwise not
{
userRoleViewModel.IsSelected = false;
}
model.Add(userRoleViewModel);
}
return View(model);
}
[HttpPost]
public async Task<IActionResult> EditUsersInRole(List<UserRoleVM> model, string roleId)
{
var role = await roleManager.FindByIdAsync(roleId); //find the role
if (role == null) // if not present then redirect back
{
ViewBag.ErrorMessage = $"Role with Id = {roleId} is not present";
return View("NotFound");
}
for (int i = 0; i < model.Count; i++)
{
var user = await userManager.FindByIdAsync(model[i].UserId);
IdentityResult result = null;
// if the checkbox is selected and the user does not have that role in db
if (model[i].IsSelected && !(await userManager.IsInRoleAsync(user, role.Name)))
{
// add the user
result = await userManager.AddToRoleAsync(user, role.Name);
}//if the checkbox is unchecked and the user has that role
else if (!model[i].IsSelected && await userManager.IsInRoleAsync(user, role.Name))
{
// delete the user from that role
result = await userManager.RemoveFromRoleAsync(user, role.Name);
}
else
{
continue;
}
if (result.Succeeded)
{
if (i < (model.Count - 1))
continue;
else
return RedirectToAction("EditRole", new { Id = roleId });
}
}
return RedirectToAction("EditRole", new { Id = roleId });
}
[HttpGet] // The Action method to get all the users
public IActionResult ListUsers()
{ //Users propertu Contains the users
var users = userManager.Users;
return View(users); //returns the users
}
[HttpGet]
public async Task<IActionResult> EditUser(string id)
{
ViewBag.ShowroomList = new SelectList(_db.Showrooms.ToList(), "Id", "Name");
var user = await userManager.FindByIdAsync(id);//find the user
if (user == null)
{
ViewBag.ErrorMessage = $"User with Id = {id} is not found";
return View("NotFound");
}
// GetClaimsAsync will retunrs all the list of user Claims
var userClaims = await userManager.GetClaimsAsync(user);
// GetRolesAsync will returns all the list of user Roles
var userRoles = await userManager.GetRolesAsync(user);
var model = new EditUserVM // populate the data
{
Id = user.Id,
Email = user.Email,
UserName = user.UserName,
City = user.City,
Claims = userClaims.Select(c => c.Value).ToList(),
Roles = userRoles
};
return View(model);
}
[HttpPost]
public async Task<IActionResult> EditUser(EditUserVM model)
{
ViewBag.ShowroomList = new SelectList(_db.Showrooms.ToList(), "Id", "Name");
var user = await userManager.FindByIdAsync(model.Id); //find the user
if (user == null) //if the user is not present then returns
{
ViewBag.ErrorMessage = $"User with Id = {model.Id} is not found";
return View("NotFound");
} //else map the properties
else
{
user.Email = model.Email;
user.UserName = model.UserName;
user.City = model.City;
var result = await userManager.UpdateAsync(user);
if (result.Succeeded) // if the model is updated the redirect
{
return RedirectToAction("ListUsers");
}
//else show the errors
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
return View(model);
}
}
[HttpPost]
public async Task<IActionResult> DeleteUser(string id)
{
var user = await userManager.FindByIdAsync(id);// find the user
if (user == null)// if not not found then return
{
ViewBag.ErrorMessage = $"User with Id = {id} is not found";
return View("NotFound");
}
else // if the user found
{
var result = await userManager.DeleteAsync(user); // del the user
if (result.Succeeded)
{
return RedirectToAction("ListUsers");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
return View("ListUsers");
}
}
[HttpPost]
public async Task<IActionResult> DeleteRole(string id)
{
var role = await roleManager.FindByIdAsync(id);
if (role == null)
{
ViewBag.ErrorMessage = $"Role with Id = {id} is not found";
return View("NotFound");
}
else
{
try
{
//throw new Exception("Test Exception");
var result = await roleManager.DeleteAsync(role);
if (result.Succeeded)
{
return RedirectToAction("ListRoles");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
return View("ListRoles");
}
// If the exception is DbUpdateException, we know we are not able to
// delete the role as there are users in the role being deleted
catch (DbUpdateException ex)
{
//Log the exception to a file. We discussed logging to a file
// using Nlog in Part 63 of ASP.NET Core tutorial
// logger.LogError($"Exception Occured : {ex}");
// Pass the ErrorTitle and ErrorMessage that you want to show to
// the user using ViewBag. The Error view retrieves this data
// from the ViewBag and displays to the user.
ViewBag.ErrorTitle = $"{role.Name} role is in use";
ViewBag.ErrorMessage = $"{role.Name} role cannot be deleted as there are users in this role. If you want to delete this role, please remove the users from the role and then try to delete";
return View("Error");
}
}
}
[HttpGet]
[AllowAnonymous]
public IActionResult AccessDenied()
{
return View();
}
}
}<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210628070848_CardelNoRestrict.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class CardelNoRestrict : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
<file_sep>/AutomotiveSols/Areas/Customer/Controllers/CartController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.BLL.ViewModels;
using AutomotiveSols.Data;
using AutomotiveSols.Static;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Stripe;
namespace AutomotiveSols.Areas.Customer.Controllers
{
[Area("Customer")]
public class CartController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _db;
[BindProperty]
public ShoppingCartVM ShoppingCartVM { get; set; }
public CartController(UserManager<ApplicationUser> userManager, ApplicationDbContext db)
{
_db = db;
_userManager = userManager;
}
public async Task<IActionResult> Index()
{
var applicationUser = await _userManager.GetUserAsync(User);
ShoppingCartVM = new ShoppingCartVM()
{
OrderHeader = new OrderHeader(),
ListCart = _db.ShoppingCarts.Include(x => x.AutoPart).Where(x => x.ApplicationUserId == applicationUser.Id).ToList()
};
ShoppingCartVM.OrderHeader.OrderTotal = 0;
ShoppingCartVM.OrderHeader.ApplicationUser = _db.ApplicationUsers.FirstOrDefault(x => x.Id == applicationUser.Id);
foreach (var list in ShoppingCartVM.ListCart)
{
list.Price = StaticDetails.GetPriceBasedOnQuantity(list.Count, list.AutoPart.Price,
list.AutoPart.Price50, list.AutoPart.Price100);
ShoppingCartVM.OrderHeader.OrderTotal += (list.Price * list.Count);
list.AutoPart.Description = StaticDetails.ConvertToRawHtml(list.AutoPart.Description);
if (list.AutoPart.Description.Length > 100)
{
list.AutoPart.Description = list.AutoPart.Description.Substring(0, 99) + "...";
}
}
ShoppingCartVM.OrderHeader.OrderTotalOriginal = ShoppingCartVM.OrderHeader.OrderTotal;
if (HttpContext.Session.GetString(StaticDetails.ssCouponCode) != null)
{
ShoppingCartVM.OrderHeader.CouponCode = HttpContext.Session.GetString(StaticDetails.ssCouponCode);
var couponFromDb = _db.Coupons.FirstOrDefault(c => c.Name.ToLower() == ShoppingCartVM.OrderHeader.CouponCode.ToLower());
ShoppingCartVM.OrderHeader.OrderTotal = StaticDetails.DiscountedPrice(couponFromDb, ShoppingCartVM.OrderHeader.OrderTotalOriginal);
}
return View(ShoppingCartVM);
}
public IActionResult AddCoupon()
{
if (ShoppingCartVM.OrderHeader.CouponCode == null)
{
ShoppingCartVM.OrderHeader.CouponCode = "";
}
HttpContext.Session.SetString(StaticDetails.ssCouponCode, ShoppingCartVM.OrderHeader.CouponCode);
return RedirectToAction(nameof(Index));
}
public IActionResult RemoveCoupon()
{
HttpContext.Session.SetString(StaticDetails.ssCouponCode, string.Empty);
return RedirectToAction(nameof(Index));
}
public IActionResult Plus(int cartId)
{
var cart = _db.ShoppingCarts.Include(x => x.AutoPart).FirstOrDefault
(c => c.Id == cartId);
cart.Count += 1;
cart.Price = StaticDetails.GetPriceBasedOnQuantity(cart.Count, cart.AutoPart.Price,
cart.AutoPart.Price50, cart.AutoPart.Price100);
_db.SaveChanges();
return RedirectToAction(nameof(Index));
}
public IActionResult Minus(int cartId)
{
var cart = _db.ShoppingCarts.Include(x => x.AutoPart).FirstOrDefault
(c => c.Id == cartId);
if (cart.Count == 1)
{
var cnt = _db.ShoppingCarts.Where(u => u.ApplicationUserId == cart.ApplicationUserId).ToList().Count;
_db.ShoppingCarts.Remove(cart);
_db.SaveChanges();
HttpContext.Session.SetInt32(StaticDetails.ssShoppingCart, cnt - 1);
}
else
{
cart.Count -= 1;
cart.Price = StaticDetails.GetPriceBasedOnQuantity(cart.Count, cart.AutoPart.Price,
cart.AutoPart.Price50, cart.AutoPart.Price100);
_db.SaveChanges();
}
return RedirectToAction(nameof(Index));
}
public IActionResult Remove(int cartId)
{
var cart = _db.ShoppingCarts.Include(x => x.AutoPart).FirstOrDefault
(c => c.Id == cartId);
var cnt = _db.ShoppingCarts.Where(u => u.ApplicationUserId == cart.ApplicationUserId).ToList().Count;
_db.ShoppingCarts.Remove(cart);
_db.SaveChanges();
HttpContext.Session.SetInt32(StaticDetails.ssShoppingCart, cnt - 1);
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Summary()
{
var applicationUser = await _userManager.GetUserAsync(User);
ShoppingCartVM = new ShoppingCartVM()
{
OrderHeader = new OrderHeader(),
ListCart = _db.ShoppingCarts.Include(x => x.AutoPart).Where(c => c.ApplicationUserId == applicationUser.Id)
};
ShoppingCartVM.OrderHeader.OrderTotal = 0;
ShoppingCartVM.OrderHeader.ApplicationUser = _db.ApplicationUsers
.FirstOrDefault(c => c.Id == applicationUser.Id);
foreach (var list in ShoppingCartVM.ListCart)
{
list.Price = StaticDetails.GetPriceBasedOnQuantity(list.Count, list.AutoPart.Price,
list.AutoPart.Price50, list.AutoPart.Price100);
ShoppingCartVM.OrderHeader.OrderTotal += (list.Price * list.Count);
}
ShoppingCartVM.OrderHeader.OrderTotalOriginal = ShoppingCartVM.OrderHeader.OrderTotal;
ShoppingCartVM.OrderHeader.Name = ShoppingCartVM.OrderHeader.ApplicationUser.Name;
ShoppingCartVM.OrderHeader.PhoneNumber = ShoppingCartVM.OrderHeader.ApplicationUser.PhoneNumber;
ShoppingCartVM.OrderHeader.StreetAddress = ShoppingCartVM.OrderHeader.ApplicationUser.StreetAddress;
ShoppingCartVM.OrderHeader.City = ShoppingCartVM.OrderHeader.ApplicationUser.City;
ShoppingCartVM.OrderHeader.State = ShoppingCartVM.OrderHeader.ApplicationUser.State;
ShoppingCartVM.OrderHeader.PostalCode = ShoppingCartVM.OrderHeader.ApplicationUser.PostalCode;
if (HttpContext.Session.GetString(StaticDetails.ssCouponCode) != null)
{
ShoppingCartVM.OrderHeader.CouponCode = HttpContext.Session.GetString(StaticDetails.ssCouponCode);
var couponFromDb = _db.Coupons.FirstOrDefault(c => c.Name.ToLower() == ShoppingCartVM.OrderHeader.CouponCode.ToLower());
ShoppingCartVM.OrderHeader.OrderTotal = StaticDetails.DiscountedPrice(couponFromDb, ShoppingCartVM.OrderHeader.OrderTotalOriginal);
}
return View(ShoppingCartVM);
}
[HttpPost]
[ActionName("Summary")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SummaryPost(string stripeToken)
{
var applicationUser = await _userManager.GetUserAsync(User);
ShoppingCartVM.OrderHeader.ApplicationUser = _db.ApplicationUsers
.FirstOrDefault(c => c.Id == applicationUser.Id);
ShoppingCartVM.ListCart = _db.ShoppingCarts.Include(x => x.AutoPart)
.Where(c => c.ApplicationUserId == applicationUser.Id).ToList();
ShoppingCartVM.OrderHeader.PaymentStatus = StaticDetails.PaymentStatusPending;
ShoppingCartVM.OrderHeader.OrderStatus = StaticDetails.StatusPending;
ShoppingCartVM.OrderHeader.ApplicationUserId = applicationUser.Id;
ShoppingCartVM.OrderHeader.OrderDate = DateTime.Now;
ShoppingCartVM.OrderHeader.ShippingDate = DateTime.Now.AddDays(7);
_db.OrderHeaders.Add(ShoppingCartVM.OrderHeader);
_db.SaveChanges();
ShoppingCartVM.OrderHeader.OrderTotalOriginal = 0;
foreach (var item in ShoppingCartVM.ListCart)
{
item.Price = StaticDetails.GetPriceBasedOnQuantity(item.Count, item.AutoPart.Price,
item.AutoPart.Price50, item.AutoPart.Price100);
OrderDetails orderDetails = new OrderDetails()
{
AutoPartId = item.AutoPartId,
OrderId = ShoppingCartVM.OrderHeader.Id,
Price = item.Price,
Count = item.Count
};
ShoppingCartVM.OrderHeader.OrderTotalOriginal += orderDetails.Count * orderDetails.Price;
_db.OrderDetails.Add(orderDetails);
}
if (HttpContext.Session.GetString(StaticDetails.ssCouponCode) != null)
{
ShoppingCartVM.OrderHeader.CouponCode = HttpContext.Session.GetString(StaticDetails.ssCouponCode);
var couponFromDb = _db.Coupons.FirstOrDefault(c => c.Name.ToLower() == ShoppingCartVM.OrderHeader.CouponCode.ToLower());
ShoppingCartVM.OrderHeader.OrderTotal = StaticDetails.DiscountedPrice(couponFromDb, ShoppingCartVM.OrderHeader.OrderTotalOriginal);
}
else
{
ShoppingCartVM.OrderHeader.OrderTotal = ShoppingCartVM.OrderHeader.OrderTotalOriginal;
}
ShoppingCartVM.OrderHeader.CouponCodeDiscount = ShoppingCartVM.OrderHeader.OrderTotalOriginal - ShoppingCartVM.OrderHeader.OrderTotal;
_db.ShoppingCarts.RemoveRange(ShoppingCartVM.ListCart);
_db.SaveChanges();
HttpContext.Session.SetInt32(StaticDetails.ssShoppingCart, 0);
if (ShoppingCartVM.OrderHeader.CashonDelivery == true)
{
//order will be created for delayed payment for authroized company
ShoppingCartVM.OrderHeader.PaymentDueDate = DateTime.Now.AddDays(10);
ShoppingCartVM.OrderHeader.PaymentStatus = StaticDetails.PaymentStatusDelayedPayment;
ShoppingCartVM.OrderHeader.OrderStatus = StaticDetails.StatusApproved;
}
else
{
//process the payment
var options = new ChargeCreateOptions
{
Amount = Convert.ToInt32(ShoppingCartVM.OrderHeader.OrderTotal * 100),
Currency = "usd",
Description = "Order ID : " + ShoppingCartVM.OrderHeader.Id,
Source = stripeToken
};
var service = new ChargeService();
Charge charge = service.Create(options);
if (charge.Id == null)
{
ShoppingCartVM.OrderHeader.PaymentStatus = StaticDetails.PaymentStatusRejected;
}
else
{
ShoppingCartVM.OrderHeader.TransactionId = charge.Id;
}
if (charge.Status.ToLower() == "succeeded")
{
ShoppingCartVM.OrderHeader.PaymentStatus = StaticDetails.PaymentStatusApproved;
ShoppingCartVM.OrderHeader.OrderStatus = StaticDetails.StatusApproved;
ShoppingCartVM.OrderHeader.PaymentDate = DateTime.Now;
}
}
_db.SaveChanges();
return RedirectToAction("OrderConfirmation", "Cart", new { id = ShoppingCartVM.OrderHeader.Id });
}
public IActionResult OrderConfirmation(int id)
{
OrderHeader orderHeader = _db.OrderHeaders.FirstOrDefault(u => u.Id == id);
//TwilioClient.Init(_twilioOptions.AccountSid, _twilioOptions.AuthToken);
//try
//{
// var message = MessageResource.Create(
// body: "Order Placed on Bulky Book. Your Order ID:" + id,
// from: new Twilio.Types.PhoneNumber(_twilioOptions.PhoneNumber),
// to: new Twilio.Types.PhoneNumber(orderHeader.PhoneNumber)
// );
//}
//catch (Exception ex)
//{
//}
return View(id);
}
}
}<file_sep>/AutomotiveSols.BLL/Models/CarFeature.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.Models
{
public class CarFeature
{
public int Id { get; set; }
public Car Car { get; set; }
public int FeatureId { get; set; }
public Features Features { get; set; }
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/QRController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.BLL.ViewModels;
using AutomotiveSols.Data;
using AutomotiveSols.Static;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class QRController : Controller
{
private readonly IWebHostEnvironment _hostEnvironment;
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _db;
public QRController(IWebHostEnvironment _hostEnvironment, UserManager<ApplicationUser> _userManager,
ApplicationDbContext _db)
{
this._hostEnvironment = _hostEnvironment;
this._userManager = _userManager;
this._db =_db;
}
public IActionResult Index()
{
var qrs = _db.QRs.ToList();
return View(qrs);
}
[HttpGet]
public IActionResult Create()
{
var model = new QR();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(QR qr)
{
if (!ModelState.IsValid)
{
return View(qr);
}
else
{
_db.QRs.Add(qr);
await _db.SaveChangesAsync();
//Image being saved
string webRootPath = _hostEnvironment.WebRootPath;
var files = HttpContext.Request.Form.Files;
var qrFromDb = _db.QRs.Find(qr.Id);
if (files.Count != 0)
{
//Image has been uploaded
var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolderQR);
var extension = Path.GetExtension(files[0].FileName);
using (var filestream = new FileStream(Path.Combine(uploads, qr.Id + extension), FileMode.Create))
{
files[0].CopyTo(filestream);
}
qrFromDb.QRCode = @"\" + StaticDetails.ImageFolderQR + @"\" + qr.Id + extension;
}
else
{
//when user does not upload image
var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolderQR + @"\" + StaticDetails.DefaultProductImage);
System.IO.File.Copy(uploads, webRootPath + @"\" + StaticDetails.ImageFolderQR + @"\" + qr.Id + ".png");
qrFromDb.QRCode = @"\" + StaticDetails.ImageFolderQR + @"\" + qr.Id + ".png";
}
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
[HttpGet]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var model = new QR();
// model = await _db.QRs.SingleOrDefaultAsync(m => m.Id == id);
if (model == null)
{
return NotFound();
}
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, QR qR)
{
if (ModelState.IsValid)
{
string webRootPath = _hostEnvironment.WebRootPath;
var files = HttpContext.Request.Form.Files;
var qrFromDb = _db.QRs.Where(m => m.Id == qR.Id ).FirstOrDefault();
if (files.Count > 0 && files[0] != null)
{
//if user uploads a new image
var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolderQR);
var new_extension = Path.GetExtension(files[0].FileName);
var old_extension = Path.GetExtension(qrFromDb.QRCode);
if (System.IO.File.Exists(Path.Combine(uploads, qR.Id + old_extension)))
{
System.IO.File.Delete(Path.Combine(uploads, qR.Id + old_extension));
}
using (var filestream = new FileStream(Path.Combine(uploads, qR.Id + new_extension), FileMode.Create))
{
files[0].CopyTo(filestream);
}
qR.QRCode = @"\" + StaticDetails.ImageFolderQR + @"\" + qR.Id + new_extension;
}
if (qR.QRCode != null)
{
qrFromDb.QRCode = qR.QRCode;
}
qrFromDb.Name = qR.Name;
qrFromDb.price = qR.price;
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(qR);
}
}
}
<file_sep>/AutomotiveSols/Models/ConnectionString.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AutomotiveSols.Models
{
public class ConnectionString
{
private static string cName = "Server=(localdb)\\mssqllocaldb;Database=aspnet-AutomotiveSols-103ECA17-1716-4B1D-9297-9171642A1348;Trusted_Connection=True;MultipleActiveResultSets=true";
public static string CName
{
get => cName;
}
}
}
<file_sep>/AutomotiveSols.BLL/Models/Trim.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.Models
{
public class Trim
{
public int Id { get; set; }
public string Name { get; set; }
public int ModelId { get; set; }
public Model Model { get; set; }
//public List<Year> Years { get; set; }
//public List<Transmission> Transmissions { get; set; }
public List<Car> Cars { get; set; }
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/CarAppointmentController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.BLL.ViewModels;
using AutomotiveSols.Data;
using AutomotiveSols.Static;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class CarAppointmentController : Controller
{
private readonly ApplicationDbContext _db;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IWebHostEnvironment _webHostEnvironment;
public CarAppointmentController(IWebHostEnvironment webHostEnvironment, ApplicationDbContext db, UserManager<ApplicationUser> userManager)
{
_db = db;
_webHostEnvironment = webHostEnvironment;
_userManager = userManager;
}
public async Task<IActionResult> Index(string searchName = null, string searchEmail = null, string searchPhone = null, string searchDate = null)
{
var saleperson = await _userManager.GetUserAsync(User);
AppointmentVM appointmentVM = new AppointmentVM()
{
Appointments = new List<Appointments>()
};
appointmentVM.Appointments = _db.Appointments.Include(x => x.SalesPerson).ToList();
if (User.IsInRole(StaticDetails.Role_Dealer))
{
appointmentVM.Appointments = _db.Appointments.Include(x=>x.SalesPerson).Where(x => x.SalesPersonId == saleperson.Id
&& x.isCar==true).ToList();
}
else if (User.IsInRole(StaticDetails.Role_Super_Dealer))
{
appointmentVM.Appointments = _db.Appointments.Include(x => x.SalesPerson).
Where(x => x.isCar == true).ToList();
}
else if (User.IsInRole(StaticDetails.Role_Admin))
{
appointmentVM.Appointments = _db.Appointments.Include(x => x.SalesPerson).ToList();
}
else
{
appointmentVM.Appointments = new List<Appointments>();
}
//search
if (searchName != null)
{
appointmentVM.Appointments = appointmentVM.Appointments.Where(a => a.CustomerName.ToLower().Contains(searchName.ToLower())).ToList();
}
if (searchEmail != null)
{
appointmentVM.Appointments = appointmentVM.Appointments.Where(a => a.CustomerEmail.ToLower().Contains(searchEmail.ToLower())).ToList();
}
if (searchPhone != null)
{
appointmentVM.Appointments = appointmentVM.Appointments.Where(a => a.CustomerPhoneNumber.ToLower().Contains(searchPhone.ToLower())).ToList();
}
if (searchDate != null)
{
try
{
DateTime appDate = Convert.ToDateTime(searchDate);
appointmentVM.Appointments = appointmentVM.Appointments.Where(a => a.AppointmentDate.ToShortDateString().Equals(appDate.ToShortDateString())).ToList();
}
catch (Exception ex)
{
}
}
return View(appointmentVM);
}
//public async Task<IActionResult> Details(int? id)
//{
// if (id == null)
// {
// return NotFound();
// }
// var users = _db.ApplicationUsers.ToList();
// List<ApplicationUser> applicationUsers = new List<ApplicationUser>();
// for (int i = 0; i < users.Count; i++)
// {
// var user = await _userManager.FindByIdAsync(users[i].Id);
// if ((await _userManager.IsInRoleAsync(user, StaticDetails.Role_Workshop)))
// {
// // add the user
// applicationUsers.Add(user);
// }
// }
// ViewBag.SalePersons = new SelectList(applicationUsers, "Id", "Name"); ;
// var serviceList = (IEnumerable<Services>)(from p in _db.Services
// join a in _db.ServicesAppointments
// on p.Id equals a.ServiceId
// where a.AppointmentId == id
// select p).Include(x => x.ServiceType);
// AppointmentDetailsVM objAppointmentVM = new AppointmentDetailsVM()
// {
// Appointments = await _db.Appointments.Include(a => a.SalesPerson).Where(a => a.Id == id).FirstOrDefaultAsync(),
// Services = serviceList.ToList()
// };
// string mimtype = "";
// int extension = 1;
// var path = $"{this._webHostEnvironment.WebRootPath}\\Reports\\Report1.rdlc";
// Dictionary<string, string> parameters = new Dictionary<string, string>();
// foreach (var item in serviceList)
// {
// if (serviceList.Count() < 1)
// {
// parameters.Add("rp1", item.Name);
// parameters.Add("rp2", item.Price.ToString());
// }
// if (serviceList.Count() < 2)
// {
// parameters.Add("rp3", item.Name);
// parameters.Add("rp4", item.Price.ToString());
// }
// }
// parameters.Add("rp5", objAppointmentVM.Appointments.CustomerName);
// parameters.Add("rp6", objAppointmentVM.Appointments.CustomerEmail);
// parameters.Add("rp7", objAppointmentVM.Appointments.CustomerPhoneNumber);
// parameters.Add("rp8", objAppointmentVM.Appointments.AppointmentDate.ToString());
// parameters.Add("rp9", objAppointmentVM.Appointments.AppointmentTime.ToString());
// LocalReport localReport = new LocalReport(path);
// var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimtype);
// return File(result.MainStream, "application/pdf");
// // return View(objAppointmentVM);
//}
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var users = _db.ApplicationUsers.ToList();
List<ApplicationUser> applicationUsers = new List<ApplicationUser>();
for (int i = 0; i < users.Count; i++)
{
var user = await _userManager.FindByIdAsync(users[i].Id);
if ((await _userManager.IsInRoleAsync(user, StaticDetails.Role_Dealer)))
{
// add the user
applicationUsers.Add(user);
}
}
ViewBag.SalePersons = new SelectList(applicationUsers, "Id", "Name"); ;
var carList = (IEnumerable<Car>)(from p in _db.Cars
join a in _db.CarAppointments
on p.Id equals a.CarId
where a.AppointmentId == id
select p).Include(x => x.Brand);
AppointmentDetailsVM objAppointmentVM = new AppointmentDetailsVM()
{
Appointments = await _db.Appointments.Include(a => a.SalesPerson).Where(a => a.Id == id).FirstOrDefaultAsync(),
Cars = carList.ToList()
};
return View(objAppointmentVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, AppointmentDetailsVM objAppointmentVM)
{
if (ModelState.IsValid)
{
objAppointmentVM.Appointments.AppointmentDate = objAppointmentVM.Appointments.AppointmentDate
.AddHours(objAppointmentVM.Appointments.AppointmentTime.Hour)
.AddMinutes(objAppointmentVM.Appointments.AppointmentTime.Minute);
var appointmentFromDb = await _db.Appointments.Where(a => a.Id == objAppointmentVM.Appointments.Id).FirstOrDefaultAsync();
appointmentFromDb.CustomerName = objAppointmentVM.Appointments.CustomerName;
appointmentFromDb.CustomerEmail = objAppointmentVM.Appointments.CustomerEmail;
appointmentFromDb.CustomerPhoneNumber = objAppointmentVM.Appointments.CustomerPhoneNumber;
appointmentFromDb.AppointmentDate = objAppointmentVM.Appointments.AppointmentDate;
appointmentFromDb.isConfirmed = objAppointmentVM.Appointments.isConfirmed;
if (User.IsInRole("Admin"))
{
appointmentFromDb.SalesPersonId = objAppointmentVM.Appointments.SalesPersonId;
}
var users = _db.ApplicationUsers.ToList();
List<ApplicationUser> applicationUsers = new List<ApplicationUser>();
for (int i = 0; i < users.Count; i++)
{
var user = await _userManager.FindByIdAsync(users[i].Id);
if ((await _userManager.IsInRoleAsync(user, StaticDetails.Role_Workshop)))
{
// add the user
applicationUsers.Add(user);
}
}
ViewBag.SalePersons = new SelectList(applicationUsers, "Id", "Name"); ;
_db.SaveChanges();
return RedirectToAction(nameof(Index));
}
return View(objAppointmentVM);
}
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/ServiceController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutomotiveSols.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting.Internal;
using AutomotiveSols.BLL.ViewModels;
using Microsoft.EntityFrameworkCore;
using System.IO;
using AutomotiveSols.Static;
using Microsoft.AspNetCore.Hosting;
using AutomotiveSols.BLL.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class ServiceController : Controller
{
private readonly ApplicationDbContext _db;
private readonly IWebHostEnvironment _hostEnvironment;
private readonly UserManager<ApplicationUser> _userManager;
[BindProperty]
public ServiceVM ServiceVM { get; set; }
public ServiceController(ApplicationDbContext db, IWebHostEnvironment hostingEnvironment
, UserManager<ApplicationUser> userManager)
{
_db = db;
_hostEnvironment = hostingEnvironment;
_userManager = userManager;
}
public async Task<IActionResult> Index()
{
var services = _db.Services.Include(s => s.ServiceType);
return View(await services.ToListAsync());
}
[HttpGet]
public IActionResult Create()
{
var model = new ServiceVM();
ViewBag.ServiceTypes = new SelectList(_db.ServiceTypes.ToList(), "Id", "Name");
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ServiceVM serviceVM)
{
if (!ModelState.IsValid)
{
return View(serviceVM);
}
var applicationUser = await _userManager.GetUserAsync(User);
serviceVM.Services.ApplicationUserId = applicationUser.Id;
serviceVM.Services.Status = false;
_db.Services.Add(serviceVM.Services);
await _db.SaveChangesAsync();
//Image being saved
string webRootPath = _hostEnvironment.WebRootPath;
var files = HttpContext.Request.Form.Files;
var serviceFromDb = _db.Services.Find(serviceVM.Services.Id);
if (files.Count != 0)
{
//Image has been uploaded
var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolder);
var extension = Path.GetExtension(files[0].FileName);
using (var filestream = new FileStream(Path.Combine(uploads, serviceVM.Services.Id + extension), FileMode.Create))
{
files[0].CopyTo(filestream);
}
serviceFromDb.ImageUrl = @"\" + StaticDetails.ImageFolder + @"\" + serviceVM.Services.Id + extension;
}
else
{
//when user does not upload image
var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolder + @"\" + StaticDetails.DefaultProductImage);
System.IO.File.Copy(uploads, webRootPath + @"\" + StaticDetails.ImageFolder + @"\" + serviceVM.Services.Id + ".png");
serviceFromDb.ImageUrl = @"\" + StaticDetails.ImageFolder + @"\" + serviceVM.Services.Id + ".png";
}
await _db.SaveChangesAsync();
ViewBag.ServiceTypes = new SelectList(_db.ServiceTypes.ToList(), "Id", "Name");
return RedirectToAction(nameof(Index));
}
[HttpGet]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var model = new ServiceVM();
ViewBag.ServiceTypes = new SelectList(_db.ServiceTypes.ToList(), "Id", "Name");
model.Services = await _db.Services.Include(x => x.ServiceType).SingleOrDefaultAsync(m => m.Id == id);
if (model.Services == null)
{
return NotFound();
}
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id)
{
if (ModelState.IsValid)
{
string webRootPath = _hostEnvironment.WebRootPath;
var files = HttpContext.Request.Form.Files;
var serviceFromDb = _db.Services.Where(m => m.Id == ServiceVM.Services.Id).FirstOrDefault();
if (files.Count > 0 && files[0] != null)
{
//if user uploads a new image
var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolder);
var new_extension = Path.GetExtension(files[0].FileName);
var old_extension = Path.GetExtension(serviceFromDb.ImageUrl);
if (System.IO.File.Exists(Path.Combine(uploads, ServiceVM.Services.Id + old_extension)))
{
System.IO.File.Delete(Path.Combine(uploads, ServiceVM.Services.Id + old_extension));
}
using (var filestream = new FileStream(Path.Combine(uploads, ServiceVM.Services.Id + new_extension), FileMode.Create))
{
files[0].CopyTo(filestream);
}
ServiceVM.Services.ImageUrl = @"\" + StaticDetails.ImageFolder + @"\" + ServiceVM.Services.Id + new_extension;
}
if (ServiceVM.Services.ImageUrl != null)
{
serviceFromDb.ImageUrl = ServiceVM.Services.ImageUrl;
}
serviceFromDb.Name = ServiceVM.Services.Name;
serviceFromDb.Price = ServiceVM.Services.Price;
serviceFromDb.ServiceTypeId = ServiceVM.Services.ServiceTypeId;
serviceFromDb.Description = ServiceVM.Services.Description;
serviceFromDb.SellerComments = ServiceVM.Services.SellerComments;
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(ServiceVM);
}
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var model = new ServiceVM();
ViewBag.ServiceTypes = new SelectList(_db.ServiceTypes.ToList(), "Id", "Name");
model.Services = await _db.Services.Include(x => x.ServiceType).SingleOrDefaultAsync(m => m.Id == id);
if (model.Services == null)
{
return NotFound();
}
return View(model);
}
//GET : Delete
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var model = new ServiceVM();
ViewBag.ServiceTypes = new SelectList(_db.ServiceTypes.ToList(), "Id", "Name");
model.Services = await _db.Services.Include(x => x.ServiceType).SingleOrDefaultAsync(m => m.Id == id);
if (model.Services == null)
{
return NotFound();
}
return View(model);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
string webRootPath = _hostEnvironment.WebRootPath;
Services services = await _db.Services.FindAsync(id);
if (services == null)
{
return NotFound();
}
else
{
var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolder);
var extension = Path.GetExtension(services.ImageUrl);
if (System.IO.File.Exists(Path.Combine(uploads, services.Id + extension)))
{
System.IO.File.Delete(Path.Combine(uploads, services.Id + extension));
}
_db.Services.Remove(services);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/FeatureController.cs
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 AutomotiveSols.BLL.Models;
using AutomotiveSols.Data;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class FeatureController : Controller
{
private readonly ApplicationDbContext _context;
public FeatureController(ApplicationDbContext context)
{
_context = context;
}
// GET: Admin/Feature
public async Task<IActionResult> Index()
{
return View(await _context.Features.ToListAsync());
}
// GET: Admin/Feature/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var features = await _context.Features
.FirstOrDefaultAsync(m => m.Id == id);
if (features == null)
{
return NotFound();
}
return View(features);
}
// GET: Admin/Feature/Create
public IActionResult Create()
{
return View();
}
// POST: Admin/Feature/Create
// To protect from overposting attacks, 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("Id,Name,Description")] Features features)
{
if (ModelState.IsValid)
{
_context.Add(features);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(features);
}
// GET: Admin/Feature/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var features = await _context.Features.FindAsync(id);
if (features == null)
{
return NotFound();
}
return View(features);
}
// POST: Admin/Feature/Edit/5
// To protect from overposting attacks, 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(int id, [Bind("Id,Name,Description")] Features features)
{
if (id != features.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(features);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!FeaturesExists(features.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(features);
}
// GET: Admin/Feature/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var features = await _context.Features
.FirstOrDefaultAsync(m => m.Id == id);
if (features == null)
{
return NotFound();
}
return View(features);
}
// POST: Admin/Feature/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var features = await _context.Features.FindAsync(id);
_context.Features.Remove(features);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool FeaturesExists(int id)
{
return _context.Features.Any(e => e.Id == id);
}
}
}
<file_sep>/AutomotiveSols/Models/OrderService.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace AutomotiveSols.Models
{
public class OrderHistoryService
{
string connectionString = ConnectionString.CName;
public DataTable GetOrders()
{
var dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SPGetOrders", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
}
return dt;
}
public DataTable GetOrdersPending()
{
var dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SPGetOrdersPending", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
}
return dt;
}
public DataTable GetOrdersApproved()
{
var dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SPGetOrdersApproved", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
}
return dt;
}
}
}
<file_sep>/AutomotiveSols/AutoPartViewModel.cs
using AutomotiveSols.BLL.Models;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace AutomotiveSols.BLL.ViewModels
{
public class AutoPartViewModel
{
public AutoPart autoPart { get; set; }
public IFormFile CoverPhoto { get; set; }
public string CoverImageUrl { get; set; }
[Display(Name = "Choose the gallery images of your Spare-part")]
public IFormFileCollection GalleryFiles { get; set; }
public List<GalleryModel> Gallery { get; set; }
}
}
<file_sep>/AutomotiveSols/CarViewModel.cs
using AutomotiveSols.BLL.Models;
using AutomotiveSols.BLL.ViewModels;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace AutomotiveSols
{
public class CarViewModel
{
public Car Car { get; set; }
public List<FeatureAssignedToCar> FeatureAssignedToCar { get; set; }
public IEnumerable<SelectListItem> BrandList { get; set; }
public IEnumerable<SelectListItem> ModelList { get; set; }
public IEnumerable<SelectListItem> MileageList { get; set; }
public IEnumerable<SelectListItem> RegistrationCityList { get; set; }
public IEnumerable<SelectListItem> TransmissionList { get; set; }
public IEnumerable<SelectListItem> TrimList { get; set; }
public IEnumerable<SelectListItem> YearList { get; set; }
public IEnumerable<SelectListItem> ShowroomList { get; set; }
public IFormFile CoverPhoto { get; set; }
public string CoverImageUrl { get; set; }
[Display(Name = "Choose the gallery images of your Spare-part")]
public IFormFileCollection GalleryFiles { get; set; }
public List<GalleryModel> Gallery { get; set; }
}
}
<file_sep>/AutomotiveSols.BLL/ViewModels/AppointmentVM.cs
using AutomotiveSols.BLL.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.ViewModels
{
public class AppointmentVM
{
public List<Appointments> Appointments { get; set; }
}
}
<file_sep>/AutomotiveSols/Areas/Customer/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.Data;
using Microsoft.EntityFrameworkCore;
using AutomotiveSols.Extensions;
using AutomotiveSols.BLL.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using AutomotiveSols.Static;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Rendering;
using AutomotiveSols.EmailServices;
using Microsoft.AspNetCore.Hosting;
namespace AutomotiveSols.Controllers
{
[Area("Customer")]
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ApplicationDbContext _db;
private IndexViewModel IndexVM;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IEmailSender _emailSender;
private readonly IWebHostEnvironment _webHostEnvironment;
public HomeController(IWebHostEnvironment webHostEnvironment, ILogger<HomeController> logger, ApplicationDbContext db,
UserManager<ApplicationUser> userManager,
IEmailSender emailSender)
{
_logger = logger;
_db = db;
_userManager = userManager;
_emailSender = emailSender;
_webHostEnvironment = webHostEnvironment;
}
[HttpGet]
public async Task<ActionResult> Index(string searchName = null, string searchCategory = null)
{
ViewBag.BrandList = new SelectList(_db.Brands.ToList(), "Id", "Name");
ViewBag.ModelList = new SelectList(_db.Models.ToList(), "Id", "Name");
ViewBag.MileageList = new SelectList(_db.Mileages.ToList(), "Id", "NumberKm");
ViewBag.RegistrationCityList = new SelectList(_db.RegistrationCities.ToList(), "Id", "Name");
ViewBag.TransmissionList = new SelectList(_db.Transmissions.ToList(), "Id", "Name");
ViewBag.TrimList = new SelectList(_db.Trims.ToList(), "Id", "Name");
ViewBag.YearList = new SelectList(_db.Years.ToList(), "Id", "SolarYear");
var features = _db.Features.ToList();
IndexVM = new IndexViewModel()
{
TotalCars = _db.Cars.Count(x => x.Status == true),
TotalServices = _db.Services.ToList().Count(x => x.Status == true),
TotalSpareParts = _db.AutoParts.Count(x => x.Status == true),
TotalUsers = _db.ApplicationUsers.Count(x => x.LockoutEnabled == true),
CategoryList = await _db.Categories.ToListAsync(),
AutoPartList = await _db.AutoParts.Include(x => x.ApplicationUser).Include(x => x.Category)
.Include(x => x.SubCategory)
.Include(x => x.PartGalleries)
.ToListAsync(),
ServiceTypes = await _db.ServiceTypes.ToListAsync(),
Services = await _db.Services.Include(x => x.ApplicationUser)
.Include(x => x.ServiceType)
.ToListAsync(),
Brands = await _db.Brands.ToListAsync(),
Cars = await _db.Cars.Include(x => x.ApplicationUser)
.Include(x => x.Brand)
.Include(x => x.Model)
.Include(x => x.Mileage)
.Include(x => x.Transmission)
.Include(x => x.Trim)
.Include(x => x.RegistrationCity)
.Include(x => x.Year)
.ToListAsync(),
FeatureAssignedToCar = features.Select(s => new FeatureAssignedToCar()
{
FeatureId = s.Id,
FeatureName = s.Name,
Assigned = false
}).ToList()
};
var applicationUser = await _userManager.GetUserAsync(User);
if (applicationUser != null)
{
var count = _db.ShoppingCarts.Where(x => x.ApplicationUserId == applicationUser.Id).ToList().Count();
HttpContext.Session.SetInt32(StaticDetails.ssShoppingCart, count);
}
if (searchCategory != null)
{
IndexVM = new IndexViewModel()
{
TotalCars = _db.Cars.Count(x => x.Status == true),
TotalServices = _db.Services.ToList().Count(x => x.Status == true),
TotalSpareParts = _db.AutoParts.Count(x => x.Status == true),
TotalUsers = _db.ApplicationUsers.Count(x => x.LockoutEnabled == true),
CategoryList = await _db.Categories.Where(x => x.Name.Contains(searchCategory)).ToListAsync(),
AutoPartList = await _db.AutoParts.Include(x => x.ApplicationUser).Include(x => x.Category)
.Include(x => x.SubCategory)
.Include(x => x.PartGalleries)
.Where(x => x.Category.Name.Contains(searchCategory) || x.Description.Contains(searchCategory))
.ToListAsync(),
ServiceTypes = await _db.ServiceTypes.Where(x => x.Name.Contains(searchCategory)).ToListAsync(),
Services = await _db.Services.Include(x => x.ApplicationUser)
.Include(x => x.ServiceType)
.Where(x => x.ServiceType.Name.Contains(searchCategory) || x.Description.Contains(searchName))
.ToListAsync(),
Brands = await _db.Brands.Where(x => x.Name.Contains(searchCategory)).ToListAsync(),
Cars = await _db.Cars.Include(x => x.ApplicationUser)
.Include(x => x.Brand)
.Include(x => x.Model)
.Include(x => x.Mileage)
.Include(x => x.Transmission)
.Include(x => x.Trim)
.Include(x => x.RegistrationCity)
.Include(x => x.Year)
.Where(x => x.Brand.Name.Contains(searchCategory)
|| x.RegistrationCity.Name.Contains(searchCategory) || x.Transmission.Name.Contains(searchCategory)
|| x.Trim.Name.Contains(searchCategory) || x.Year.SolarYear.Contains(searchCategory))
.ToListAsync(),
FeatureAssignedToCar = features.Select(s => new FeatureAssignedToCar()
{
FeatureId = s.Id,
FeatureName = s.Name,
Assigned = false
}).ToList()
};
}
if (searchName != null)
{
IndexVM = new IndexViewModel()
{
TotalCars = _db.Cars.Count(x => x.Status == true),
TotalServices = _db.Services.ToList().Count(x => x.Status == true),
TotalSpareParts = _db.AutoParts.Count(x => x.Status == true),
TotalUsers = _db.ApplicationUsers.Count(x => x.LockoutEnabled == true),
CategoryList = await _db.Categories.ToListAsync(),
AutoPartList = await _db.AutoParts.Include(x => x.ApplicationUser).Include(x => x.Category)
.Include(x => x.SubCategory)
.Include(x => x.PartGalleries)
.Where(x => x.Name.Contains(searchName) || x.Description.Contains(searchName))
.ToListAsync(),
ServiceTypes = await _db.ServiceTypes.ToListAsync(),
Services = await _db.Services.Include(x => x.ApplicationUser)
.Include(x => x.ServiceType)
.Where(x => x.Name.Contains(searchName) || x.Description.Contains(searchName))
.ToListAsync(),
Brands = await _db.Brands.ToListAsync(),
Cars = await _db.Cars.Include(x => x.ApplicationUser)
.Include(x => x.Brand)
.Include(x => x.Model)
.Include(x => x.Mileage)
.Include(x => x.Transmission)
.Include(x => x.Trim)
.Include(x => x.RegistrationCity)
.Include(x => x.Year)
.Where(x => x.Brand.Name.Contains(searchName) || x.Mileage.NumberKm.Contains(searchName)
|| x.RegistrationCity.Name.Contains(searchName) || x.Transmission.Name.Contains(searchName)
|| x.Trim.Name.Contains(searchName) || x.Year.SolarYear.Contains(searchName))
.ToListAsync(),
FeatureAssignedToCar = features.Select(s => new FeatureAssignedToCar()
{
FeatureId = s.Id,
FeatureName = s.Name,
Assigned = false
}).ToList()
};
}
return View(IndexVM);
}
[HttpGet]
public async Task<IActionResult> Validate()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Validate(DecisionVM decisionVM)
{
if(decisionVM.SaleOwn== true)
{
Random r = new Random();
int num = r.Next();
HttpContext.Session.SetInt32(StaticDetails.Code, num);
await _emailSender.SendEmailAsync("<EMAIL>", "Confirm your activity",
$" This is your Validation Code {num}");
return RedirectToAction(nameof(Verify));
}
else
{
return RedirectToAction(nameof(QRAd));
}
}
[Authorize]
[HttpGet]
public async Task<IActionResult> QRAd()
{
var qr = _db.QRs.OrderByDescending(x=>x.Id)
.Take(1)
.ToList()
.FirstOrDefault();
return View(qr);
}
[Authorize]
[HttpGet]
public async Task<IActionResult> Verify()
{
return View();
}
[HttpPost]
public IActionResult Verify(CodeVM codeVM)
{
int? codeSession = HttpContext.Session.GetInt32(StaticDetails.Code);
if (codeVM != null)
{
if (codeVM.Code == codeSession)
{
return RedirectToAction(nameof(UserAd));//////////////
}
else
{
return RedirectToAction(nameof(UserAd));//////////////
}
}
else
{
return RedirectToAction(nameof(UserAd));//////
}
}
[Authorize]
public async Task<IActionResult> UserAd(bool isSuccess = false, int carId = 0)
{
ViewBag.BrandList = new SelectList(_db.Brands.ToList(), "Id", "Name");
ViewBag.ModelList = new SelectList(_db.Models.ToList(), "Id", "Name");
ViewBag.MileageList = new SelectList(_db.Mileages.ToList(), "Id", "NumberKm");
ViewBag.RegistrationCityList = new SelectList(_db.RegistrationCities.ToList(), "Id", "Name");
ViewBag.TransmissionList = new SelectList(_db.Transmissions.ToList(), "Id", "Name");
ViewBag.TrimList = new SelectList(_db.Trims.ToList(), "Id", "Name");
ViewBag.YearList = new SelectList(_db.Years.ToList(), "Id", "SolarYear");
ViewBag.ShowroomList = new SelectList(_db.Showrooms.ToList(), "Id", "Name");
var features = _db.Features.ToList();
CarViewModel carViewModel = new CarViewModel()
{
FeatureAssignedToCar = features.Select(s => new FeatureAssignedToCar()
{
FeatureId = s.Id,
FeatureName = s.Name,
Assigned = false
}).ToList()
};
var model = carViewModel;
ViewBag.IsSuccess = isSuccess;
ViewBag.CarId = carId;
return View(model);
}
[Authorize]
public async Task<IActionResult> UserAdFeature(bool isSuccess = false, int carId = 0)
{
ViewBag.BrandList = new SelectList(_db.Brands.ToList(), "Id", "Name");
ViewBag.ModelList = new SelectList(_db.Models.ToList(), "Id", "Name");
ViewBag.MileageList = new SelectList(_db.Mileages.ToList(), "Id", "NumberKm");
ViewBag.RegistrationCityList = new SelectList(_db.RegistrationCities.ToList(), "Id", "Name");
ViewBag.TransmissionList = new SelectList(_db.Transmissions.ToList(), "Id", "Name");
ViewBag.TrimList = new SelectList(_db.Trims.ToList(), "Id", "Name");
ViewBag.YearList = new SelectList(_db.Years.ToList(), "Id", "SolarYear");
ViewBag.ShowroomList = new SelectList(_db.Showrooms.ToList(), "Id", "Name");
var features = _db.Features.ToList();
CarViewModel carViewModel = new CarViewModel()
{
FeatureAssignedToCar = features.Select(s => new FeatureAssignedToCar()
{
FeatureId = s.Id,
FeatureName = s.Name,
Assigned = false
}).ToList()
};
var model = carViewModel;
ViewBag.IsSuccess = isSuccess;
ViewBag.CarId = carId;
return View(model);
}
public async Task<IActionResult> DetailsPart(int id)
{
var partFromDb =await _db.AutoParts.Include(x => x.ApplicationUser)
.Include(x => x.Category)
.Include(x => x.SubCategory)
.Include(x => x.PartGalleries)
.FirstOrDefaultAsync(x=>x.Id ==id);
ShoppingCart cartObj = new ShoppingCart()
{
AutoPart = partFromDb,
AutoPartId = partFromDb.Id
};
return View(cartObj);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public async Task<IActionResult> DetailsPart(ShoppingCart CartObject)
{
CartObject.Id = 0;
if (ModelState.IsValid)
{
//then we will add to cart
var applicationUser = await _userManager.GetUserAsync(User);
CartObject.ApplicationUserId = applicationUser.Id;
ShoppingCart cartFromDb = await _db.ShoppingCarts.Where(u => u.ApplicationUserId == CartObject.ApplicationUserId
&& u.AutoPartId == CartObject.AutoPartId).Include(x => x.AutoPart).Include(x => x.ApplicationUser)
.FirstOrDefaultAsync();
if (cartFromDb == null)
{
//no records exists in database for that product for that user
_db.ShoppingCarts.Add(CartObject);
}
else
{
cartFromDb.Count += CartObject.Count;
//_unitOfWork.ShoppingCart.Update(cartFromDb);
}
await _db.SaveChangesAsync();
var count = _db.ShoppingCarts.Where(x => x.ApplicationUserId == CartObject.ApplicationUserId)
.ToList().Count();
//HttpContext.Session.SetObject(SD.ssShoppingCart, CartObject);
HttpContext.Session.SetInt32(StaticDetails.ssShoppingCart, count);
return RedirectToAction(nameof(Index));
}
else
{
var partFromDb = await _db.AutoParts.Where(x => x.Id == CartObject.AutoPartId)
.Include(x => x.Category)
.Include(x => x.SubCategory).FirstOrDefaultAsync();
ShoppingCart cartObj = new ShoppingCart()
{
AutoPart = partFromDb,
AutoPartId = partFromDb.Id
};
return View(cartObj);
}
}
[HttpGet]
[Authorize]
public async Task<IActionResult> DetailsCar(int id)
{
var car = await _db.Cars.Include(m => m.ApplicationUser)
.Include(x => x.Brand)
.Include(x => x.Model)
.Include(x => x.Mileage)
.Include(x => x.Transmission)
.Include(x => x.Trim)
.Include(x => x.RegistrationCity)
.Include(x => x.Year)
.Where(m => m.Id == id).FirstOrDefaultAsync();
return View(car);
}
[HttpPost, ActionName("DetailsCar")]
[ValidateAntiForgeryToken]
public IActionResult DetailsCarPost(int id)
{
List<int> tempCart = HttpContext.Session.Get<List<int>>("carCart");
if (tempCart == null)
{
tempCart = new List<int>();
}
tempCart.Add(id);
HttpContext.Session.Set("carCart", tempCart);
return RedirectToAction("Index", "Home", new { area = "Customer" });
}
public IActionResult RemoveCar(int id)
{
List<int> tempCart = HttpContext.Session.Get<List<int>>("carCart");
if (tempCart.Count > 0)
{
if (tempCart.Contains(id))
{
tempCart.Remove(id);
}
}
HttpContext.Session.Set("carCart", tempCart);
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Details(int id)
{
var service = await _db.Services.Include(m => m.ServiceType).Where(m => m.Id == id).FirstOrDefaultAsync();
return View(service);
}
[HttpPost, ActionName("Details")]
[ValidateAntiForgeryToken]
public IActionResult DetailsPost(int id)
{
List<int> tempCart = HttpContext.Session.Get<List<int>>("tempCart");
if (tempCart == null)
{
tempCart = new List<int>();
}
tempCart.Add(id);
HttpContext.Session.Set("tempCart", tempCart);
return RedirectToAction("Index", "Home", new { area = "Customer" });
}
public IActionResult Remove(int id)
{
List<int> tempCart = HttpContext.Session.Get<List<int>>("tempCart");
if (tempCart.Count > 0)
{
if (tempCart.Contains(id))
{
tempCart.Remove(id);
}
}
HttpContext.Session.Set("tempCart", tempCart);
return RedirectToAction(nameof(Index));
}
public IActionResult Profile()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>/AutomotiveSols.BLL/Models/ApplicationUser.cs
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace AutomotiveSols.BLL.Models
{
public class ApplicationUser :IdentityUser
{
[Required]
public string Name { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public int? ShowroomId { get; set; }
public Showroom Showroom { get; set; }
[NotMapped]
public string Role { get; set; }
public ShoppingCart ShoppingCart { get; set; }
public List<OrderHeader> OrderHeaders { get; set; }
public List<AutoPart> AutoParts { get; set; }
public List<Car> Cars { get; set; }
public List<Services> Services { get; set; }
public List<Appointments> Appointments { get; set; }
}
}
<file_sep>/AutomotiveSols.BLL/ViewModels/CodeVM.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.ViewModels
{
public class CodeVM
{
public int? Code { get; set; }
}
}
<file_sep>/AutomotiveSols/Areas/Admin/Controllers/ServiceTypeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutomotiveSols.BLL.Models;
using AutomotiveSols.Data;
using Microsoft.AspNetCore.Mvc;
namespace AutomotiveSols.Areas.Admin.Controllers
{
[Area("Admin")]
public class ServiceTypeController : Controller
{
private readonly ApplicationDbContext _db;
public ServiceTypeController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
return View(_db.ServiceTypes.ToList());
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ServiceType serviceType)
{
if (ModelState.IsValid)
{
_db.Add(serviceType);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(serviceType);
}
[HttpGet]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var serviceType = await _db.ServiceTypes.FindAsync(id);
if (serviceType == null)
{
return NotFound();
}
return View(serviceType);
}
//POST Edit action Method for The serice type
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, ServiceType serviceType)
{
if (id != serviceType.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
_db.Update(serviceType);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(serviceType);
}
//GET Details of the Serice types
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var serviceType = await _db.ServiceTypes.FindAsync(id);
if (serviceType == null)
{
return NotFound();
}
return View(serviceType);
}
//GET Delete the serive type by passing the id
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var serviceType = await _db.ServiceTypes.FindAsync(id);
if (serviceType == null)
{
return NotFound();
}
return View(serviceType);
}
//POST Delete for the better security
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var serviceType = await _db.ServiceTypes.FindAsync(id);
_db.ServiceTypes.Remove(serviceType);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210626112731_changesInCar.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class changesInCar : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Car_AspNetUsers_ApplicationUserId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_Brand_BranId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_Mileage_MileageId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_Model_ModelId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_RegistrationCity_RegistrationCityId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_Transmissions_TransmissionId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_Trim_TrimId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_Car_Year_YearId",
table: "Car");
migrationBuilder.DropForeignKey(
name: "FK_CarFeature_Features_FeatureId",
table: "CarFeature");
migrationBuilder.DropForeignKey(
name: "FK_CarFeature_Car_Id",
table: "CarFeature");
migrationBuilder.DropPrimaryKey(
name: "PK_Year",
table: "Year");
migrationBuilder.DropPrimaryKey(
name: "PK_Trim",
table: "Trim");
migrationBuilder.DropPrimaryKey(
name: "PK_RegistrationCity",
table: "RegistrationCity");
migrationBuilder.DropPrimaryKey(
name: "PK_Model",
table: "Model");
migrationBuilder.DropPrimaryKey(
name: "PK_Mileage",
table: "Mileage");
migrationBuilder.DropPrimaryKey(
name: "PK_CarFeature",
table: "CarFeature");
migrationBuilder.DropPrimaryKey(
name: "PK_Car",
table: "Car");
migrationBuilder.DropPrimaryKey(
name: "PK_Brand",
table: "Brand");
migrationBuilder.RenameTable(
name: "Year",
newName: "Years");
migrationBuilder.RenameTable(
name: "Trim",
newName: "Trims");
migrationBuilder.RenameTable(
name: "RegistrationCity",
newName: "RegistrationCities");
migrationBuilder.RenameTable(
name: "Model",
newName: "Models");
migrationBuilder.RenameTable(
name: "Mileage",
newName: "Mileages");
migrationBuilder.RenameTable(
name: "CarFeature",
newName: "CarFeatures");
migrationBuilder.RenameTable(
name: "Car",
newName: "Cars");
migrationBuilder.RenameTable(
name: "Brand",
newName: "Brands");
migrationBuilder.RenameIndex(
name: "IX_CarFeature_Id",
table: "CarFeatures",
newName: "IX_CarFeatures_Id");
migrationBuilder.RenameIndex(
name: "IX_Car_YearId",
table: "Cars",
newName: "IX_Cars_YearId");
migrationBuilder.RenameIndex(
name: "IX_Car_TrimId",
table: "Cars",
newName: "IX_Cars_TrimId");
migrationBuilder.RenameIndex(
name: "IX_Car_TransmissionId",
table: "Cars",
newName: "IX_Cars_TransmissionId");
migrationBuilder.RenameIndex(
name: "IX_Car_RegistrationCityId",
table: "Cars",
newName: "IX_Cars_RegistrationCityId");
migrationBuilder.RenameIndex(
name: "IX_Car_ModelId",
table: "Cars",
newName: "IX_Cars_ModelId");
migrationBuilder.RenameIndex(
name: "IX_Car_MileageId",
table: "Cars",
newName: "IX_Cars_MileageId");
migrationBuilder.RenameIndex(
name: "IX_Car_BranId",
table: "Cars",
newName: "IX_Cars_BranId");
migrationBuilder.RenameIndex(
name: "IX_Car_ApplicationUserId",
table: "Cars",
newName: "IX_Cars_ApplicationUserId");
migrationBuilder.AddPrimaryKey(
name: "PK_Years",
table: "Years",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_Trims",
table: "Trims",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_RegistrationCities",
table: "RegistrationCities",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_Models",
table: "Models",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_Mileages",
table: "Mileages",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_CarFeatures",
table: "CarFeatures",
columns: new[] { "FeatureId", "Id" });
migrationBuilder.AddPrimaryKey(
name: "PK_Cars",
table: "Cars",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_Brands",
table: "Brands",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_CarFeatures_Features_FeatureId",
table: "CarFeatures",
column: "FeatureId",
principalTable: "Features",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CarFeatures_Cars_Id",
table: "CarFeatures",
column: "Id",
principalTable: "Cars",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Cars_AspNetUsers_ApplicationUserId",
table: "Cars",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Cars_Brands_BranId",
table: "Cars",
column: "BranId",
principalTable: "Brands",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Cars_Mileages_MileageId",
table: "Cars",
column: "MileageId",
principalTable: "Mileages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Cars_Models_ModelId",
table: "Cars",
column: "ModelId",
principalTable: "Models",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Cars_RegistrationCities_RegistrationCityId",
table: "Cars",
column: "RegistrationCityId",
principalTable: "RegistrationCities",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Cars_Transmissions_TransmissionId",
table: "Cars",
column: "TransmissionId",
principalTable: "Transmissions",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Cars_Trims_TrimId",
table: "Cars",
column: "TrimId",
principalTable: "Trims",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Cars_Years_YearId",
table: "Cars",
column: "YearId",
principalTable: "Years",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_CarFeatures_Features_FeatureId",
table: "CarFeatures");
migrationBuilder.DropForeignKey(
name: "FK_CarFeatures_Cars_Id",
table: "CarFeatures");
migrationBuilder.DropForeignKey(
name: "FK_Cars_AspNetUsers_ApplicationUserId",
table: "Cars");
migrationBuilder.DropForeignKey(
name: "FK_Cars_Brands_BranId",
table: "Cars");
migrationBuilder.DropForeignKey(
name: "FK_Cars_Mileages_MileageId",
table: "Cars");
migrationBuilder.DropForeignKey(
name: "FK_Cars_Models_ModelId",
table: "Cars");
migrationBuilder.DropForeignKey(
name: "FK_Cars_RegistrationCities_RegistrationCityId",
table: "Cars");
migrationBuilder.DropForeignKey(
name: "FK_Cars_Transmissions_TransmissionId",
table: "Cars");
migrationBuilder.DropForeignKey(
name: "FK_Cars_Trims_TrimId",
table: "Cars");
migrationBuilder.DropForeignKey(
name: "FK_Cars_Years_YearId",
table: "Cars");
migrationBuilder.DropPrimaryKey(
name: "PK_Years",
table: "Years");
migrationBuilder.DropPrimaryKey(
name: "PK_Trims",
table: "Trims");
migrationBuilder.DropPrimaryKey(
name: "PK_RegistrationCities",
table: "RegistrationCities");
migrationBuilder.DropPrimaryKey(
name: "PK_Models",
table: "Models");
migrationBuilder.DropPrimaryKey(
name: "PK_Mileages",
table: "Mileages");
migrationBuilder.DropPrimaryKey(
name: "PK_Cars",
table: "Cars");
migrationBuilder.DropPrimaryKey(
name: "PK_CarFeatures",
table: "CarFeatures");
migrationBuilder.DropPrimaryKey(
name: "PK_Brands",
table: "Brands");
migrationBuilder.RenameTable(
name: "Years",
newName: "Year");
migrationBuilder.RenameTable(
name: "Trims",
newName: "Trim");
migrationBuilder.RenameTable(
name: "RegistrationCities",
newName: "RegistrationCity");
migrationBuilder.RenameTable(
name: "Models",
newName: "Model");
migrationBuilder.RenameTable(
name: "Mileages",
newName: "Mileage");
migrationBuilder.RenameTable(
name: "Cars",
newName: "Car");
migrationBuilder.RenameTable(
name: "CarFeatures",
newName: "CarFeature");
migrationBuilder.RenameTable(
name: "Brands",
newName: "Brand");
migrationBuilder.RenameIndex(
name: "IX_Cars_YearId",
table: "Car",
newName: "IX_Car_YearId");
migrationBuilder.RenameIndex(
name: "IX_Cars_TrimId",
table: "Car",
newName: "IX_Car_TrimId");
migrationBuilder.RenameIndex(
name: "IX_Cars_TransmissionId",
table: "Car",
newName: "IX_Car_TransmissionId");
migrationBuilder.RenameIndex(
name: "IX_Cars_RegistrationCityId",
table: "Car",
newName: "IX_Car_RegistrationCityId");
migrationBuilder.RenameIndex(
name: "IX_Cars_ModelId",
table: "Car",
newName: "IX_Car_ModelId");
migrationBuilder.RenameIndex(
name: "IX_Cars_MileageId",
table: "Car",
newName: "IX_Car_MileageId");
migrationBuilder.RenameIndex(
name: "IX_Cars_BranId",
table: "Car",
newName: "IX_Car_BranId");
migrationBuilder.RenameIndex(
name: "IX_Cars_ApplicationUserId",
table: "Car",
newName: "IX_Car_ApplicationUserId");
migrationBuilder.RenameIndex(
name: "IX_CarFeatures_Id",
table: "CarFeature",
newName: "IX_CarFeature_Id");
migrationBuilder.AddPrimaryKey(
name: "PK_Year",
table: "Year",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_Trim",
table: "Trim",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_RegistrationCity",
table: "RegistrationCity",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_Model",
table: "Model",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_Mileage",
table: "Mileage",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_Car",
table: "Car",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_CarFeature",
table: "CarFeature",
columns: new[] { "FeatureId", "Id" });
migrationBuilder.AddPrimaryKey(
name: "PK_Brand",
table: "Brand",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_Car_AspNetUsers_ApplicationUserId",
table: "Car",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_Brand_BranId",
table: "Car",
column: "BranId",
principalTable: "Brand",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_Mileage_MileageId",
table: "Car",
column: "MileageId",
principalTable: "Mileage",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_Model_ModelId",
table: "Car",
column: "ModelId",
principalTable: "Model",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_RegistrationCity_RegistrationCityId",
table: "Car",
column: "RegistrationCityId",
principalTable: "RegistrationCity",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_Transmissions_TransmissionId",
table: "Car",
column: "TransmissionId",
principalTable: "Transmissions",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_Trim_TrimId",
table: "Car",
column: "TrimId",
principalTable: "Trim",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Car_Year_YearId",
table: "Car",
column: "YearId",
principalTable: "Year",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CarFeature_Features_FeatureId",
table: "CarFeature",
column: "FeatureId",
principalTable: "Features",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CarFeature_Car_Id",
table: "CarFeature",
column: "Id",
principalTable: "Car",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20211001164510_carisfeaturedandpaymentstatus.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class carisfeaturedandpaymentstatus : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "Status",
table: "Payments",
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "isFeatured",
table: "Cars",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Status",
table: "Payments");
migrationBuilder.DropColumn(
name: "isFeatured",
table: "Cars");
}
}
}
<file_sep>/AutomotiveSols.DAL/Data/Migrations/20210528133453_enforcenoactionondelete.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AutomotiveSols.Data.Migrations
{
public partial class enforcenoactionondelete : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
table: "AspNetUserTokens");
migrationBuilder.DropForeignKey(
name: "FK_AutoParts_Categories_CategoryId",
table: "AutoParts");
migrationBuilder.DropForeignKey(
name: "FK_AutoParts_SubCategories_SubCategoryId",
table: "AutoParts");
migrationBuilder.DropForeignKey(
name: "FK_OrderDetails_AutoParts_AutoPartId",
table: "OrderDetails");
migrationBuilder.DropForeignKey(
name: "FK_OrderDetails_OrderHeaders_OrderId",
table: "OrderDetails");
migrationBuilder.DropForeignKey(
name: "FK_Services_ServiceTypes_ServiceTypeId",
table: "Services");
migrationBuilder.DropForeignKey(
name: "FK_ServicesAppointments_Appointments_AppointmentId",
table: "ServicesAppointments");
migrationBuilder.DropForeignKey(
name: "FK_ServicesAppointments_Services_ServiceId",
table: "ServicesAppointments");
migrationBuilder.DropForeignKey(
name: "FK_ShoppingCarts_AutoParts_AutoPartId",
table: "ShoppingCarts");
migrationBuilder.DropForeignKey(
name: "FK_SubCategories_Categories_CategoryId",
table: "SubCategories");
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "AspNetUserTokens",
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(128)",
oldMaxLength: 128);
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AspNetUserTokens",
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(128)",
oldMaxLength: 128);
migrationBuilder.AlterColumn<string>(
name: "ProviderKey",
table: "AspNetUserLogins",
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(128)",
oldMaxLength: 128);
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AspNetUserLogins",
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(128)",
oldMaxLength: 128);
migrationBuilder.AddForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
table: "AspNetUserTokens",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AutoParts_Categories_CategoryId",
table: "AutoParts",
column: "CategoryId",
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AutoParts_SubCategories_SubCategoryId",
table: "AutoParts",
column: "SubCategoryId",
principalTable: "SubCategories",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrderDetails_AutoParts_AutoPartId",
table: "OrderDetails",
column: "AutoPartId",
principalTable: "AutoParts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrderDetails_OrderHeaders_OrderId",
table: "OrderDetails",
column: "OrderId",
principalTable: "OrderHeaders",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Services_ServiceTypes_ServiceTypeId",
table: "Services",
column: "ServiceTypeId",
principalTable: "ServiceTypes",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ServicesAppointments_Appointments_AppointmentId",
table: "ServicesAppointments",
column: "AppointmentId",
principalTable: "Appointments",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ServicesAppointments_Services_ServiceId",
table: "ServicesAppointments",
column: "ServiceId",
principalTable: "Services",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ShoppingCarts_AutoParts_AutoPartId",
table: "ShoppingCarts",
column: "AutoPartId",
principalTable: "AutoParts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_SubCategories_Categories_CategoryId",
table: "SubCategories",
column: "CategoryId",
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
table: "AspNetUserTokens");
migrationBuilder.DropForeignKey(
name: "FK_AutoParts_Categories_CategoryId",
table: "AutoParts");
migrationBuilder.DropForeignKey(
name: "FK_AutoParts_SubCategories_SubCategoryId",
table: "AutoParts");
migrationBuilder.DropForeignKey(
name: "FK_OrderDetails_AutoParts_AutoPartId",
table: "OrderDetails");
migrationBuilder.DropForeignKey(
name: "FK_OrderDetails_OrderHeaders_OrderId",
table: "OrderDetails");
migrationBuilder.DropForeignKey(
name: "FK_Services_ServiceTypes_ServiceTypeId",
table: "Services");
migrationBuilder.DropForeignKey(
name: "FK_ServicesAppointments_Appointments_AppointmentId",
table: "ServicesAppointments");
migrationBuilder.DropForeignKey(
name: "FK_ServicesAppointments_Services_ServiceId",
table: "ServicesAppointments");
migrationBuilder.DropForeignKey(
name: "FK_ShoppingCarts_AutoParts_AutoPartId",
table: "ShoppingCarts");
migrationBuilder.DropForeignKey(
name: "FK_SubCategories_Categories_CategoryId",
table: "SubCategories");
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "AspNetUserTokens",
type: "nvarchar(128)",
maxLength: 128,
nullable: false,
oldClrType: typeof(string));
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AspNetUserTokens",
type: "nvarchar(128)",
maxLength: 128,
nullable: false,
oldClrType: typeof(string));
migrationBuilder.AlterColumn<string>(
name: "ProviderKey",
table: "AspNetUserLogins",
type: "nvarchar(128)",
maxLength: 128,
nullable: false,
oldClrType: typeof(string));
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AspNetUserLogins",
type: "nvarchar(128)",
maxLength: 128,
nullable: false,
oldClrType: typeof(string));
migrationBuilder.AddForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
table: "AspNetUserTokens",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AutoParts_Categories_CategoryId",
table: "AutoParts",
column: "CategoryId",
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AutoParts_SubCategories_SubCategoryId",
table: "AutoParts",
column: "SubCategoryId",
principalTable: "SubCategories",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrderDetails_AutoParts_AutoPartId",
table: "OrderDetails",
column: "AutoPartId",
principalTable: "AutoParts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrderDetails_OrderHeaders_OrderId",
table: "OrderDetails",
column: "OrderId",
principalTable: "OrderHeaders",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Services_ServiceTypes_ServiceTypeId",
table: "Services",
column: "ServiceTypeId",
principalTable: "ServiceTypes",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ServicesAppointments_Appointments_AppointmentId",
table: "ServicesAppointments",
column: "AppointmentId",
principalTable: "Appointments",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ServicesAppointments_Services_ServiceId",
table: "ServicesAppointments",
column: "ServiceId",
principalTable: "Services",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ShoppingCarts_AutoParts_AutoPartId",
table: "ShoppingCarts",
column: "AutoPartId",
principalTable: "AutoParts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_SubCategories_Categories_CategoryId",
table: "SubCategories",
column: "CategoryId",
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}
<file_sep>/AutomotiveSols.BLL/Models/Category.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomotiveSols.BLL.Models
{
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public int DisplayOrder { get; set; }
public List<SubCategory> SubCategories { get; set; }
public List<AutoPart> AutoParts { get; set; }
}
}
<file_sep>/AutomotiveSols.BLL/Models/Payment.cs
namespace AutomotiveSols.BLL.Models
{
public class Payment
{
public int Id { get; set; }
public string PaymentImage { get; set; }
public int? CarId { get; set; }
public bool? Status { get; set; }
public Car Car { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
} | 456fd71c512bc927495f82043c853dfae40df7ba | [
"C#"
] | 60 | C# | Husnain19/FYP3 | f19e2d4fd67e8d07d6b2c979dfa357d90bb1ef27 | 0c0d847755d22832df1d2a9a4d8407acd5694633 |
refs/heads/master | <repo_name>superchengwisdom/HappyNote<file_sep>/base/src/main/java/com/sjtu/yifei/base/BaseFragment.kt
package com.sjtu.yifei.base
import android.support.v4.app.Fragment
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
/**
* 类描述:
* 创建人:yifei
* 创建时间:2018/6/27
* 修改人:
* 修改时间:
* 修改备注:
*/
open class BaseFragment : Fragment() {
var TAG = this.javaClass.simpleName
private var mCompositeDisposable: CompositeDisposable? = null
override fun onDetach() {
super.onDetach()
unSubscribe()
}
/**
* 优化rx 内存泄漏问题
*
* @param disposable
*/
fun subscribe(disposable: Disposable?) {
if (disposable != null) {
if (mCompositeDisposable == null) {
mCompositeDisposable = CompositeDisposable()
}
mCompositeDisposable?.add(disposable)
}
}
/**
* 优化rx 内存泄漏问题
*/
private fun unSubscribe() {
if (mCompositeDisposable != null) {
mCompositeDisposable?.clear()
}
}
}<file_sep>/login/src/main/java/com/sjtu/yifei/login/LoginInterceptor.kt
package com.sjtu.yifei.login
import android.widget.Toast
import com.sjtu.yifei.annotation.Interceptor
import com.sjtu.yifei.route.AInterceptor
import com.sjtu.yifei.route.ActivityCallback
import com.sjtu.yifei.route.ActivityLifecycleMonitor
import com.sjtu.yifei.route.Routerfit
import com.sjtu.yifei.router.RouterPath
import com.sjtu.yifei.router.RouterService
@Interceptor(priority = 3)
class LoginInterceptor : AInterceptor {
override fun intercept(chain: AInterceptor.Chain) {
//需要登录
// if (RouterPath.LAUNCHER_BUS1.equals(chain.path(), ignoreCase = true)) {
// Routerfit.register(RouterService::class.java).openLoginUi(ActivityCallback { result, data ->
// if (result == Routerfit.RESULT_OK) {//登录成功
// Toast.makeText(ActivityLifecycleMonitor.getTopActivity(), "登录成功", Toast.LENGTH_SHORT).show()
// chain.proceed()
// } else {
// Toast.makeText(ActivityLifecycleMonitor.getTopActivity(), "请先完成登录", Toast.LENGTH_SHORT).show()
// }
// })
// } else {
// chain.proceed()
// }
chain.proceed()
}
companion object {
private const val TAG = "LoginInterceptor"
}
}
<file_sep>/hybrid/src/main/java/com/sjtu/yifei/hybrid/web/BridgeWebViewClient.java
package com.sjtu.yifei.hybrid.web;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.sjtu.yifei.base.OkHttpClientManager;
import com.sjtu.yifei.base.util.LogUtil;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* 如果要自定义WebViewClient必须要集成此类
* Created by bruce on 10/28/15.
*/
public class BridgeWebViewClient extends WebViewClient {
private String TAG = "BridgeWebViewClient";
private BridgeWebView webView;
private final OkHttpClient client;
public BridgeWebViewClient(BridgeWebView webView) {
this.webView = webView;
client = OkHttpClientManager.Companion.getInstance().getBaseClient("webview");
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try {
url = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (url.startsWith(BridgeUtil.YY_RETURN_DATA)) { // 如果是返回数据
webView.handlerReturnData(url);
return true;
} else if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) { //
webView.flushMessageQueue();
return true;
} else {
return this.onCustomShouldOverrideUrlLoading(view, url) || super.shouldOverrideUrlLoading(view, url);
}
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
String url = request.getUrl().toString();
try {
url = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
if (url.startsWith(BridgeUtil.YY_RETURN_DATA)) { // 如果是返回数据
webView.handlerReturnData(url);
return true;
} else if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) { //
webView.flushMessageQueue();
return true;
} else {
return this.onCustomShouldOverrideUrlLoading(view, url) || super.shouldOverrideUrlLoading(view, request);
}
} else {
return super.shouldOverrideUrlLoading(view, request);
}
}
protected boolean onCustomShouldOverrideUrlLoading(WebView view, String url) {
return false;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
BridgeUtil.webViewLoadLocalJs(view, BridgeWebView.toLoadJs);
if (webView.getStartupMessage() != null) {
for (Message m : webView.getStartupMessage()) {
webView.dispatchMessage(m);
}
webView.setStartupMessage(null);
}
onCustomPageFinished(view, url);
}
protected void onCustomPageFinished(WebView view, String url) {
}
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
WebResourceResponse response = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
// response = loadResponse(request);
}
return response != null ? response : super.shouldInterceptRequest(view, request);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private WebResourceResponse loadResponse(WebResourceRequest request) {
String url = request.getUrl().toString();
// suppress favicon requests as we don't display them anywhere
if (!url.endsWith(".js")) {
return null;
}
try {
Map<String, String> headers = request.getRequestHeaders();
Request.Builder builder = new Request.Builder().url(url);
for (Map.Entry<String, String> entry : headers.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
Request okReq = builder.build();
final long startMillis = System.currentTimeMillis();
final Response okResp = client.newCall(okReq).execute();
final long dtMillis = System.currentTimeMillis() - startMillis;
LogUtil.Companion.d(TAG, url + "\n Got response after " + dtMillis + "ms");
return okHttpResponseToWebResourceResponse(okResp);
} catch (Exception e) {
LogUtil.Companion.e(TAG, "Failed to load request: " + url);
e.printStackTrace();
return null;
}
}
/**
* Convert OkHttp {@link Response} into a {@link WebResourceResponse}
*
* @param resp The OkHttp {@link Response}
* @return The {@link WebResourceResponse}
*/
private WebResourceResponse okHttpResponseToWebResourceResponse(Response resp) {
final String contentTypeValue = resp.header("Content-Type");
if (contentTypeValue != null) {
if (contentTypeValue.indexOf("charset=") > 0) {
final String[] contentTypeAndEncoding = contentTypeValue.split("; ");
final String contentType = contentTypeAndEncoding[0];
final String charset = contentTypeAndEncoding[1].split("=")[1];
return new WebResourceResponse(contentType, charset, resp.body().byteStream());
} else {
return new WebResourceResponse(contentTypeValue, null, resp.body().byteStream());
}
} else {
return new WebResourceResponse("application/octet-stream", null, resp.body().byteStream());
}
}
}
<file_sep>/base/src/main/java/com/sjtu/yifei/base/OkHttpClientManager.kt
package com.sjtu.yifei.base
import com.sjtu.yifei.base.util.AppUtils
import com.sjtu.yifei.base.util.NetworkUtil
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit
/**
* 类描述:
* 创建人:yifei
* 创建时间:2018/10/23
* 修改人:
* 修改时间:
* 修改备注:
*/
class OkHttpClientManager private constructor() {
companion object {
val instance: OkHttpClientManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
OkHttpClientManager()
}
}
private var clients: MutableMap<String, OkHttpClient> = HashMap()
fun getBaseClient(key: String): OkHttpClient {
var client: OkHttpClient? = clients[key]
if (client == null) {
client = getOkHttpClient()
clients[key] = client
}
return client
}
private fun getOkHttpClient(): OkHttpClient {
//添加一个log拦截器,打印所有的log
val httpLoggingInterceptor = HttpLoggingInterceptor()
//可以设置请求过滤的水平,body,basic,headers
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
return OkHttpClient.Builder()
.addInterceptor(addCacheInterceptor())
// .addInterceptor(addHeaderInterceptor())
// .addInterceptor(addQueryParameterInterceptor())
.addInterceptor(httpLoggingInterceptor) //日志,所有的请求响应度看到
.connectTimeout(60L, TimeUnit.SECONDS)
.readTimeout(60L, TimeUnit.SECONDS)
.writeTimeout(60L, TimeUnit.SECONDS)
.build()
}
/**
* 设置公共参数
*/
private fun addQueryParameterInterceptor(): Interceptor {
return Interceptor { chain ->
val originalRequest = chain.request()
val request: Request
val modifiedUrl = originalRequest.url().newBuilder()
.addQueryParameter("deviceModel", AppUtils.getMobileModel())
.build()
request = originalRequest.newBuilder().url(modifiedUrl).build()
chain.proceed(request)
}
}
/**
* 设置头
*/
private fun addHeaderInterceptor(): Interceptor {
return Interceptor { chain ->
val originalRequest = chain.request()
val requestBuilder = originalRequest.newBuilder()
// Provide your custom header here
.header("token", BaseApplication.token)
.method(originalRequest.method(), originalRequest.body())
val request = requestBuilder.build()
chain.proceed(request)
}
}
/**
* 设置缓存
*/
private fun addCacheInterceptor(): Interceptor {
return Interceptor { chain ->
var request = chain.request()
if (!NetworkUtil.isNetworkAvailable(BaseApplication.context)) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build()
}
val response = chain.proceed(request)
if (NetworkUtil.isNetworkAvailable(BaseApplication.context)) {
val maxAge = 0
// 有网络时 设置缓存超时时间0个小时 ,意思就是不读取缓存数据,只对get有用,post没有缓冲
response.newBuilder()
.header("Cache-Control", "public, max-age=$maxAge")
.removeHeader("Retrofit")// 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
.build()
} else {
// 无网络时,设置超时为4周 只对get有用,post没有缓冲
val maxStale = 60 * 60 * 24 * 28
response.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=$maxStale")
.removeHeader("nyn")
.build()
}
response
}
}
}<file_sep>/app/src/debug/java/com/sjtu/yifei/happynote/GLApplication.kt
package com.sjtu.yifei.happynote
import com.sjtu.yifei.base.BaseApplication
import com.sjtu.yifei.base.util.AppUtils
import com.sjtu.yifei.performance.PerformanceDetection
import com.sjtu.yifei.route.Routerfit
/**
* 类描述:
* 创建人:yifei
* 创建时间:2018/6/27
* 修改人:
* 修改时间:
* 修改备注:
*/
class GLApplication : BaseApplication() {
override fun onCreate() {
super.onCreate()
/**
* This process is dedicated to LeakCanary for heap analysis.
* You should not init your app in this process.
*/
if (PerformanceDetection.instance.isInAnalyzerProcess(this)) {
return
}
if (AppUtils.isAppProcess(this)) {
Routerfit.init(this)
PerformanceDetection.instance.initLeakCanary(this, true)
}
}
}<file_sep>/business/src/main/java/com/sjtu/yifei/business/bean/TabInfoBean.kt
package com.sjtu.yifei.eyes.bean
/**
* 类描述:
* 创建人:yifei
* 创建时间:2018/10/25
* 修改人:
* 修改时间:
* 修改备注:
*/
data class TabInfoBean(val tabInfo: TabInfo) {
data class TabInfo(val tabList: ArrayList<Tab>)
data class Tab(val id: Long, val name: String, val apiUrl: String)
}<file_sep>/business/src/main/java/com/sjtu/yifei/business/bean/CategoryBean.kt
package com.sjtu.yifei.eyes.bean
import java.io.Serializable
/**
* 类描述:
* 创建人:yifei
* 创建时间:2018/10/25
* 修改人:
* 修改时间:
* 修改备注:
* desc:分类 Bean
*/
data class CategoryBean(val id: Long, val name: String, val description: String, val bgPicture: String, val bgColor: String, val headerImage: String) : Serializable<file_sep>/business/src/main/java/com/sjtu/yifei/list/DetailListActivity.kt
package com.sjtu.yifei.list
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import android.widget.TextView
import com.sjtu.yifei.annotation.Route
import com.sjtu.yifei.base.BaseActivity
import com.sjtu.yifei.business.R
import com.sjtu.yifei.route.Routerfit
import com.sjtu.yifei.router.RouterPath
import com.sjtu.yifei.router.RouterService
import kotlinx.android.synthetic.main.activity_detail_list.*
@Route(path = RouterPath.LAUNCHER_DETAIL_LIST)
class DetailListActivity : BaseActivity() {
companion object {
val items = listOf(
"给初学者的RxJava2.0教程(七): Flowable",
"Android之View的诞生之谜",
"Android之自定义View的死亡三部曲之Measure",
"Using ThreadPoolExecutor in Android ",
"Kotlin 泛型定义与 Java 类似,但有着更多特性支持。",
"Android异步的姿势,你真的用对了吗?",
"Android 高质量录音库。",
"Android 边缘侧滑效果,支持多种场景下的侧滑退出。"
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail_list)
listview.layoutManager = LinearLayoutManager(this)
listview.adapter = MainAdapter(items)
}
class MainAdapter(val items : List<String>) : RecyclerView.Adapter<MainAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(TextView(parent.context))
}
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.textView.text = items[position]
holder.textView.setOnClickListener {
Routerfit.register(RouterService::class.java).openBus1Ui(position)
}
}
class ViewHolder(val textView: TextView) : RecyclerView.ViewHolder(textView)
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.sjtu.yifei.autoinject'
autoinject {
isDebug = true //是否在gradle console 中输出transform log
}
android {
compileSdkVersion versions.compileSdkVersion
defaultConfig {
applicationId "com.sjtu.yifei.happynote"
minSdkVersion versions.min_sdk
targetSdkVersion versions.target_sdk
versionCode 1
versionName "1.0"
vectorDrawables.useSupportLibrary = true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
signingConfigs {
releaseconfig {
keyAlias 'yifei'
keyPassword '<PASSWORD>'
storeFile file('keystore.jks')
storePassword '<PASSWORD>'
}
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.releaseconfig
debuggable false
jniDebuggable false
renderscriptDebuggable false
zipAlignEnabled true
}
}
dexOptions {
javaMaxHeapSize "4g"
}
lintOptions {
abortOnError false
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
kapt yifei.auto_complier
implementation project(path: ':router')
implementation project(path: ':base')
implementation project(path: ':login')
implementation project(path: ':business')
implementation project(path: ':editor')
implementation project(path: ':hybrid')
implementation project(path: ':performance')
testImplementation testSupport.junit
androidTestImplementation testSupport.testRunner
androidTestImplementation testSupport.testEspresso
}
<file_sep>/app/src/release/java/com/sjtu/yifei/happynote/GLApplication.kt
package com.sjtu.yifei.happynote
import com.sjtu.yifei.base.BaseApplication
import com.sjtu.yifei.base.util.AppUtils
import com.sjtu.yifei.route.Routerfit
/**
* 类描述:
* 创建人:yifei
* 创建时间:2018/6/27
* 修改人:
* 修改时间:
* 修改备注:
*/
class GLApplication : BaseApplication() {
override fun onCreate() {
super.onCreate()
if (AppUtils.isAppProcess(this)) {
Routerfit.init(this)
}
}
}<file_sep>/base/src/main/java/com/sjtu/yifei/base/util/LogUtil.kt
package com.sjtu.yifei.base.util
import android.util.Log
/**
* 类描述:这里可以使用任意自己熟悉或者流行的log库,而不用修改业务层的log代码
* 创建人:yifei
* 创建时间:2018/10/29
* 修改人:
* 修改时间:
* 修改备注:
*/
class LogUtil {
companion object {
// 设置为false则可以使得Log不输出
var enable: Boolean = true
fun isEnable(enable: Boolean) {
LogUtil.enable = enable
}
fun v(tag: String, msg: String) {
if (enable) {
Log.v(tag, msg)
}
}
fun d(tag: String, msg: String) {
if (enable) {
Log.d(tag, msg)
}
}
fun i(tag: String, msg: String) {
if (enable) {
Log.i(tag, msg)
}
}
fun e(tag: String, msg: String) {
if (enable) {
Log.e(tag, msg)
}
}
}
}<file_sep>/business/src/main/java/com/sjtu/yifei/business/api/RetrofitManager.kt
package com.sjtu.yifei.business.api
import com.sjtu.yifei.base.OkHttpClientManager
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
/**
* 类描述:
* 创建人:yifei
* 创建时间:2018/11/1
* 修改人:
* 修改时间:
* 修改备注:
*/
class RetrofitManager private constructor() {
companion object {
val instance: RetrofitManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
RetrofitManager()
}
}
private var retrofitBuilder: Retrofit.Builder = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(OkHttpClientManager.instance.getBaseClient("retrofit"))
fun <T> create(apiClass: Class<T>, baseUrl: String): T {
return retrofitBuilder.baseUrl(baseUrl)
.build()
.create(apiClass)
}
}<file_sep>/router/src/main/java/com/sjtu/yifei/router/RouterService.kt
package com.sjtu.yifei.router
import com.sjtu.yifei.annotation.Extra
import com.sjtu.yifei.annotation.Go
import com.sjtu.yifei.route.ActivityCallback
import com.sjtu.yifei.router.RouterPath.LAUNCHER_BUS1
import com.sjtu.yifei.router.RouterPath.LAUNCHER_DETAIL_LIST
import com.sjtu.yifei.router.RouterPath.LAUNCHER_EDITOR
import com.sjtu.yifei.router.RouterPath.LAUNCHER_HYBRID
import com.sjtu.yifei.router.RouterPath.LAUNCHER_LOGIN
interface RouterService {
@Go(LAUNCHER_LOGIN)
fun openLoginUi(@Extra callback: ActivityCallback): Boolean
@Go(LAUNCHER_EDITOR)
fun openEditorUi(): Boolean
@Go(LAUNCHER_EDITOR)
fun openEditorUi(@Extra callback: ActivityCallback): Boolean
@Go(LAUNCHER_BUS1)
fun openBus1Ui(@Extra("position") position: Int): Boolean
@Go(LAUNCHER_DETAIL_LIST)
fun openDetailList(): Boolean
@Go(LAUNCHER_HYBRID)
fun openHybridUi(@Extra("url") url: String): Boolean
@Go(LAUNCHER_HYBRID)
fun openHybridUi(@Extra("url") url: String, @Extra callback: ActivityCallback): Boolean
}<file_sep>/base/src/main/java/com/sjtu/yifei/base/util/AsyncWriteThread.kt
package com.sjtu.yifei.base.util
import android.os.Environment
import java.io.File
import java.io.IOException
import java.util.concurrent.ConcurrentLinkedQueue
import okio.Okio
/**
* 类描述:异步写入字符串到文件中
* 创建人:yifei
* 创建时间:2018/10/29
* 修改人:
* 修改时间:
* 修改备注:
*/
class AsyncWriteThread(private val dirName: String, private val fileName: String) : Thread() {
companion object {
fun init(dirName: String, fileName: String) {
val asyncWriteThread = AsyncWriteThread(dirName, fileName)
}
}
private var isRunning = false
private val lock = java.lang.Object()
var file: File? = null
private set
private val mQueue = ConcurrentLinkedQueue<String>()
val isFinish: Boolean
get() = mQueue.isEmpty() && !isRunning
init {
if (file == null) {
file = initFile()
}
if (file != null) {
isRunning = true
}
}
fun enqueue(str: String) {
mQueue.add(str)
if (!isRunning) {
awake()
}
}
/**
* 判断文件是否存在
*
* @return
*/
val isFileExist: Boolean
get() = if (file == null) {
false
} else file!!.exists() && file!!.length() > 3
/**
* 删除文件
*/
fun deleteFile(): Boolean {
return if (file == null) {
false
} else file!!.exists() && file!!.delete()
}
private fun awake() {
synchronized(lock) {
lock.notify()
}
}
override fun run() {
while (true) {
synchronized(lock) {
isRunning = true
while (!mQueue.isEmpty()) {
try {
//pop出队列的头字符串写入到文件中
write(mQueue.poll())
} catch (e: Exception) {
e.printStackTrace()
}
}
isRunning = false
try {
lock.wait()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}
}
private fun write(json: String) {
try {
if (file == null || !file!!.exists()) {
file = initFile()
}
Okio.buffer(Okio.appendingSink(file!!))
.writeUtf8(json)
.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun initFile(): File? {
if (exist()) {
val dir = File(dirName)
if (!dir.exists()) {
dir.mkdirs()
}
val file = File(this.dirName, fileName)
try {
if (!file.exists()) {
if (file.createNewFile()) {
return file
}
} else {
return file
}
} catch (e: IOException) {
e.printStackTrace()
}
}
return null
}
private fun exist(): Boolean {
return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
}
}
<file_sep>/performance/src/debug/java/com/sjtu/yifei/performance/PerformanceDetection.kt
package com.sjtu.yifei.performance
import android.app.Application
import android.support.v4.app.Fragment
import com.squareup.leakcanary.AndroidExcludedRefs
import com.squareup.leakcanary.LeakCanary
import com.squareup.leakcanary.RefWatcher
/**
* 类描述:内存泄漏配置
* 创建人:yifei
* 创建时间:2018/7/23
* 修改人:
* 修改时间:
* 修改备注:
*/
class PerformanceDetection private constructor() {
companion object {
val instance: PerformanceDetection by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
PerformanceDetection()
}
}
private var refWatcher: RefWatcher? = null
fun isInAnalyzerProcess(application: Application): Boolean {
return LeakCanary.isInAnalyzerProcess(application)
}
/**
* 观察fragment内存泄漏
* @param fragment
*/
fun watcherFragment(fragment: Fragment) {
refWatcher?.watch(fragment)
}
/**
* 必须在UI线程中初始化
*/
fun initLeakCanary(application: Application, isOpenWatcher: Boolean) {
if (BuildConfig.DEBUG && isOpenWatcher) {
if (refWatcher == null) {
val excludedRefs = AndroidExcludedRefs.createAppDefaults()
.staticField("android.view.inputmethod.InputMethodManager", "sInstance")
.instanceField("android.view.inputmethod.InputMethodManager", "mLastSrvView")
.instanceField("android.support.v7.widget.AppCompatEditText", "mContext")
.instanceField("com.android.internal.policy.DecorView", "mPressGestureDetector")
.instanceField("com.android.internal.policy.DecorView", "mContextRoot")
.instanceField("android.widget.LinearLayout", "mContext")
.instanceField("com.android.internal.policy.PhoneWindow\$DecorView", "mContext")
.instanceField("android.support.v7.widget.SearchView\$SearchAutoComplete", "mContext")
.build()
refWatcher = LeakCanary.refWatcher(application)
.excludedRefs(excludedRefs)
.listenerServiceClass(AppLeakCanaryService::class.java)
.buildAndInstall()
}
}
}
}
<file_sep>/performance/src/debug/java/com/sjtu/yifei/performance/AppLeakCanaryService.kt
package com.sjtu.yifei.performance
import com.squareup.leakcanary.AnalysisResult
import com.squareup.leakcanary.DisplayLeakService
import com.squareup.leakcanary.HeapDump
class AppLeakCanaryService : DisplayLeakService() {
override fun afterDefaultHandling(heapDump: HeapDump, result: AnalysisResult, leakInfo: String) {
super.afterDefaultHandling(heapDump, result, leakInfo)
// TODO: 2018/7/9 这里可以将内存泄漏上传到自己到服务器上
}
}
<file_sep>/build.gradle
buildscript {
apply from: 'depconfig.gradle'
addRepos(repositories)
dependencies {
classpath cp.android_gradle_plugin
classpath cp.kotlin_gradle_plugin
classpath cp.autoInject
}
repositories {
google()
}
}
allprojects {
addRepos(repositories)
}
task clean(type: Delete) {
delete rootProject.buildDir
}
<file_sep>/editor/src/main/java/com/sjtu/yifei/editor/api/ApiService.kt
package com.sjtu.yifei.editor.api
/**
* 类描述:
* 创建人:yifei
* 创建时间:2018/10/25
* 修改人:
* 修改时间:
* 修改备注:
*/
interface ApiService {
companion object {
const val BASE_URL = "http://baobab.kaiyanapp.com/api/"
}
}<file_sep>/depconfig.gradle
def versions = [:]
versions.android_gradle_plugin = '3.2.1'
versions.kotlin_version = '1.2.71'
versions.compileSdkVersion = 27
versions.min_sdk = 16
versions.target_sdk = 27
versions.build_tools = "28.0.3"
versions.support = '27.1.1'
versions.cl = '1.1.3'
versions.multidex = '1.0.2'
versions.autoApi = '1.6.0'
versions.autoComplier = '1.5.0'
versions.autoInject = '1.0.1'
versions.retrofit2 = '2.4.0'
versions.rxandroid = '2.1.0'
versions.logging_interceptor = '3.10.0'
versions.junit = '4.12'
versions.testRunner = '1.0.2'
versions.testEspresso = '3.0.2'
versions.leakcanary = '1.6.2'
ext.versions = versions
def cp = [:]
cp.android_gradle_plugin = "com.android.tools.build:gradle:$versions.android_gradle_plugin"
cp.kotlin_gradle_plugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:$versions.kotlin_version"
cp.kotlin_stdlib = "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$versions.kotlin_version"
cp.autoInject = "com.sjtu.yifei:auto-inject:$versions.autoInject"
ext.cp = cp
def support = [:]
support.annotations = "com.android.support:support-annotations:$versions.support"
support.app_compat = "com.android.support:appcompat-v7:$versions.support"
support.recyclerview = "com.android.support:recyclerview-v7:$versions.support"
support.cardview = "com.android.support:cardview-v7:$versions.support"
support.design = "com.android.support:design:$versions.support"
support.v4 = "com.android.support:support-v4:$versions.support"
support.cl = "com.android.support.constraint:constraint-layout:$versions.cl"
ext.support = support
def yifei = [:]
yifei.auto_complier = "com.sjtu.yifei:auto-complier:$versions.autoComplier"
yifei.auto_api = "com.sjtu.yifei:auto-api:$versions.autoApi"
ext.yifei = yifei
// retrofit & rxandroid
def net = [:]
net.retrofit = "com.squareup.retrofit2:retrofit:$versions.retrofit2"
net.adapter_rxjava2 = "com.squareup.retrofit2:adapter-rxjava2:$versions.retrofit2"
net.converter_gson = "com.squareup.retrofit2:converter-gson:$versions.retrofit2"
net.rxandroid = "io.reactivex.rxjava2:rxandroid:$versions.rxandroid"
net.logging_interceptor = "com.squareup.okhttp3:logging-interceptor:$versions.logging_interceptor"
ext.net = net
def canary = [:]
canary.leakcanary_android = "com.squareup.leakcanary:leakcanary-android:$versions.leakcanary"
canary.leakcanary_android_no_op = "com.squareup.leakcanary:leakcanary-android-no-op:$versions.leakcanary"
canary.leakcanary_support_fragment = "com.squareup.leakcanary:leakcanary-support-fragment:$versions.leakcanary"
ext.canary = canary
def testSupport = [:]
testSupport.junit = "junit:junit:$versions.junit"
testSupport.testRunner = "com.android.support.test:runner:$versions.testRunner"
testSupport.testEspresso = "com.android.support.test.espresso:espresso-core:$versions.testEspresso"
ext.testSupport = testSupport
def addRepos(RepositoryHandler handler) {
handler.maven { url 'https://dl.bintray.com/iyifei/maven' }
handler.maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
handler.maven { url "https://jitpack.io" }
handler.mavenCentral()
handler.google()
handler.jcenter()
}
ext.addRepos = this.&addRepos<file_sep>/base/src/main/java/com/sjtu/yifei/base/BaseApplication.kt
package com.sjtu.yifei.base
import android.app.Application
import android.content.Context
import kotlin.properties.Delegates
/**
* 类描述:
* 创建人:yifei
* 创建时间:2018/6/27
* 修改人:
* 修改时间:
* 修改备注:
*/
open class BaseApplication : Application() {
companion object {
var context: Context by Delegates.notNull()
var token: String by Delegates.notNull()
}
override fun onCreate() {
super.onCreate()
context = applicationContext
token = ""
}
override fun onTerminate() {
super.onTerminate()
}
}<file_sep>/hybrid/src/main/java/com/sjtu/yifei/hybrid/HybridActivity.kt
package com.sjtu.yifei.hybrid
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.text.TextUtils
import android.view.*
import android.webkit.*
import com.sjtu.yifei.annotation.Route
import com.sjtu.yifei.base.BaseActivity
import com.sjtu.yifei.base.util.FileUtil
import com.sjtu.yifei.base.util.LogUtil
import com.sjtu.yifei.base.util.NetworkUtil
import com.sjtu.yifei.base.util.setupActionBar
import com.sjtu.yifei.hybrid.web.BridgeWebView
import com.sjtu.yifei.hybrid.web.BridgeWebViewClient
import com.sjtu.yifei.router.RouterPath
import kotlinx.android.synthetic.main.hybrid_activity.*
import java.io.File
@Route(path = RouterPath.LAUNCHER_HYBRID)
class HybridActivity : BaseActivity() {
companion object {
const val EXTRA_SEARCH_KEY = "url"
}
private lateinit var webView: BridgeWebView
private var mUrl: String = ""
private var currentTime: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
currentTime = System.currentTimeMillis()
setContentView(R.layout.hybrid_activity)
setupActionBar(R.id.toolbar) {
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
}
mUrl = intent.getStringExtra(EXTRA_SEARCH_KEY)
webView = BridgeWebView(applicationContext)
webView_root.addView(webView,0,ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
initWebSettings()
initWebViewClient()
initWebChromeClient()
if (!TextUtils.isEmpty(mUrl)) {
if (mUrl.startsWith("www.")) {
mUrl = "https://$mUrl"
}
webView.loadUrl(mUrl)
}
}
@SuppressLint("SetJavaScriptEnabled")
private fun initWebSettings() {
webView.removeJavascriptInterface("searchBoxJavaBridge_")
webView.removeJavascriptInterface("accessibilityTraversal")
webView.removeJavascriptInterface("accessibility")
val settings = webView.settings
//支持JS
settings.javaScriptEnabled = true
//设置适应屏幕
settings.useWideViewPort = true
settings.loadWithOverviewMode = true
//支持缩放
settings.setSupportZoom(false)
//隐藏原生的缩放控件
settings.displayZoomControls = false
//支持内容重新布局
settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
settings.supportMultipleWindows()
settings.setSupportMultipleWindows(true)
//设置缓存模式
settings.domStorageEnabled = true
settings.databaseEnabled = true
settings.cacheMode = WebSettings.LOAD_DEFAULT
settings.setAppCacheEnabled(true)
val cacheDir = FileUtil.getCacheDir(webView.context)
settings.setAppCachePath("$cacheDir${File.separator}webAppCache")
LogUtil.e(TAG, "WebView file path is $cacheDir${File.separator}webAppCache")
//设置可访问文件
settings.allowFileAccess = true
//支持获取手势焦点
webView.requestFocusFromTouch()
//当webview调用requestFocus时为webview设置节点
settings.setNeedInitialFocus(true)
//支持自动加载图片
settings.loadsImagesAutomatically = Build.VERSION.SDK_INT >= 19
settings.setNeedInitialFocus(true)
//设置编码格式
settings.defaultTextEncodingName = "UTF-8"
if (NetworkUtil.isNetworkAvailable(this.applicationContext)) {
settings.cacheMode = WebSettings.LOAD_DEFAULT
} else {
settings.cacheMode = WebSettings.LOAD_CACHE_ONLY
}
/* if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
settings.safeBrowsingEnabled = true
}*/
}
private fun initWebViewClient() {
webView.webViewClient = object : BridgeWebViewClient(webView) {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
currentTime = System.currentTimeMillis()
progressBar.visibility = View.VISIBLE
}
override fun onCustomPageFinished(view: WebView?, url: String?) {
super.onCustomPageFinished(view, url)
progressBar.progress = 100
progressBar.visibility = View.GONE
LogUtil.d(TAG, "HybridActivity load web view cost:${System.currentTimeMillis() - currentTime}")
}
override fun onCustomShouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return true
}
@RequiresApi(Build.VERSION_CODES.M)
override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
super.onReceivedError(view, request, error)
LogUtil.e(TAG, "onReceivedError: ${error?.errorCode} -> ${error?.description}")
}
@TargetApi(Build.VERSION_CODES.M)
override fun onReceivedHttpError(view: WebView?, request: WebResourceRequest?, errorResponse: WebResourceResponse?) {
super.onReceivedHttpError(view, request, errorResponse)
LogUtil.e(TAG, "onReceivedHttpError: ${errorResponse?.statusCode} -> ${errorResponse?.reasonPhrase}")
}
override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
super.onReceivedSslError(view, handler, error)
LogUtil.e(TAG, "onReceivedSslError: ${error?.toString()}")
}
}
}
private fun initWebChromeClient() {
webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
progressBar.progress = newProgress - 5
}
override fun onReceivedTitle(view: WebView?, title: String?) {
super.onReceivedTitle(view, title)
setTitle(title)
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.hybrid_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return when (item?.itemId) {
R.id.hybrid_menu_refresh -> {
webView.reload()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed()
return true
}
return super.onKeyDown(keyCode, event)
}
override fun onBackPressed() {
if (webView.canGoBack()) {
webView.goBack()
} else {
super.onBackPressed()
}
}
override fun onDestroy() {
super.onDestroy()
webView_root.removeView(webView)
webView.removeAllViews()
webView.destroy()
}
}
<file_sep>/business/src/main/java/com/sjtu/yifei/business/Bus1Activity.kt
package com.sjtu.yifei.business
import android.os.Bundle
import com.sjtu.yifei.annotation.Route
import com.sjtu.yifei.base.BaseActivity
import com.sjtu.yifei.base.util.LogUtil
import com.sjtu.yifei.base.util.setupActionBar
import com.sjtu.yifei.business.api.ApiService
import com.sjtu.yifei.eyes.bean.HomeBean
import com.sjtu.yifei.router.RouterPath
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_bus1.*
@Route(path = RouterPath.LAUNCHER_BUS1)
class Bus1Activity : BaseActivity() {
companion object {
const val EXTRA_POSITION = "position"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bus1)
setupActionBar(R.id.toolbar) {
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
}
val position = intent.getIntExtra(EXTRA_POSITION, -1)
tv1.text = "position: $position"
subscribe(ApiService.apiService.getFirstHomeData()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<HomeBean>() {
override fun onComplete() {
}
override fun onNext(t: HomeBean) {
LogUtil.d(TAG, t.toString())
}
override fun onError(e: Throwable) {
}
}))
}
}
<file_sep>/base/build.gradle
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion versions.compileSdkVersion
defaultConfig {
minSdkVersion versions.min_sdk
targetSdkVersion versions.target_sdk
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
api fileTree(dir: 'libs', include: ['*.jar'])
api cp.kotlin_stdlib
// Support libraries
api support.annotations
api support.app_compat
api support.recyclerview
api support.cardview
api support.design
api support.v4
api support.cl
// retrofit & rxandroid
api net.retrofit
api net.adapter_rxjava2
api net.converter_gson
api net.rxandroid
api net.logging_interceptor
testImplementation testSupport.junit
androidTestImplementation testSupport.testRunner
androidTestImplementation testSupport.testEspresso
}
<file_sep>/editor/src/main/java/com/sjtu/yifei/editor/ui/EditorActivity.kt
package com.sjtu.yifei.editor.ui
import android.os.Bundle
import android.widget.Toast
import com.sjtu.yifei.annotation.Route
import com.sjtu.yifei.base.BaseActivity
import com.sjtu.yifei.base.util.setupActionBar
import com.sjtu.yifei.editor.R
import com.sjtu.yifei.route.ActivityCallback
import com.sjtu.yifei.route.Routerfit
import com.sjtu.yifei.router.RouterPath.LAUNCHER_EDITOR
import com.sjtu.yifei.router.RouterService
import kotlinx.android.synthetic.main.content_editor.*
@Route(path = LAUNCHER_EDITOR)
open class EditorActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_editor)
setupActionBar(R.id.toolbar) {
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
}
initData()
}
private fun initData() {
tv.setOnClickListener {
Routerfit.register(RouterService::class.java).openHybridUi("https://www.taobao.com", ActivityCallback { result, data ->
Toast.makeText(MainActivity@ this.baseContext, "${result == Routerfit.RESULT_OK} $data", Toast.LENGTH_SHORT).show()
})
}
tv_finish_success.setOnClickListener {
Routerfit.setResult(Routerfit.RESULT_OK, "调用 editor 成功")
finish()
}
}
}<file_sep>/router/src/main/java/com/sjtu/yifei/router/RouterPath.kt
package com.sjtu.yifei.router
object RouterPath {
const val LAUNCHER_LOGIN = "login/LoginActivity"
const val LAUNCHER_EDITOR = "editor/EditorActivity"
const val LAUNCHER_BUS1 = "business/Bus1Activity"
const val LAUNCHER_DETAIL_LIST = "business/DetailListActivity"
const val LAUNCHER_HYBRID = "hybrid/HybridActivity"
}<file_sep>/base/src/main/java/com/sjtu/yifei/base/BaseActivity.kt
package com.sjtu.yifei.base
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
/**
* 类描述:
* 创建人:yifei
* 创建时间:2018/6/27
* 修改人:
* 修改时间:
* 修改备注:
*/
open class BaseActivity : AppCompatActivity() {
var TAG = this.javaClass.simpleName
private var mCompositeDisposable: CompositeDisposable? = null
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
val id = item?.itemId
if (android.R.id.home == id) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
override fun onDestroy() {
unSubscribe()
super.onDestroy()
}
/**
* 优化rx 内存泄漏问题
*
* @param disposable
*/
fun subscribe(disposable: Disposable?) {
if (disposable != null) {
if (mCompositeDisposable == null) {
mCompositeDisposable = CompositeDisposable()
}
mCompositeDisposable?.add(disposable)
}
}
/**
* 优化rx 内存泄漏问题
*/
private fun unSubscribe() {
if (mCompositeDisposable != null) {
mCompositeDisposable?.clear()
}
}
}<file_sep>/app/src/main/java/com/sjtu/yifei/happynote/MainActivity.kt
package com.sjtu.yifei.happynote
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.widget.Toast
import com.sjtu.yifei.base.BaseActivity
import com.sjtu.yifei.base.util.setupActionBar
import com.sjtu.yifei.route.ActivityCallback
import com.sjtu.yifei.route.Routerfit
import com.sjtu.yifei.router.RouterService
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : BaseActivity() {
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
message.setText(R.string.title_home)
type_navigation = R.id.navigation_home
return@OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
message.setText(R.string.title_dashboard)
type_navigation = R.id.navigation_dashboard
return@OnNavigationItemSelectedListener true
}
R.id.navigation_notifications -> {
message.setText(R.string.title_notifications)
type_navigation = R.id.navigation_notifications
return@OnNavigationItemSelectedListener true
}
}
false
}
private var type_navigation: Int = R.id.navigation_home
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setupActionBar(R.id.toolbar) {
setDisplayHomeAsUpEnabled(false)
setDisplayShowHomeEnabled(true)
setTitle(R.string.app_name)
}
message.setOnClickListener {
when (type_navigation) {
R.id.navigation_home -> Routerfit.register(RouterService::class.java).openDetailList()
R.id.navigation_dashboard -> Routerfit.register(RouterService::class.java).openEditorUi(ActivityCallback { result, data ->
Toast.makeText(MainActivity@ this, "${result == Routerfit.RESULT_OK} $data", Toast.LENGTH_SHORT).show()
})
R.id.navigation_notifications -> Routerfit.register(RouterService::class.java).openHybridUi("www.baidu.com")
}
}
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
}
}
<file_sep>/base/src/main/java/com/sjtu/yifei/base/util/FileUtil.kt
package com.sjtu.yifei.base.util
import android.content.Context
import android.os.Environment
/**
* 类描述:
* 创建人:yifei
* 创建时间:2018/11/1
* 修改人:
* 修改时间:
* 修改备注:
*/
class FileUtil {
companion object {
/**
* /data/data/com.xxx.xxx/cache
*/
fun getCacheDir(context: Context): String {
return if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
|| !Environment.isExternalStorageRemovable())
context.externalCacheDir!!.path
else
context.cacheDir.path
}
/**
* /data/data/com.xxx.xxx/files
*/
fun getFilesDir(context: Context): String {
return if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
|| !Environment.isExternalStorageRemovable())
context.externalCacheDir!!.path
else
context.filesDir.path
}
}
}<file_sep>/business/src/main/java/com/sjtu/yifei/business/api/ApiService.kt
package com.sjtu.yifei.business.api
import com.sjtu.yifei.eyes.bean.AuthorInfoBean
import com.sjtu.yifei.eyes.bean.CategoryBean
import com.sjtu.yifei.eyes.bean.HomeBean
import com.sjtu.yifei.eyes.bean.TabInfoBean
import io.reactivex.Observable
import retrofit2.http.GET
import retrofit2.http.Query
import retrofit2.http.Url
/**
* 类描述:https://github.com/git-xuhao/KotlinMvp
* 创建人:yifei
* 创建时间:2018/10/25
* 修改人:
* 修改时间:
* 修改备注:
*/
interface ApiService {
companion object {
private const val BASE_URL = "http://baobab.kaiyanapp.com/api/"
val apiService: ApiService by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
RetrofitManager.instance.create(ApiService::class.java, BASE_URL)
}
}
/**
* 首页精选
*/
@GET("v2/feed")
fun getFirstHomeData(): Observable<HomeBean>
/**
* 根据 nextPageUrl 请求数据下一页数据
*/
@GET
fun getMoreHomeData(@Url url: String): Observable<HomeBean>
/**
* 根据item id获取相关视频
*/
@GET("v4/video/related?")
fun getRelatedData(@Query("id") id: Long): Observable<HomeBean.Issue>
/**
* 获取分类
*/
@GET("v4/categories")
fun getCategory(): Observable<ArrayList<CategoryBean>>
/**
* 获取分类详情List
*/
@GET("v4/categories/videoList?")
fun getCategoryDetailList(@Query("id") id: Long): Observable<HomeBean.Issue>
/**
* 获取更多的 Issue
*/
@GET
fun getIssueData(@Url url: String): Observable<HomeBean.Issue>
/**
* 获取全部排行榜的Info(包括,title 和 Url)
*/
@GET("v4/rankList")
fun getRankList(): Observable<TabInfoBean>
/**
* 获取搜索信息
*/
@GET("v1/search?&num=10&start=10")
fun getSearchData(@Query("query") query: String): Observable<HomeBean.Issue>
/**
* 热门搜索词
*/
@GET("v3/queries/hot")
fun getHotWord(): Observable<ArrayList<String>>
/**
* 关注
*/
@GET("v4/tabs/follow")
fun getFollowInfo(): Observable<HomeBean.Issue>
/**
* 作者信息
*/
@GET("v4/pgcs/detail/tab?")
fun getAuthorInfo(@Query("id") id: Long): Observable<AuthorInfoBean>
}<file_sep>/settings.gradle
include ':app', ':base', ':router', ':editor', ':hybrid', ':business', ':login', ':performance'
| 757d4a541918cae349381ee16cd6ec3b4867e2bc | [
"Java",
"Kotlin",
"Gradle"
] | 30 | Kotlin | superchengwisdom/HappyNote | 9ad49e5c28d6aae0c45e3f64eeee5f5b6d7124f1 | fe467e4dd844aa982de47e2d585fa53c040d4696 |
refs/heads/master | <repo_name>cjaiswal131/OpenCV<file_sep>/camera_blocked_outfocus/blur_degree.py
import cv2
def variance_of_laplacian(image):
return cv2.Laplacian(image, cv2.CV_64F).var()
cap = cv2.VideoCapture(0)
if cap.isOpened():
ret, frame = cap.read()
else:
ret =False
while True:
ret, frame = cap.read()
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fm = variance_of_laplacian(gray_frame)
text = "focused"
if fm < 50:
text = 'defocused'
cv2.putText(frame, text, (5, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
cv2.putText(frame, "{}: {:.2f}".format('blur degree', fm), (5, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 3)
cv2.imshow("frame", frame)
if cv2.waitKey(30) == 27 & 0xff:
break
cap.release()
cv2.destroyAllWindows()
<file_sep>/MotionTrackingDetecting.py
import cv2
import numpy as np
def motionDetection():
cap = cv2.VideoCapture(0)
cap.set(3,800)
cap.set(4,600)
if cap.isOpened():
ret, frame = cap.read()
else:
ret = False
ret, frame1 = cap.read()
ret, frame2 = cap.read()
while(ret):
d = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(d, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
ret, th = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
dilated = cv2.dilate(th, np.ones((3,3), np.uint8), iterations=10)
eroded = cv2.erode(dilated, np.ones((3, 3), np.uint8), iterations=10)
c, h = cv2.findContours(eroded, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(frame1, c, -1, (0,0,255), 2)
cv2.imshow('original', frame2)
cv2.imshow('contours', frame1)
if cv2.waitKey(1)==27:
break
frame1=frame2
ret, frame2 = cap.read()
cv2.destroyAllWindows()
cap.release()
if __name__=="__main__":
motionDetection()<file_sep>/camera_blocked_outfocus/camera_tampering_detection.py
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
kernel = np.ones((5, 5), np.uint8)
while (True):
ret, frame = cap.read()
if (frame is None):
print("End of frame")
break
else:
a = 0
bounding_rect = []
fgmask = fgbg.apply(frame)
fgmask = cv2.erode(fgmask, kernel, iterations=5)
fgmask = cv2.dilate(fgmask, kernel, iterations=5)
cv2.imshow('frame', frame)
contours, _ = cv2.findContours(fgmask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for i in range(0, len(contours)):
bounding_rect.append(cv2.boundingRect(contours[i]))
for i in range(0, len(contours)):
if bounding_rect[i][2] >= 40 or bounding_rect[i][3] >= 40:
a = a + (bounding_rect[i][2]) * bounding_rect[i][3]
if (a >= int(frame.shape[0]) * int(frame.shape[1]) / 3):
cv2.putText(frame, "TAMPERING DETECTED", (5, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
cv2.imshow('frame', frame)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()<file_sep>/Frozen&Black_pictures.py
import cv2
import os
# function to check given image is black image or frozen image
def black_and_frozen_image():
# image path on my local directory
path1 = 'images/frozen4.jpeg'
frozen_img = cv2.imread(path1, 1)
for file_type in ['neg']:
for img in os.listdir(file_type):
try:
current_image_path = str(file_type) + '/' + str(img)
match = cv2.imread(current_image_path)
if frozen_img.shape == match.shape:
cv2.imshow('frozen_image', frozen_img)
else:
cv2.imshow('black_image', match)
except Exception as e:
print(str(e))
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
black_and_frozen_image()
<file_sep>/face_detection.py
# importing cv2 library
import cv2
# drawing rectangular boundary on face, mouth, eyes
def draw_boundary(img, classifier, scalFactor, minNeighbors, color, text):
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
features = classifier.detectMultiScale(gray_img, scalFactor, minNeighbors)
coords = []
for (x, y, w, h) in features:
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, text, (x, y - 4), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 1, cv2.LINE_AA)
coords = [x, y, w, h]
return coords
# detecting face, mouth, nose, eyes
def detect(img, faceCascade, eyeCascade, noseCascade, mouthCascade):
color = {"blue": (255, 0, 0), "red": (0, 0, 255), "green": (0, 255, 0), "white": (255, 255, 255)}
coords = draw_boundary(img, faceCascade, 1.1, 10, color['blue'], "Face")
if len(coords) == 4:
roi_img = img[coords[1]:coords[1] + coords[3], coords[0]:coords[0] + coords[2]]
coords = draw_boundary(roi_img, eyeCascade, 1.1, 14, color['red'], "eye")
coords = draw_boundary(roi_img, noseCascade, 1.1, 10, color['green'], "nose")
coords = draw_boundary(roi_img, mouthCascade, 1.1, 20, color['white'], "mouth")
return img
# different classifier path
faceCascade = cv2.CascadeClassifier('opencv-master/data/haarcascades/haarcascade_frontalface_default.xml')
eyeCascade = cv2.CascadeClassifier('opencv-master/data/haarcascades/haarcascade_eye.xml')
noseCascade = cv2.CascadeClassifier('opencv-master/data/haarcascades/nariz.xml')
mouthCascade = cv2.CascadeClassifier('opencv-master/data/haarcascades/mouth.xml')
cap = cv2.VideoCapture(-1)
while True:
_, img = cap.read()
img = detect(img, faceCascade, eyeCascade, noseCascade, mouthCascade)
cv2.imshow('face_detection', img)
if cv2.waitKey(1) == 27:
break
cv2.destroyAllWindows()
cap.release()
<file_sep>/Hand_gesture_image.py
import cv2
# function to find hand gesture in images
def main():
img = cv2.imread('images/hand.png')
hand_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, th = cv2.threshold(hand_img, 75, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(th, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
hull = [cv2.convexHull(c) for c in contours]
final = cv2.drawContours(hand_img, hull, -1, (255, 0, 0))
cv2.imshow('original', img)
cv2.imshow('thresholded', th)
cv2.imshow('final', final)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
<file_sep>/extract images from video.py
import cv2
import os
try:
# creating a folder named data
print('folder created')
if not os.path.exists('data'):
os.makedirs('data')
except OSError:
print ('Error: Creating directory of data')
cam = cv2.VideoCapture("/home/hinclude/opencv_project/videos/tum hi ho.mp4")
currentframe = 0
while True:
ret, frame = cam.read()
if ret:
# if video is still left continue creating images
name = './data/frame' + str(currentframe) + '.jpg'
print ('Creating...' + name)
cv2.imwrite(name, frame)
currentframe += 1
else:
break
if cv2.waitKey(1) == 27:
break
cam.release()
cv2.destroyAllWindows()<file_sep>/camera_blocked_outfocus/motion and blur detection.py
import cv2
import numpy as np
def variance_of_laplacian(image):
return cv2.Laplacian(image, cv2.CV_64F).var()
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
fgbg = cv2.createBackgroundSubtractorMOG2()
kernel = np.ones((3, 3), np.uint8)
while True:
ret, frame = cap.read()
if (frame is None):
print("camera is blocked")
break
else:
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
a = 0
bounding_rect = []
fgmask = fgbg.apply(frame)
fgmask = cv2.erode(fgmask, kernel, iterations=5)
fgmask = cv2.dilate(fgmask, kernel, iterations=5)
fm = variance_of_laplacian(gray_frame)
contours, _ = cv2.findContours(fgmask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for i in range(0, len(contours)):
bounding_rect.append(cv2.boundingRect(contours[i]))
for i in range(0, len(contours)):
if bounding_rect[i][2] >= 40 or bounding_rect[i][3] >= 40:
a = a + (bounding_rect[i][2]) * bounding_rect[i][3]
if fm < 40 or (a >= int(frame.shape[0]) * int(frame.shape[1]) / 3):
cv2.putText(frame, "defocused", (5, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
cv2.putText(frame, "{}: {:.2f}".format('blur degree', fm), (5, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 3)
cv2.imshow('frame', frame)
if cv2.waitKey(30) == 27 & 0xff:
break
cap.release()
cv2.destroyAllWindows()<file_sep>/background_reduction.py
import cv2
# reading video clip
cap = cv2.VideoCapture('videos/tum hi ho.mp4')
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
if ret == True:
cv2.imshow("original", frame)
cv2.imshow("fg", fgmask)
else:
ret = False
if cv2.waitKey(30) == 27:
break
# releasing video capturing and destroying reading windows
cap.release()
cv2.destroyAllWindows()
<file_sep>/dense_detection.py
# importing libraries
import numpy as np
import cv2
def detect(frame, step_size, feature_scale, frame_vound):
detector = cv2.FastFeatureDetector_create()
return detector.detect(frame)
# capturing live video
cap = cv2.VideoCapture(0)
if cap.isOpened():
ret, frame = cap.read()
else:
ret = False
while True:
ret, frame = cap.read()
frame_sift = np.copy(frame)
gray_frame = cv2.cvtColor(frame_sift, cv2.COLOR_BGR2GRAY)
keypoints = detect(frame, 20, 20, 5)
dense_frame = cv2.drawKeypoints(gray_frame, keypoints, cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
cv2.imshow('original frame', frame)
cv2.imshow('dense frame', dense_frame)
if cv2.waitKey(1) == 27:
break
# releasing video capturing variable and destroying video window
cap.release()
cv2.destroyAllWindows()
| 74096184033bf404f5ba374f63d6e7eb8ec5e8cb | [
"Python"
] | 10 | Python | cjaiswal131/OpenCV | e037d1902601e77c932e67a069fc439287895a94 | 33db565fecd493fbca65e5d8065e6641b8a07133 |
refs/heads/master | <repo_name>aospiridonov/MyFirstProgrammTcp<file_sep>/src/robotmanipulation.cpp
#include "robotmanipulation.h"
#include <QTimer>
RobotManipulation::RobotManipulation(QObject *parent) : QObject(parent)
{
}
void RobotManipulation::connect()
{
mSocket.connectToHost(QString("192.168.77.1"), 4444);
if (!mSocket.waitForConnected(3000)) {
// If not, warn user.
qDebug() <<"Connection failed.";
} else {
qDebug() <<"Ok, connection is established";
}
}
void RobotManipulation::connectIP(const QString &ipDevice)
{
mSocket.connectToHost(ipDevice, 4444);
if (!mSocket.waitForConnected(3000)) {
// If not, warn user.
qDebug() <<"Connection failed.";
} else {
qDebug() <<"Ok, connection is established";
}
}
void RobotManipulation::connectIPport(const QString &ipDevice, quint16 port)
{
mSocket.connectToHost(ipDevice, port);
if (!mSocket.waitForConnected(3000)) {
qDebug() <<"Connection failed.";
} else {
qDebug() <<"Ok, connection is established";
}
}
void RobotManipulation::sendCommand(const QString &action)
{
if (mSocket.state() != QTcpSocket::ConnectedState) {
qDebug() <<"send failed.";
return;
}
if (mSocket.write((action + "\n").toLatin1()) == -1) {
qDebug() <<"Connection failed.";
}
}
RobotManipulation::~RobotManipulation()
{
mSocket.disconnectFromHost();
mSocket.waitForDisconnected(3000);
}
<file_sep>/src/robotmanipulation.h
#ifndef ROBOTMANIPULATION_H
#define ROBOTMANIPULATION_H
#include <QObject>
#include <QtNetwork/QTcpSocket>
#include <QDebug>
class RobotManipulation : public QObject
{
Q_OBJECT
public:
explicit RobotManipulation(QObject *parent = 0);
~RobotManipulation();
QTcpSocket mSocket;
Q_INVOKABLE void connect();
Q_INVOKABLE void connectIP(const QString &ipDevice);
Q_INVOKABLE void connectIPport(const QString &ipDevice, quint16 port);
Q_INVOKABLE void sendCommand(const QString &action);
signals:
public slots:
};
#endif // ROBOTMANIPULATION_H
| d9e899a047ea1c1b1352ecbd1e4f1a73b7eca31e | [
"C++"
] | 2 | C++ | aospiridonov/MyFirstProgrammTcp | 891887c0d4b44d437e73726a89f38f35b6e00b58 | 8a9021a58794dd39c32b11ef724564610843fd7f |
refs/heads/master | <repo_name>guivahl/instagram-bot<file_sep>/config-example.py
username="YOUR_LOGIN_HERE"
password="<PASSWORD>"
users_to_follow=[
"FIRST_USER_FOLLOWERS",
"OTHER_USER_FOLLOWERS"
]
white_list=[
"STILL_FOLLOW_THIS_USER",
"THIS_ONE_TOO"
]
<file_sep>/constants.py
ONE_MINUTE_TO_SECONDS = 60
ONE_HOUR_TO_SECONDS = 60 * ONE_MINUTE_TO_SECONDS
ONE_DAY_TO_SECONDS = 24 * ONE_HOUR_TO_SECONDS
<file_sep>/README.md
# Instagram Bot
An Instagram bot that follows an other user followers and unfollow users who didn't follow you back.
### Prerequisites
You will need to have installed:
```
Python3
Pip
Instapy
```
## Getting Started
Rename the "config-example.py" file to "config.py" and set your credentials:
* The "username" and "password" are from Instagram login.
* On "users_to_follow" you should put the list of users the script will use to get new followers.
* On the "white_list" you can put the users that don't follow your account, but you still want to follow them anyway.
To run the script:
```sh
python -u path/to/main.py
```
## Documentation
* [Instapy](https://github.com/timgrossmann/InstaPy) - Used to connect and manage Instagram features
<file_sep>/main.py
from instapy import InstaPy
import config
import constants
session = InstaPy(username=config.username, password=<PASSWORD>)
session.login()
session.set_skip_users(
skip_private=False,
skip_no_profile_pic=True,
no_profile_pic_percentage=100,
skip_business=True,
business_percentage=100
)
user_nonfollowers=session.pick_nonfollowers(username=config.username, live_match=True, store_locally=True)
filtered_user_nonfollowers=list(set(user_nonfollowers) - set(config.white_list))
session.follow_user_followers(
config.users_to_follow,
amount=5,
randomize=False,
sleep_delay=constants.ONE_MINUTE_TO_SECONDS
)
session.unfollow_users(
amount=20,
custom_list_enabled=True,
custom_list=filtered_user_nonfollowers,
style="RANDOM",
unfollow_after=(3 * constants.ONE_DAY_TO_SECONDS),
sleep_delay=constants.ONE_MINUTE_TO_SECONDS
)
session.end() | d83bd478d2602544ba8ac96d9894618525c29135 | [
"Markdown",
"Python"
] | 4 | Python | guivahl/instagram-bot | d6827d24f8a9f3d7ef750fa995ec67c1a0c79574 | aaee122837715dbc0b481e91c4f8bef269d533c1 |
refs/heads/master | <file_sep>import React from 'react'
import "./Form.css";
import { useHistory } from 'react-router';
import Header from '../header';
const FormSuccess = () => {
const history = useHistory();
const navigateTo = () => history.push('/dashboard');
const thankyouContainer={
position: `absolute`,
width: `100px`,
height: `516px`,
bleft: `193px`,
top: `200px`,
}
const thankyou={
position: `absolute`,
width: `643px`,
height: `72px`,
left:`400px`,
top: `2px`,
fontFamily:` Poppins`,
fontStyle: `normal`,
fontWeight:`500`,
fontSize:`48px`,
lineHeight:`72px`,
/* identical to box height */
color:`#8FC3FA`,
}
const midtext={
position: `absolute`,
width: `1053px`,
height: `224px`,
left: `110px`,
top: `58px`,
fontFamily: `Poppin`,
fontStyle: `normal`,
fontWeight: `normal`,
fontSize: `30px`,
lineHeight: `45px`,
display: `flex`,
alignItems: `center`,
textAlign: `center`,
color: `#000000`,
}
const button ={
position: `absolute`,
width: `401px`,
height: `58px`,
left: `225px`,
top: `150px`,
borderWidth:1,
borderColor:'#8FC3FA`',
borderRadius:50,
fontFamily:`Poppins`,
fontStyle: `normal`,
fontWeight: `600`,
fontSize: `24px`,
lineHeight: `36px`,
display: `flex`,
alignItems: `center`,
textAlign:'center',
justifyContent: 'center',
color: `#8FC3FA`,
backgroundcolor: `white`,
}
return (
<>
<Header/>
<div style= {thankyouContainer}>
<div style={thankyou}> Thank You for your opinion</div>
<div style={midtext} >Your survey will be reviewed and your reward points will be provided to your domble account. You can review your reward points in ‘Total Rewards’ section of your dashboard</div>
<div style = {button}>
<input type= 'button'
style={button}
name= 'submit1'
value='Take me to my dashboard'
href='#'
onClick={navigateTo}
/>
</div>
</div>
</>
)
}
export default FormSuccess;<file_sep>import React,{Component} from 'react';
class SocialMedia extends Component{
render(){
const btn3={
background:"rgba(255,255,255,0)",
borderWidth:0,
width:'64px',
height:'64px',
borderRadius:'64px'
}
const icon_container={
margin:0,
width:'420px',
display:'flex',
justifyContent:'center'
}
return (
<>
<div style={icon_container}>
<button style={btn3}> <img src="./images/twitterlogo.png"></img></button>
<button style={btn3}> <img src="./images/facebooklogo.png"></img></button>
<button style={btn3}> <img src="./images/googlelogo.png"></img></button>
</div>
</>
);
}
}
export default SocialMedia; <file_sep>
import React, {Component} from 'react';
class ThankYou extends Component{
handleclickok=()=>{
this.props.history.push("/");
}
render(){
const conatiner={
width:"100vw",
height:"100vh",
display:'flex',
flexDirection:"column",
alignItems:'center',
position:'relative'
}
const thank={
textAlign:"center",
color:"#8FC3FA",
fontSize:"70px",
fontWeight:500,
position:'absolute',
top:'300px'
}
const text={
fontSize:"24px",
fontWeight:"bold",
textAlign:'center'
}
const btn={
width:"140px",
height:"50px",
color:'white',
backgroundColor:"#2B6777",
borderRadius:"20px",
borderWidth:"0px",
position:"absolute",
right:"20px",
bottom:"30px"
}
const img_btn={
position:'absolute',
bottom:"10px",
left:"20px"
}
return (
<div style={conatiner}>
<svg width="100vw" height="350" viewBox="0 0 1440 200" fill="none" xmlns="http://www.w3.org/2000/svg">
<ellipse cx="720" cy="-100" rx="50vw" ry="300" fill="#2B6777"/>
</svg>
<div style={thank}>Thanks!</div>
<div style={{position:'absolute',top:'400px'}}>
<div style={text}>Thank you for your patience and for completing our sign up form. </div>
<div style={text}>Your account will be verifed soon and your Domble ID will be sent to your email</div>
</div>
<div style={img_btn}>
<img src="./images/send.png" alt=""/>
</div>
<button style={btn} onClick={this.handleclickok}>OK</button>
</div>
);
}
}
export default ThankYou;
<file_sep>import React,{Component} from 'react';
import { Link } from 'react-router-dom';
import Profile from '../profile/profile'
;class FormHeader extends Component{
render(){
const header_style={
height:'150px',
backgroundColor:'#2B6777',
position:'relative',
display:'flex',
alignItems:'center'
}
const navbar={
position:'absolute',
display:'flex',
right:'100px'
}
const domblestyle={
fontSize:'68px',
color:'#5C5C5C',
marginLeft:'100px'
}
const navitem={
width:'110px',
color:'white',
textDecoration:'none'
}
return (
<div style={header_style}>
<div style={domblestyle}>
Domble
</div>
<div style={navbar}>
<div style={navitem}>Home</div>
<Link style={navitem} to={"/aboutus"}>About Us</Link>
<Link style={navitem} to={"/profile"}>DashBoard</Link>
</div>
</div>
);
}
}
export default FormHeader;<file_sep>import React,{Component} from 'react';
import FormNavigation from '../../Components/formnavigation/formnavigation';
import RegisterInput from '../../Components/registter_input/registerinput';
import SocialMedia from '../../Components/socialmedia';
class Register extends Component{
handleclickkyc=()=>{
this.props.history.push("/detailform1");
}
render(){
const maincontainer={
width:'100%',
height:'100vh',
display:'flex',
flexDisplay:'row'
}
const leftcontainer={
width:"45%",
height:'100%',
position:'relative'
}
const rightcontainer={
width:"55%",
height:'100%',
position:'relative',
display:'flex',
flexDirection:'column',
alignItems:'center'
}
const nav={
position:'absolute',
top:20,
right:0
}
const card={
width:"350px",
height:'240px',
position:'absolute',
borderRadius:'10px',
background:'rgba(255,255,255,0.2)',
display:'flex',
flexDirection:'column',
justifyContent:'space-evenly',
alignItems:'center',
top:'140px',
left:"25%"
}
const btn1={
width:222,
height:60,
borderRadius:60,
border:'3px solid white',
background:'rgba(255,255,255,0)',
fontSize:'30px',
color:'white'
}
const text1={
color:'white',
fontSize:'36px',
fontWeight:500,
textAlign:'center',
margin:0
}
const text2={
color:'white',
fonstSize:"24px",
margin:0,
textAlign:'center'
}
const kyc_text={
position:'absolute',
fontSize:'24px',
width:"55%",
bottom:"250px"
}
const formcontainer={
display:'flex',
flexDirection:'column',
alignItems:'center'
}
const btn2={
marginTop:'40px',
width:222,
color:'white',
height:'60px',
borderRadius:'60px',
backgroundColor:'#8FC3FA',
fontSize:'30px',
fontWeight:500,
borderWidth:0,
}
const text={
fontSize:"64px",
fontWeight:"bold",
color:'#5C5C5C',
marginTop:'60px'
}
const formcontent={
display:'flex',
flexDirection:'column',
alignItems:'center'
}
const signup={
marginTop:'30px',
marginBottom:'10px',
fontSize:"24px",
fontWeight:500
}
const img_style={
position:'absolute',
bottom:0,
right:-90,
}
return (
<div style={maincontainer}>
<div style={leftcontainer}>
<div style={formcontainer}>
<div style={text}>Sign Up</div>
<form style={formcontent}>
<RegisterInput value="UserName" icons="./icons/user.svg" handlechange={this.getname}/>
<RegisterInput value="Email" is_em={true} icons="./icons/email.svg" handlechange={this.getemail}/>
<RegisterInput value="<PASSWORD>" icons="./icons/lock.svg" is_pass={true} handlechange={this.getPassword}/>
<input type="submit" style={btn2} value="Login"></input>
</form>
<div style={signup}> Or Sign up with social platforms</div>
<SocialMedia/>
</div>
<div style={img_style}>
<img src="./images/bg_img.png" alt="" height="370px"></img>
</div>
</div>
<div style={rightcontainer}>
<svg width="100%" height="100%" viewBox="0 0 767 1120" fill="none" xmlns="http://www.w3.org/2000/svg">
<ellipse cx="45vw" cy="40vh" rx="60vw" ry="60vw" fill="#2B6777"/>
</svg>
<div style={nav}>
<FormNavigation fontcolor={'white'}/>
</div>
<div style={card}>
<p style={text1}>One Of Us?</p>
<p style={text2}>Log back into your account</p>
<button style={btn1}>Login</button>
</div>
<div style={kyc_text}>
You must fill your KYC form in order to be eligible to perform the review and testing
</div>
<div style={{position:"absolute",bottom:120}}>
<button style={btn1} onClick={this.handleclickkyc}>KYC FORM</button>
</div>
</div>
</div>
);
}
}
export default Register;<file_sep>import React, {Component} from 'react';
import { Link } from 'react-router-dom';
class FormNavigation extends Component{
render(){
const text_nav={
fontSize:'18px',
fontWeight:500,
color:this.props.fontcolor,
textAlign:'left',
width:'140px',
height:'40px',
textDecoration:'none'
}
return (
<div style={{display:'flex',width:'420px',justifyContent:'space-evenly'}}>
<Link to={"/"} style={text_nav}>Login</Link>
<Link style={text_nav} to={"/aboutus"}>About Us</Link>
<Link to={"/register"} style={text_nav}> Register</Link>
</div>
);
}
}
FormNavigation.defaultProps={
fontcolor:'black'
}
export default FormNavigation;<file_sep>import "./Body.css";
import Header from '../header'
import Card from "./Card";
import Welcome from "./Welcome";
const plBody = () => {
return (
<>
<Header/>
<Welcome/>
<div className="body">
<button className="title">Websites</button>
<section className="cardlist">
<Card name="Mercedes" star="4" />
<Card name="Audi" star="4" />
<Card name="Tesla" star="4" />
<Card name="Porshe" star="4" />
</section>
<button className="title">Apps</button>
<section className="cardlist">
<Card name="Lenovo" star="4" />
<Card name="Dell" star="4" />
<Card name="Canon" star="4" />
<Card name="Sony" star="4" />
</section>
</div>
</>
);
};
export default plBody;
<file_sep>import React, {Component} from 'react';
class RegisterInput extends Component{
change=(event)=>{
event.preventDefault();
const value=event.target.value;
console.log(value);
this.props.handlechange(value);
}
render(){
const input_container={
marginTop:'20px',
display:'flex',
width:'420px',
height:'60px',
borderRadius:'60px',
backgroundColor:'#E7E1E1',
alignItems:'center',
paddingLeft:'10px',
paddingRight:'10px'
}
const input_style={
width:"90%",
background:"rgba(255,255,255,0)",
borderWidth:0,
outline:'none',
flexWrap:'wrap',
fontSize:'24px'
}
return (
<>
<div style={input_container}>
<img src={this.props.icons} alt="icon"></img>
<input placeholder={this.props.value} style={input_style} onChange={this.change} type={(this.props.is_pass)?"Password" : (this.props.is_em) ? "email" : "text"}></input>
</div>
</>);
}
}
RegisterInput.defaultProps={
is_pass:false,
is_em:false
};
export default RegisterInput;<file_sep>import React,{Component} from 'react';
class DetailFormInput extends Component{
render(){
const input_container={
display:'flex',
justifyContent:'space-between',
alignItems:'center',
width:'70%',
marginRight:"20px"
}
const label_style={color:'white',
fontSize:'18px',
fontWeight:500,
marginLeft:'80px',
textAlign:'left',
width:"20%"
}
const input_style={
width:'50%',
background:'rgba(255,255,255,0.2)',
borderRadius:'8px',
border:'1px solid white',
height:'36px',
outline:'none',
color:'white'
}
return (
<div style={input_container}>
<div style={label_style}>{this.props.value}</div>
<input style={input_style}></input>
</div>
);
}
}
export default DetailFormInput;<file_sep>import React,{Component} from 'react';
import DetailFormInput from './detailforminput';
import FormHeader from './header_detailform';
class Form1 extends Component{
clicknext=()=>{
this.props.history.push("/detailform2");
}
clickback=()=>
{
this.props.history.push("/");
}
render(){
const form={
position:'relative',
width:"80%",
backgroundColor:"black",
height:"60vh",
margin:"auto",
borderRadius:"18px",
display:'flex',
flexDirection:'column',
justifyContent:'space-evenly',
top:"80px"
}
const container={
width:"100wh",
height:"100vh"
}
const btn={
width:'20px',
height:"20px",
background:"rgba(255,255,255,0)",
borderWidth:"0px",
outline:0,
margin:'0px 20px',
padding:'5px'
}
const btns={
display:'flex',
justifyContent:'flex-end',
alignItems:'center'
}
const text={
width:"80%",
fontSize:"24px",
fontWeight:"bold",
position:"absolute",
left:"10%",
marginTop:"20px"
}
return (
<div style={container}>
<FormHeader/>
<div style={text}>
Please enter your details
</div>
<form style={form}>
<DetailFormInput value={"Name"}/>
<DetailFormInput value={"DOB"}/>
<DetailFormInput value={"Citizenship No"}/>
<DetailFormInput value={"Father's Name"}/>
<DetailFormInput value={"Email"}/>
<DetailFormInput value={"Mobile Number"}/>
<DetailFormInput value={"Gender"}/>
<div style={btns}>
<button style={btn} onClick={this.clicknext}>
<svg width="20px" height="20px" viewBox="0 0 25 27" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M19.734 12.7772L15.8097 8.57927L16.6894 7.62012L22.1334 13.4437L16.6936 19.3747L15.8055 18.4247L19.7472 14.1271L1.25102 14.1747L1.24805 12.8247L19.734 12.7772Z" fill="white"/>
</svg>
</button>
<button style={btn} onClick={this.clickback}>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1 11.0003H10.3333C12.9107 11.0003 15 8.91099 15 6.33366C15 3.75633 12.9107 1.66699 10.3333 1.66699H5.66667" stroke="white" stroke-width="2" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4.33333 7.66699L1 11.0003L4.33333 14.3337" stroke="white" stroke-width="2" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</button>
</div>
</form>
</div>
);
}
}
export default Form1;<file_sep>import {BrowserRouter as Router} from 'react-router-dom'
import Body from './Components/LandingPage/Body/index';
import Login from './Components/Login/login';
import { Route, Switch } from 'react-router-dom';
import Register from './Pages/regsiter/register';
import DetailForm1 from './Pages/detailform/form1';
import DetailForm2 from './Pages/detailform/form2';
import Thankyou from './Pages/detailform/thankyou';
import Dashboard from './Pages/dashboard/dashboard';
import Profile from './Pages/profile/profile';
import AboutUs from './Pages/aboutus/aboutus';
import plBody from './Components/PostLogin/Body';
import Info from './Components/PostLogin/Info';
import Welcome from './Components/PostLogin/Welcome';
import FormSignup from './Components/Survey/FormSignup';
import FormSuccess from './Components/Survey/FormSuccess';
function App() {
return (
<Router >
<Switch>
<Route exact path = "/" component = { Body} />
<Route path="/login" component={Login }/>
<Route path = "/register" component = { Register } />
<Route path = "/detailform1" component = { DetailForm1 }/>
<Route path = "/detailform2" component = { DetailForm2 }/>
<Route path = "/detailform3" component = { Thankyou }/>
<Route path = "/dashboard" component = { Dashboard }/>
<Route path="/profile" component={Profile}/>
<Route path="/aboutus" component={AboutUs}/>
<Route path="/welcome" component={Welcome}/>
<Route path="/plBody" component={plBody}/>
<Route path="/info" component={Info}/>
<Route path="/form" component={FormSignup}/>
<Route path="/formSuccess" component={FormSuccess}/>
</Switch>
</Router>
)
};
export default App;
<file_sep>import "./Info.css";
import { AiFillStar } from "react-icons/ai";
import Header from '../header';
import { useHistory } from "react-router";
const Info = () => {
const history = useHistory();
const navigateTo = () => history.push('/form');
return (
<>
<Header/>
<div className="info">
<section className="logo-part">
<img src="./Domble.JPG" alt="Domble Logo" />
<h3 className="company-name"><NAME></h3>
<div className="star">
<AiFillStar style={{ color: "orange" }} />
<AiFillStar style={{ color: "orange" }} />
<AiFillStar style={{ color: "orange" }} />
<AiFillStar style={{ color: "orange" }} />
</div>
<p> 4 out of 5 </p>
</section>
<section className="info-text">
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown printer took a galley of type and
scrambled it to make a type specimen book. It has survived not only
five centuries, but also the leap into electronic typesetting,
remaining essentially unchanged. It was popularised in the 1960s with
the release of Letraset sheets containing Lorem Ipsum passages, and
more recently with desktop publishing software like Aldus PageMaker
including versions of Lorem Ipsum
</p>
<br />
<p>
It is a long established fact that a reader will be distracted by the
readable content of a page when looking at its layout. The point of
using Lorem Ipsum is that it has a more-or-less normal distribution of
letters, as opposed to using 'Content here, content here', making it
look like readable English.
</p>
<button className="btn-check-website" onClick={navigateTo}>Search</button>
</section>
</div>
</>
);
};
export default Info;
<file_sep>import "./Welcome.css";
const Welcome = () => {
return (
<div className="welcome">
<h3 className="name">Welcome Sudip</h3>
{/* <p>button here</p> */}
<button className="search">Search</button>
</div>
);
};
export default Welcome;
<file_sep>import styled from 'styled-components'
import {Link as LinkR} from 'react-router-dom' //For importing Link
import {Link as LinkScroll} from 'react-scroll' // For scroll in Nav Menu
//exporting to the tags in index page
export const Nav = styled.div`
position:sticky;
background: #85B8E7;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
font-size: 1 rem;
top: 0;
z-index:1;
background-color: #background: #85B8E7;
@media screen and (max-width:9600px){
transition: 0.8s all ease;
}
`;
export const Navbarcontainer = styled.div
`
display:flex;
justify-content: space-around;
height: 80px;
z-index: 0;
width: 100%
padding: 0 24px;
max-width: 1100px;
`;
export const NavMenu=styled.ul`
display: flex;
align-items:center;
list-style:none;
text-align: center;
color: #fff;
position:relative;
margin-right: -600px;
@media screen and (max-width : 768px)
{
display: none;
}
`;
export const NavItem =styled.li
`
padding-right:25px;
padding-left:25px;
padding-top:60px;
height: 80px;
`;
export const NavLinks = styled(LinkScroll)
`
color: #fff;
display: flex;
align-items: Center;
text: decoration:none;
padding:0 1 rem;
height: 100%
cursor:pointer;
font-family: Times New Roman;
&.active
{
border-bottom: 3px solid #01bf71;
}
`;
//Neck section
export const Neck = styled.nav`
position: sticky;
top:0px;
align-items:center;
background: #000;
height: 125px;
display: flex;
justify-content: center;
align-items: center;
font-size: 1 rem;
top: 0;
z-index:1000;
background-color: #fff ;
@media screen and (max-width:9600px){
transition: 0.8s all ease;
}
`;
export const NeckContainer = styled.div
`
display:flex;
justify-content: space-around;
height: 80px;
z-index: 1;
width: 100%
padding: 0 24px;
max-width: 1100px;
`;
export const NeckMenu=styled.ul`
display: flex;
align-items:Center;
list-style:none;
color: #fff;
margin-right: -600px;
@media screen and (max-width : 768px)
{
display: none;
}
`;
export const NeckItem =styled.li
`
align-items:Center;
padding-right:20px;
padding-left:20px;
padding-top:60px;
height: 100px;
`;
export const NeckLinks = styled(LinkScroll)
`
color: #000;
display: flex;
align-items: Center;
text: decoration:none;
padding:0 1 rem;
height: 100%
cursor:pointer;
font-family: Times New Roman;
&.active
{
border-bottom: 3px solid #01bf71;
}
`;
export const Necklogo = styled(LinkR)
`
align-items:center;
color: #000;
justify:self: flex-start;
cursor: pointer;
font-size: 1.6rem;
font-family: Times New Roman;
display: inline-block;
align-items:Center;
margin-left: 100px;
font-weight: bold;
text-decoration: none;
position:absolute;
left:10px;
top: 15px;
`;
export const MobileIcon = styled.div
`display: none;
@media screen and (max-width:768px)
{
display:block;
position: absolute;
top:0;
right:0;
transform: translate(-100% , 60%);
font-size: 1.8 rem;
cursor:pointer;
color: #fff;
}
`;
export const IconContainer =styled.div
`
position: relative;
align-item:center;
padding-left: 30px;
padding-right:30px;
padding bottom:100px;
`
| dedf0c27697d84a63d985d4d8099cf8bfec494f1 | [
"JavaScript"
] | 14 | JavaScript | kishankc123/domble | b082413291d985ad98b9f3513fb0d1efdb68b774 | 7ac8c32cf4b96bc1c41da672131b364dec843ab9 |
refs/heads/master | <repo_name>nc-trevorb/hackerrank<file_sep>/spec/spec_helper.rb
require 'rspec'
require 'pry'
Dir[File.expand_path("./lib/**/*.rb")].each(&method(:require))<file_sep>/lib/lisp.rb
class ParseError < StandardError; end
def evaluate(input)
case input[0]
when "'"
symbols = get_symbols(input[1..-1])
symbols.map{|s| evaluate(s)}
when '('
symbols = get_symbols(input)
apply(symbols)
when /\d/
if input =~ /^\d*$/
input.to_i
else
raise ParseError.new("can't parse #{input}")
end
else
raise ParseError.new("can't start with #{input[0]}")
end
end
def apply(symbols)
return if symbols.empty?
applied = symbols.dup
symbols.each_with_index do |s, i|
if s.is_a?(Array)
applied[i] = apply(s).to_s
end
end
case applied.first
when '+', '-', '*', '/'
applied[1..-1].map{|x| evaluate(x)}.inject(applied.first)
else
raise ParseError.new('invalid symbol')
end
end
def get_symbols(input_sexpr)
sexpr = input_sexpr.strip
if !(sexpr.start_with?('(') && sexpr.end_with?(')'))
raise ParseError.new('unbalanced parens')
else
str = sexpr[1..-2]
first_paren = str.index('(')
if first_paren
last_paren = str.rindex(')')
sub_expression = str[first_paren..last_paren]
str[0..(first_paren-1)].split + [get_symbols(sub_expression)] + str[(last_paren+1)..-1].split
else
str.split
end
end
end
<file_sep>/spec/lisp_spec.rb
require 'spec_helper'
describe "#evaluate" do
context "for valid inputs" do
ERROR = 'error!'
{
# start with just integers
"should evaluate numbers" => ["1", 1],
"should evaluate empty list" => ["'()", []],
"should evaluate list of numbers" => ["'(1 2 3)", [1, 2, 3]],
"should raise an error for lists missing closing parens" => ["'(1 2", ERROR],
"should evaluate null expression" => ["()", nil],
"should raise an error for missing close-parens" => ["(", ERROR],
"should raise an error for missing open-parens" => [")", ERROR],
"should raise an error for unbalanced s-expressions" => ["(+ 1", ERROR],
# evaluate functions
"should evaluate addition" => ["(+ 6 2)", 8],
"should evaluate subtraction" => ["(- 6 2)", 4],
"should evaluate multiplication" => ["(* 6 2)", 12],
"should evaluate division" => ["(/ 6 2)", 3],
"should raise an error for bogus functions" => ["(bogus 1 2 3)", ERROR],
"should raise an error for division by zero" => ["(/ 1 0)", ERROR],
# stricter parsing
"should raise an error for invalid symbols" => ["1asdf", ERROR],
"should raise an error for trying to apply non-function" => ["(1 2 3)", ERROR],
# # recursive evaluation
"recursive evaluation" => ["(+ 6 (- 10 2))", 14],
"deep recursive evaluation" => ["(+ 6 (- 10 (+ 2 4)))", 10],
# # add floats
# "floats" => ["1.5", 1.5],
# "float arithmetic" => ["(+ 1.5 (- 3.6 1.2))", 3.9],
# # add strings
# "strings" => ['"asdf"', "asdf"],
# "string functions" => ['(concat "as" "df")', "asdf"],
# "should raise an error for type mismatch" => ['(+ "asdf" 3)', ERROR],
# # add bindings
# "bindings" => ["(let (x 1) (+ x 2))", 3],
}.each do |desc, (expression, result)|
it "#{desc}: `#{expression} → #{result}`" do
if result == ERROR
expect { evaluate(expression) }.to raise_error(StandardError)
else
expect(evaluate(expression)).to eq(result)
end
end
end
end
end | 8b55e4a1e809623d287d4dfb59d768aeff919c95 | [
"Ruby"
] | 3 | Ruby | nc-trevorb/hackerrank | 0c3e504344509499155ca34164d0a962710ab1ba | 7977d58f7ad14e6e22bdc4b7f83d688d479de7f5 |
refs/heads/master | <repo_name>daozhangXDZ/Brunetons-Improved-Atmospheric-Scattering<file_sep>/README.md
# Brunetons-Improved-Atmospheric-Scattering
This is a fork from the [Scrawk](https://github.com/Scrawk/Brunetons-Improved-Atmospheric-Scattering) repo. It uses the exposed interface "IBeforeCameraRender" (available from Unity's Scriptable LightweightPipeline) to generate and bind the Bruneton resources required to light a scene. This is a work in progress and is fairly clunky to set up.
How to use:
1. Import the Assets from this repository into a project
2. Assign the BrunetonSkyboxMaterial as the Skybox Material
3. Add a script compopnent to the main camera of your project and assign the BrunetonCameraScript to it
4. Assign the Precomputation shader as the compute shader for the BrunetonCameraScript
To use the lookups to light the scene:
1. Merge "Lighting.hlsl.txt" with "Lighweight RP\ShaderLibrary\Lighting.hlsl"
2. Merge "LitForwardPass.hlsl.txt" with "Lighweight RP\Shaders\LitForwardPass.hlsl"
To tweak the Sky settings edit the BrunetonSkyboxMaterial properties:
- Mie Scattering (Scattering caused by particles with size comparable to the wavelengths of visible light)
- Rayleigh Scattering (Scattering caused by particles with sizemuch smaller than the wavelengths of visible light)
- Ozone (Scattering caused by the particles in the ozone layer)
- Phase (The Henyey-Greenstein phase function term)
- Fog (Amount of fog)
- Sun Size (Size of the sun)
- Sun Edge (Size of the edge of the sun)


<file_sep>/Assets/BrunetonsImprovedAtmosphere/Scripts/BrunetonCameraScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering.LightweightPipeline;
using BrunetonsImprovedAtmosphere;
namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{
[DisallowMultipleComponent]
[ExecuteInEditMode]
public class BrunetonPrecomputeLookupsComponent : MonoBehaviour, IBeforeCameraRender
{
struct BrunetonParameters
{
public float m_mieScattering;
public float m_raleightScattering;
public float m_ozoneDesnity;
public float m_phase;
public float m_fogAmount;
public float m_sunSize;
public float m_sunEdge;
static bool Equals(ref BrunetonParameters a, ref BrunetonParameters b)
{
return
(
a.m_mieScattering == b.m_mieScattering &&
a.m_raleightScattering == b.m_raleightScattering &&
a.m_ozoneDesnity == b.m_ozoneDesnity &&
a.m_phase == b.m_phase
);
}
};
static BrunetonParameters BrunetonParams;
static int kNumScatteringOrders = 4;
static int kLambdaMin = 360;
static int kLambdaMax = 830;
static bool kUseConstantSolarSpectrum = false;
static bool kUseOzone = true;
static bool kUseCombinedTextures = true;
static bool kUseHalfPrecision = false;
static bool kDoWhiteBalance = false;
static float kExposure = 10;
static float kSunAngularRadius = 0.00935f / 2.0f * 7.5f;
static float kBottomRadius = 6360000.0f;
static float kLengthUnitInMeters = 1000.0f;
static string kBrenetonComputeLookupsTag = "Breneton Compute Lookups";
static LUMINANCE kUseLuminance = LUMINANCE.NONE;
Model m_model;
public bool BrunetonLookupsDirty()
{
Material skybox = RenderSettings.skybox;
if (!skybox || !skybox.shader || skybox.shader.name != "Skybox/BunetonSkybox")
{
return false;
}
BrunetonParameters brunetonParamsToCompare;
brunetonParamsToCompare.m_mieScattering = skybox.GetFloat("_MieScatteringScalar");
brunetonParamsToCompare.m_raleightScattering = skybox.GetFloat("_RayleighScatteringScalar");
brunetonParamsToCompare.m_ozoneDesnity = skybox.GetFloat("_OzoneDensity");
brunetonParamsToCompare.m_phase = skybox.GetFloat("_Phase");
brunetonParamsToCompare.m_fogAmount = skybox.GetFloat("_FogAmount");
brunetonParamsToCompare.m_sunSize = skybox.GetFloat("_SunSize");
brunetonParamsToCompare.m_sunEdge = skybox.GetFloat("_SunEdge");
BrunetonParams.m_fogAmount = brunetonParamsToCompare.m_fogAmount;
BrunetonParams.m_sunSize = brunetonParamsToCompare.m_sunSize;
BrunetonParams.m_sunEdge = brunetonParamsToCompare.m_sunEdge;
if (!BrunetonCameraScript.Equals(BrunetonParams, brunetonParamsToCompare))
{
BrunetonParams = brunetonParamsToCompare;
return true;
}
return false;
}
void CreateBrunetonModel()
{
double[] kSolarIrradiance = new double[]
{
1.11776, 1.14259, 1.01249, 1.14716, 1.72765, 1.73054, 1.6887, 1.61253,
1.91198, 2.03474, 2.02042, 2.02212, 1.93377, 1.95809, 1.91686, 1.8298,
1.8685, 1.8931, 1.85149, 1.8504, 1.8341, 1.8345, 1.8147, 1.78158, 1.7533,
1.6965, 1.68194, 1.64654, 1.6048, 1.52143, 1.55622, 1.5113, 1.474, 1.4482,
1.41018, 1.36775, 1.34188, 1.31429, 1.28303, 1.26758, 1.2367, 1.2082,
1.18737, 1.14683, 1.12362, 1.1058, 1.07124, 1.04992
};
double[] kOzoneCrossSection = new double[]
{
1.18e-27, 2.182e-28, 2.818e-28, 6.636e-28, 1.527e-27, 2.763e-27, 5.52e-27,
8.451e-27, 1.582e-26, 2.316e-26, 3.669e-26, 4.924e-26, 7.752e-26, 9.016e-26,
1.48e-25, 1.602e-25, 2.139e-25, 2.755e-25, 3.091e-25, 3.5e-25, 4.266e-25,
4.672e-25, 4.398e-25, 4.701e-25, 5.019e-25, 4.305e-25, 3.74e-25, 3.215e-25,
2.662e-25, 2.238e-25, 1.852e-25, 1.473e-25, 1.209e-25, 9.423e-26, 7.455e-26,
6.566e-26, 5.105e-26, 4.15e-26, 4.228e-26, 3.237e-26, 2.451e-26, 2.801e-26,
2.534e-26, 1.624e-26, 1.465e-26, 2.078e-26, 1.383e-26, 7.105e-27
};
double kDobsonUnit = 2.687e20;
double kMaxOzoneNumberDensity = 300.0 * kDobsonUnit / 15000.0;
double kConstantSolarIrradiance = 1.5;
double kTopRadius = 6420000.0;
double kRayleigh = 1.24062e-6;
double kRayleighScaleHeight = 8000.0;
double kMieScaleHeight = 1200.0;
double kMieAngstromAlpha = 0.0;
double kMieAngstromBeta = 5.328e-3;
double kMieSingleScatteringAlbedo = 0.9;
double kGroundAlbedo = 0.1;
double max_sun_zenith_angle = (kUseHalfPrecision ? 102.0 : 120.0) / 180.0 * Mathf.PI;
DensityProfileLayer rayleigh_layer = new DensityProfileLayer("rayleigh", 0.0, 1.0, -1.0 / kRayleighScaleHeight, 0.0, 0.0);
DensityProfileLayer mie_layer = new DensityProfileLayer("mie", 0.0, 1.0, -1.0 / kMieScaleHeight, 0.0, 0.0);
List<DensityProfileLayer> ozone_density = new List<DensityProfileLayer>();
ozone_density.Add(new DensityProfileLayer("absorption0", 25000.0, 0.0, 0.0, 1.0 / 15000.0, -2.0 / 3.0));
ozone_density.Add(new DensityProfileLayer("absorption1", 0.0, 0.0, 0.0, -1.0 / 15000.0, 8.0 / 3.0));
List<double> wavelengths = new List<double>();
List<double> solar_irradiance = new List<double>();
List<double> rayleigh_scattering = new List<double>();
List<double> mie_scattering = new List<double>();
List<double> mie_extinction = new List<double>();
List<double> absorption_extinction = new List<double>();
List<double> ground_albedo = new List<double>();
for (int l = kLambdaMin; l <= kLambdaMax; l += 10)
{
double lambda = l * 1e-3; // micro-meters
double mie = kMieAngstromBeta / kMieScaleHeight * System.Math.Pow(lambda, -kMieAngstromAlpha);
wavelengths.Add(l);
if (kUseConstantSolarSpectrum)
solar_irradiance.Add(kConstantSolarIrradiance);
else
solar_irradiance.Add(kSolarIrradiance[(l - kLambdaMin) / 10]);
rayleigh_scattering.Add(kRayleigh * System.Math.Pow(lambda, -4) * BrunetonParams.m_raleightScattering);
mie_scattering.Add(mie * kMieSingleScatteringAlbedo * BrunetonParams.m_mieScattering);
mie_extinction.Add(mie);
absorption_extinction.Add(kUseOzone ? BrunetonParams.m_ozoneDesnity * kMaxOzoneNumberDensity * kOzoneCrossSection[(l - kLambdaMin) / 10] : 0.0);
ground_albedo.Add(kGroundAlbedo);
}
m_model = new Model();
m_model.HalfPrecision = kUseHalfPrecision;
m_model.CombineScatteringTextures = kUseCombinedTextures;
m_model.UseLuminance = kUseLuminance;
m_model.Wavelengths = wavelengths;
m_model.SolarIrradiance = solar_irradiance;
m_model.SunAngularRadius = kSunAngularRadius;
m_model.BottomRadius = kBottomRadius;
m_model.Exposure = kExposure;
m_model.DoWhiteBalance = kDoWhiteBalance;
m_model.TopRadius = kTopRadius;
m_model.RayleighDensity = rayleigh_layer;
m_model.RayleighScattering = rayleigh_scattering;
m_model.MieDensity = mie_layer;
m_model.MieScattering = mie_scattering;
m_model.MieExtinction = mie_extinction;
m_model.MiePhaseFunctionG = BrunetonParams.m_phase;
m_model.AbsorptionDensity = ozone_density;
m_model.AbsorptionExtinction = absorption_extinction;
m_model.GroundAlbedo = ground_albedo;
m_model.MaxSunZenithAngle = max_sun_zenith_angle;
m_model.LengthUnitInMeters = kLengthUnitInMeters;
}
public void ExecuteBeforeCameraRender(LightweightRenderPipeline pipelineInstance, ScriptableRenderContext context, Camera camera)
{
CommandBuffer cmd = CommandBufferPool.Get(kBrenetonComputeLookupsTag);
if ((m_model == null) || BrunetonLookupsDirty())
{
CreateBrunetonModel();
m_model.Init(BrunetonCameraScript.BrunetonComputeShader, kNumScatteringOrders);
}
else
{
m_model.FogAmount = BrunetonParams.m_fogAmount;
m_model.SunSize = BrunetonParams.m_sunSize;
m_model.SunEdge = BrunetonParams.m_sunEdge;
m_model.BindToPipeline(cmd, null, null);
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
}
}
[DisallowMultipleComponent]
[ExecuteInEditMode]
public class BrunetonCameraScript : MonoBehaviour
{
// Hack to get the compute shader for the Editor's Camera
static public ComputeShader BrunetonComputeShader;
public ComputeShader m_compute;
void Start()
{
BrunetonComputeShader = m_compute;
BrunetonPrecomputeLookupsComponent toAdd = new BrunetonPrecomputeLookupsComponent();
if (gameObject.GetComponent<BrunetonPrecomputeLookupsComponent>() == null)
gameObject.AddComponent<BrunetonPrecomputeLookupsComponent>();
foreach (SceneView sv in SceneView.sceneViews)
{
Camera cc = sv.camera;
if (cc.GetComponent<BrunetonPrecomputeLookupsComponent>() == null)
cc.gameObject.AddComponent<BrunetonPrecomputeLookupsComponent>();
}
}
}
| 3ff2bed43b9944d2d93130ce613a3ec978fe4e63 | [
"Markdown",
"C#"
] | 2 | Markdown | daozhangXDZ/Brunetons-Improved-Atmospheric-Scattering | 22f62146f33a88f9b3205c5ab72dd00f31bc29f8 | cb2bdbbc67a870b6e5a6fd2b14a7112f1991d95b |
refs/heads/master | <repo_name>drakedevel/eagle-tools<file_sep>/README.md
Command-line tools for working with EAGLE PCB files.
Very much a work-in-progress -- not many features yet, use at your own risk.
Requires Python 3.5+. Run `./cli.py --help` for usage.
<file_sep>/eagletools/cli.py
import click
import os
import re
from tabulate import tabulate
from typing import TextIO, Tuple
from xml.etree.ElementTree import Element, ElementTree, SubElement
from hwpy.value import Value
from .parser import Library, Part, Schematic, load_file, parse_file, _text_at
def _part_sort_key(value: Tuple[str, Part]) -> Tuple[str, int]:
match = re.fullmatch(r'([A-Z]+)([0-9]+)', value[0])
if match:
return match.group(1), int(match.group(2))
return value[0], 0
def _format_dev(dev: str, var: str=None, tech: str=None) -> str:
result = dev
if var is not None:
if '?' in result:
result = result.replace('?', var)
else:
result = result + var
if tech is not None:
if '*' in result:
result = result.replace('*', tech)
else:
result = result + tech
return result
def _summary(desc: str) -> str:
lines = [l.strip() for l in desc.split('\n')]
for line in lines:
if not line:
continue
if line != desc:
return line + ' ...'
return line
return ''
@click.group()
def cli() -> None:
pass
@cli.command()
@click.option('--output', '-o', type=click.Path(exists=True, file_okay=False),
default='.', help="Output directory (default current)")
@click.argument('in_f', type=click.File('r'))
def extract(output: str, in_f: TextIO) -> None:
"""Extract libraries from a board or schematic"""
# Load and validate input file
type_, et, element = load_file(in_f)
if type_ not in ('board', 'schematic'):
raise ValueError("This command requires board or schematic files")
version = et.getroot().attrib['version']
# Extract each library
for lib_elt in element.iterfind('./libraries/library'):
root = Element('eagle', attrib={'version': version})
drawing = SubElement(root, 'drawing')
library = SubElement(drawing, 'library')
library.extend(lib_elt)
et = ElementTree(root)
et.write(os.path.join(output, '{}.lbr'.format(lib_elt.attrib['name'])),
encoding='utf-8')
@cli.command(name='list')
@click.argument('in_f', type=click.File('r'))
def cmd_list(in_f: TextIO) -> None:
"""List the contents of a library"""
parsed = parse_file(in_f)
if not isinstance(parsed, Library):
raise NotImplementedError("Only libraries are supported at this time")
if parsed.name:
print("Name: {}".format(parsed.name))
if parsed.description:
print("Description: {}".format(_summary(parsed.description)))
print("Packages:")
for name, pkg in sorted(parsed.packages.items()):
print(" {}".format(name))
descr = _text_at(pkg, './description')
if descr:
print(" Description: {}".format(_summary(descr)))
print("Symbols:")
for name, sym in sorted(parsed.symbols.items()):
print(" {}".format(name))
descr = _text_at(sym, './description')
if descr:
print(" Description: {}".format(_summary(descr)))
print("Devices:")
for dev_name, dev in sorted(parsed.devices.items()):
print(" {}".format(dev_name))
if dev.description:
print(" Description: {}".format(_summary(dev.description)))
if dev.variants:
print(" Variants:")
for var_name, var in sorted(dev.variants.items()):
print(" {} pkg={}".format(_format_dev(dev_name, var_name),
var.package))
if var.technologies.keys() != {''}:
for tech_name in sorted(var.technologies.keys()):
formatted = _format_dev(dev_name, var_name, tech_name)
print(" {}".format(formatted))
@cli.command()
@click.option('--format', type=click.Choice(['table', 'machine']),
default='table', help="Data output format.")
@click.argument('sch_f', type=click.File('r'))
def parts(format: str, sch_f: TextIO) -> None:
"""List used parts/libraries in a schematic"""
parsed = parse_file(sch_f)
if not isinstance(parsed, Schematic):
raise ValueError("This command requires a schematic file")
data = []
for name, part in sorted(parsed.parts.items(), key=_part_sort_key):
tech = parsed.libraries[part.library_ref].devices[part.device].variants[part.variant].technologies[part.technology]
attrs = tech.attributes.copy()
attrs.update(part.attributes)
value = part.value
if value:
try:
value = Value.parse(value).to_str(True)
except ValueError:
pass
data.append((name, str(part.library_ref), _format_dev(part.device, part.variant,
part.technology),
value or '', attrs.get('MPN', '')))
if format == 'table':
print(tabulate(data, headers=['Part', 'Library', 'Device', 'Value', 'MPN']))
elif format == 'machine':
for line in data:
print(' '.join(line))
else:
raise ValueError(format)
<file_sep>/setup.py
from setuptools import setup
setup(
name='eagletools',
description='Tools for manipulating PCB files created by EAGLE CAD',
version='0.1dev',
author='<NAME>',
author_email='<EMAIL>',
license='Apache-2.0',
packages=['eagletools'],
package_data={'eagletools': ['py.typed']},
install_requires=[
'click>=6.7',
'defusedxml>=0.5.0',
'hwpy@git+ssh://git@github.com/drakedevel/hwpy@master',
'tabulate>=0.7.7',
],
entry_points={
'console_scripts': [
'eagletools = eagletools.cli:cli'
],
},
zip_safe=False,
)
<file_sep>/eagletools/parser.py
from typing import Callable, Dict, NamedTuple, Optional, TYPE_CHECKING, TextIO, Tuple, TypeVar, Union
from xml.etree.ElementTree import ElementTree, Element
if TYPE_CHECKING:
from xml.etree.ElementTree import parse as parse_xml_et
else:
from defusedxml.ElementTree import parse as parse_xml_et
T = TypeVar('T')
class LibraryRef(NamedTuple):
name: str
urn: str
def __str__(self) -> str:
if self.urn:
return f'{self.name} ({self.urn})'
return self.name
def _parse_bool(value: str) -> bool:
if value == 'no':
return False
if value == 'yes':
return True
raise ValueError(value)
def _parse_library_map(element: Element, query: str) \
-> Dict[LibraryRef, 'Library']:
result = {}
for e in element.iterfind(query):
lib = Library.from_et(e)
result[lib.ref] = lib
return result
def _parse_map(element: Element, query: str, parser: Callable[[Element], T]) \
-> Dict[str, T]:
return {e.attrib['name']: parser(e) for e in element.iterfind(query)}
def _text_at(element: Element, query: str, none_ok: bool=True) \
-> Optional[str]:
found = element.find(query)
if found is None:
if none_ok:
return None
raise ValueError('Element not found for query {!r}'.format(query))
return found.text
class Board:
@classmethod
def from_et(cls, element: Element) -> 'Board':
raise NotImplementedError()
class Technology:
def __init__(self, name: str, attributes: Dict[str, str]) -> None:
self.name = name
self.attributes = attributes
@classmethod
def from_et(cls, element: Element) -> 'Technology':
name = element.attrib['name']
attributes = _parse_map(element, './attribute',
lambda e: e.attrib['value'])
return cls(name, attributes)
class Variant:
def __init__(self, name: str, package: Optional[str],
technologies: Dict[str, Technology]) -> None:
self.name = name
self.package = package
self.technologies = technologies
@classmethod
def from_et(cls, element: Element) -> 'Variant':
name = element.attrib['name']
package = element.attrib.get('package')
techs = _parse_map(element, './technologies/technology',
Technology.from_et)
return cls(name, package, techs)
class Device:
def __init__(self, name: str, prefix: str, uservalue: bool,
description: Optional[str], gates: Dict[str, Element],
variants: Dict[str, Variant]) -> None:
self.name = name
self.prefix = prefix
self.uservalue = uservalue
self.description = description
self.gates = gates
self.variants = variants
@classmethod
def from_et(cls, element: Element) -> 'Device':
name = element.attrib['name']
prefix = element.attrib.get('prefix', '')
uservalue = _parse_bool(element.attrib.get('uservalue', 'no'))
description = _text_at(element, './description')
gates = _parse_map(element, './gates/gate', lambda e: e)
variants = {}
for var_elt in element.iterfind('./devices/device'):
var_name = var_elt.attrib.get('name', '')
variants[var_name] = Variant.from_et(var_elt)
return cls(name, prefix, uservalue, description, gates, variants)
class Library:
def __init__(self, name: Optional[str], urn: str,
description: Optional[str],
packages: Dict[str, Element],
symbols: Dict[str, Element],
devices: Dict[str, Device]) -> None:
self.name = name
self.urn = urn
self.description = description
self.packages = packages
self.symbols = symbols
self.devices = devices
@classmethod
def from_et(cls, element: Element) -> 'Library':
# Per DTD, name is only present within board/schematic files
name = element.attrib.get('name')
urn = element.attrib.get('urn', '')
description = _text_at(element, './description')
packages = _parse_map(element, './packages/package', lambda e: e)
symbols = _parse_map(element, './symbols/symbol', lambda e: e)
devices = _parse_map(element, './devicesets/deviceset',
Device.from_et)
return cls(name, urn, description, packages, symbols, devices)
@property
def ref(self) -> LibraryRef:
if self.name is None:
raise AttributeError("Can't get ref of Library with no name")
return LibraryRef(self.name, self.urn)
class Part:
def __init__(self, name: str, library: str, library_urn: str, device: str,
variant: str, technology: str, value: Optional[str],
attributes: Dict[str, str]) -> None:
self.name = name
self.library = library
self.library_urn = library_urn
self.device = device
self.variant = variant
self.technology = technology
self.value = value
self.attributes = attributes
@classmethod
def from_et(cls, element: Element) -> 'Part':
name = element.attrib['name']
library = element.attrib['library']
library_urn = element.attrib.get('library_urn', '')
device = element.attrib['deviceset']
variant = element.attrib['device']
technology = element.attrib.get('technology', '')
value = element.attrib.get('value')
attributes = _parse_map(element, './attribute',
lambda e: e.attrib['value'])
return cls(name, library, library_urn, device, variant, technology,
value, attributes)
@property
def library_ref(self) -> LibraryRef:
return LibraryRef(self.library, self.library_urn)
class Schematic:
def __init__(self, description: Optional[str],
libraries: Dict[LibraryRef, Library],
parts: Dict[str, Part]) -> None:
self.description = description
self.libraries = libraries
self.parts = parts
@classmethod
def from_et(cls, element: Element) -> 'Schematic':
description = _text_at(element, './description')
libraries = _parse_library_map(element, './libraries/library')
parts = _parse_map(element, './parts/part', Part.from_et)
return cls(description, libraries, parts)
def load_file(source: TextIO) -> Tuple[str, ElementTree, Element]:
et = parse_xml_et(source)
if et.getroot().tag != 'eagle':
raise ValueError('Not an EAGLE file')
board = et.find('./drawing/board')
if board:
return 'board', et, board
library = et.find('./drawing/library')
if library:
return 'library', et, library
schematic = et.find('./drawing/schematic')
if schematic:
return 'schematic', et, schematic
raise ValueError('Corrupt or unhandled EAGLE file')
def parse_file(source: TextIO) -> Union[Board, Library, Schematic]:
type_, et, element = load_file(source)
if type_ == 'board':
return Board.from_et(element)
if type_ == 'library':
return Library.from_et(element)
if type_ == 'schematic':
return Schematic.from_et(element)
assert False, "load_file returned unknown type"
| 3783a298342ff27705f22eae8f8a9e43054c005e | [
"Markdown",
"Python"
] | 4 | Markdown | drakedevel/eagle-tools | e7f2bedd800b0f929c03ec209f341ab25ac5bab0 | 1facf6fb93a395303c77dd226df8e559621d7afd |
refs/heads/master | <repo_name>byhat/middle-finger-detection<file_sep>/detectors/finger_detector.py
import math
import cv2
import mediapipe as mp
from enum import Enum
# Represents three possible hand gestures.
class HandGesture(Enum):
No = 0 # Could not recognize
Point = 1 # Pointing fingers
Yeah = 2 # The "Peace" sign
Mid = 3 # The middle finger
# A class for detecting the middle finger.
class FingerDetector:
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
drawing_styles = mp.solutions.drawing_styles
def __init__(self):
self.model = self.mp_hands.Hands(
min_detection_confidence=0.5,
min_tracking_confidence=0.5)
# Classifying hand gestures and checking for middle fingers.
# Returns an array of (hand landmarks, hand gesture).
# See also https://google.github.io/mediapipe/solutions/hands.html.
def detect(self, image):
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image.flags.writeable = False
results = self.model.process(image)
out = []
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
finger_stat = self._check_finger(hand_landmarks)
out.append((hand_landmarks, finger_stat))
return out
# Draws hand landmarks on an image.
# Hand landmarks is returned from FingerDetector.check().
def draw_landmarks(self, image, landmarks):
self.mp_drawing.draw_landmarks(
image, landmarks, self.mp_hands.HAND_CONNECTIONS,
self.drawing_styles.get_default_hand_landmark_style(),
self.drawing_styles.get_default_hand_connection_style())
def mid_finger_region(self, image, hand_landmarks):
l = hand_landmarks.landmark
h, w = image.shape[:2]
HandLandmark = self.mp_hands.HandLandmark
tip_pos = int(l[HandLandmark.MIDDLE_FINGER_TIP].x * w), int(l[HandLandmark.MIDDLE_FINGER_TIP].y * h)
mcp_pos = int(l[HandLandmark.MIDDLE_FINGER_MCP].x * w), int(l[HandLandmark.MIDDLE_FINGER_MCP].y * h)
return tip_pos, mcp_pos
def _check_finger(self, hand_landmarks, threshold=0.6):
HandLandmark = self.mp_hands.HandLandmark
mid_len = self._finger_len(hand_landmarks, HandLandmark.MIDDLE_FINGER_TIP)
index_len = self._finger_len(hand_landmarks, HandLandmark.INDEX_FINGER_TIP)
ring_len = self._finger_len(hand_landmarks, HandLandmark.RING_FINGER_TIP)
pinky_len = self._finger_len(hand_landmarks, HandLandmark.PINKY_TIP)
if index_len * threshold > max(mid_len, ring_len, pinky_len):
return HandGesture.Point
if mid_len * threshold > max(index_len, ring_len, pinky_len):
return HandGesture.Mid
if (index_len + mid_len) / 2 * threshold > max(ring_len, pinky_len):
return HandGesture.Yeah
return HandGesture.No
@staticmethod
def _finger_len(hand_landmarks, finger_tip):
l = hand_landmarks.landmark
width = l[finger_tip].x - l[finger_tip - 3].x
height = l[finger_tip].y - l[finger_tip - 3].y
return math.sqrt(width ** 2 + height ** 2)
<file_sep>/background.py
import cv2
from detectors import background_detector
detector = background_detector.BackgroundDetector()
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
while cap.isOpened():
success, image = cap.read()
if not success:
continue
is_positive, thresh = detector.detect(image)
if is_positive:
cv2.imwrite("out/1.png", image)
cv2.imwrite("out/2.png", detector.background)
cv2.imwrite("out/3.png", thresh)
cv2.imshow("WIN", image)
if cv2.waitKey(5) & 0xFF == 27:
break
cap.release()
<file_sep>/README.md
# middle-finger-detection
This repoository contains the source code for https://pyseez.com/2021/08/middle-finger-detection/.
This code detects simple hand gestures (pointing, peace sign, etc) as well as the middle finger
by using OpenCV and pretrained models in MediaPipe.
If the finger is detected, this program tries to censor it.
To test the code, run `python main.py`
after installing OpenCV 4 (with contrib) and MediaPipe dependencies.
<file_sep>/main.py
import cv2
import numpy as np
from detectors import finger_detector
ft = cv2.freetype.createFreeType2()
ft.loadFontData(fontFileName='/usr/share/fonts/cantarell/Cantarell-Thin.otf', id=0)
def main_fn():
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
detector = finger_detector.FingerDetector()
while cap.isOpened():
success, image = cap.read()
if not success:
continue
result = detector.detect(image)
for (landmarks, finger_stat) in result:
if finger_stat == finger_detector.HandGesture.Point:
ft.putText(image, "One", (200, 200), 120, (255, 255, 255), 2, cv2.LINE_AA, True)
elif finger_stat == finger_detector.HandGesture.Yeah:
ft.putText(image, "Two", (200, 200), 120, (255, 255, 255), 2, cv2.LINE_AA, True)
elif finger_stat == finger_detector.HandGesture.Mid:
reg = detector.mid_finger_region(image, landmarks)
cv2.line(image, reg[0], reg[1], (255, 255, 255), 64)
cv2.line(image, reg[0], reg[1], (0, 0, 0), 48)
cv2.imwrite("out/middle.png", image)
else:
detector.draw_landmarks(image, landmarks)
cv2.imshow('Friendly Python', image)
if cv2.waitKey(5) & 0xFF == 27:
break
cap.release()
if __name__ == "__main__":
cv2.namedWindow("Friendly Python", cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty("Friendly Python", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
main_fn()
<file_sep>/effect.py
import cv2
import numpy as np
from detectors import finger_detector
def mark_fingers(image, proc_image):
checker = finger_detector.FingerDetector()
out = checker.detect(image)
for (landmarks, stat) in out:
checker.draw_landmarks(proc_image, landmarks)
def process(im):
im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im = cv2.GaussianBlur(im, (5, 5), 0)
_, im = cv2.threshold(im, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
im = cv2.erode(im, np.ones((4, 4), np.uint8), iterations=1)
return im
def post_process(im):
im = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR)
# im[:, :, :2] = 80
im[:, :, 0] = 80
return im
im = cv2.imread("img/1.png")
# im = imutils.resize(im, width=720)
im_proc = cv2.imread("img/1.png")
mark_fingers(im, im_proc)
# cv2.imshow("IM", im_proc)
# cv2.waitKey()
cv2.imwrite("out/art-1.png", im_proc)
<file_sep>/detectors/background_detector.py
import cv2
import numpy as np
class BackgroundDetector:
def __init__(self, delta=0.05, threshold=0.05):
self.background = None
self.delta = delta
self.threshold = threshold
def detect(self, frame):
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if self.background is None:
self.background = frame
return False, None
is_positive, thresh = self._detect(frame)
if not is_positive:
self.background = self.background * (1 - self.delta) + frame * self.delta
self.background = self.background.astype(np.uint8)
return is_positive, thresh
def _detect(self, frame):
diff = cv2.absdiff(self.background, frame)
_, thresh = cv2.threshold(diff, 40, 255, cv2.THRESH_BINARY)
thresh = cv2.erode(thresh, np.ones((5, 5), np.uint8))
return np.mean(thresh) > self.threshold, thresh
| e5ee8ff4129a20a5b45b55005f7cf45bef9435fa | [
"Markdown",
"Python"
] | 6 | Python | byhat/middle-finger-detection | 8083cc2a553209261ae6fef46877b3649837fb3c | ad3956d5bb4f2bdf12a6a5327e197f2713e86301 |
refs/heads/master | <file_sep>
//html targets
let notPlaying = document.getElementById('not-playing');
let isPlaying = document.getElementById('is-playing');
let humanImg = document.getElementById('human-img');
let computerImg = document.getElementById('computer-img');
let humanTotal = document.getElementById('human-total');
let computerTotal = document.getElementById('computer-total');
let winner = document.getElementById('winner');
// image urls
let rockImg = 'https://kicd-am.sagacom.com/wp-content/blogs.dir/107/files/2015/08/meteorite.jpg';
let paperImg = 'https://cdn0.iconfinder.com/data/icons/rock-paper-scissors-emoji/792/rock-paper-scissors-emoji-cartoon-019-512.png';
let scissorsImg = 'https://i.pinimg.com/originals/bf/8c/2b/bf8c2ba6ae2d088eebe4f1892a7617e1.jpg';
let lizardImg = 'https://filmschoolrejects.com/wp-content/uploads/2017/05/0zMD2gwXO-cRZ_QRl.jpg';
let spockImg = 'https://www.martialdevelopment.com/wp-content/uploads/spock-nerve-pinch.jpg';
let questionMarkImg = 'https://www.stickpng.com/assets/thumbs/5a4613ddd099a2ad03f9c994.png';
//
//Actions Object | who beats who
let gameActions = {
'rock': {
'paper': false,
'scissors': true,
'lizard': true,
'spock': false,
},
'paper': {
'rock': true,
'scissors': false,
'lizard': false,
'spock': true,
},
'scissors': {
'paper': true,
'rock': false,
'lizard': true,
'spock': false,
},
'lizard': {
'paper': true,
'scissors': false,
'rock': false,
'spock': true,
},
'spock': {
'paper': false,
'scissors': true,
'lizard': false,
'rock': true,
}
}
//Computers and Humans current state
let computerActionState = '';
let computerScore = 0;
let humanActionState = '';
let humanScore = 0;
//Actions Array
let gameArray = ['rock', 'paper', 'scissors', 'lizard', 'spock']
function startGame() {
// Hide play game button
notPlaying.style.display = 'none';
//Show game
isPlaying.style.display = 'block';
}
function endGame() {
// Hide play game button
notPlaying.style.display = 'flex';
//Show game
isPlaying.style.display = 'none';
resetScores();
}
function takingTurn(val, player) {
let imgUrl = '';
switch (val) {
case 'rock':
imgUrl = rockImg;
break;
case 'paper':
imgUrl = paperImg;
break;
case 'scissors':
imgUrl = scissorsImg;
break;
case 'lizard':
imgUrl = lizardImg;
break;
case 'spock':
// @ts-ignore
imgUrl = spockImg;
break;
}
if (player == 'computer') {
// @ts-ignore
computerImg.src = imgUrl;
computerActionState = val;
whoWins();
} else if (player == 'human') {
// @ts-ignore
humanImg.src = imgUrl;
humanActionState = val;
}
}
function humanTurn(val) {
takingTurn(val, 'human');
computerTurn();
}
function computerTurn() {
randomImg('computer');
}
function randomImg(player) {
let num = Math.floor(Math.random() * 5);
takingTurn(gameArray[num], player)
}
//checking for winner
function whoWins() {
if (gameActions[humanActionState][computerActionState] && humanActionState != computerActionState) {
humanScore++;
changeScores()
winner.textContent = "Win!";
winner.style.color = "green";
if (humanScore == 5) {
resetScores();
alert('You win!')
}
} else if (humanActionState == computerActionState) {
winner.textContent = "Tie...";
winner.style.color = 'blue'
} else {
computerScore++;
changeScores()
winner.textContent = "Loser";
winner.style.color = 'red';
if (computerScore == 5) {
resetScores();
alert('You lose!')
}
}
}
function changeScores() {
humanTotal.textContent = humanScore.toString();
computerTotal.textContent = computerScore.toString();
}
function resetScores() {
humanScore = 0;
computerScore = 0;
changeScores();
} | f696569e5bd2535fc18d0ff598c8f097430488fb | [
"JavaScript"
] | 1 | JavaScript | devingrayt6/Rock-Paper-Scissors | 58b33e17f49ebeb29d606cc0a05789891cd65595 | 50dd646f9ca7ec046989ab8d3a6cca4c97b4f159 |
refs/heads/main | <repo_name>patorseing/todoapp-datawow<file_sep>/src/test/8.editdeletewithchecknuncheckchangemenu.spec.js
// Generated by Selenium IDE
const { Builder, By, Key } = require("selenium-webdriver");
import { timeout } from "../util/timeout";
describe("8_edit_delete_with_check_n_uncheck_change_menu", function () {
timeout(30000);
let driver;
beforeEach(async function () {
driver = await new Builder().forBrowser("chrome").build();
});
afterEach(async function () {
await driver.quit();
});
it("8_edit_delete_with_check_n_uncheck_change_menu", async function () {
await driver.get("http://localhost:3000/");
await driver.manage().window().setRect(1920, 1080);
await driver
.findElement(By.css(".root-container:nth-child(6) .edit"))
.click();
await driver
.findElement(
By.css(".root-container:nth-child(6) button:nth-child(1) > p")
)
.click();
await driver.findElement(By.name("todo")).click();
await driver.findElement(By.name("todo")).click();
{
const element = await driver.findElement(By.name("todo"));
await driver.actions({ bridge: true }).doubleClick(element).perform();
}
await driver.findElement(By.name("todo")).sendKeys("Edit");
await driver.findElement(By.name("todo")).sendKeys(Key.ENTER);
await driver.findElement(By.css(".dropbtn")).click();
await driver
.findElement(By.css(".group > button:nth-child(2) > p"))
.click();
await driver
.findElement(By.css(".root-container:nth-child(3) .toolkit-edit svg"))
.click();
await driver
.findElement(By.css(".root-container:nth-child(4) .edit"))
.click();
await driver
.findElement(
By.css(".root-container:nth-child(3) button:nth-child(1) > p")
)
.click();
await driver
.findElement(
By.css(".root-container:nth-child(4) button:nth-child(1) > p")
)
.click();
await driver.findElement(By.name("todo")).click();
await driver.findElement(By.name("todo")).click();
{
const element = await driver.findElement(By.name("todo"));
await driver.actions({ bridge: true }).doubleClick(element).perform();
}
await driver.findElement(By.name("todo")).sendKeys("All Done");
await driver
.findElement(By.css(".input-container:nth-child(3) .save-btn"))
.click();
await driver.findElement(By.name("todo")).click();
await driver.findElement(By.name("todo")).sendKeys("Done");
await driver
.findElement(By.css(".input-container:nth-child(4) .save-btn"))
.click();
await driver.findElement(By.css(".dropbtn")).click();
await driver.findElement(By.css("button:nth-child(3) > p")).click();
await driver
.findElement(By.css(".root-container:nth-child(4) .checkbox svg"))
.click();
await driver.findElement(By.css(".dropbtn > p")).click();
await driver
.findElement(By.css(".group > button:nth-child(1) > p"))
.click();
await driver
.findElement(By.css(".root-container:nth-child(5) .edit"))
.click();
await driver
.findElement(By.css(".root-container:nth-child(6) .toolkit-edit svg"))
.click();
await driver
.findElement(By.css(".root-container:nth-child(7) .toolkit-edit path"))
.click();
await driver
.findElement(By.css(".root-container:nth-child(7) .color-delete > p"))
.click();
await driver
.findElement(By.css(".root-container:nth-child(6) .color-delete > p"))
.click();
await driver
.findElement(By.css(".root-container:nth-child(5) .color-delete > p"))
.click();
await driver.close();
});
});
<file_sep>/src/test/2.addbyclick.spec.js
// Generated by Selenium IDE
const { Builder, By } = require("selenium-webdriver");
import { timeout } from "../util/timeout";
describe("2_add_by_click", function () {
timeout(30000);
let driver;
beforeEach(async function () {
driver = await new Builder().forBrowser("chrome").build();
});
afterEach(async function () {
await driver.quit();
});
it("2_add_by_click", async function () {
await driver.get("http://localhost:3000/");
await driver.manage().window().setRect(1920, 1080);
await driver.findElement(By.name("todo")).click();
await driver.findElement(By.name("todo")).sendKeys("test by click");
await driver.findElement(By.css(".save-btn")).click();
await driver.close();
});
});
<file_sep>/src/services/crudData.js
import {
ADD_DATA,
LOAD_DATA,
LOADING,
UPDATE_DATA,
REMOVE_DATA,
} from "../contexts/AppState";
import { v4 as uuidv4 } from "uuid";
export const createData = async (dispatch, task) => {
// You can await here
try {
task.id = uuidv4();
fetch(`${window.env.API_URL}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(task),
});
dispatch({ type: ADD_DATA, payload: task });
} catch (err) {
alert(err.message);
}
};
export const readData = async (dispatch) => {
// You can await here
dispatch({ type: LOADING });
try {
const response = await fetch(window.env.API_URL);
const todoList = await response.json();
await dispatch({ type: LOAD_DATA, payload: todoList });
} catch (err) {
alert(err.message);
dispatch({ type: LOAD_DATA, payload: [] });
}
};
export const updateData = async (dispatch, task) => {
// You can await here
try {
fetch(`${window.env.API_URL}/${task.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(task),
});
dispatch({ type: UPDATE_DATA, payload: task });
} catch (err) {
alert(err.message);
}
};
export const deleteData = async (dispatch, id) => {
// You can await here
try {
fetch(`${window.env.API_URL}/${id}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
});
dispatch({ type: REMOVE_DATA, payload: id });
} catch (err) {
alert(err.message);
}
};
<file_sep>/src/contexts/AppState.js
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
export const display = {
true: { display: "grid" },
false: { display: "none" },
};
export const menu = ["All", "Done", "Undone"];
export const CHANGE_MENU = "CHANGE MENU";
export const LOADING = "LOADING";
export const Loading = {
true: (
<span className="loading">
<FontAwesomeIcon icon="spinner" title="spinner"/>
</span>
),
false: <></>,
};
export const LOAD_DATA = "LOAD DATA";
export const ADD_DATA = "ADD DATA";
export const UPDATE_DATA = "UPDATE DATA";
export const REMOVE_DATA = "REMOVE DATA";
<file_sep>/src/test/4.editbyclick.spec.js
// Generated by Selenium IDE
const { Builder, By } = require("selenium-webdriver");
import { timeout } from "../util/timeout";
describe("4_edit_by_click", function () {
timeout(30000);
let driver;
beforeEach(async function () {
driver = await new Builder().forBrowser("chrome").build();
});
afterEach(async function () {
await driver.quit();
});
it("4_edit_by_click", async function () {
await driver.get("http://localhost:3000/");
await driver.manage().window().setRect(1920, 1080);
await driver
.findElement(By.css(".root-container:nth-child(6) .toolkit-edit svg"))
.click();
await driver
.findElement(
By.css(".root-container:nth-child(6) button:nth-child(1) > p")
)
.click();
await driver.findElement(By.name("todo")).click();
await driver.findElement(By.name("todo")).click();
await driver.findElement(By.name("todo")).sendKeys("test edit by click");
await driver
.findElement(By.css(".input-container:nth-child(6) .save-btn"))
.click();
await driver.close();
});
});
<file_sep>/src/components/ToDoItem.js
import { useState, useContext } from "react";
import { CheckBox } from "./checkBox";
import { EllipsisH } from "../res/ellipsisH";
import { display } from "../contexts/AppState";
import { MenuButton } from "./menuButton";
import { AddTodoField } from "./addTodo";
import { deleteData } from "../services/crudData";
import { AppContext } from "../contexts/AppContext";
import PropTypes from "prop-types"
export const ToDoItem = ({ task }) => {
const { dispatch } = useContext(AppContext);
const [showEdit, setShowEdit] = useState(false);
const [show, setShow] = useState(false);
const inputStyle = {
true: {
textDecorationLine: "line-through",
color: "#A9A9A9",
},
false: {
color: "black",
},
};
const menus = [
{
menu: "Edit",
fnc: () => {
setShowEdit(true);
toggleHandler();
},
},
{
menu: "Delete",
fnc: () => {
deleteData(dispatch, task.id);
toggleHandler();
},
},
];
const toggleHandler = () => {
setShow(!show);
};
const component = {
true: <AddTodoField todo={task} switchShow={setShowEdit} />,
false: (
<div className="root-container">
<div className="input-container">
<div className="box-checklist">
<div className="checkbox">
<CheckBox task={task} />
</div>
<div className="box-checklist-show">
<p className="todofield" style={inputStyle[task.completed]}>
{task.title}
</p>
</div>
<div className="toolkit-edit">
<button
className="edit"
aria-haspopup="true"
onClick={toggleHandler}
>
<EllipsisH />
</button>
<div className="dropdown-edit" style={{ ...display[show] }}>
<div className="group-edit">
{menus.map((menu, i) => (
<MenuButton
expect={menu.menu}
fnc={menu.fnc}
main={task.id}
key={i}
/>
))}
</div>
</div>
</div>
</div>
</div>
</div>
),
};
return component[showEdit];
};
ToDoItem.propTypes = {
task: PropTypes.shape({
id: PropTypes.string,
title: PropTypes.string,
completed: PropTypes.bool,
})
}
<file_sep>/src/test/5.delete.spec.js
// Generated by Selenium IDE
const { Builder, By } = require("selenium-webdriver");
import { timeout } from "../util/timeout";
describe("5_delete", function () {
timeout(30000);
let driver;
beforeEach(async function () {
driver = await new Builder().forBrowser("chrome").build();
});
afterEach(async function () {
await driver.quit();
});
it("5_delete", async function () {
await driver.get("http://localhost:3000/");
await driver.manage().window().setRect(1920, 1080);
await driver
.findElement(By.css(".root-container:nth-child(5) path"))
.click();
await driver
.findElement(By.css(".root-container:nth-child(5) .color-delete > p"))
.click();
await driver
.findElement(By.css(".root-container:nth-child(5) .toolkit-edit svg"))
.click();
await driver
.findElement(By.css(".root-container:nth-child(5) .color-delete > p"))
.click();
await driver.close();
});
});
<file_sep>/src/components/addTodo.js
import { useState, useContext, useEffect } from "react";
import { createData, updateData } from "../services/crudData";
import { AppContext } from "../contexts/AppContext";
import { display } from '../contexts/AppState';
import classNames from "classnames";
export const AddTodoField = ({ todo, switchShow }) => {
const initTodo = { title: "", completed: false };
const [show, setShow] = useState(false);
const [edit, setEdit] = useState(false);
const [task, setTask] = useState(initTodo);
const { dispatch } = useContext(AppContext);
const func = {
true: () => {
updateData(dispatch, task);
switchShow(false);
},
false: () => {
createData(dispatch, task);
},
};
useEffect(() => {
const checkSetEdit = () => {
if (todo) {
setTask(todo);
setEdit(true);
setShow(true);
}
};
checkSetEdit();
}, [todo]);
const handleChange = (e) => {
setTask({ ...task, title: e.target.value });
};
const save = () => {
const og = task;
try {
func[edit](task);
setTask(initTodo);
setShow(false);
} catch (error) {
setTask(og);
}
};
const keyPress = (e) => {
if (e.keyCode === 13) {
save();
}
};
const handleSave = () => {
save();
};
return (
<div className={classNames('input-container', {"last": !edit})}>
<div className="box-checklist">
<div className="box-checklist-input">
<input
className="todofield-input"
type="text"
name="todo"
placeholder="Add your todo..."
onKeyDown={keyPress}
value={task.title}
onChange={handleChange}
onFocus={() => {
setShow(true);
}}
/>
</div>
<div className='box-checklist-save' style={{...display[show]}}>
<button className="save-btn" onClick={handleSave}>
Save
</button>
</div>
</div>
</div>
);
};
<file_sep>/src/App.js
import "./styles/App.scss";
import { useReducer, useEffect } from "react";
import { AppContext, initialState } from "./contexts/AppContext";
import { reducer } from "./contexts/AppReducer";
import { readData } from "./services/crudData";
import { Progress } from "./components/progressPanel";
import { TaskHeader } from "./components/TaskHeader";
import { TodoPanel } from "./components/toDoPanel";
import { AddTodoField } from "./components/addTodo";
import registerFaIcons from './res/registerFaIcons';
registerFaIcons();
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
// adjust args to your needs
readData(dispatch);
}, []);
return (
<AppContext.Provider value={{ state, dispatch }}>
<div className="App">
<div className="root-container">
<div className="box">
<div className="root-container">
<Progress />
<TaskHeader />
</div>
<TodoPanel />
<AddTodoField />
</div>
</div>
</div>
</AppContext.Provider>
);
}
export default App;
<file_sep>/src/mock/api.js
export const getToDoList = () => {
return new Promise((resolve) =>
setTimeout(() => {
resolve({
json: () =>
Promise.resolve([
{
id: "5fe3f4ca-193c-4170-83c1-cb5a19908601",
title: "Buy food for dinner",
completed: true,
},
{
id: "f619466c-a016-4281-b584-7db2795d103d",
title: "Call Marie at 10.00 PM",
completed: false,
},
{
id: "5fe3f4ca-193c-4170-83c1-cb5a19908602",
title: "Write a react blog post",
completed: false,
},
]),
});
},500)
// 200 + Math.random() * 300)
);
};
<file_sep>/src/test/6.addandchangemenu.spec.js
// Generated by Selenium IDE
const { Builder, By, Key } = require("selenium-webdriver");
import { timeout } from "../util/timeout";
describe("6_add_and_change_menu", function () {
timeout(30000);
let driver;
beforeEach(async function () {
driver = await new Builder().forBrowser("chrome").build();
});
afterEach(async function () {
await driver.quit();
});
it("6_add_and_change_menu", async function () {
await driver.get("http://localhost:3000/");
await driver.manage().window().setRect(1920, 1080);
await driver.findElement(By.name("todo")).click();
await driver.findElement(By.name("todo")).sendKeys("All");
await driver.findElement(By.name("todo")).sendKeys(Key.ENTER);
await driver.findElement(By.css(".dropbtn")).click();
await driver
.findElement(By.css(".group > button:nth-child(2) > p"))
.click();
await driver.findElement(By.name("todo")).click();
await driver.findElement(By.name("todo")).sendKeys("Done");
await driver.findElement(By.css(".save-btn")).click();
await driver.findElement(By.css(".dropbtn")).click();
await driver.findElement(By.css("button:nth-child(3) > p")).click();
await driver.findElement(By.name("todo")).click();
await driver.findElement(By.name("todo")).sendKeys("Undone");
await driver.findElement(By.name("todo")).sendKeys(Key.ENTER);
await driver.findElement(By.css(".dropbtn > p")).click();
await driver
.findElement(By.css(".group > button:nth-child(1) > p"))
.click();
await driver.close();
});
});
| 8f22a0cb706490cce26078d0efa16e3d3473b935 | [
"JavaScript"
] | 11 | JavaScript | patorseing/todoapp-datawow | dd6299797a31564ac446cfb8c252b33b58e2f7fa | 2a731170902c8117c4af35d08ee2696ba76abdee |
refs/heads/master | <repo_name>SpaaaaceMan/ACM<file_sep>/src/algorithms/AbstractAlgo.java
package algorithms;
import java.util.ArrayList;
import GraphModel.Edge;
import GraphModel.Graph;
public abstract class AbstractAlgo implements IStrategyACM{
protected Graph mainGraph;
protected Graph acm;
protected ArrayList<Edge> edgesNotInACM;
protected int finalWeight;
public void createACM() {
System.out.println("Arbre couvrant minimal obtenu à l'aide de l'algorithme de " + getNameAlgo());
edgesNotInACM = new ArrayList<Edge>();
edgesNotInACM = mainGraph.getEdges();
acm = new Graph(getMainGraph().getName() + "ACM(" + getNameAlgo() + ")", mainGraph.isWeighted());
finalWeight = 0;
initACM();
}
public int getMin(ArrayList<Edge> edgesFound) {
int values[] = new int [edgesFound.size()];
for (int i = 0; i < values.length; i++) {
values[i] = edgesFound.get(i).getValue();
}
int min = values[0];
if (values.length > 1) {
for (int i = 1; i < values.length; i++) {
if (values[i] < min) {
min = values[i];
}
}
}
return min;
}
public Graph getMainGraph() {
return mainGraph;
}
public void setMainGraph(Graph mainGraph) {
this.mainGraph = mainGraph;
}
}
<file_sep>/StrategyKruskal.java
package algorithms;
import java.util.ArrayList;
import GraphModel.Edge;
import GraphModel.Graph;
import GraphModel.Vertice;
public class StrategyKruskal extends AbstractAlgo {
private ArrayList<Graph> subGraphs = new ArrayList<>();
public Graph findACM(Graph graph) {
setMainGraph(graph);
createACM();
int lastIndex = mainGraph.getVertices().size() - 1;
//parcours des arêtes triées par poids
for (Edge e : edgesNotInACM) {
//lorsque le nombre d'arête de l'acm = N - 1 c'est fini
if (acm.getEdges().size() == lastIndex) break;
Graph subGraph1 = null;
Graph subGraph2 = null;
//TO DO attention les sous graphes ne sont jamais affecté !!!
for (Graph g : subGraphs) {
for (Vertice v : g.getVertices()) {
//si le sous-graphe possède l'un des sommets de l'arête minimale courante
if (v.getEdges().contains(e)) {
if (subGraph1 == null) {
subGraph2 = g;
}
else
subGraph1 = g;
break;
}
}
}
if (!willCreateACycle(subGraph1, e)) {
//acm.addEdge(e);
mergeSubGraphs(subGraph1, subGraph2, e);
acm = subGraph1;
}
}
return acm;
}
public void initACM() {
sortEdgesByWeight();
for (Vertice v : mainGraph.getVertices()) {
String name = "subGraph(" + v.getName() + ")";
Graph subGraph = new Graph(name , mainGraph.isWeighted());
subGraph.addVertice(v);
subGraphs.add(subGraph);
}
}
private void mergeSubGraphs(Graph subGraph1, Graph subGraph2, Edge e) {
for (Vertice v : subGraph2.getVertices()) {
//subGraph1.addVertice(v);
}
subGraph1.addEdge(e);
subGraphs.remove(subGraph2);
}
/**
* @brief check if add edges to the acm will create a cycle
* @param edges list of edges to check
* @return TRUE if an edge induces the creation of a cycle, FALSE otherwise
*/
public boolean willCreateACycle(Graph g, Edge e) {
if (!g.getVertices().contains(e.getVertice1()) || !g.getVertices().contains(e.getVertice2())) {
return false;
}
return true;
}
private void sortEdgesByWeight() {
if (edgesNotInACM == null || edgesNotInACM.size() == 0) {
return;
}
quickSort(0, edgesNotInACM.size() - 1);
}
private void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
// calculate pivot number, I am taking pivot as middle index number
int pivot = edgesNotInACM.get(lowerIndex+(higherIndex-lowerIndex)/2).getValue();
// Divide into two arrays
while (i <= j) {
/**
* In each iteration, we will identify a number from left side which
* is greater then the pivot value, and also we will identify a number
* from right side which is less then the pivot value. Once the search
* is done, then we exchange both numbers.
*/
while (edgesNotInACM.get(i).getValue() < pivot) {
i++;
}
while (edgesNotInACM.get(j).getValue() > pivot) {
j--;
}
if (i <= j) {
exchangeNumbers(i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
}
private void exchangeNumbers(int i, int j) {
Edge temp = edgesNotInACM.get(i);
edgesNotInACM.set(i, edgesNotInACM.get(j));
edgesNotInACM.set(j, temp);
}
public String getNameAlgo() {
return "kruskal";
}
}
<file_sep>/Client.java
package client;
import algorithms.IStrategyACM;
import algorithms.StrategyKruskal;
import algorithms.StrategyPrim;
import GraphModel.Graph;
import GraphModel.Vertice;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
Graph g = new Graph("mon graph", true);
Vertice v1 = new Vertice("S1");
Vertice v2 = new Vertice("S2");
Vertice v3 = new Vertice("S3");
Vertice v4 = new Vertice("S4");
Vertice v5 = new Vertice("S5");
Vertice v6 = new Vertice("S6");
Vertice v7 = new Vertice("S7");
Vertice v8 = new Vertice("S8");
Vertice v9 = new Vertice("S9");
g.addVertice(v1);
g.addVertice(v2);
g.addVertice(v3);
g.addVertice(v4);
g.addVertice(v5);
g.addVertice(v6);
g.addVertice(v7);
g.addVertice(v8);
g.addVertice(v9);
g.addEdge(v1, v2, 8);
g.addEdge(v2, v3, 7);
g.addEdge(v3, v4, 9);
g.addEdge(v4, v5, 10);
g.addEdge(v5, v6, 2);
g.addEdge(v6, v8, 1);
g.addEdge(v8, v9, 8);
g.addEdge(v9, v1, 4);
g.addEdge(v1, v8, 11);
g.addEdge(v8, v7, 7);
g.addEdge(v7, v6, 6);
g.addEdge(v7, v2, 2);
g.addEdge(v2, v5, 4);
//IStrategyACM strat = new StrategyPrim();
IStrategyACM strat = new StrategyKruskal();
Graph acm = strat.findACM(g);
System.out.println(g.toString());
System.out.println(acm.toString());
}
}
<file_sep>/IStrategyACM.java
package algorithms;
import GraphModel.Graph;
public interface IStrategyACM {
public Graph findACM(Graph graph);
public String getNameAlgo();
public void initACM();
}
<file_sep>/README.md
# ACM
Devoir 2 d'algorithmique avancé
<file_sep>/src/GraphModel/Vertice.java
package GraphModel;
import java.util.ArrayList;
public class Vertice {
private String name;
private ArrayList<Edge> edges;
public Vertice(String name) {
this.name = name;
this.edges = new ArrayList<Edge>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
public ArrayList<Edge> getEdges() {
return edges;
}
public void setEdges(ArrayList<Edge> edges) {
this.edges = edges;
}
}
<file_sep>/serweb3.c
#include "bor-util.h"
#include "bor-timer.h"
#define TRUE 1
#define FALSE 0
#define SLOT_NB 30
#define REQSIZE 4096
#define REPSIZE 4096
int mainLoop;
typedef enum {E_LIBRE, E_LIRE_REQUETE, E_ECRIRE_REPONSE, E_LIRE_FICHIER, E_ENVOYER_FICHIER} Etat;
typedef enum { M_NONE, M_GET, M_TRACE} Id_methode;
typedef enum {
C_OK = 200,
C_BAD_REQUEST = 400,
C_NOT_FOUND = 404,
C_METHOD_UNKNOWN = 501
} Code_reponse;
typedef struct {
char methode[REQSIZE],
url[REQSIZE],
version[REQSIZE],
chemin[REQSIZE];
Id_methode id_meth;
Code_reponse code_rep;
} Infos_entete;
typedef struct {
Etat etat;
char fic_bin[FICSIZE]; /* memorise [tronçon] in a file */
int fic_pos; /* current position in the [tronçon] */
int fic_len; /* size of the [tronçon] */
int soc; /* Socket de service, defaut : -1 */
struct sockaddr_in adr; /* Adresse du client */
char req[REQSIZE]; /* Requete du client */
int req_pos; /* position courante lecture requete */
int fin_entete; /* position fin de l'entete */
char rep[REPSIZE]; /* Reponse au client */
int rep_pos; /* position reponse non-envoyé */
int fic_fd; /* file descriptor of the webpage */
int handle; /* handle of a timer */
} Slot;
typedef struct {
Slot slots[SLOT_NB];
int soc_ec; /* Socket d'ecoute */
struct sockaddr_in adr; /* Adresse du serveur */
} Serveur;
char *get_http_error_message (Code_reponse code) {
switch (code) {
case C_OK: return "OK";
case C_BAD_REQUEST: return "BAD REQUEST";
case C_NOT_FOUND: return "ERROR 404 : NOT FOUND";
case C_METHOD_UNKNOWN: return "UNKNOWN METHODE";
default: return "UNKNOWN ERROR";
}
}
Id_methode get_id_methode (char *methode) {
if (strcasecmp(methode, "GET") == 0) {
return M_GET;
}
if (strcasecmp(methode, "TRACE") == 0) {
return M_TRACE;
}
return M_NONE;
}
void init_slot (Slot *o) {
o->etat = E_LIBRE;
o->soc = -1;
o->req[0] = '\0';
o->req_pos = 0;
o->fin_entete = 0;
o->rep[0] = '\0';
o->rep_pos = 0;
o->fic_fd = -1;
o->fic_len = 0;
o->fic_pos = 0;
}
int slot_est_libre (Slot *o) {
return o->etat == E_LIBRE;
}
void liberer_slot (Slot *o) {
if (slot_est_libre(o)) return;
if (o->fic_fd != -1) close(o->fic_fd);
bor_timer_remove(o->handle);
close(o->soc);
init_slot(o);
}
void init_serveur (Serveur *ser) {
printf("Server : initialization...\n");
for (size_t i = 0; i < SLOT_NB; i++) {
init_slot(&ser->slots[i]);
}
ser->soc_ec = -1;
}
int chercher_slot_libre (Serveur *ser) {
for (size_t i = 0; i < SLOT_NB; i++) {
if (slot_est_libre(&ser->slots[i])) return i;
}
return -1;
}
int demarrer_serveur (Serveur *ser, int port) {
printf("Server : starting...\n");
init_serveur(ser);
ser->soc_ec = bor_create_socket_in( SOCK_STREAM, port, &ser->adr);
if (ser->soc_ec < 0) {
return -1;
}
if (bor_listen(ser->soc_ec, 8) < 0) {
close(ser->soc_ec);
return -1;
}
return 0;
}
void fermer_serveur (Serveur *ser) {
printf("Server : closing...\n");
close(ser->soc_ec);
for (size_t i = 0; i < SLOT_NB; i++) {
liberer_slot(&ser->slots[i]);
}
}
int accepter_connexion (Serveur *ser) {
printf("Serveur: connexion en cours...\n");
struct sockaddr_in adr_tmp;
int soc_tmp = bor_accept_in(ser->soc_ec, &adr_tmp);
if (soc_tmp < 0) {
return -1;
}
int slot = chercher_slot_libre(ser);
if (slot < 0) {
printf("Serveur: plus de slot libre : %s\n", bor_adrtoa_in(&adr_tmp));
close(soc_tmp);
return 0; //pb temporaire
}
printf("Serveur[%d]: connexion etablie avec %s\n", soc_tmp, bor_adrtoa_in(&adr_tmp));
Slot *o = &ser->slots[slot];
o->handle = bor_timer_add(30000, o);
o->etat = E_LIRE_REQUETE;
o->soc = soc_tmp;
o->adr = adr_tmp;
return 1;
}
int preparer_fichier (Slot *o, Infos_entete *ie) {
sscanf(ie->url, "%[^? ]", ie->chemin);
printf("server [%d]: chemin capté : %s\n", o->soc, ie->chemin);
int k = open(ie->chemin, O_RDWR, 0644);
if (k < 0) {
perror("Server error: echec ouverture fichier");
return -1;
}
o->fic_fd = k;
return 0;
}
int lire_suite_requete (Slot *o) {
int k = bor_read_str (o->soc, o->req + o->req_pos, REQSIZE - o->req_pos);
if (k > 0) {
o->req_pos += k;
}
return k;
}
int chercher_fin_entete (Slot *o, int debut) {
for (size_t i = debut; o->req[i] != '\0'; i++) {
if ((o->req[i] == '\n' && o->req[i+1] == '\n') ||
(o->req[i] == '\r' && o->req[i+1] == '\n' && o->req[i+2] == '\r' && o->req[i+3] == '\n')) {
return i;
}
}
return -1;
}
void analyser_requete (Slot *o, Infos_entete *ie) {
ie->methode[0] = 0;
ie->url[0] = 0;
ie->version[0] = 0;
sscanf(o->req, "%s %s %s", ie->methode, ie->url, ie->version);
printf("Server [%d]: methode : %s url : %s version : %s\n", o->soc, ie->methode, ie->url, ie->version);
if (ie->methode[0] == 0 || ie->url[0] == 0 || ie->version[0] == 0 ) {
printf("Billy ?\n");
ie->code_rep = C_BAD_REQUEST;
return;
}
ie->id_meth = get_id_methode(ie->methode);
if (ie->id_meth == M_NONE) {
ie->code_rep = C_METHOD_UNKNOWN;
return;
}
if (ie->id_meth == M_GET) {
int k = preparer_fichier(o, ie);
if (k < 0) {
ie->code_rep = C_NOT_FOUND;
return;
}
}
ie->code_rep = C_OK;
}
void preparer_reponse (Slot *o, Infos_entete *ie) {
int pos = 0;
pos += sprintf (o->rep+pos,"HTTP/1.1 ");
pos += sprintf (o->rep+pos, "%d", ie->code_rep);
pos += sprintf (o->rep+pos, "%s", get_http_error_message(ie->code_rep));
pos += sprintf (o->rep+pos,"\nDate: ");
time_t tmp;
time(&tmp);
pos += sprintf (o->rep+pos, "%d", ctime(&tmp));
pos += sprintf (o->rep+pos,"Server: serweb2\nConnection: close\nContent-Type: ");
if (ie->code_rep != C_OK) {
pos += sprintf (o->rep+pos, "text/html\n\n");
pos += sprintf (o->rep+pos, "<html><head>\n");
pos += sprintf (o->rep+pos, " <title>");
pos += sprintf (o->rep+pos, "%s", get_http_error_message(ie->code_rep));
pos += sprintf (o->rep+pos, "</title>\n");
pos += sprintf (o->rep+pos, "</head><body>\n");
pos += sprintf (o->rep+pos, " <h1>%d : %s</h1>\n", ie->code_rep, get_http_error_message(ie->code_rep));
pos += sprintf (o->rep+pos, "</body></html>\n");
return;
}
switch (ie->id_meth) {
case M_TRACE:
pos += sprintf (o->rep+pos, "message/http\n\n");
pos += sprintf (o->rep+pos, o->req);
break;
case M_GET:
pos += sprintf (o->rep+pos, "text/html\n\n");
pos += sprintf (o->rep+pos, "<html><head>\n");
pos += sprintf (o->rep+pos, " <title>Fichier trouvé</title>\n");
pos += sprintf (o->rep+pos, "</head><body>\n");
pos += sprintf (o->rep+pos, " <h1>Fichier trouvé</h1>\n");
pos += sprintf (o->rep+pos, "</body></html>\n");
break;
}
}
int proceder_lecture_requete(Slot *o) {
/*printf("Server : request detected\n");
char buf[1024];
ssize_t res = bor_read_str(o->soc, buf, sizeof(buf));
if (res <= 0) {
return res;
}
printf("Client %s : %s\n", bor_adrtoa_in(&o->adr), buf);
o->etat = E_ECRIRE_REPONSE;
printf("Server [%d]: state -> writing answer\n", o->soc);
return res;*/
int prec_pos = o->req_pos;
int k = lire_suite_requete (o);
if (k <= 0) {
return -1;
}
int debut = prec_pos - 3;
if (debut < 0) debut = 0;
o->fin_entete = chercher_fin_entete (o, debut);
if (o->fin_entete < 0) {
printf("Serveur [%d: requete incomplete]\n", o->soc);
return 1;
}
printf("Serveur [%d]: requete complete : %s\n", o-> soc, o->req);
Infos_entete ie;
analyser_requete (o, &ie);
preparer_reponse (o, &ie);
o->etat = E_ECRIRE_REPONSE;
return 1;
}
int ecrire_suite_reponse (Slot *o) {
int k = bor_write_str (o->soc, o->rep + o->rep_pos);
if (k > 0) {
o->rep_pos += k;
}
return k;
}
int proceder_ecriture_reponse(Slot *o) {
printf("Server : sending answer\n");
/*char buf [1024];
sprintf(buf,
"HTTP/1.1 500 erreur du serveur \n\n\
<html><body><h1>Les gauffres sont en cours de cuisson!!!</h1></body></html>"
);
ssize_t res = bor_write_str(o->soc, buf);
if (res <= 0) {
return res;
}
printf("Server -> Client %s : %s\n", bor_adrtoa_in(&o->adr), buf);
printf("Server [%d]: state -> Reading request\n", o->soc);
o->etat = E_LIRE_REQUETE;
return 0; // Couper la connexion pour que le navigateur affiche la réponse*/
int k = ecrire_suite_reponse(o);
if (k < 0 ) return -1;
if (o->rep_pos < (int) strlen (o->rep)) {
printf("Serveur [%d]: reponse incomplete\n", o->soc);
return 1;
}
if (o->fic_fd != -1) {
o->etat = E_LIRE_FICHIER;
return 1;
}
else
return -1;
}
int proceder_lecture_fichier(Slot *o) {
o->fic_len = bor_read(o->soc, o->fic_bin, FICSIZE);
if (o->fic_len <= 0) {
return -1;
}
o->fic_pos = 0;
o->etat = E_ENVOYER_FICHIER;
return 1;
}
int proceder_envoi_fichier(Slot *o) {
int k = bor_write(o->soc, o->fic_bin + o->fic_pos, FICSIZE);
if(k < 0)
return k;
o->fic_pos += k;
if(o->fic_pos < o->fic_len) {
printf("Un message que je l'aime\n");
return 1;
}
o->etat = E_LIRE_FICHIER;
return 1;
}
void traiter_slot_si_eligible (Slot *o, fd_set *set_read, fd_set *set_write) {
if (slot_est_libre(o)) return;
int k = 1; //pour eviter une deconnexion par defaut, si k pas initialisé dans le switch
switch (o->etat) {
case E_LIRE_REQUETE:
if (FD_ISSET(o->soc, set_read))
k = proceder_lecture_requete(o);
break;
case E_ECRIRE_REPONSE:
if (FD_ISSET(o->soc, set_write))
k = proceder_ecriture_reponse(o);
break;
case E_LIRE_FICHIER:
if (FD_ISSET(o->soc, set_read))
k = proceder_lecture_fichier(o);
break;
case E_ENVOYER_FICHIER:
if (FD_ISSET(o->soc, set_write))
k = proceder_envoi_fichier(o);
break;
default:;
}
if (k <= 0) {
printf("Serveur[%d]: liberation du slot\n", o->soc);
liberer_slot(o);
}
}
void inserer_fd (int fd, fd_set *set, int *maxfd) {
FD_SET(fd, set);
if (*maxfd < fd) *maxfd = fd;
}
void preparer_select (Serveur *ser, int *maxfd, fd_set *set_read, fd_set *set_write) {
FD_ZERO (set_read);
FD_ZERO (set_write);
*maxfd = -1;
inserer_fd (ser->soc_ec, set_read, maxfd);
for (size_t i = 0; i < SLOT_NB; i++) {
Slot *o = &ser->slots[i];
switch (o->etat) {
case E_LIBRE:
continue;
break;
case E_LIRE_REQUETE:
inserer_fd (o->soc, set_read, maxfd);
break;
case E_ECRIRE_REPONSE:
inserer_fd (o->soc, set_write, maxfd);
break;
case E_LIRE_FICHIER:
inserer_fd (o->soc, set_read, maxfd);
break;
case E_ENVOYER_FICHIER:
inserer_fd (o->soc, set_write, maxfd);
break;
default:;
}
}
}
int faire_scrutation (Serveur *ser, int *maxFd, fd_set *set_read, fd_set *set_write) {
preparer_select(ser, maxFd, set_read, set_write);
int res = select(*maxFd + 1, set_read, set_write, NULL, bor_timer_delay());
if (res < 0) {
if (errno == EINTR) {
printf("Signal received\n");
return res;
}
else {
perror("select");
return res;
}
}
else if (res == 0){
Slot *o = bor_timer_data();
printf("Connection interrompu[%d] : timeout\n", o->soc);
liberer_slot(o);
}
// FD's processing
else {
if(FD_ISSET(ser->soc_ec, set_read)) {
res = accepter_connexion(ser);
if (res < 0) {
return res;
}
}
for (size_t i = 0; i < SLOT_NB; ++i) {
traiter_slot_si_eligible(&ser->slots[i], set_read, set_write);
}
}
return 1;
}
void interruptionHandler(int sig) {
(void) sig;
printf("Server : interruption detected\n");
mainLoop = 0;
}
int main (int argc, char *argv[]) {
if (argc - 1 != 1) {
fprintf(stderr, "Error, not enough arguments.\nUsage : %s port", argv[0]);
return 1;
}
int port;
if (sscanf(argv[1], "%d ", &port) == EOF) {
fprintf(stderr, "Error : invalid argument for port\n");
return 1;
}
Serveur ser;
if (demarrer_serveur(&ser, port) < 0) {
fprintf(stderr, "Error : on server starting. Maybe port is invalid\n");
return 1;
}
mainLoop = 1;
bor_signal(SIGINT, interruptionHandler, SA_RESTART);
int res = 0;
int maxFd;
fd_set setRead, setWrite;
while(mainLoop) {
res = faire_scrutation(&ser, &maxFd, &setRead, &setWrite);
if(res < 0) {
fprintf(stderr, "error on scrutation\n");
}
}
fermer_serveur(&ser);
printf("Server : closed\n");
return (res < 0 ? 1 : 0);
}
<file_sep>/src/algorithms/StrategyKruskal.java
package algorithms;
import java.util.ArrayList;
import GraphModel.Edge;
import GraphModel.Graph;
public class StrategyKruskal extends AbstractAlgo {
public Graph findACM(Graph graph) {
setMainGraph(graph);
createACM();
for (Edge e : edgesNotInACM) {
}
return null;
}
public void initACM() {
sort();
Edge first = edgesNotInACM.get(0);
acm.addEdge(first);
edgesNotInACM.remove(first);
}
public boolean isACycle(ArrayList<Edge> edges) {
for (Edge e : edges) {
if (!acm.getVertices().contains(e.getVertice1()) || !acm.getVertices().contains(e.getVertice2())) {
return false;
}
}
return true;
}
public void sort() {
if (edgesNotInACM == null || edgesNotInACM.size() == 0) {
return;
}
quickSort(0, edgesNotInACM.size() - 1);
}
private void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
// calculate pivot number, I am taking pivot as middle index number
int pivot = edgesNotInACM.get(lowerIndex+(higherIndex-lowerIndex)/2).getValue();
// Divide into two arrays
while (i <= j) {
/**
* In each iteration, we will identify a number from left side which
* is greater then the pivot value, and also we will identify a number
* from right side which is less then the pivot value. Once the search
* is done, then we exchange both numbers.
*/
while (edgesNotInACM.get(i).getValue() < pivot) {
i++;
}
while (edgesNotInACM.get(j).getValue() > pivot) {
j--;
}
if (i <= j) {
exchangeNumbers(i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
}
private void exchangeNumbers(int i, int j) {
Edge temp = edgesNotInACM.get(i);
edgesNotInACM.set(i, edgesNotInACM.get(j));
edgesNotInACM.set(j, temp);
}
public String getNameAlgo() {
return "kruskal";
}
}
| 9f7a6964794bf240af9f4d5eaa7ec02d44a2cda0 | [
"Markdown",
"Java",
"C"
] | 8 | Java | SpaaaaceMan/ACM | 5f6b60c0cd43143a6b33cc308e03a66efcd690ba | d1f01e81f00e70191e63e7093a9523ba1b38573f |
refs/heads/master | <repo_name>Artem-Marakhovskyi/smart-house-web-api<file_sep>/SmartHouse.Bll/Sensors/Services/ISensorService.cs
using SmartHouse.Entities;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace SmartHouse.Bll.Sensors.Services
{
public interface ISensorService
{
/// <summary>
/// Gets all sensors.
/// </summary>
/// <returns>Returns all sensors</returns>
Task<IEnumerable<Sensor>> GetAllAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets sensor by id.
/// </summary>
/// <param name="mac">Sensor id</param>
/// <param name="cancellationToken"></param>
/// <returns>Returns sensor by id</returns>
Task<Sensor> GetByMACAsync(string mac, CancellationToken cancellationToken);
/// <summary>
/// Updates device.
/// </summary>
/// <param name="sensorUpdateDto">Sensor updating model</param>
/// <param name="cancellationToken"></param>
/// <returns>Returns id of updated entity</returns>
Task<bool> UpdateAsync(Sensor sensorUpdateDto, CancellationToken cancellationToken);
/// <summary>
/// Deletes sensor.
/// </summary>
/// <param name="mac">Sensor id</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task DeleteAsync(string mac, CancellationToken cancellationToken);
/// <summary>
/// Gets statistics from specific date.
/// </summary>
/// <param name="dateTime">Date to start searching statistics from</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<TelemetryDynamic>> GetStatisticsAsync(DateTime dateTime, CancellationToken cancellationToken);
/// <summary>
/// Checks does db contains specific entity
/// </summary>
/// <param name="mac">Sensor mac</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> ContainsEntityWithMACAsync(string mac, CancellationToken cancellationToken);
}
}<file_sep>/SmartHouse.Api/MappingConfiguration/SensorDtoModelMappingProfile.cs
using AutoMapper;
using SmartHouse.Api.Models.Sensors;
using SmartHouse.Entities;
namespace SmartHouse.Api.MappingConfiguration
{
public class SensorDtoModelMappingProfile : Profile
{
public SensorDtoModelMappingProfile()
{
CreateMap<Sensor, SensorViewModel>();
CreateMap<SensorViewModel, Sensor>();
CreateMap<TelemetryDynamic, TelemetryDynamicViewModel>();
}
}
}
<file_sep>/SmartHouse.Api/Models/SmartHouse/SmartHouseViewModel.cs
using SmartHouse.Api.Models.Devices;
using SmartHouse.Api.Models.Sensors;
using System.Collections.Generic;
namespace SmartHouse.Api.Models.SmartHouse
{
public class SmartHouseViewModel
{
public List<DeviceViewModel> DeviceViewModels { get; set; }
public List<SensorViewModel> SensorViewModels { get; set; }
}
}
<file_sep>/SmartHouse.Bll.Tests/Devices/Services/DeviceServiceTest.cs
using AutoFixture;
using AutoFixture.AutoMoq;
using Moq;
using SmartHouse.Bll.Devices.Services;
using SmartHouse.Entities;
using SmartHub.Dal.Interfaces;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace SmartHouse.Bll.Tests.Devices.Services
{
public class DeviceServiceTest
{
private static readonly IFixture Fixture = new Fixture().Customize(new AutoMoqCustomization());
private static readonly Mock<IRepository<Device>> MockDeviceRepository = Fixture.Freeze<Mock<IRepository<Device>>>();
private readonly DeviceService _deviceService = new DeviceService(MockDeviceRepository.Object);
[Fact]
public async Task GetAllDevicesAsync_WhenCalled_ReturnsAllDevices()
{
// Arrange
MockDeviceRepository.Setup(repository => repository.GetAll(new CancellationToken(false)))
.ReturnsAsync(GetAllDevicesMethodTest(Fixture));
// Act
var devices = await _deviceService.GetAllAsync(CancellationToken.None);
// Assert
Assert.IsAssignableFrom<IEnumerable<Device>>(devices);
Assert.NotNull(devices);
}
[Fact]
public async Task GetAllDevicesAsync_WhenCalled_ReturnsEmpty()
{
// Arrange
MockDeviceRepository.Setup(repository => repository.GetAll(new CancellationToken(true)))
.ReturnsAsync(() => null);
// Act
var devices = await _deviceService.GetAllAsync(CancellationToken.None);
// Assert
Assert.Empty(devices);
}
[Fact]
public async Task GetByMACAsync_WhenCalled_ReturnsDevice()
{
// Arrange
var deviceModel = Fixture.Create<Device>();
MockDeviceRepository.Setup(repository => repository.GetByMAC("123", new CancellationToken(false)))
.ReturnsAsync(() => deviceModel);
// Act
var device = await _deviceService.GetByMACAsync("123", CancellationToken.None);
// Assert
Assert.NotNull(device);
Assert.IsType<Device>(device);
}
[Fact]
public async Task GetByMACAsync_WhenCalled_ReturnsNull()
{
// Arrange
MockDeviceRepository.Setup(repository => repository.GetByMAC("123", new CancellationToken(false)))
.ReturnsAsync(() => null);
// Act
var device = await _deviceService.GetByMACAsync("123", CancellationToken.None);
// Assert
Assert.Null(device);
}
[Fact]
public async Task UpdateAsync_WhenCalled_ReturnsTrue()
{
// Arange
var result = false;
var device = Fixture.Create<Device>();
MockDeviceRepository.Setup(repository => repository.Update(device, new CancellationToken(false)))
.Returns(() => null);
// Act
try
{
await _deviceService.UpdateAsync(device, CancellationToken.None);
}
catch (Exception e)
{
}
result = true;
// Assert
Assert.True(result);
}
[Fact]
public async Task DeleteAsync_WhenCalled_ReturnsTrue()
{
// Arange
var result = false;
var fixture = new Fixture().Customize(new AutoMoqCustomization());
MockDeviceRepository.Setup(repository => repository.Remove("1111", new CancellationToken(false)))
.Returns(() => null);
// Act
try
{
await _deviceService.DeleteAsync("1111", CancellationToken.None);
}
catch (Exception e)
{
}
result = true;
// Assert
Assert.True(result);
}
[Fact]
public async Task ContainsEntityWithMacAsync_WhenCalled_ReturnsTrue()
{
// Arrange
MockDeviceRepository.Setup(repository => repository.ContainsEntityWithMAC("1111", new CancellationToken(false)))
.ReturnsAsync(() => true);
// Act
var result = await _deviceService.ContainsEntityWithMACAsync("1111", CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task ContainsEntityWithMacAsync_WhenCalled_ReturnsFalse()
{
// Arrange
MockDeviceRepository.Setup(repository => repository.ContainsEntityWithMAC("1111", new CancellationToken(false)))
.ReturnsAsync(() => false);
// Act
var result = await _deviceService.ContainsEntityWithMACAsync("1111", CancellationToken.None);
// Assert
Assert.False(result);
}
private IEnumerable<Device> GetAllDevicesMethodTest(IFixture fixture)
{
var devices = fixture.Create<List<Device>>();
return devices;
}
}
}
<file_sep>/SmartHouse.Bll/Devices/Services/IDeviceService.cs
using SmartHouse.Entities;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace SmartHouse.Bll.Devices.Services
{
public interface IDeviceService
{
/// <summary>
/// Gets all devices.
/// </summary>
/// <returns>Returns all devices</returns>
Task<IEnumerable<Device>> GetAllAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets device by id.
/// </summary>
/// <param name="mac">Device id</param>
/// <param name="cancellationToken"></param>
/// <returns>Returns device by id</returns>
Task<Device> GetByMACAsync(string mac, CancellationToken cancellationToken);
/// <summary>
/// Updates device.
/// </summary>
/// <param name="deviceUpdateDto">Device updating model</param>
/// <param name="cancellationToken"></param>
/// <returns>Returns id of updated entity</returns>
Task<bool> UpdateAsync(Device deviceUpdateDto, CancellationToken cancellationToken);
/// <summary>
/// Deletes device.
/// </summary>
/// <param name="mac">Device id</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task DeleteAsync(string mac, CancellationToken cancellationToken);
/// <summary>
/// Checks does db contains specific entity
/// </summary>
/// <param name="mac">Device mac</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> ContainsEntityWithMACAsync(string mac, CancellationToken cancellationToken);
}
}<file_sep>/SmartHouse.Bll/SmartHouse/Services/ISmartHouseService.cs
using SmartHouse.Entities;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace SmartHouse.Bll.SmartHouse.Services
{
public interface ISmartHouseService
{
/// <summary>
/// Gets all sensors.
/// </summary>
/// <returns>Returns all sensors</returns>
Task<IEnumerable<Sensor>> GetAllSensorsAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets all devices.
/// </summary>
/// <returns>Returns all devices</returns>
Task<IEnumerable<Device>> GetAllDevicesAsync(CancellationToken cancellationToken);
}
}<file_sep>/SmartHouse.Api/Models/Sensors/SensorViewModel.cs
using SmartHouse.Entities;
using System.Collections.Generic;
namespace SmartHouse.Api.Models.Sensors
{
public class SensorViewModel
{
public string ConnectionId { get; set; }
public SlaveStatus Status { get; set; }
public string MAC { get; set; }
private List<Device> Devices { get; set; }
private TelemetryData Data { get; set; }
}
}
<file_sep>/SmartHouse.Api/SmartHubConnection/HubConnectionService.cs
using Microsoft.AspNetCore.SignalR.Client;
using SmartHouse.Entities;
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace SmartHouse.Api.SmartHubConnection
{
public class HubConnectionService : IHubConnectionService
{
private int NumberPort { get; }
private HubConnection ClientConnection { get; set; }
private string Url { get; set; }
public HubConnectionService(int port)
{
NumberPort = port;
}
public void Run()
{
var client = new UdpClient();
var requestData = Encoding.ASCII.GetBytes("Hi! I`m API and I have some requirements for you!!!");
var serverEndpoint = new IPEndPoint(IPAddress.Any, 0);
do
{
client.EnableBroadcast = true;
client.Send(requestData, requestData.Length, new IPEndPoint(IPAddress.Broadcast, NumberPort));
var serverResponseData = client.Receive(ref serverEndpoint);
var stringified = Encoding.ASCII.GetString(serverResponseData);
Console.WriteLine("Recived {0} from {1}", stringified, serverEndpoint.Address);
Url = stringified;
}
while (Url == null);
client.Close();
}
/// <summary>
/// Calls through SignalR.Client Hub(separate progect) to execute method "Run".
/// This method can change working status of specific device/sensor.
/// </summary>
/// <param name="houseSlaveInvoker">Model that comes from clients.</param>
public async void OnOffMethod(BaseHouseSlaveInvoker houseSlaveInvoker)
{
ClientConnectionAsync();
await ClientConnection.SendAsync("Run", houseSlaveInvoker);
}
/// <summary>
/// Calls through SignalR.Client Hub(separate progect) to execute method "ReturnAllDevices".
/// </summary>
/// <returns>Dictionary of received items.</returns>
public async Task<ConcurrentDictionary<string, Device>> GetAllDevicesAsync()
{
ClientConnectionAsync();
var result = await ClientConnection.InvokeCoreAsync<ConcurrentDictionary<string, Device>>("ReturnAllDevices", new object[0]);
return result;
}
/// <summary>
/// Calls through SignalR.Client Hub(separate progect) to execute method "ReturnAllSensors".
/// </summary>
/// <returns>Dictionary of received items.</returns>
public async Task<ConcurrentDictionary<string, Sensor>> GetAllSensorsAsync()
{
ClientConnectionAsync();
var result = await ClientConnection.InvokeCoreAsync<ConcurrentDictionary<string, Sensor>>("ReturnAllSensors", new object[0]);
return result;
}
private async void ClientConnectionAsync()
{
ClientConnection = new HubConnectionBuilder().WithUrl(Url).Build();
await ClientConnection.StartAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected");
}
});
}
}
}
<file_sep>/SmartHouse.Api.Tests/DeviceControllerTests/GetAllAsyncMethodTest.cs
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Moq;
using SmartHouse.Api.Controllers;
using SmartHouse.Api.Models.Devices;
using SmartHouse.Bll.Devices.Services;
using SmartHouse.Entities;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace SmartHouse.Api.Tests.DeviceControllerTests
{
public class GetAllAsyncMethodTest
{
[Fact]
public async Task GetAll_WhenCalled_ReturnsOkResult()
{
// Arrange
var mockService = new Mock<IDeviceService>();
var mockMapper = new Mock<IMapper>();
mockService.Setup(service => service.GetAllAsync(CancellationToken.None))
.ReturnsAsync(GetDevicesTest);
mockMapper.Setup(mapper => mapper.Map<IEnumerable<DeviceViewModel>>(GetDevicesTest()))
.Returns(MapDevicesToViewModelsTest);
var controller = new DevicesController(mockService.Object, mockMapper.Object);
// Act
var devices = await controller.GetAllAsync();
// Assert
Assert.IsAssignableFrom<IActionResult>(devices);
Assert.NotNull(devices);
}
//[Fact]
public async Task GetAll_WhenCavcelled_ReturnsCancelled()
{
// Arrange
var mockService = new Mock<IDeviceService>();
var mockMapper = new Mock<IMapper>();
mockService.Setup(service => service.GetAllAsync(new CancellationToken(false)))
.ReturnsAsync(() => null);
var controller = new DevicesController(mockService.Object, mockMapper.Object);
// Act
var devices = await controller.GetAllAsync();
// Assert
Assert.IsType<NotFoundResult>(devices);
}
private IEnumerable<Device> GetDevicesTest()
{
var devices = new List<Device>
{
new Device
{
ConnectionId = "0001",
MAC = "Dev1",
Methods = new List<HouseSlaveInvoker>(),
Status = SlaveStatus.On
},
new Device
{
ConnectionId = "0002",
MAC = "Dev2",
Methods = new List<HouseSlaveInvoker>(),
Status = SlaveStatus.On
}
};
return devices;
}
private IEnumerable<DeviceViewModel> MapDevicesToViewModelsTest()
{
var deviceViewModels = new List<DeviceViewModel>();
deviceViewModels.Add(new DeviceViewModel());
deviceViewModels.Add(new DeviceViewModel());
return deviceViewModels;
}
}
}
<file_sep>/SmartHouse.Api/MappingConfiguration/DeviceDtoModelModelMappingProfile.cs
using AutoMapper;
using SmartHouse.Api.Models.Devices;
using SmartHouse.Entities;
namespace SmartHouse.Api.MappingConfiguration
{
public class DeviceDtoModelModelMappingProfile : Profile
{
public DeviceDtoModelModelMappingProfile()
{
CreateMap<Device, DeviceViewModel>();
CreateMap<DeviceViewModel, Device>();
}
}
}
<file_sep>/SmartHouse.Api/Controllers/DevicesController.cs
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using SmartHouse.Api.Models.Devices;
using SmartHouse.Bll.Devices.Services;
using SmartHouse.Entities;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace SmartHouse.Api.Controllers
{
[Route("api/[controller]")]
public class DevicesController : Controller
{
private readonly IDeviceService _deviceService;
private readonly IMapper _mapper;
public DevicesController(IDeviceService service, IMapper mapper)
{
_deviceService = service;
_mapper = mapper;
}
/// <summary>
/// Get all devices
/// </summary>
/// <returns>Returns all devices</returns>
/// <response code="200">Always</response>
[HttpGet]
[ProducesResponseType(200)]
public async Task<IActionResult> GetAllAsync()
{
var devices = await _deviceService.GetAllAsync(CancellationToken.None);
var deviceViewModels = _mapper.Map<IEnumerable<DeviceViewModel>>(devices);
return Ok(deviceViewModels);
}
/// <summary>
/// Get device by mac
/// </summary>
/// <returns>Returns device by mac</returns>
/// <response code="200">If item exists</response>
/// <response code="404">If doen`t item exists</response>
[HttpGet("mac")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public async Task<IActionResult> GetAsync(string mac)
{
var device = await _deviceService.GetByMACAsync(mac, CancellationToken.None);
if (device == null)
return NotFound();
var deviceViewModel = _mapper.Map<DeviceViewModel>(device);
return Ok(deviceViewModel);
}
/// <summary>
/// Updates device.
/// </summary>
/// <param name="deviceUpdateModel">Device update model</param>
/// <response code="200">If item updated correctly</response>
/// <response code="404">If doesn`t item exists</response>
[HttpPut]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public async Task<IActionResult> UpdateAsync(DeviceViewModel deviceUpdateModel)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var device = _mapper.Map<Device>(deviceUpdateModel);
var result = await _deviceService.UpdateAsync(device, CancellationToken.None);
if (result == false)
return NotFound();
return Ok(deviceUpdateModel);
}
/// <summary>
/// Deletes device
/// </summary>
/// <param name="mac">Device mac</param>
/// <response code="204">Always</response>
[HttpDelete("mac")]
[ProducesResponseType(204)]
public async Task<IActionResult> DeleteAsync(string mac)
{
await _deviceService.DeleteAsync(mac, CancellationToken.None);
return NoContent();
}
}
}
<file_sep>/SmartHouse.Api/Controllers/SmartHouseController.cs
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using SmartHouse.Api.Models.Devices;
using SmartHouse.Api.Models.Sensors;
using SmartHouse.Api.Models.SmartHouse;
using SmartHouse.Bll.SmartHouse.Services;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace SmartHouse.Api.Controllers
{
[Route("api/[controller]")]
public class SmartHouseController : Controller
{
private readonly ISmartHouseService _service;
private readonly IMapper _mapper;
public SmartHouseController(ISmartHouseService service, IMapper mapper)
{
_service = service;
_mapper = mapper;
}
/// <summary>
/// Get all sensors and devices.
/// </summary>
/// <returns>Returns all sensors and devices. </returns>
/// <response code="200">Always</response>
[HttpGet]
[ProducesResponseType(200)]
public async Task<IActionResult> GetAllAsync(CancellationToken cancellationToken = default(CancellationToken))
{
Parallel.Invoke(
()=> _service.GetAllSensorsAsync(cancellationToken),
()=> _service.GetAllDevicesAsync(cancellationToken));
var sensors = await _service.GetAllSensorsAsync(cancellationToken);
var sensorsViewModels = _mapper.Map<List<SensorViewModel>>(sensors);
var devices = await _service.GetAllDevicesAsync(cancellationToken);
var devicesViewModels = _mapper.Map<List<DeviceViewModel>>(devices);
var totalResult = new SmartHouseViewModel();
totalResult.SensorViewModels = sensorsViewModels;
totalResult.DeviceViewModels = devicesViewModels;
return Ok(totalResult);
}
}
}
<file_sep>/SmartHouse.Api/SmartHubConnection/IHubConnectionService.cs
using SmartHouse.Entities;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace SmartHouse.Api.SmartHubConnection
{
public interface IHubConnectionService
{
void Run();
void OnOffMethod(BaseHouseSlaveInvoker houseSlaveInvoker);
Task<ConcurrentDictionary<string, Device>> GetAllDevicesAsync();
Task<ConcurrentDictionary<string, Sensor>> GetAllSensorsAsync();
}
}<file_sep>/SmartHouse.Api/Controllers/HubController.cs
using Microsoft.AspNetCore.Mvc;
using SmartHouse.Api.SmartHubConnection;
using SmartHouse.Entities;
using System.Collections.Generic;
namespace SmartHouse.Api.Controllers
{
[Route("api/[controller]")]
public class HubController : Controller
{
private readonly IHubConnectionService _connection;
public HubController(IHubConnectionService connection)
{
_connection = connection;
_connection.Run();
}
/// <summary>
/// Represents method to on/off device or sensor
/// </summary>
/// <param name="invoker">BaseHouseSlaveInvoker model</param>
[HttpPut("devices-sensors")]
public void OnOffMethod([FromBody] BaseHouseSlaveInvoker invoker)
{
_connection.OnOffMethod(invoker);
}
/// <summary>
/// Get all devices from hub
/// </summary>
/// <returns>Collection of devices</returns>
[HttpGet("devices")]
public IEnumerable<Device> GetAllDevices()
{
var devices = _connection.GetAllDevicesAsync();
var devicesDictionary = devices.Result;
var devicesList = devicesDictionary.Values;
return devicesList;
}
/// <summary>
/// Get all sensors from hub
/// </summary>
/// <returns>Collection of sensors</returns>
[HttpGet("sensors")]
public IEnumerable<Sensor> GetAllSensors()
{
var sensors = _connection.GetAllSensorsAsync();
var sensorsConcurrentDictionary = sensors.Result;
var sensorsList = sensorsConcurrentDictionary.Values;
return sensorsList;
}
}
}
<file_sep>/SmartHouse.Api/Models/Devices/DeviceViewModel.cs
using SmartHouse.Entities;
using System.Collections.Generic;
namespace SmartHouse.Api.Models.Devices
{
public class DeviceViewModel
{
public string ConnectionId { get; set; }
public SlaveStatus Status { get; set; }
public string MAC { get; set; }
public bool IsWorked { get; set; }
public List<HouseSlaveInvokerViewModel> Methods { get; set; }
}
}
<file_sep>/SmartHouse.Bll.Tests/Sensors/Services/SensorServiceTest.cs
using AutoFixture;
using AutoFixture.AutoMoq;
using Moq;
using SmartHouse.Bll.Sensors.Services;
using SmartHouse.Entities;
using SmartHub.Dal.Interfaces;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace SmartHouse.Bll.Tests.Sensors.Services
{
public class SensorServiceTest
{
private static readonly IFixture Fixture = new Fixture().Customize(new AutoMoqCustomization());
private static readonly Mock<IRepository<Sensor>> MockSensorRepository = Fixture.Freeze<Mock<IRepository<Sensor>>>();
private static readonly Mock<IRepository<TelemetryDynamic>> MockTelemetryDynamicRepository = Fixture.Freeze<Mock<IRepository<TelemetryDynamic>>>();
private readonly SensorService _sensorService = new SensorService(MockSensorRepository.Object, MockTelemetryDynamicRepository.Object);
[Fact]
public async Task GetAllDevicesAsync_WhenCalled_ReturnsAllSensors()
{
// Arange
MockSensorRepository.Setup(repository => repository.GetAll(new CancellationToken(false)))
.ReturnsAsync(GetAllSensorsTest(Fixture));
// Act
var sensors = await _sensorService.GetAllAsync(CancellationToken.None);
// Assert
Assert.IsAssignableFrom<IEnumerable<Sensor>>(sensors);
Assert.NotEmpty(sensors);
}
[Fact]
public async Task GetAllDevicesAsync_WhenCalled_ReturnsEmpty()
{
// Arange
MockSensorRepository.Setup(repository => repository.GetAll(CancellationToken.None))
.ReturnsAsync(() => null);
// Act
var sensors = await _sensorService.GetAllAsync(CancellationToken.None);
// Assert
Assert.Null(sensors);
}
[Fact]
public async Task GetAllDevicesAsync_WhenCalled_ReturnsSensor()
{
// Arange
var sensorModel = Fixture.Create<Sensor>();
MockSensorRepository.Setup(repository => repository.GetByMAC("1111", new CancellationToken(false)))
.ReturnsAsync(() => sensorModel);
// Act
var sensor = await _sensorService.GetByMACAsync("1111", CancellationToken.None);
// Assert
Assert.IsType<Sensor>(sensor);
Assert.NotNull(sensor);
}
[Fact]
public async Task GetAllSensorsAsync_WhenCalled_ReturnsEmpty()
{
// Arange
MockSensorRepository.Setup(repository => repository.GetByMAC("1111", new CancellationToken(false)))
.ReturnsAsync(() => null);
// Act
var sensor = await _sensorService.GetByMACAsync("1111", CancellationToken.None);
// Assert
Assert.Null(sensor);
}
[Fact]
public async Task UpdateAsync_WhenCalled_ReturnsTrue()
{
// Arange
var result = false;
var sensor = Fixture.Create<Sensor>();
MockSensorRepository.Setup(repository => repository.Update(sensor, new CancellationToken(false)))
.Returns(() => null);
// Act
try
{
await _sensorService.DeleteAsync("1111", CancellationToken.None);
}
catch (Exception e)
{
}
result = true;
// Assert
Assert.True(result);
}
[Fact]
public async Task DeleteAsync_WhenCalled_ReturnsTrue()
{
// Arange
var result = false;
MockSensorRepository.Setup(repository => repository.Remove("1111", new CancellationToken(false)))
.Returns(() => null);
// Act
try
{
await _sensorService.DeleteAsync("1111", CancellationToken.None);
}
catch (Exception e)
{
}
result = true;
// Assert
Assert.True(result);
}
[Fact]
public async Task ContainsEntityWithMacAsync_WhenCalled_ReturnsTrue()
{
// Arange
MockSensorRepository.Setup(repository =>
repository.ContainsEntityWithMAC("1111", new CancellationToken(false)))
.ReturnsAsync(() => true);
// Act
var result = await _sensorService.ContainsEntityWithMACAsync("1111", CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task ContainsEntityWithMacAsync_WhenCalled_ReturnsFalse()
{
// Arange
MockSensorRepository.Setup(repository =>
repository.ContainsEntityWithMAC("1111", new CancellationToken(false)))
.ReturnsAsync(() => false);
// Act
var result = await _sensorService.ContainsEntityWithMACAsync("1111", CancellationToken.None);
// Assert
Assert.False(result);
}
private IEnumerable<Sensor> GetAllSensorsTest(IFixture fixture)
{
var sensors = fixture.Create<List<Sensor>>();
return sensors;
}
}
}<file_sep>/SmartHouse.Api/DependencyInjectionExtensions.cs
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SmartHouse.Api.SmartHubConnection;
using SmartHouse.Bll.Devices.Services;
using SmartHouse.Bll.Sensors.Services;
using SmartHouse.Bll.SmartHouse.Services;
using SmartHouse.Entities;
using SmartHub.Dal.Context;
using SmartHub.Dal.Interfaces;
using SmartHub.Dal.Repositories;
using Swashbuckle.AspNetCore.Swagger;
namespace SmartHouse.Api
{
public static class DependencyInjectionExtensions
{
public static IServiceCollection ResolveDalDependencies(this IServiceCollection services,
IConfiguration configuration)
{
var databaseConnection = configuration.GetSection("MongoDb:ConnectionString").Value;
var databaseName = configuration.GetSection("MongoDb:DbName").Value;
var hubConnection = configuration.GetSection("HubConnection:Port").Value;
services.AddSingleton<IHubConnectionService>(hc =>
new HubConnectionService(int.Parse(hubConnection)));
services.AddTransient<IDatabase>(x =>
new Database(databaseConnection, databaseName));
return services;
}
public static IServiceCollection ResolveServicesDependencies(this IServiceCollection services)
{
services.AddTransient<ISensorService, SensorService>();
services.AddTransient<IDeviceService, DeviceService>();
services.AddTransient<ISmartHouseService, SmartHouseService>();
services.AddTransient<IRepository<Device>, Repository<Device>>();
services.AddTransient<IRepository<Sensor>, Repository<Sensor>>();
services.AddTransient<IRepository<TelemetryDynamic>, Repository<TelemetryDynamic>>();
return services;
}
public static IServiceCollection RegisterSwagger(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Title = "Smart House API",
Version = "v1"
});
c.IncludeXmlComments(
@"bin\Debug\netcoreapp2.0\SmartHouse.Api.xml");
});
return services;
}
}
}
<file_sep>/SmartHouse.Bll/Devices/Services/DeviceService.cs
using SmartHouse.Entities;
using SmartHub.Dal.Interfaces;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace SmartHouse.Bll.Devices.Services
{
public class DeviceService : IDeviceService
{
private readonly IRepository<Device> _deviceRepository;
public DeviceService(IRepository<Device> repository)
{
_deviceRepository = repository;
}
public async Task<IEnumerable<Device>> GetAllAsync(CancellationToken cancellationToken)
{
return await _deviceRepository.GetAll(cancellationToken);
}
public async Task<Device> GetByMACAsync(string mac, CancellationToken cancellationToken)
{
return await _deviceRepository.GetByMAC(mac, cancellationToken);
}
public async Task<bool> UpdateAsync(Device deviceUpdateDto, CancellationToken cancellationToken)
{
var doesContainedInDb = await _deviceRepository.ContainsEntityWithMAC(deviceUpdateDto.MAC, cancellationToken);
if (!doesContainedInDb)
return false;
try
{
await _deviceRepository.Update(deviceUpdateDto, cancellationToken);
}
catch (Exception e)
{
return false;
}
return true;
}
public async Task DeleteAsync(string mac, CancellationToken cancellationToken)
{
await _deviceRepository.Remove(mac, cancellationToken);
}
public async Task<bool> ContainsEntityWithMACAsync(string mac, CancellationToken cancellationToken)
{
return await _deviceRepository.ContainsEntityWithMAC(mac, cancellationToken);
}
}
}
<file_sep>/SmartHouse.Bll/Sensors/Services/SensorService.cs
using SmartHouse.Entities;
using SmartHub.Dal.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace SmartHouse.Bll.Sensors.Services
{
public class SensorService : ISensorService
{
private readonly IRepository<Sensor> _sensorRepository;
private readonly IRepository<TelemetryDynamic> _telemetryRepository;
public SensorService(IRepository<Sensor> repository, IRepository<TelemetryDynamic> telemetryRepository)
{
_sensorRepository = repository;
_telemetryRepository = telemetryRepository;
}
public async Task<IEnumerable<Sensor>> GetAllAsync(CancellationToken cancellationToken)
{
return await _sensorRepository.GetAll(cancellationToken);
}
public async Task<Sensor> GetByMACAsync(string mac, CancellationToken cancellationToken)
{
return await _sensorRepository.GetByMAC(mac, cancellationToken);
}
public async Task<bool> UpdateAsync(Sensor sensorUpdateDto, CancellationToken cancellationToken)
{
var doesContainedInDb = await _sensorRepository.ContainsEntityWithMAC(sensorUpdateDto.MAC, cancellationToken);
if (!doesContainedInDb)
return false;
try
{
await _sensorRepository.Update(sensorUpdateDto, cancellationToken);
}
catch (Exception e)
{
return false;
}
return true;
}
public async Task DeleteAsync(string mac, CancellationToken cancellationToken)
{
await _sensorRepository.Remove(mac, cancellationToken);
}
public async Task<IEnumerable<TelemetryDynamic>> GetStatisticsAsync(DateTime dateTime, CancellationToken cancellationToken)
{
var allTelemetry = await _telemetryRepository.GetAll(cancellationToken);
var matchingCriteria = allTelemetry.Where(td => td.TimeRecieve > dateTime && td.TimeRecieve <= DateTime.Now);
return matchingCriteria;
}
public async Task<bool> ContainsEntityWithMACAsync(string mac, CancellationToken cancellationToken)
{
return await _sensorRepository.ContainsEntityWithMAC(mac, cancellationToken);
}
}
}
<file_sep>/SmartHouse.Api/Models/Devices/HouseSlaveInvokerViewModel.cs
using System.Collections.Generic;
namespace SmartHouse.Api.Models.Devices
{
public class HouseSlaveInvokerViewModel
{
public string ConnectionId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<string> Arguments { get; set; }
}
}
<file_sep>/SmartHouse.Bll/SmartHouse/Services/SmartHouseService.cs
using SmartHouse.Entities;
using SmartHub.Dal.Interfaces;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace SmartHouse.Bll.SmartHouse.Services
{
public class SmartHouseService : ISmartHouseService
{
private readonly IRepository<Sensor> _sensorsRepository;
private readonly IRepository<Device> _devicesRepository;
public SmartHouseService(IRepository<Sensor> sensorsRepository, IRepository<Device> devicesRepository)
{
_sensorsRepository = sensorsRepository;
_devicesRepository = devicesRepository;
}
public Task<IEnumerable<Sensor>> GetAllSensorsAsync(CancellationToken cancellationToken)
{
return _sensorsRepository.GetAll(cancellationToken);
}
public Task<IEnumerable<Device>> GetAllDevicesAsync(CancellationToken cancellationToken)
{
return _devicesRepository.GetAll(cancellationToken);
}
}
}
<file_sep>/SmartHouse.Api/Models/Sensors/TelemetryDataViewModel.cs
namespace SmartHouse.Api.Models.Sensors
{
public class TelemetryDataViewModel
{
public string MACSensor { get; set; }
public string Value { get; set; }
public string Type { get; set; }
}
}
<file_sep>/SmartHouse.Api/Controllers/SensorsController.cs
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using SmartHouse.Api.Models.Sensors;
using SmartHouse.Bll.Sensors.Services;
using SmartHouse.Entities;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace SmartHouse.Api.Controllers
{
[Route("api/[controller]")]
public class SensorsController : Controller
{
private readonly ISensorService _sensorService;
private readonly IMapper _mapper;
public SensorsController(ISensorService service, IMapper mapper)
{
_sensorService = service;
_mapper = mapper;
}
/// <summary>
/// Get all sensors.
/// </summary>
/// <returns>Returns all sensors</returns>
/// <response code="200">Always</response>
[HttpGet]
[ProducesResponseType(200)]
public async Task<IActionResult> GetAllAsync()
{
var sensors = await _sensorService.GetAllAsync(CancellationToken.None);
var sensorViewModels = _mapper.Map<IEnumerable<SensorViewModel>>(sensors);
return Ok(sensorViewModels);
}
/// <summary>
/// Get sensor by mac.
/// </summary>
/// <param name="mac">Sensor`s mac</param>
/// <returns>Returns sensor by mac.</returns>
/// <response code="200">If item exists</response>
/// <response code="404">If item exists</response>
[HttpGet("mac")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public async Task<IActionResult> GetAsync(string mac)
{
var sensor = await _sensorService.GetByMACAsync(mac, CancellationToken.None);
if (sensor == null)
return NotFound();
var sensorViewModel = _mapper.Map<SensorViewModel>(sensor);
return Ok(sensorViewModel);
}
/// <summary>
/// Get all telemetry
/// </summary>
/// <param name="date">Start date</param>
/// <response code="200">Always</response>
[Route("getAllTelemetry")]
[HttpGet]
[ProducesResponseType(200)]
public async Task<IActionResult> GetAllTelemetryAsync(string date)
{
var dateTime = DateTime.Parse(date);
var telemetry = await _sensorService.GetStatisticsAsync(dateTime, CancellationToken.None);
return Ok(telemetry);
}
/// <summary>
/// Updates sensor.
/// </summary>
/// <param name="sensorUpdateModel">sensor update model.</param>
/// <response code="200">If item updated correctly</response>
/// <response code="404">If doesn`t item exists</response>
[HttpPut]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public async Task<IActionResult> UpdateAsync(SensorViewModel sensorUpdateModel)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var sensor = _mapper.Map<Sensor>(sensorUpdateModel);
var result = await _sensorService.UpdateAsync(sensor, CancellationToken.None);
if (result == false)
return NotFound();
return Ok(sensor);
}
/// <summary>
/// Deletes sensor.
/// </summary>
/// <param name="mac">Sensor`s mac.</param>
/// <response code="200">Always</response>
[HttpDelete("mac")]
[ProducesResponseType(200)]
public async Task<IActionResult> Delete(string mac)
{
await _sensorService.DeleteAsync(mac, CancellationToken.None);
return NoContent();
}
}
}
<file_sep>/SmartHouse.Api/Models/Sensors/TelemetryDynamicViewModel.cs
using System;
namespace SmartHouse.Api.Models.Sensors
{
public class TelemetryDynamicViewModel
{
public string Id { get; set; }
public TelemetryDataViewModel Data = new TelemetryDataViewModel();
public DateTime TimeRecieve { get; set; }
}
}
<file_sep>/SmartHouse.Api/MappingConfiguration/SmartHouseDtoModelMappingProfile.cs
using AutoMapper;
using SmartHouse.Api.Models.Devices;
using SmartHouse.Api.Models.Sensors;
using SmartHouse.Api.Models.SmartHouse;
namespace SmartHouse.Api.MappingConfiguration
{
public class SmartHouseDtoModelMappingProfile : Profile
{
public SmartHouseDtoModelMappingProfile()
{
CreateMap<SensorViewModel, SmartHouseViewModel>();
CreateMap<DeviceViewModel, SmartHouseViewModel>();
}
}
}
| 7bb40ccb82cab4f8f73fcb5e7a1ec007be38e1b6 | [
"C#"
] | 25 | C# | Artem-Marakhovskyi/smart-house-web-api | 9697d43848c5aa76b06ee7540045e3636f76762e | 7bb0ed510c48edfc18e0d14e3d5f1d55247918e5 |
refs/heads/master | <repo_name>ete02/ievgen-teslenko-kodilla-java<file_sep>/kodilla-exception/src/main/java/com/kodilla/exception/test/RouteNotFoundException.java
package com.kodilla.exception.test;
public class RouteNotFoundException extends Exception {
RouteNotFoundException(String airport) {
// metoda super pozwoli mi wywołać konstruktor klasy nadrzędnej (tej, z której dziedziczymy)
super("Airport: '" + airport + "' - not found.");
}
}
<file_sep>/kodilla-patterns2/src/main/java/com/kodilla/patterns2/observer/homework/Mentor.java
package com.kodilla.patterns2.observer.homework;
public class Mentor implements Observer{
private String username;
public Mentor(String username) {
this.username = username;
}
@Override
public void update(Queue queue) {
System.out.println(username + ": task(s) need to be check - " + queue.getTaskQueue().getLast());
}
}
<file_sep>/kodilla-patterns/src/test/java/com/kodilla/patterns/strategy/social/UserTestSuite.java
package com.kodilla.patterns.strategy.social;
import org.junit.*;
public class UserTestSuite {
private static int testCounter;
@BeforeClass
public static void beforeAllTests() {
System.out.println("This is the beginning of tests.");
}
@AfterClass
public static void afterAllTests() {
System.out.println("All tests are finished.");
}
@Before
public void beforeEveryTest() {
testCounter++;
System.out.println("Preparing to execute test #" + testCounter);
}
@Test
public void testDefaultSharingStrategies() {
//Given
User beata = new Millenials("<NAME>");
User jo = new YGeneration("<NAME>");
User dan = new ZGeneration("<NAME>");
//When
String beataSharePostFrom = beata.sharePost();
System.out.println("Beate posts from: " + beataSharePostFrom);
String joSharePostFrom = jo.sharePost();
System.out.println("Jo posts from: " + joSharePostFrom);
String danSharePostFrom = dan.sharePost();
System.out.println("Dan posts from: " + danSharePostFrom);
//Then
Assert.assertEquals("Facebook", beataSharePostFrom);
Assert.assertEquals("Twitter", joSharePostFrom);
Assert.assertEquals("Snapchat", danSharePostFrom);
}
@Test
public void testIndividualSharingStrategy() {
//Given
User beata = new Millenials("<NAME>");
//When
String beataSharePostFrom = beata.sharePost();
System.out.println("Beata posts from: " + beataSharePostFrom);
beata.setSocialPublisher(new TwitterPublisher());
beataSharePostFrom = beata.sharePost();
System.out.println("Beata posts from: " + beataSharePostFrom);
//Then
Assert.assertEquals("Twitter", beataSharePostFrom);
}
}<file_sep>/kodilla-sudoku/src/main/java/com/kodilla/sudoku/FillSudoku.java
package com.kodilla.sudoku;
import java.util.Random;
public class FillSudoku {
private static final Random RANDOM = new Random();
private SudokuBoard board;
public FillSudoku(SudokuBoard board) {
this.board = board;
}
public void fillBoard(){
}
}
<file_sep>/kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/challenges/orderservice/ProductOrderRepository.java
package com.kodilla.good.patterns.challenges.orderservice;
public class ProductOrderRepository implements OrderRepository {
public boolean createOrder(User user, Product product, int quantity) {
System.out.println("User Order " + user.getName() + " " + user.getLastName() + " for " + quantity
+ " qua. product " + product.getName() + " has been saved in the database.");
return true;
}
}
<file_sep>/kodilla-exception/src/main/java/com/kodilla/exception/test/ThirdChallenge.java
package com.kodilla.exception.test;
public class ThirdChallenge {
public static void main(String[] args) throws RouteNotFoundException {
FlightSearcher thirdChallenge = new FlightSearcher();
Flight myFlight1 = new Flight("Warsaw", "Paris");
Flight myFlight2 = new Flight("Warsaw", "Berlin");
Flight myFlight3 = new Flight("Berlin", "New-York. ");
try {
thirdChallenge.findFlight(myFlight1);
} catch (RouteNotFoundException e) {
System.out.println(e);
}
try {
thirdChallenge.findFlight(myFlight2);
} catch (RouteNotFoundException e) {
System.out.println(e);
}
try {
thirdChallenge.findFlight(myFlight3);
} catch (RouteNotFoundException e) {
System.out.println(e);
}
}
}<file_sep>/kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/challenges/food2door/Application.java
package com.kodilla.good.patterns.challenges.food2door;
public class Application {
public static void main(String[] args) {
DeliveryRequest deliveryRequest = new DeliveryRequest
("Extra Food Shop", "orange", 5, "kg");
DeliveryProcessor deliveryProcessor = new DeliveryProcessor();
deliveryProcessor.order(deliveryRequest);
}
}
<file_sep>/kodilla-testing/src/test/java/com/kodilla/testing/forum/statistics/ForumStatisticsTestSuite.java
package com.kodilla.testing.forum.statistics;
import com.kodilla.testing.forum.statistics.*;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ForumStatisticsTestSuite {
@Test // Simplify When users: 0, posts:0, comments:0 I can provide in 1 with dif. sol.
public void testCalculateStatisticsCase1() {
Statistics statisticsMock = mock(Statistics.class);
CalculateAdvStatistics calculateAdvStatistics = new CalculateAdvStatistics(statisticsMock);
Assert.assertEquals(0, calculateAdvStatistics.usersCount);
Assert.assertEquals(0, calculateAdvStatistics.averagePostsPerUser, 0.01);
Assert.assertEquals(0, calculateAdvStatistics.averageCommentsPerUser, 0.01);
Assert.assertEquals(0, calculateAdvStatistics.averageCommentsPerPost, 0.01);
Assert.assertEquals(0,calculateAdvStatistics.numberOfComments);
Assert.assertEquals(0,calculateAdvStatistics.numberOfPosts);
}
@Test //Simplify When users: 100, posts:1000, comments:100
public void testCalculateStatisticsCase2() {
Statistics statisticsMock = mock(Statistics.class);
ArrayList<String> names = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
names.add("user" + i);
}
when(statisticsMock.usersNames()).thenReturn(names);
when(statisticsMock.postsCount()).thenReturn(1000);
when(statisticsMock.commentsCount()).thenReturn(100);
CalculateAdvStatistics calculateAdvStatistics = new CalculateAdvStatistics(statisticsMock);
Assert.assertEquals(100, calculateAdvStatistics.usersCount);
Assert.assertEquals(10, calculateAdvStatistics.averagePostsPerUser, 0.01);
Assert.assertEquals(1, calculateAdvStatistics.averageCommentsPerUser, 0.01);
Assert.assertEquals(0.1, calculateAdvStatistics.averageCommentsPerPost, 0.01);
}
@Test //users: 100, posts:1000, comments:10000
public void testCalculateStatisticsCase3() {
Statistics statisticsMock = mock(Statistics.class);
ArrayList<String> names = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
names.add("user" + i);
}
when(statisticsMock.usersNames()).thenReturn(names);
when(statisticsMock.postsCount()).thenReturn(1000);
when(statisticsMock.commentsCount()).thenReturn(10000);
CalculateAdvStatistics calculateAdvStatistics = new CalculateAdvStatistics(statisticsMock);
Assert.assertEquals(100, calculateAdvStatistics.usersCount);
Assert.assertEquals(10, calculateAdvStatistics.averagePostsPerUser, 0.01);
Assert.assertEquals(100, calculateAdvStatistics.averageCommentsPerUser, 0.01);
Assert.assertEquals(10, calculateAdvStatistics.averageCommentsPerPost, 0.01);
}
}<file_sep>/kodilla-stream/src/main/java/com/kodilla/stream/StreamMain.java
package com.kodilla.stream;
import com.kodilla.stream.book.Book;
import com.kodilla.stream.book.BookDirectory;
import com.kodilla.stream.forumuser.Forum;
import com.kodilla.stream.forumuser.ForumUser;
import com.kodilla.stream.lambda.ExecuteSaySomething;
import com.kodilla.stream.lambda.Processor;
import com.kodilla.stream.lambda.Executor;
import com.kodilla.stream.beautifier.PoemBeautifier;
import com.kodilla.stream.beautifier.PoemDecorator;
import com.kodilla.stream.iterate.NumbersGenerator;
import com.kodilla.stream.lambda.ExpressionExecutor;
import com.kodilla.stream.reference.FunctionalCalculator;
import com.kodilla.stream.person.People;
import com.kodilla.stream.book.BookDirectory;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Map;
import com.kodilla.stream.book.Book;
public class StreamMain<text> {
public static void main(String[] args) {
/*final SaySomething saySomething = new SaySomething();
saySomething.say();*/
/*final Processor processor = new Processor();
final ExecuteSaySomething executeSaySomething = new ExecuteSaySomething();
processor.execute(executeSaySomething);*/
/*fianl Processor processor = new Processor();
final Executor codeToExecute = () -> System.out.println("bbb");
processor.execute(codeToExecute);*/
/*final Processor processor = new Processor();
processor.execute(() -> System.out.println("bbb"));*/
/*final ExpressionExecutor expressionExecutor = new ExpressionExecutor();
System.out.println("Calculating expressions with lambdas");
expressionExecutor.executeExpression(10,5, (a, b) -> a + b);
expressionExecutor.executeExpression(10,5, (a, b) -> a - b);
expressionExecutor.executeExpression(10,5, (a, b) -> a * b);
expressionExecutor.executeExpression(10,5, (a, b) -> a / b);
expressionExecutor.executeExpression(10, 5, FunctionalCalculator::addAToB);
expressionExecutor.executeExpression(10, 5, FunctionalCalculator::subAFromB);
expressionExecutor.executeExpression(10, 5, FunctionalCalculator::multiplyAByB);
expressionExecutor.executeExpression(10, 5, FunctionalCalculator::divideAByB);*/
/*final PoemBeautifier poemBeautifier = new PoemBeautifier();
poemBeautifier.beautify("Text to Decorate", text -> text.toUpperCase());
poemBeautifier.beautify("Text to Decorate", text -> "ABC" + text + "ABC");
poemBeautifier.beautify("Text to Decorate", text -> text.toLowerCase());
poemBeautifier.beautify("Text to Decorate", text -> {
if (text.length() % 2 == 0) {
return text + "- even number of characters";
} else {
return text + "- odd number of characters";
}
});
}*/
/* System.out.println("Using Stream to generate even numbers from 1 to 20");
NumbersGenerator.generateEven(20); */
/*People.getList().stream()
.map(String::toUpperCase)
.filter(s -> s.length() > 11)
.map(s -> s.substring(0,s.indexOf(' ')+ 2) + ".")
.filter(s -> s.substring(0,1).equals("M"))
.forEach(System.out::println); */
/* BookDirectory theBookDirectory = new BookDirectory();
theBookDirectory.getList().stream()
.filter(book -> book.getYearOfPublication() > 2005)
.forEach(System.out::println); */
/*BookDirectory theBookDirectory = new BookDirectory();
List<Book> theResultListOfBooks = theBookDirectory.getList().stream()
.filter(book -> book.getYearOfPublication() > 2005)
.collect(Collectors.toList());
System.out.println("# elements: " + theResultListOfBooks.size());
theResultListOfBooks.stream()
.forEach(System.out::println); */
/* BookDirectory theBookDirectory = new BookDirectory();
Map<String, Book> theResultMapOfBooks = theBookDirectory.getList().stream()
.filter(book -> book.getYearOfPublication() > 2005)
.collect(Collectors.toMap(Book::getSignature, book -> book));
System.out.println("# elements: " + theResultMapOfBooks.size());
theResultMapOfBooks.entrySet().stream()
.map(entry -> entry.getKey() + ": " + entry.getValue())
.forEach(System.out::println); */
/*BookDirectory theBookDirectory = new BookDirectory();
String theResultStringOfBooks = theBookDirectory.getList().stream()
.filter(book -> book.getYearOfPublication() > 2005)
.map(Book::toString)
.collect(Collectors.joining(",\n","<<",">>")); // [2]
System.out.println(theResultStringOfBooks);*/
Forum forum = new Forum();
Map theResultOfUserList = forum.getList().stream()
.filter(forumUser -> forumUser.getSex() == 'M')
.filter(forumUser -> forumUser.getNumberOfPosts() > 1)
.filter(forumUser -> {
Period period = Period.between(forumUser.getBirthDate(), LocalDate.now());
int ageOfUser = period.getYears();
return ageOfUser >= 20;
})
.collect(Collectors.toMap(ForumUser::getUserId, ForumUser::getUsername));
System.out.println(theResultOfUserList);
}
}<file_sep>/kodilla-stream/src/main/java/com/kodilla/stream/forumuser/Forum.java
package com.kodilla.stream.forumuser;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class Forum {
private final List<ForumUser> theUserList = new ArrayList<>();
public Forum() {
theUserList.add(new ForumUser(1, "<NAME>",
'M', LocalDate.of(1979, 10, 16), 19));
theUserList.add(new ForumUser(2, "<NAME>",
'F', LocalDate.of(1989, 9, 30), 7));
theUserList.add(new ForumUser(3, "<NAME>",
'M', LocalDate.of(1990, 1, 20), 75));
theUserList.add(new ForumUser(4, "<NAME>",
'M', LocalDate.of(2010, 10, 16), 0));
theUserList.add(new ForumUser(5, "<NAME>",
'F', LocalDate.of(1961, 8, 3), 15));
theUserList.add(new ForumUser(6, "<NAME>",
'F', LocalDate.of(1985, 10, 16), 18));
theUserList.add(new ForumUser(7, "<NAME>",
'M', LocalDate.of(2005, 10, 16), 10));
}
public List<ForumUser> getList() {
return new ArrayList<>(theUserList);
}
}
<file_sep>/kodilla-patterns/src/test/java/com/kodilla/patterns/prototype/library/LibraryTestSuite.java
package com.kodilla.patterns.prototype.library;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
public class LibraryTestSuite {
@Test
public void testGetBooks(){
//GIVEN
Book book1 = new Book("Dzień", "Don", LocalDate.of(2018, 1, 21));
Book book2 = new Book("Myśl", "Ben", LocalDate.of(2019, 4, 01));
Book book3 = new Book("Alt", "Anb", LocalDate.of(2001, 6, 24));
Library library = new Library("My Library");
library.getBooks().add(book1);
library.getBooks().add(book2);
library.getBooks().add(book3);
Library clonedLibrary = null;
try{
clonedLibrary=library.shallowCopy();
clonedLibrary.setName("My second library");
}
catch(CloneNotSupportedException e){
System.out.println(e);
}
Library deepClonedLibrary = null;
try{
deepClonedLibrary = library.deepCopy();
deepClonedLibrary.setName("My third library");
}
catch(CloneNotSupportedException e){
System.out.println(e);
}
//WHEN
library.getBooks().remove(book3);
//THEN
System.out.println(library.getBooks());
Assertions.assertEquals(2, library.getBooks().size());
System.out.println(clonedLibrary.getBooks());
Assertions.assertEquals(2, clonedLibrary.getBooks().size());
System.out.println(deepClonedLibrary.getBooks());
Assertions.assertEquals(3, deepClonedLibrary.getBooks().size());
}
}
<file_sep>/kodilla-patterns/src/main/java/com/kodilla/patterns/factory/tasks/TaskFactory.java
package com.kodilla.patterns.factory.tasks;
public final class TaskFactory {
public final Task makeTask(final TaskType taskClass) {
switch (taskClass) {
case SHOPPING:
return new ShoppingTask("SHOPPING TASK", "<NAME> <NAME>ISKY 0,7L", 2);
case PAINTING:
return new PaintingTask("PAINTING TASK", "Pink", "Toilet");
case DRIVING:
return new DrivingTask("DRIVING TASK", "Driving School \"NEW HORIZON\" - 1906 Elliott Street, Manchester UK", "Lamborghini Aventador SVJ Roadster");
default:
return null;
}
}
}
<file_sep>/kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/challenges/flight/FlightRequestRetriever.java
package com.kodilla.good.patterns.challenges.flight;
public class FlightRequestRetriever {
public FlightRequest retrieve() {
String departureAirport = "Warsaw";
String arriveAirport = "Berlin";
return new FlightRequest(departureAirport, arriveAirport);
}
}
<file_sep>/kodilla-spring/src/test/java/com/kodilla/spring/portfolio/BoardTestSuite.java
package com.kodilla.spring.portfolio;
import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
public class BoardTestSuite {
private static int testCounter;
@BeforeClass
public static void beforeAllTests() {
System.out.println("This is the beginning of tests.");
}
@AfterClass
public static void afterAllTests() {
System.out.println("All tests are finished.");
}
@Before
public void beforeEveryTest() {
testCounter++;
System.out.println("Preparing to execute test #" + testCounter);
}
@Test
public void testTaskAdd() {
//Given
ApplicationContext context = new AnnotationConfigApplicationContext(BoardConfig.class);
Board board = context.getBean(Board.class);
//When
board.getToDoList().getTasksList().add("Task 1 is in ToDoList");
board.getInProgressList().getTasksList().add("Task 2 is in InProgressList");
board.getDoneList().getTasksList().add("Task 3 is in DoneList");
//Then
Assert.assertEquals("Task 1 is in ToDoList", board.getToDoList().getTasksList().get(0));
Assert.assertEquals("Task 2 is in InProgressList", board.getInProgressList().getTasksList().get(0));
Assert.assertEquals("Task 3 is in DoneList", board.getDoneList().getTasksList().get(0));
}
}
<file_sep>/kodilla-exception/src/main/java/com/kodilla/exception/test/FlightSearcher.java
package com.kodilla.exception.test;
import java.util.HashMap;
public class FlightSearcher {
private HashMap<String, Boolean> flightDestination = new HashMap<>();
public FlightSearcher() {
flightDestination.put("Warsaw", true);
flightDestination.put("Cracow", true);
flightDestination.put("Wroclaw", true);
flightDestination.put("Lublin", false);
}
public void findFlight(Flight flight) throws RouteNotFoundException {
/*
if (!flightDestination.containsKey(searchAirport)) {
throw new RouteNotFoundException(searchAirport);
}
System.out.println("");*/
String arrivalAirport = flight.getArrivalAirport();
Boolean aBoolean = flightDestination.get(arrivalAirport);
if (!aBoolean) throw new RouteNotFoundException(arrivalAirport);
}
}
<file_sep>/kodilla-testing/src/main/java/com/kodilla/testing/weather/stub/WeatherForecast.java
package com.kodilla.testing.weather.stub;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class WeatherForecast {
private Temperatures temperatures;
public WeatherForecast(Temperatures temperatures) {
this.temperatures = temperatures;
}
public Map<String, Double> calculateForecast() {
Map<String, Double> resultMap = new HashMap<>();
for (Map.Entry<String, Double> temperature :
temperatures.getTemperatures().entrySet()) {
// adding 1 celsius degree to current value
// as a temporary weather forecast
resultMap.put(temperature.getKey(), temperature.getValue() + 1.0); // [1]
}
return resultMap;
}
public double averageTemperature() {
Collection<Double> temps = this.temperatures.getTemperatures().values();
double sum = 0;
for (Double i : temps) {
sum += i;
}
return sum / temps.size();
}
public double medianTemperature() {
final double result;
Double[] tab = new Double[temperatures.getTemperatures().size()];
int i = 0;
for (Double temperature : temperatures.getTemperatures().values()) {
tab[i] = temperature;
i++;
}
Arrays.sort(tab);
if (tab.length % 2 == 0) {
result = (tab[tab.length / 2] + tab[tab.length / 2 - 1]) / 2;
} else {
result = tab[tab.length / 2];
}
return result;
}
}
<file_sep>/kodilla-testing/src/main/java/com/kodilla/testing/forum/statistics/CalculateAdvStatistics.java
package com.kodilla.testing.forum.statistics;
public class CalculateAdvStatistics {
public int usersCount;
public double averagePostsPerUser;
public double averageCommentsPerUser;
public double averageCommentsPerPost;
public int numberOfPosts;
public int numberOfComments;
public int getNumberOfPosts() {
return numberOfPosts;
}
public int getNumberOfComments() {
return numberOfComments;
}
public CalculateAdvStatistics(Statistics statistics) {
this.usersCount = statistics.usersNames().size();
if (statistics.usersNames().size() != 0) {
double posts = statistics.postsCount();
this.averagePostsPerUser = posts / statistics.usersNames().size();
} else {
System.out.println("Error/0");
}
if (statistics.usersNames().size() != 0) {
double comments = statistics.commentsCount();
this.averageCommentsPerUser = comments / statistics.usersNames().size();
} else {
System.out.println("Error/0");
}
if (statistics.postsCount() != 0) {
double comments = statistics.commentsCount();
this.averageCommentsPerPost = comments / statistics.postsCount();
} else {
System.out.println("Error/0");
}
}
public void ShowStatistics() {
System.out.println(this.usersCount + " " + this.averagePostsPerUser + " " + this.averageCommentsPerPost + " " + this.averageCommentsPerPost);
}
}
| ae65840b874ffee3b651fe270a20ec95f8485b29 | [
"Java"
] | 17 | Java | ete02/ievgen-teslenko-kodilla-java | 25ef82ce64b0cfc41514e48cb45ad76c635de7a3 | 9f2e89eba629537f5fbf57f6c6f50bff53b4d941 |
refs/heads/master | <repo_name>flashery/event-scheduler<file_sep>/resources/js/app.js
require("./bootstrap");
import Vue from "vue";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import locale from "element-ui/lib/locale/lang/en";
import EventScheduler from "./component/EventScheduler";
Vue.use(ElementUI, { locale });
Vue.component("event-scheduler", EventScheduler);
const app = new Vue({
el: "#root",
});
| 4332fe0b7282750fb0c5a770973b7a0c91fa08a5 | [
"JavaScript"
] | 1 | JavaScript | flashery/event-scheduler | 3b0d0fef7c2167333f65361d32f84726d8b9e3f5 | 65b080b71179ceb24ac4f5992c463c3617a78744 |
refs/heads/master | <repo_name>WillAshC21/PigLatinTranslator<file_sep>/main.js
let tran = "";
let ar = [];
function translate() {
let word = document.getElementById('word').value;
let name = word;
let translator = "";
const latin = "ay";
let characters = [];
let space = name.split(' ');
for (let i = 0; i < space.length; i++) {
let sub = space[i].substring(0, 1);
let sub2 = space[i].substring(1, space[i].length);
let total = sub2 + sub + latin;
characters.push(total);
}
tran = characters.join(' ');
let totalOne = tran.charAt(0).toUpperCase();
let totalStr = tran.charAt(0).toUpperCase() + tran.substring(1, tran.length).toLowerCase();
ar.push(totalStr);
document.getElementById('translated-list').innerText = ar.join('\n ');
}
document.getElementById('submit').addEventListener("click", translate);
| 0f62b54796c421ad566170e6b7f067dad5c0b04a | [
"JavaScript"
] | 1 | JavaScript | WillAshC21/PigLatinTranslator | 710629c98899d3e2a76ee25eda068be0127e6305 | fc881361effe9359d9cd2459146828202ca98366 |
refs/heads/master | <file_sep>package be.lsinf1225.ezmeal;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Gaetan on 11/05/2017.
* <NAME>
*/
public class Afficher_Recette extends AppCompatActivity {
/*
DBHelper myManager = new DBHelper(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.afficher_recette);
String titreFlag = getIntent().getStringExtra("titreFlag"); //on choppe la lettre qui vient de l'activité précédente
Toast.makeText(Afficher_Recette.this, titreFlag, Toast.LENGTH_SHORT).show();
//titre
TextView titre = (TextView) findViewById(R.id.TVtitre);
titre.setText(titreFlag);
//image
//String imgBDD = myManager.searchData2(titreFlag, "image");
//Toast.makeText(Afficher_Recette.this, imgBDD, Toast.LENGTH_SHORT).show();
ImageView iv = (ImageView) findViewById(IVbig);;
int[] IMAGES = {R.mipmap.imgbig1, R.mipmap.imgbig2, R.mipmap.imgbig3, R.mipmap.imgbig4, R.mipmap.imgbig5, R.mipmap.imgbig6, R.mipmap.imgbig7, R.mipmap.imgbig8, R.mipmap.imgbig9, R.mipmap.imgbig10,
R.mipmap.imgbig11, R.mipmap.imgbig12, R.mipmap.imgbig13, R.mipmap.imgbig14, R.mipmap.imgbig15, R.mipmap.imgbig16, R.mipmap.imgbig17, R.mipmap.imgbig18};
//R.mipmap.img13 R.mipmap.img14, R.mipmap.img15, R.mipmap.img16};
for(int m=1; m<=IMAGES.length; m++){
if(imgBDD.equals("img"+m)){
//if(Integer.toString(IMAGES[m]).equals(imgFromBDD)){ //Si l'image correspond dans la bdd
iv.setImageResource(IMAGES[m-1]);
}
else{
}
}
//les aliments de la recette ok
ArrayList arr = new ArrayList();
ArrayList arr2 = new ArrayList();
//arr = myManager.getAlimentsRecette(titreFlag,"aliment");
//arr2 = myManager.getAlimentsRecette(titreFlag,"quantite");
TextView aliments = (TextView) findViewById(R.id.TValiments);
String result = TextUtils.join(System.getProperty("line.separator"), arr);
aliments.setText(result);
TextView quantite = (TextView) findViewById(R.id.TVquantite);
String result2 = TextUtils.join(System.getProperty("line.separator"), arr2);
quantite.setText(result2);
//le reste
String descriptionFromBDD = myManager.searchData2(titreFlag, "description");
TextView description = (TextView) findViewById(R.id.TVdescription);
description.setText(descriptionFromBDD);
String etapeFromBDD = myManager.searchData2(titreFlag, "etape");
TextView etape = (TextView) findViewById(R.id.TVetapes);
etape.setText(etapeFromBDD);
String tpreparatoinFromBDD = myManager.searchData2(titreFlag, "Tpreparation");
TextView tprepa = (TextView) findViewById(R.id.TVpreparation);
tprepa.setText(tpreparatoinFromBDD);
String tcuissonFromBDD = myManager.searchData2(titreFlag, "Tcuisson");
TextView tcuiss = (TextView) findViewById(R.id.TVcuisson);
tcuiss.setText(tcuissonFromBDD);
String diffFromBDD = myManager.searchData2(titreFlag, "facilite");
TextView diff = (TextView) findViewById(R.id.TVdiff);
diff.setText(diffFromBDD);
String persFromBDD = myManager.searchData2(titreFlag, "nbr");
TextView nbr = (TextView) findViewById(R.id.TVnbr);
nbr.setText(persFromBDD);
}
public void onBtnClick(View v) {
if (v.getId() == R.id.bRetour) {
onBackPressed();
}
}
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class AfficherRecette extends AppCompatActivity {
android.support.v7.widget.Toolbar toolbar4;
ListView listView4;
DBHelper myManager = new DBHelper(this);
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.afficher_liste_recette);
String ingredient = getIntent().getStringExtra("ingredients");
toolbar4 = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar4);
toolbar4.setTitle("Recettes");
ArrayList<String> listerecette = new ArrayList<String>();
listerecette = myManager.getRecetteIngredient(ingredient);
listView4 = (ListView) findViewById(R.id.listView4);
ArrayAdapter<String> mAdapter4 = new ArrayAdapter<>(AfficherRecette.this, android.R.layout.simple_list_item_1, listerecette);
listView4.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> adapterView4, View view4, int i4, long l4){
Intent intent4 = new Intent(AfficherRecette.this, Main5Activity.class);
intent4.putExtra("recettes", listView4.getItemAtPosition(i4).toString());
startActivity(intent4);
}
});
listView4.setAdapter(mAdapter4);
}
}
*/
}
| b7ed63f06da784c2679836ff7ee5e1cfef336647 | [
"Java"
] | 1 | Java | GGortz/EZMealLASTVERSION | 5cc5cc4889e3399087903c32591c1b3dbd46de2b | 4ca0a80ce24fe670359931105ee82fe7e47dc51c |
refs/heads/master | <repo_name>tmiky91/Lab02<file_sep>/Lab2_Alien/src/it/polito/tdp/alien/AlienController.java
package it.polito.tdp.alien;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class AlienController {
AlienDictionary dizionario;
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private TextField txtWord;
@FXML
private Button btnTranslate;
@FXML
private TextArea txtResult;
@FXML
private Button btnClearText;
@FXML
void doReset(ActionEvent event) {
txtResult.clear();
}
@FXML
void doTranslate(ActionEvent event) {
String risultato[];
risultato = txtWord.getText().split(" ");
if(risultato.length==1) {
txtResult.setText(dizionario.translateWord(risultato[0]));
}
if(risultato.length==2) {
dizionario.addWord(risultato[0],risultato[1]);
txtResult.setText(dizionario.translateWord(risultato[0]));
}
}
@FXML
void initialize() {
assert txtWord != null : "fx:id=\"txtWord\" was not injected: check your FXML file 'Alien.fxml'.";
assert btnTranslate != null : "fx:id=\"btnTranslate\" was not injected: check your FXML file 'Alien.fxml'.";
assert txtResult != null : "fx:id=\"txtResult\" was not injected: check your FXML file 'Alien.fxml'.";
assert btnClearText != null : "fx:id=\"btnClearText\" was not injected: check your FXML file 'Alien.fxml'.";
dizionario = new AlienDictionary();
}
}
| 73f528bcc1a114e4a3b019e8bf003547b194778d | [
"Java"
] | 1 | Java | tmiky91/Lab02 | 1f6dee47a92f1790d8712204ac92414262936af3 | d825271a109dd3be9462bbf48cf62031cd5ebe47 |
refs/heads/master | <file_sep>class _Main {
static function a () : void {}
static function a (x : number) : void {}
static function a (x : string) : void {}
native static function a (x : number,
y : string) : void {}
static function main(args : string[]) : void {
_Main.a([1]);
}
}
<file_sep>/*EXPECTED
1
2
3
4
*/
class _Main {
function bar () : Enumerable.<number> {
yield 1;
yield 2;
}
function foo () : Enumerable.<number> {
var b = this.bar();
try {
while (true) {
yield b.next();
}
} catch (e : StopIteration) {
// pass
}
yield 3;
yield 4;
}
static function main (args : string[]) : void {
var g = (new _Main).foo();
log g.next();
log g.next();
log g.next();
log g.next();
}
}
<file_sep>class A {
function constructor() {
B.
}
}
class B {
static var n : number;
}
/*EXPECTED
[
{
"word" : "<"
},
{
"word" : "n",
"definedClass" : "B",
"type" : "number"
}
]
*/
/*JSX_OPTS
--complete 3:5
*/
<file_sep>/*
* Copyright (c) 2012 DeNA Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import "js.jsx";
import "console.jsx";
import "js/web.jsx";
import "./browser-platform.jsx";
import "../compiler.jsx";
import "../optimizer.jsx";
import "../jsemitter.jsx";
import "../util.jsx";
class ScriptLoader {
static var seen = new Map.<boolean>;
static var optimizationLevel = 0;
static function load() : void {
var scripts = dom.document.getElementsByTagName("script");
for (var i = 0, l = scripts.length; i < l; ++i) {
var script = scripts[i] as HTMLScriptElement;
if(script.type == "application/jsx") {
var id = script.src ? script.src : script.innerHTML;
if (ScriptLoader.seen.hasOwnProperty(id)) {
continue;
}
ScriptLoader.seen[id] = true;
ScriptLoader.loadScript(script);
}
}
}
static function loadScript(script : HTMLScriptElement) : void {
var t0 = Date.now();
var platform = new BrowserPlatform();
var c = new Compiler(platform);
var o = new Optimizer();
var emitter = new JavaScriptEmitter(platform);
c.setEmitter(emitter);
var sourceFile;
if(script.src) {
sourceFile = script.src.replace(/^.*\//, "");
}
else {
sourceFile = "<script>";
platform.setFileContent(sourceFile, script.innerHTML);
}
c.addSourceFile(null, sourceFile);
if(ScriptLoader.optimizationLevel > 0) {
var optimizeCommands = Optimizer.getReleaseOptimizationCommands().filter((command) -> { return command != "no-log"; });
o.setup(optimizeCommands);
o.setEnableRunTimeTypeCheck(false);
emitter.setEnableRunTimeTypeCheck(false);
}
c.setOptimizer(o);
if(! c.compile()) {
throw new Error("Failed to compile!");
}
var output = emitter.getOutput();
if(ScriptLoader.optimizationLevel > 1) {
output = platform.applyClosureCompiler(output, "SIMPLE_OPTIMIZATIONS", false);
}
var compiledScript = dom.document.createElement("script");
var scriptSection = dom.document.createTextNode(output);
compiledScript.appendChild(scriptSection);
script.parentNode.appendChild(compiledScript);
console.log("jsx-script-loader: load " + sourceFile + " in " + (Date.now() - t0) as string + " ms.");
var applicationArguments = script.getAttribute("data-arguments");
if (applicationArguments) { // run it if data-argumenrs is supplied
var args = JSON.parse(applicationArguments);
if (args instanceof Array.<variant>) {
var array = args as Array.<variant>;
for (var i = 0; i < array.length; ++i) {
if (typeof array[i] != "string") {
throw new TypeError("Not an array of string: arguments[i] is " + JSON.stringify(array[i]));
}
}
}
else {
throw new TypeError("Not an array of string: " + applicationArguments);
}
platform.debug(Util.format("run _Main.main()@%1 with %2", [sourceFile, applicationArguments]));
var jsxModule = js.global['JSX'];
assert jsxModule != null;
var jsxRequire = jsxModule['require'] as (string) -> variant;
assert jsxRequire != null;
var jsxRuntime = jsxRequire(sourceFile);
assert jsxRuntime != null;
var jsxMain = jsxRuntime["_Main"];
assert jsxMain != null;
js.invoke(jsxMain, "main$AS", [ args ]);
}
}
}
class _Main {
static function main(args : string[]) : void {
ScriptLoader.load();
}
}
<file_sep>/*EXPECTED
f
1
42
foo
f
10
20
foo
f
100
200
bar
g
[value]
g
foo
h
[value]
bar
*/
class _Main {
var value = "value";
// instance method
function f(a : number, b : number = 42, c : string = "foo") : void {
log "f";
log a;
log b;
log c;
}
// complex expression
function g(a : string = "[" + this.value + "]") : void {
log "g";
log a;
}
// non-void
function h(a : string = "[" + this.value + "]") : string {
return a;
}
static function main(args : string[]) : void {
var o = new _Main;
o.f(1);
o.f(10, 20);
o.f(100, 200, "bar");
o.g();
o.g("foo");
log "h";
log o.h();
log o.h("bar");
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>module.exports = function(grunt) {
'use strict';
var pkg = grunt.file.readJSON('package.json');
grunt.initConfig({
srcDir: "src",
buildDir: "bin",
watch: {
jsx: {
files: ['<%= srcDir %>/*.jsx', '!<%= srcDir %>/meta.jsx'],
tasks: ['exec:make_compiler']
},
},
exec: {
make_compiler: {
command: "make compiler",
},
},
});
for (var key in pkg.devDependencies) {
if (/grunt-/.test(key)) {
grunt.loadNpmTasks(key);
}
}
grunt.registerTask('default', ['exec:make_compiler']);
};
// vim: set expandtab tabstop=2 shiftwidth=2:
<file_sep>class _Main {
class Foo {
}
static var a = _Main.Foo;
}
<file_sep>/*EXPECTED
2
*/
/*JSX_OPTS
--optimize fold-const,dce
*/
class _Main {
static function main (args : string[]) : void {
var a = 1;
if (42 as number) {
a = 2;
}
log a;
}
}<file_sep>/*EXPECTED
hello:[object Object]
*/
class _Main {
override function toString() : string {
return "hello:" + super.toString();
}
static function main(args : string[]) : void {
log new _Main().toString();
}
}
<file_sep>/*EXPECTED
foo
*/
interface I.<T> {
function f() : T;
}
class C implements I.<string> {
override function f() : string {
return "foo";
}
}
class _Main {
static function main(args : string[]) : void {
var i : I.<string> = new C();
log i.f();
}
}
<file_sep>/*EXPECTED
Hi
*/
class Base.<T> {
function f() : void {
log "Hi";
}
}
class Derived.<T> extends Base.<T> {
}
class _Main {
static function main(args : string[]) : void {
(new Derived.<number>).f();
}
}
<file_sep>/*EXPECTED
4
*/
class _Main {
static function main(args : string[]) : void {
var f : (number) -> number;
f = (n) -> n + 1;
var n = f(3);
log n;
}
}
<file_sep>// an example for class inheritance and interfaces
interface Flyable {
function fly() : void;
}
abstract class Animal {
function eat() : void {
log "An animal is eating!";
}
}
class Bat extends Animal implements Flyable {
override function fly() : void {
log "A bat is flying!";
}
}
abstract class Insect {
}
class Bee extends Insect implements Flyable {
override function fly() : void {
log "A bee is flying!";
}
}
class _Main {
static function takeAnimal(animal : Animal) : void {
animal.eat();
}
static function takeFlyable(flyingBeing : Flyable) : void {
flyingBeing.fly();
}
static function main(args : string[]) : void {
var bat = new Bat();
_Main.takeAnimal(bat); // OK. A bat is an animal.
_Main.takeFlyable(bat); // OK. A bat can fly.
var bee = new Bee();
_Main.takeFlyable(bee); // OK. A bee is also flyable.
}
}
// vim: set expandtab:
<file_sep>/*EXPECTED
2
0
hello
1
hola
1
*/
class _Main {
static var a = [ 3 ] : int[];
static function f() : int[] {
log "hello";
return _Main.a;
}
var m : int = 3;
function g() : _Main {
log "hola";
return this;
}
static function main(args : string[]) : void {
var i : int = 4;
i /= 2;
log i;
i = 1;
i /= 3;
log i;
_Main.f()[0] /= 2;
log _Main.a[0];
var t = new _Main;
t.g().m /= 2;
log t.m;
}
}
<file_sep>/*EXPECTED
1
2
-1
4
0.5
1
*/
/*JSX_OPTS
--optimize fold-const
*/
class _Main {
static const ZERO : int = 0;
static const ONE : int = _Main.ZERO + 1;
static const TWO : int = _Main.ONE + 1;
static function main(args : string[]) : void {
log _Main.ONE;
log _Main.ONE + _Main.ONE;
log _Main.ONE - _Main.TWO;
log _Main.TWO * _Main.TWO;
log _Main.ONE / _Main.TWO; // / and % operations return floating point
log _Main.ONE % _Main.TWO;
}
}
<file_sep>/*EXPECTED
2
4
6
6
8
2
*/
/*JSX_OPTS
--optimize lcse
*/
class _Main {
var n = 1;
function constructor() {
// test this.prop
var r = this.n + this.n;
log r;
r = (this.n = 2) + this.n;
log r;
this.n = 3;
r = this.n + this.n;
log r;
}
function constructor(b : boolean) {
// no test
}
static function main(args : string[]) : void {
var t2 = new _Main(false);
// test this.prop
var t = new _Main;
// test local.prop
var r = t.n + t.n;
log r;
r = (t.n = 4) + t.n;
log r;
t = t2;
r = t.n + t.n;
log r;
}
}
<file_sep>/*EXPECTED
10
20
30
*/
class _Main {
static function f(i : int) : void {
log i;
}
static function main(args : string[]) : void {
_Main.f(10.5);
var n = 20.5;
_Main.f(n);
var mn : Nullable.<number> = 30.5;
_Main.f(mn);
}
}
<file_sep>/*EXPECTED
123
*/
class _Main {
static var m = { k: 123 };
static function main(args : string[]) : void {
var n = _Main.m["k"];
log n;
}
}
<file_sep>/*EXPECTED
1,2,3,1
*/
class Test {
static function f() : void {
var a : Array.<MayBeUndefined.<number>>;
}
}
<file_sep>(function () {
function words() {
var w = {};
for (var i = 0; i < arguments.length; ++i) {
w[arguments[i]] = true;
}
return w;
}
CodeMirror.defineMIME("application/jsx", {
name: "clike",
keywords: words(
"break", "continue",
"new", "delete", "in", "instanceof", "typeof", "as", "__noconvert__",
"return", "var", "const", "__readonly__",
"this", "__FILE__", "__LINE__",
"case", "default",
"throw",
"static", "final", "override", "native", "__fake__", "extends", "abstract",
"function",
"import", "from", "into",
"_Main", "_Test",
"debugger", "assert", "log",
// reserved but unused: byte char double enum export float goto long package private protected public short synchronized throws transient volatile arguments
// block keywords
"class", "interface", "mixin",
"if", "else", "switch",
"while", "for", "do",
"try", "catch", "finally"
),
blockKeywords: words(
"class", "interface", "mixin",
"if", "else", "switch",
"while", "for", "do",
"try", "catch", "finally"
),
atoms: words("true", "false", "null", "NaN", "Infinity"),
builtin: words(
"Array", "boolean", "Boolean", "Date", "number", "Number", "Map", "int", "Object", "string", "String", "RegExp", "JSON", "Nullable", "variant", "void",
"Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError"
)
});
}());
// vim: set expandtab:
// vim: set tabstop=2:
// vim: set shiftwidth=2:
<file_sep>/*EXPECTED
ABcAB
*/
class _Main {
static function main(args : string[]) : void {
log "abcab".replace(/ab/g, "AB");
}
}
<file_sep>/*EXPECTED
5
*/
/*JSX_OPTS
--optimize fold-const,dce
*/
class _Main {
static function foo () : number {
var a = true ? 1 : 2;
if (! false) {
a = 3;
}
if (true && false) {
a = 4;
}
if (true || false) {
a = 5;
}
return a;
}
static function main (args : string[]) : void {
log _Main.foo();
}
}<file_sep>class T {
var p : Q;
function constructor(b : Q) {
}
}
/*EXPECTED
[]
*/
/*JSX_OPTS
--complete 3:29
*/
<file_sep>/*EXPECTED
1
A
hello
*/
class A {
override function toString() : string {
return "A";
}
}
class _Main {
static function foo.<T>(x : T, a : number) : void {
log a;
}
static function bar.<T>(x : T, a : A) : void {
log a.toString();
}
static function baz.<T>(x : T, a : () -> string) : void {
log a();
}
static function main(args : string[]) : void {
var v = 0; // dummy, but any kind of type should be ok
_Main.foo(v, 1);
_Main.bar(v, new A);
_Main.baz(v, function () { return "hello"; });
}
}
<file_sep>// Reversi ported from https://bitbucket.org/7shi/ts-reversi
import "js/web.jsx";
class Config {
static const STAGE_WIDTH = 320;
static const STAGE_HEIGHT = 260;
}
class Board {
var canvas : HTMLCanvasElement;
var cx : CanvasRenderingContext2D;
var board : number[][];
var win : number[][];
var player : number;
var black : number;
var white : number;
var message : string;
var ignore = false;
var showWin = false;
var think : () -> void;
function constructor(canvas : HTMLCanvasElement) {
this.init();
if (! canvas) return;
this.canvas = canvas;
this.cx = canvas.getContext("2d") as CanvasRenderingContext2D;
this.draw();
this.think = () -> { this.thinkMonteCarlo(); };
canvas.addEventListener("mousedown",
(e) -> { this.onMouseDown(e as MouseEvent); });
}
function init() : void {
this.board = [
[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, 2, 1, 0, 0, 0],
[0, 0, 0, 1, 2, 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]
];
this.win = [
new number[],
new number[],
new number[],
new number[],
new number[],
new number[],
new number[],
new number[]
];
this.player = 1;
this.message = "";
this.count();
}
function draw() : void {
var cx = this.cx;
cx.fillStyle = "green";
cx.fillRect(0, 0, this.canvas.width, this.canvas.height);
cx.strokeStyle = "black";
for (var i = 0; i <= 8; i++) {
cx.beginPath();
cx.moveTo(i * 30 + 10, 10);
cx.lineTo(i * 30 + 10, 250);
cx.moveTo( 10, i * 30 + 10);
cx.lineTo(250, i * 30 + 10);
cx.stroke();
}
cx.font = "10pt sans-serif";
cx.textAlign = "center";
cx.textBaseline = "middle";
for (var y = 0; y <= 7; y++) {
for (var x = 0; x <= 7; x++) {
this.drawStone(x, y, this.board[y][x]);
if (this.showWin && this.win != null && this.win[y][x] != null) {
cx.fillStyle = "red";
cx.fillText(this.win[y][x] as string,
x * 30 + 25, y * 30 + 25);
}
}
}
this.drawStone(8.3, 6.5, this.player);
cx.fillText("Turn", 275, 245);
this.drawStone(8.3, 0, 1);
cx.fillText(this.black as string, 275, 55);
this.drawStone(8.3, 2, 2);
cx.fillText(this.white as string, 275, 115);
if (this.message != "") {
cx.fillStyle = "white";
cx.strokeStyle = "red";
cx.beginPath();
cx.rect(20, 120, 220, 20);
cx.fill();
cx.stroke();
cx.fillStyle = "black";
cx.fillText(this.message, 120, 130);
}
}
function drawStone(x : number, y : number, c : number) : void {
var cx = this.cx;
if (c == 1) {
cx.fillStyle = "black";
} else if (c == 2) {
cx.fillStyle = "white";
} else {
return;
}
cx.beginPath();
cx.arc(x * 30 + 25, y * 30 + 25, 14, 0, 2 * Math.PI);
cx.fill();
}
function next(x : number, y : number) : void {
if (0 <= x && x <= 7 && 0 <= y && y <= 7) {
this.board[y][x]++;
if (this.board[y][x] == 3) {
this.board[y][x] = 0;
}
}
}
function put(x : number, y : number) : number {
var stone = 0;
stone += this.putDirection(x, y, 1, 0);
stone += this.putDirection(x, y, -1, 0);
stone += this.putDirection(x, y, 0, 1);
stone += this.putDirection(x, y, 0, -1);
stone += this.putDirection(x, y, 1, 1);
stone += this.putDirection(x, y, 1, -1);
stone += this.putDirection(x, y, -1, 1);
stone += this.putDirection(x, y, -1, -1);
if (stone > 0) {
this.board[y][x] = this.player;
stone++;
this.count();
}
return stone;
}
function putDirection(x : number, y : number, dx : number, dy : number) : number {
var stone = this.countDirection(x, y, dx, dy);
for (var i = 1; i <= stone; i++) {
this.board[y + dy * i][x + dx * i] = this.player;
}
return stone;
}
function check(x : number, y : number, n : number) : boolean {
return 0 <= x && x <= 7 && 0 <= y && y <= 7 && this.board[y][x] == n;
}
function change() : number {
this.player = 3 - this.player;
if (this.canPut()) return 1;
this.player = 3 - this.player;
if (this.canPut()) return 2;
if (this.black > this.white) {
this.message = "Black Wins!";
} else if (this.black < this.white) {
this.message = "White Wins!";
} else {
this.message = "Draw!";
}
return 3;
}
function count() : void {
this.black = 0;
this.white = 0;
for (var y = 0; y <= 7; y++) {
for (var x = 0; x <= 7; x++) {
if (this.board[y][x] == 1) {
this.black++;
} else if (this.board[y][x] == 2) {
this.white++;
}
}
}
}
function checkCount(x : number, y : number) : boolean {
return this.countDirection(x, y, 1, 0) > 0 ||
this.countDirection(x, y, -1, 0) > 0 ||
this.countDirection(x, y, 0, 1) > 0 ||
this.countDirection(x, y, 0, -1) > 0 ||
this.countDirection(x, y, 1, 1) > 0 ||
this.countDirection(x, y, 1, -1) > 0 ||
this.countDirection(x, y, -1, 1) > 0 ||
this.countDirection(x, y, -1, -1) > 0;
}
function countDirection(x : number, y : number, dx : number, dy : number) : number {
if (this.check(x, y, 0)) {
var rival = 3 - this.player;
var stone = 0;
var x1 = x + dx;
var y1 = y + dy;
while (this.check(x1, y1, rival)) {
stone++;
x1 += dx;
y1 += dy;
}
if (stone > 0 && this.check(x1, y1, this.player)) {
return stone;
}
}
return 0;
}
function canPut() : boolean {
for (var y = 0; y <= 7; y++) {
for (var x = 0; x <= 7; x++) {
if (this.checkCount(x, y)) {
return true;
}
}
}
return false;
}
function thinkRandom() : number[] {
var x, y;
do {
x = Math.floor(Math.random() * 8);
y = Math.floor(Math.random() * 8);
} while (this.put(x, y) == 0);
return [x, y];
}
function countPut(x: number, y: number) : number {
var stone = 0;
if (this.check(x, y, 0)) {
stone += this.countDirection(x, y, 1, 0);
stone += this.countDirection(x, y, -1, 0);
stone += this.countDirection(x, y, 0, 1);
stone += this.countDirection(x, y, 0, -1);
stone += this.countDirection(x, y, 1, 1);
stone += this.countDirection(x, y, 1, -1);
stone += this.countDirection(x, y, -1, 1);
stone += this.countDirection(x, y, -1, -1);
}
return stone;
}
function thinkMost() : void {
var max = 0, tx = 0, ty = 0;
for (var y = 0; y <= 7; y++) {
for (var x = 0; x <= 7; x++) {
var stone = this.countPut(x, y);
if (max < stone) {
max = stone;
tx = x;
ty = y;
}
}
}
if (max > 0) this.put(tx, ty);
}
function clone() : Board {
var ret = new Board(null);
for (var y = 0; y <= 7; y++) {
for (var x = 0; x <= 7; x++) {
ret.board[y][x] = this.board[y][x];
}
}
ret.player = this.player;
ret.black = this.black;
ret.white = this.white;
return ret;
}
function thinkMonteCarlo() : void {
this.win = [
new number[],
new number[],
new number[],
new number[],
new number[],
new number[],
new number[],
new number[]
];
for (var i = 1; i <= 1000; i++) {
var board = this.clone();
var pt = board.thinkRandom();
var x = pt[0], y = pt[1];
while (board.change() != 3) {
board.thinkRandom();
}
if ((this.player == 1 && board.black > board.white) ||
(this.player == 2 && board.black < board.white)) {
if (this.win[y][x] == null) {
this.win[y][x] = 1;
} else {
this.win[y][x]++;
}
} else if (board.black != board.white) {
if (this.win[y][x] == null) {
this.win[y][x] = -1;
} else {
this.win[y][x]--;
}
}
}
var max = null : Nullable.<number>;
var tx = 0;
var ty = 0;
for (var y = 0; y <= 7; y++) {
for (var x = 0; x <= 7; x++) {
if (this.win[y][x] != null &&
(max == null || max < this.win[y][x])) {
max = this.win[y][x];
tx = x;
ty = y;
}
}
}
if (max != null) {
this.put(tx, ty);
} else {
this.thinkRandom();
}
}
function onMouseDown(e : MouseEvent) : void {
if (this.ignore) return;
if (this.message != "") {
this.init();
this.draw();
return;
}
var r = this.canvas.getBoundingClientRect();
var x = Math.floor((e.clientX - r.left - 10) / 30);
var y = Math.floor((e.clientY - r.top - 10) / 30);
if (this.put(x, y) == 0) return;
this.win = null;
var chg = this.change();
this.draw();
if (chg != 1) return;
this.ignore = true;
dom.window.setTimeout(function start() : void {
this.think();
var chg = this.change();
this.draw();
if (chg == 2) {
start();
}
else {
this.ignore = false;
}
}, 50);
}
function configureFromForm() : void {
var levels = dom.document.getElementsByName('level');
for (var i = 0; i < levels.length; i++) {
var radio = levels[i] as HTMLInputElement;
if (radio.checked) {
switch (radio.value) {
case "random":
this.think = () -> { this.thinkRandom(); };
break;
case "most":
this.think = () -> { this.thinkMost(); };
break;
case "montecarlo":
this.think = () -> { this.thinkMonteCarlo(); };
break;
default:
log "no such algorithm: " + radio.value;
}
}
var showWinningRate = dom.id("show_winning_rate") as HTMLInputElement;
assert showWinningRate != null;
this.showWin = showWinningRate.checked;
this.draw();
}
}
}
class _Main {
static function createCanvas() : HTMLCanvasElement {
var canvas = dom.createElement('canvas') as HTMLCanvasElement;
canvas.width = Config.STAGE_WIDTH;
canvas.height = Config.STAGE_HEIGHT;
dom.id('world').appendChild(canvas);
return canvas;
}
static function main(args : string[]) : void {
var board = new Board(_Main.createCanvas());
board.configureFromForm();
dom.id('configuration').addEventListener('click', (e) -> { board.configureFromForm(); });
}
}
// vim: set expandtab :
// vim: set tabstop=2 :
// vim: set shiftwidth=2 :
<file_sep>/*EXPECTED
1,2,3
*/
class _Main {
static function main(args : string[]) : void {
log [1, 3, 2].sort((x, y) -> x - y).join(",");
}
}
<file_sep>class Map {
}
<file_sep>/*EXPECTED
true
*/
/*JSX_OPTS
--optimize fold-const
*/
class _Main {
static function main(args : string[]) : void {
log JSX.DEBUG;
}
}
<file_sep>/*EXPECTED
hello
5
a
abc
10
a
*/
class _Main {
static function main(args : string[]) : void {
log "hello".toString();
log "hello".length;
log String.fromCharCode(97);
var s = "abc";
log s.toString();
var i = 10;
log i.toString(); // overloaded
log i.toString(16);
}
}
<file_sep>/*EXPECTED
4
65535
-1
1
3
6
*/
/*JSX_OPTS
--optimize fold-const
*/
class _Main {
static function main(args : string[]) : void {
log 1 << 2;
log -1 >>> 16;
log -1 >> 16;
log 7 & 1;
log 1 | 2;
log 7 ^ 1;
}
}
<file_sep>/*EXPECTED
foo
bar
*/
class C {
static function useTryCatch.<T>(message : string) : void {
try {
throw new T(message);
}
catch (e : T) {
log e.message;
}
}
}
class _Main {
static function main(args : string[]) : void {
C.useTryCatch.<SyntaxError>("foo");
C.useTryCatch.<TypeError>("bar");
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>class _Main {
static function f(n : number = "abc") : void {
}
}
<file_sep>// issues/1 [lexer] fix regexp vs. div
/*EXPECTED
ok
*/
class _Main {
static function main(args : string[]) : void {
var a = 4 / 2;
//var b = /foo/; // FIXME
var c = 4 / 2 / 1;
//var d = 4 / 2 ? /foo/ : /bar/; // FIXME
var e = (4) / 2 / 1;
var e = a / 2 / 1;
// var f = /foo/ / 2; // should be tokanized
// var g = "foo" / 2; // should be tokenized
log "ok";
}
}
// vim: set noexpandtab:
<file_sep>interface I {
}
class T implements I, I {
}
<file_sep>
// testing static const
class Test {
static function run() : void {
Math.PI = 3;
log Math.PI;
}
}
<file_sep>/*EXPECTED
true
Hello, world!
*/
// issue #152
// with double-quoted
native class StringDecoder {
function constructor(encodingName : string);
} = "require('string_decoder').StringDecoder";
// with single-quoted
native class util {
static function format(format : string, ...args : variant) : string;
} = 'require("util")';
class _Main {
static function main(args : string[]) : void {
var sd = new StringDecoder('utf8');
log sd instanceof StringDecoder;
log util.format("Hello, %s!", "world");
}
}
<file_sep>/*EXPECTED
4
5
*/
class _Main {
static function lambda(x : number) : function (: number) : number {
return function (y : number) : number {
return x + y;
};
}
static function main(args : string[]) : void {
var f = _Main.lambda(3);
log f(1);
log f(2);
}
}
<file_sep>/*EXPECTED
f
*/
class _Main {
static function main(args : string[]) : void {
if (false)
throw new Error();
else
log "f";
}
}
// vim: set expandtab:
<file_sep>/*EXPECTED
0,0
1,2
*/
class Point {
var _x = 0;
var _y = 0;
function constructor() {
}
function constructor(x : number, y : number) {
this._x = x;
this._y = y;
}
function say() : void {
log this._x.toString() + "," + this._y.toString();
}
}
class _Main {
static function main(args : string[]) : void {
new Point().say();
new Point(1, 2).say();
}
}
<file_sep>/*EXPECTED
caught
caught 2
*/
/*JSX_OPTS
*/
class _Main {
static function main(args : string[]) : void {
try {
String.fromCharCode(_Main.b());
log "failed";
} catch (e : Error) {
log "caught";
}
try {
String.fromCharCode(97, _Main.b());
log "failed 2";
} catch (e : Error) {
log "caught 2";
}
}
static function b() : Nullable.<number> {
return null;
}
}
// vim: set expandtab:
<file_sep>/*EXPECTED
hello
hello
hello
hello
*/
class _Main {
var f : function () : void;
function constructor() {
this.f = function () : void {
log "hello";
};
}
static function main(args : string[]) : void {
var t = new _Main();
t.f();
new _Main().f();
var f = t.f;
f();
var g : function () : void = t.f;
g();
}
}
<file_sep>import "053.private-class/foo.jsx";
class Test extends _Foo {
}
<file_sep>class Test {
var v : Nullable.<Nullable.<number>>;
}
<file_sep>import 'js.jsx';
import 'js/web.jsx';
import 'timer.jsx';
import 'webgl-util.jsx';
import 'mvq.jsx';
import 'kingyo.jsx';
import 'poi.jsx';
import 'water.jsx';
import 'rendertexture.jsx';
class _Main {
static function main(args:string[]) : void {
Game.main('webgl-canvas', 'life-bar');
}
}
class Game {
static const viewDistance = 80;
static const viewLean = 0.2;
static const near = 2;
static const far = 1000;
static const fovh = 0.2;
static const fovv = 0.2;
static var gl = null:WebGLRenderingContext;
static var projMat =
new M44().setFrustum(
-Game.near * Game.fovh,
Game.near * Game.fovh,
-Game.near * Game.fovv,
Game.near * Game.fovv,
Game.near,
Game.far
);
static var viewMat =
new M44().setTranslation(0, 0, -Game.viewDistance)
.mul(new M44().setRotationX(-Game.viewLean));
static var poi = null:Poi;
static var water = null:Water;
static var canvas = null:HTMLCanvasElement;
static var renderTex = null:RenderTexture;
static var bltProg = null:WebGLProgram;
static var bltULocs = null:Map.<WebGLUniformLocation>;
static var bltALocs = null:Map.<int>;
static var bltVTBuf = null:WebGLBuffer;
static var life = 1;
static var poi_down_time = 0;
static const damage_per_second = 0.5;
static var life_bar = null:HTMLDivElement;
static var life_bar_width = 100;
static var status_text = null:HTMLDivElement;
static var startTime = 0;
static function main(canvas_id:string, life_id:string) : void {
var canvas = dom.id(canvas_id) as HTMLCanvasElement;
var ww = dom.window.innerWidth;
var wh = dom.window.innerHeight;
var canvas_size = Math.min(ww, wh);
canvas.width = canvas_size;
canvas.height = canvas_size;
Game.status_text = dom.id('status') as HTMLDivElement;
Game.life_bar = dom.id(life_id) as HTMLDivElement;
var lbw = Game.life_bar.style.width;
Game.life_bar_width = lbw.substring(0, lbw.length - 2) as int;
var gl = Util.getWebGL(canvas_id);
Game.gl = gl;
Poi.initWithGL(gl);
Kingyo.initWithGL(gl);
Water.initWithGL(gl);
RenderTexture.initWithGL(gl);
Game.poi = new Poi();
Kingyo.init(20);
Game.water = new Water();
Game.bltProg = Util.getProgram('vt.vs', 'vt.fs');
Game.bltULocs = Util.getUniformLocations(Game.bltProg);
Game.bltALocs = Util.getAttribLocations(Game.bltProg);
Game.bltVTBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, Game.bltVTBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0,0, 1,0, 1,1, 0,1]), gl.STATIC_DRAW);
var getPoint = function(e:Event) : number[] {
var px = 0;
var py = 0;
if(e instanceof MouseEvent) {
var me = e as MouseEvent;
px = me.clientX;
py = me.clientY;
}
else if(e instanceof TouchEvent) {
var te = e as TouchEvent;
px = te.touches[0].pageX;
py = te.touches[0].pageY;
}
return [ px, py ];
};
var lastTouchPos = [0, 0];
var calcMousePosOnXYPlane = function(p:number[]) : number[] {
// window coordinate
var wx = p[0] / canvas.width * 2 - 1;
var wy = -p[1] / canvas.height * 2 + 1;
// eye position
var epos = new V3(0, 0, Game.viewDistance).transformBy(new M33().setRotateX(Game.viewLean));
// pointer direction
var pdir = new V3(Game.fovh * wx, Game.fovv * wy, -1).transformBy(new M33().setRotateX(Game.viewLean)).normalize();
// hit position
var hpos = pdir.clone().mul(epos.z / -pdir.z).add(epos);
return [hpos.x, hpos.y];
};
var touchStart = function(e:Event) : void {
e.preventDefault();
lastTouchPos = getPoint(e);
var pos = calcMousePosOnXYPlane(lastTouchPos);
Game.poi.setPosition(pos[0], pos[1]);
if (Game.poi.tearing() || Kingyo.numRests() == 0) {
// reset game
Game.life = 1;
Game.life_bar.style.width = Game.life_bar_width.toString()+"px";
Game.poi.tear(false);
Kingyo.reset();
Game.status_text.innerHTML = 'click to start';
} else {
if (!Game.poi.tearing()) {
Game.poi.down(true);
Game.poi_down_time = Date.now() / 1000;
if (Game.startTime == 0) Game.startTime = Date.now();
}
var hit = Kingyo.hit(pos[0], pos[1]);
if (hit.length > 0) {
Game.poi.tear(true);
Game.playSound('tear.mp3');
Game.startTime = 0;
}
Game.water.setImpulse(
pos[0]/40+0.5,
pos[1]/40+0.5,
0.03,
0
);
}
};
canvas.addEventListener("mousedown", touchStart);
canvas.addEventListener("touchstart", touchStart);
var touchEnd = function(e:Event) : void {
e.preventDefault();
if (e instanceof MouseEvent) lastTouchPos = getPoint(e);
var pos = calcMousePosOnXYPlane(lastTouchPos);
Game.poi.setPosition(pos[0], pos[1]);
if (Game.poi.down()) {
if (!Game.poi.tearing()) {
var hit = Kingyo.hit(pos[0], pos[1]);
Kingyo.fish(hit);
if (hit.length > 0) Game.playSound('fish.mp3');
if (Kingyo.numRests() == 0) Game.startTime = 0;
}
Game.water.setImpulse(
pos[0]/40+0.5,
pos[1]/40+0.5,
0.03,
1
);
}
Game.poi.down(false);
};
canvas.addEventListener("mouseup", touchEnd);
canvas.addEventListener("touchend", touchEnd);
var touchMove = function(e:Event) : void {
e.preventDefault();
lastTouchPos = getPoint(e);
var pos = calcMousePosOnXYPlane(lastTouchPos);
Game.poi.setPosition(pos[0], pos[1]);
if (Game.poi.down()) {
Game.water.setImpulse(
pos[0]/40+0.5,
pos[1]/40+0.5,
0.02,
0.2
);
}
};
canvas.addEventListener("mousemove", touchMove);
canvas.addEventListener("touchmove", touchMove);
canvas.onmouseout = function(e:Event) : void {
var pos = calcMousePosOnXYPlane(getPoint(e));
Game.poi.setPosition(pos[0], pos[1]);
Game.poi.down(false);
};
canvas.oncontextmenu = function(e:Event) : void {e.preventDefault();};
canvas.style.cursor = 'none';
Game.canvas = canvas;
Game.renderTex = new RenderTexture(canvas.width, canvas.height);
var raf = (dom.window.location.hash == "#raf");
log "use native RAF: " + raf as string;
Timer.useNativeRAF(raf);
function update_render(time:number) : void {
Game.update();
Game.render();
Timer.requestAnimationFrame(update_render);
}
update_render(0);
log 'game start!';
}
static function playSound(url:string) : void {
var s = dom.document.createElement('audio') as HTMLAudioElement;
s.src = url;
s.play();
}
static function update() : void {
var t = Date.now() / 1000;
Kingyo.update(t);
Game.water.step(t);
if (Game.poi.down()) {
Game.life -= (t - Game.poi_down_time) * Game.damage_per_second;
Game.poi_down_time = t;
if (Game.life < 0 && !Game.poi.tearing()) {
Game.life = 0;
Game.poi.tear(true);
Game.playSound('tear.mp3');
Game.startTime = 0;
}
Game.life_bar.style.width = (Game.life*Game.life_bar_width).toString()+"px";
}
if (Game.startTime > 0) {
Game.status_text.innerHTML = (((Date.now() - Game.startTime)|0)/1000).toString() + '[s]';
}
}
static function render() : void {
Game.update();
var gl = Game.gl;
Game.renderTex.begin();
gl.clearColor(0.2, 0.6, 0.8, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE);
Kingyo.drawUnderWater(Game.projMat, Game.viewMat);
if (Game.poi.down()) Game.poi.draw(Game.projMat, Game.viewMat);
//Game.water.debugDraw();
Game.renderTex.end();
gl.clear(gl.DEPTH_BUFFER_BIT);
gl.useProgram(Game.bltProg);
gl.bindTexture(gl.TEXTURE_2D, Game.renderTex.texture());
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.uniform1i(Game.bltULocs['texture'], 0);
gl.uniformMatrix4fv(Game.bltULocs['projectionMatrix'], false, new M44().setOrtho(0,1,0,1,-1,0).array());
gl.uniformMatrix4fv(Game.bltULocs['modelviewMatrix'], false, new M44().setIdentity().array());
gl.bindBuffer(gl.ARRAY_BUFFER, Game.bltVTBuf);
gl.vertexAttribPointer(Game.bltALocs['vertex'], 2, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(Game.bltALocs['texcoord'], 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(Game.bltALocs['vertex']);
gl.enableVertexAttribArray(Game.bltALocs['texcoord']);
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
gl.disableVertexAttribArray(Game.bltALocs['vertex']);
gl.disableVertexAttribArray(Game.bltALocs['texcoord']);
Game.water.draw(Game.projMat, Game.viewMat, Game.renderTex.texture(), Game.canvas.offsetWidth, Game.canvas.offsetHeight);
Kingyo.drawAboveWater(Game.projMat, Game.viewMat);
if (!Game.poi.down()) Game.poi.draw(Game.projMat, Game.viewMat);
Util.checkGLError();
}
}
<file_sep>import "*.jsx";
<file_sep>/*EXPECTED
abc
ABC
012
*/
class _Main {
static function main(args : string[]) : void {
var f = String.fromCharCode;
log f(97, 98, 99);
var g : function (... : number) : string;
g = String.fromCharCode;
log f(65, 66, 67);
var h : (... number) -> string = String.fromCharCode;
log h(48, 49, 50);
}
}
<file_sep>/*EXPECTED
*/
/*JSX_OPTS
--optimize no-assert
*/
class _Main {
static function main(args : string[]) : void {
assert true;
}
}
<file_sep>/*EXPECTED
ok
*/
/*JS_SETUP
function _() {
console.log("ok");
}
*/
native class _ {
}
class _Main {
function constructor() {
log "should never get called";
}
static function main(args : string[]) : void {
new _();
}
}
<file_sep>/*EXPECTED
Error: hi
EvalError: hi
error not caught
*/
class C.<ThrowType, CatchType> {
function constructor() {
try {
throw new ThrowType("hi");
} catch (e : CatchType) {
log e.toString();
}
}
}
class _Main {
static function main(args : string[]) : void {
try {
new C.<Error, Error>;
new C.<EvalError, Error>;
new C.<Error, EvalError>; // throws an exception
} catch (e : Error) {
log "error not caught";
}
}
}
<file_sep>abstract class B {
abstract function f() : void;
abstract function g() : void;
}
class D extends B {
}
<file_sep>/*EXPECTED
mixin
*/
interface I {
function message() : string;
}
mixin Mixin implements I {
override function message() : string {
return "mixin";
}
}
class Concrete implements Mixin {
}
class _Main {
static function main(args:string[]) : void {
log new Concrete().message();
}
}
<file_sep>class Base {
function constructor(x : number) {
}
}
class Derived extends Base {
function constructor() {
}
}
<file_sep>class T {
}
class T {
}
<file_sep>mixin M {
abstract var i : number;
}
class T implements M {
override var i : string;
}
<file_sep>/*EXPECTED
foo
*/
/*JSX_OPTS
--optimize dce
*/
class _Main {
static function main (args : string[]) : void {
var a = new number[];
a.length;
log "foo";
}
}
<file_sep>/*EXPECTED
1
2
*/
class _Main {
static function foo.<T>(a : T) : T {
return a;
}
static function main(args : string[]) : void {
log _Main.foo(1);
log _Main.foo("2");
}
}
<file_sep>class Test {
static function f() : void {
function g(a) {
return a + 1;
}
}
}
<file_sep>/*EXPECTED
-1
null
0
null
1
*/
class _Main {
static function main(args : string[]) : void {
var a = [ 0 ];
a.push(null);
a.push(1);
a.unshift(null);
a.unshift(-1);
log a[0];
log a[1];
log a[2];
log a[3];
log a[4];
}
}
<file_sep>
aobench.jsx.js: aobench.jsx
jsx --release --executable web --output $@ $<
<file_sep>/*EXPECTED
ok
*/
import "./194.imported-class-in-templates/b.jsx";
class _Main {
static function main(args : string[]) : void {
log B.<string>.f();
}
}
<file_sep>class Test {
static function run() : void {
var a = 42;
log typeof a;
}
}
<file_sep>abstract class Test {
static function run() : void {
new Test();
}
}
<file_sep>/*EXPECTED
foo
*/
/*JSX_OPTS
--optimize inline,dce
*/
class _Main {
static function functionWithSideEffect() : number {
log "foo";
return 0;
}
static function main(args : string[]) : void {
var x = { foo : _Main.functionWithSideEffect(), bar : 42 };
// x is unused intentionally
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>class Test {
var x : number;
function run() : void {
var copy = foo;
this.x = Math.abs(copy);
}
}
<file_sep>/*EXPECTED
(124975000000,249975000000)
*/
/*JSX_OPTS
--optimize lto,inline,unbox
*/
/*BENCHMARK
30
*/
class Point {
var x : number;
var y : number;
function constructor(x : number, y : number) {
this.x = x;
this.y = y;
}
function add(other : Point) : void {
this.x += other.x;
this.y += other.y;
}
override function toString() : string {
return "(" + this.x as string + "," + this.y as string + ")";
}
}
class _Main {
static function loop(cnt : number) : void {
var v = new Point(0, 0);
for (var i = 0; i < 5000; ++i) {
for (var j = 0; j < cnt; ++j) {
v.add(new Point(i, j));
}
}
log v.toString();
}
static function main(args : string[]) : void {
_Main.loop(("100" + "00") as number);
}
}
<file_sep>/*EXPECTED
2
2
*/
/*JSX_OPTS
--optimize lto,inline
*/
class _Main {
static function f(n : number) : number {
var t = 1;
t += n;
return t;
}
function f(n : number) : number {
var t = 1;
t += n;
return t;
}
static function main(args : string[]) : void {
var n = _Main.f(1);
log n;
n = new _Main().f(1);
log n;
}
}
<file_sep>#!/bin/sh
# try: cp tool/git-hooks-pre-push .git/hooks/pre-push
set -xe
make compiler
perl -Mlib=extlib/lib/perl5 extlib/bin/prove t/009.self-hosting.t
<file_sep>
class Fib {
static function fib1(n : int) : int {
if (n <= 2)
return 1;
else
return Fib.fib1(n - 1) + Fib.fib1(n - 2);
}
static function fib2(n : number) : number {
return n <= 2 ? 1 : Fib.fib2(n - 1) + Fib.fib2(n - 2);
}
static function fib3(n : int) : int {
if (n <= 2)
return 1;
var value = 1;
var prevValue = 1;
for (var i = 3; i <= n; i++) {
var t = value + prevValue;
prevValue = value;
value = t;
}
return value;
}
static function fib4(n : int) : int {
switch (n) {
case 1:
case 2:
return 1;
default:
return Fib.fib4(n - 1) + Fib.fib4(n - 2);
}
}
static function fib5(n : int, a : int = 1, b : int = 1) : int {
switch (n) {
case 1:
case 2:
return a;
default:
return Fib.fib5(n - 1, a + b, a);
}
}
}
class _Main {
static function main(args : string[]) : void {
var n = args.length > 0 ? args[0] as number : 10;
log "fib1(" + n as string + ") = " + Fib.fib1(n) as string;
log "fib2(" + n as string + ") = " + Fib.fib2(n) as string;
log "fib3(" + n as string + ") = " + Fib.fib3(n) as string;
log "fib4(" + n as string + ") = " + Fib.fib4(n) as string;
log "fib5(" + n as string + ") = " + Fib.fib5(n) as string;
}
}
<file_sep>class Test {
var a : function() : void;
function constructor() {
this.a = function() : number {
return 1;
};
}
}
<file_sep>/*EXPECTED
foo
*/
class _Main {
static function main(args : string[]) : void {
var foo = function foo() : void {
var a = foo;
log "foo";
};
foo();
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>import "test-case.jsx";
class _Test extends TestCase {
function test1() :void {
this.expect("hello").toBe("hello");
this.expect("world").toBe("world");
}
function test2() :void {
this.expect(42).toBe(42);
}
}
<file_sep>import "./lib/foo.jsx";
class C {
function f() : void {
new Foo().
/*EXPECTED
[
{
"word" : "instanceMemberMethod",
"args" : [],
"definedClass" : "Foo",
"returnType" : "void",
"type" : "Foo.function () : void"
},
{
"word" : "toString",
"args" : [],
"definedClass" : "Object",
"returnType" : "string",
"type" : "Object.function () : string"
}
]
*/
/*JSX_OPTS
--complete 5:15
*/
// vim: set expandtab tabstop=2 shiftwidth=2:
<file_sep>/*EXPECTED
1
hello
bar
2
hello
world
*/
class _Main {
static function main(args : string[]) : void {
var j : variant = {
n: 1,
s: "hello",
m: {
foo: "bar"
},
a: [
"hello",
"world"
]
} : Map.<variant>;
log j["n"];
log j["s"];
log j["m"]["foo"];
log j["a"]["length"];
for (var i = 0; i < j["a"]["length"] as number; ++i) {
log j["a"][i];
}
}
}
<file_sep>/*EXPECTED
10
-10
*/
class C.<T> {
static function f(a : (T) -> T = (x) -> x) : void {
log a(10);
}
}
class _Main {
static function main(args : string[]) : void {
C.<number>.f();
C.<number>.f((x) -> -x);
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>/*EXPECTED
1
2
*/
class _Main {
static function foo.<T>(a : Nullable.<T>) : T {
return a;
}
static function main(args : string[]) : void {
var a : Nullable.<number> = 1;
log _Main.foo(a);
var b : Nullable.<string> = "2";
log _Main.foo(b);
}
}
<file_sep>/*JSX_OPTS
--minify
*/
/*EXPECTED
123
abc
*/
class _Main {
__export__ static var _ = 123;
static var abc = "abc";
static function main(args : string[]) : void {
log _Main._;
log _Main.abc;
}
}
<file_sep>/*EXPECTED
x 100
x 100
x 100
x 100
*/
class _Main {
static function main(args : string[]) : void {
log "x", (99+1) as string;
log "x " + ((99+1) as string);
log "x " + (99+1) as string;
log "x " + (99+1).toString();
}
}
<file_sep>/*EXPECTED
0
1
*/
/*JSX_OPTS
--optimize return-if
*/
class _Main {
static function f(b : boolean) : number {
if (b)
return 1;
else
return 0;
}
static function main(args : string[]) : void {
log _Main.f(false);
log _Main.f(true);
}
}
<file_sep>/*EXPECTED
1
undefined
*/
class _Main {
static function main(args : string[]) : void {
var a = {
x: 3,
y: 1,
z: 4
};
log a["y"];
delete a["y"];
log a["y"];
}
}
<file_sep>/*EXPECTED
0
*/
/*JSX_OPTS
--optimize fold-const
*/
class _Main {
static function main (args : string[]) : void {
log Math.sin(0);;
}
}
<file_sep>class _Main {
static function f(x : Array.<number>) : void {}
static function f(x : Array.<string>) : void {}
static function g(x : Map.<number>) : void {}
static function g(x : Map.<string>) : void {}
static function main(args : string[]) : void {
_Main.f([]);
_Main.g({});
}
}<file_sep>/*EXPECTED
*/
class _Main {
static var x : Nullable.<Array.<number>> = null;
static var y : Nullable.<number[]> = null;
static function main(args : string[]) : void {
_Main.x = [ 1, 2, 3 ];
_Main.y = [ 1, 2, 3 ];
}
}
<file_sep>class Test {
static var foo = Test.x;
static var bar = Unknown;
static function run() : void {
log Test.foo;
log Test.bar;
}
}
<file_sep>// do not run if --minify is set
/*JSX_OPTS
*/
/*EXPECTED
importing#say
imported#say
inner.say
*/
import "js.jsx"; // FIXME only run this test on js emitter
import "064.JSX_file/foo.jsx";
import "064.JSX_file/inner.jsx";
class _Private {
function constructor(x : number) {
}
static function say() : void {
log "importing#say";
}
}
class _Main {
static function testInner() : void {
// "unclassify" optimizer changes the interface, thus disabled
// js.eval("(new (JSX.require('t/run/064.JSX_file/inner.jsx')['Outer.Inner$'])).say$()");
js.eval("JSX.require('t/run/064.JSX_file/inner.jsx')['Outer.Inner'].say$()");
}
static function main(args : string[]) : void {
var doit = (function () : function (: string) : void {
var jsx = js.global["JSX"] as Map.<variant>;
var require = jsx["require"] as function (: string) : Map.<variant>;
return function (path : string) : void {
var klass = require(path)["_Private"] as Map.<variant>;
var say = klass["say$"] as function () : void;
say();
};
})();
doit("t/run/064.JSX_file.jsx");
doit("t/run/064.JSX_file/foo.jsx");
_Main.testInner();
}
}
<file_sep>/***
* JSX development server started by `make server`
* includes JSX compiler for web (try/build/jsx-compiler.js).
*
*/
"use strict";
var http = require("http"),
url = require("url"),
path = require("path"),
child_process = require("child_process"),
fs = require("fs");
// version check
try {
var nodeVersionParts = process.version.match(/(\d+)/g);
var nodeVersion = (+nodeVersionParts[0]) + (nodeVersionParts[1] / 1000) + (nodeVersionParts[2]/ (1000*1000));
if(nodeVersion < 0.006) {
throw new Error("Requires nodejs v0.6.0 or later");
}
}
catch(e) {
console.warn("Unexpected node.js version (>=0.6.0 required), because: %s", e.toString());
}
function finish(response, uri, status, content_type, content) {
var len = content.length;
var headers = {
"Cache-Control" : "no-cache",
"Content-Length" : len
};
if(content_type) {
headers["Content-Type"] = content_type;
}
else if(/\.jsx$/.test(uri)) {
headers["Content-Type"] = "text/plain";
}
else if(/\.js$/.test(uri)) {
headers["Content-Type"] = "application/javascript";
}
else if(/\.css$/.test(uri)) {
headers["Content-Type"] = "text/css";
}
else if(/\.png$/.test(uri)) {
headers["Content-Type"] = "image/png";
}
else if(/\.jpe?g$/.test(uri)) {
headers["Content-Type"] = "image/jpeg";
}
else if(/\//.test(uri) || /\.html$/.test(uri)) {
headers["Content-Type"] = "text/html";
}
console.log("%s %s %s %s (%s bytes)", (new Date()).toISOString(), status, headers["Content-Type"] || "(unknown type)", uri, len);
response.writeHead(status, headers);
response.write(content, "binary");
response.end();
}
function serveFile(response, uri, filename) {
fs.exists(filename, function(exists) {
if(!exists) {
finish(response, uri, 404, "text/plain", "404 Not Found\n");
return;
}
if (fs.statSync(filename).isDirectory()) {
filename += '/index.html';
}
fs.readFile(filename, "binary", function(err, content) {
if(err) {
finish(response, uri, 500, "text/plain", err + "\n");
return;
}
finish(response, uri, 200, undefined, content);
});
});
}
function saveProfile(request, response) {
var profileDir = "web/.profile";
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,PUT,GET,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,*");
if (request.method != "POST" || request.method == "PUT") {
response.end();
return;
}
function twodigits(s) {
s = s.toString();
while (s.length < 2) {
s = "0" + s;
}
return s;
}
function YYYYmmddHHMMSS() {
var d = new Date();
return d.getFullYear() + '-' +
twodigits(d.getMonth() + 1) + '-' +
twodigits(d.getDate()) + '-' +
twodigits(d.getHours()) +
twodigits(d.getMinutes()) +
twodigits(d.getSeconds());
}
var body = "";
// accumulate all data
request.on("data", function (data) {
body += data;
});
request.on("end", function () {
// parse as JSON
try {
var json = JSON.parse(body);
} catch (e) {
response.writeHead(400, "Bad Request", {
"Content-Type": "text/plain"
});
response.write("POST data is corrupt: " + e.toString());
response.end();
return;
}
// save
try {
fs.mkdirSync(profileDir);
} catch (e) {
// FIXME ignore EEXIST only, but how?
}
var id = YYYYmmddHHMMSS();
fs.writeFileSync(profileDir + "/" + id + ".json", JSON.stringify(json));
// send response
response.writeHead(200, "OK", {
"Location" : "http://" + request.headers.host + "/web/profiler.html?" + id,
"Content-Type": "text/plain"
});
response.write("saved profile at http://" + request.headers.host + "/web/profiler.html?" + id);
response.end();
console.info("[I] saved profile at http://" + request.headers.host + "/web/profiler.html?" + id);
});
}
function listProfileResults(request, response) {
var results = fs.readdirSync("web/.profile").filter(function (file) {
return /\d{4}-\d{2}-\d{2}-\d{4}/.test(file);
}).map(function (file) {
return file.replace(/\.\w+$/, "");
}).sort(function (a, b) {
return b.localeCompare(a)
});
response.writeHead(200, "OK", {
"Content-Type": "application/json"
});
response.write(JSON.stringify(results), "utf8");
response.end();
}
function main(args) {
var port = args[0] || "5000";
var httpd = http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname;
if(uri === "/") {
response.writeHead(301, {
Location: "try/"
});
response.end();
return;
}
// profiler stuff
if (/^\/post-profile\/?$/.test(uri)) {
return saveProfile(request, response);
}
else if (/\/\.profile\/results\.json$/.test(uri)) {
return listProfileResults(request, response);
}
var filename = path.join(process.cwd(), uri);
if(/(?:\.html|\/)$/.test(filename)) {
child_process.execFile(
"perl", ["web/build.pl"],
function(error, stdout, stderr) {
if(error) {
finish(response, uri, 500, "text/plain", error + "\n");
return;
}
serveFile(response, uri, filename);
});
}
else {
serveFile(response, uri, filename);
}
});
httpd.listen(parseInt(port, 10));
console.log("Open http://localhost:" + port + "/");
}
main(process.argv.slice(2));
<file_sep>/*EXPECTED
hello
goodbye
*/
import "js.jsx";
abstract class BaseClass {
abstract __export__ function hello() : void;
}
interface BaseInterface {
__export__ function goodbye() : void;
}
class _Main extends BaseClass implements BaseInterface {
override function hello() : void {
log "hello";
}
override function goodbye() : void {
log "goodbye";
}
static function main(args : string[]) : void {
js.eval("(new (JSX.require('t/run/259.export-funcs-abstract.jsx')._Main)).hello()");
js.eval("(new (JSX.require('t/run/259.export-funcs-abstract.jsx')._Main)).goodbye()");
}
}
<file_sep>class Test {
static function run() : void {
var a = [] : MayBeUndefined.<number> [];
}
}
<file_sep>/*EXPECTED
1
2
3 2
*/
/*JSX_OPTS
--optimize unbox
*/
class Point {
var x : number;
var y : number;
function constructor(x : number, y : number) {
this.y = y;
this.x = x;
}
}
class _Main {
static function f(n : number) : number {
log n;
return n;
}
static function main(args : string[]) : void {
var pt = new Point(_Main.f(1), _Main.f(2));
pt.x += 2;
log pt.x, pt.y;
}
}
<file_sep>/*EXPECTED
3,1,4
1,2,3
a,b,c
1:2:3
2
1
undefined
1
5
undefined
0,1,2,3,4,5,6,7
7,6,5,4,3,2,1,0
*/
class _Main {
static function reverse_cmp(x : Nullable.<number>, y : Nullable.<number>) : number {
return y - x;
}
static function main(args : string[]) : void {
log [ 3, 1, 4 ].toString();
log [ 1 ].concat([ 2, 3 ]).toString();
log [ "a", "b", "c" ].join();
log [ 1, 2, 3 ].join(":");
var a = [ 1, 2 ];
log a.pop();
log a.pop();
log a.pop();
log a.push(5);
log a.shift();
log a.shift();
log [ 0, 2, 4, 6, 7, 5, 3, 1 ].sort().join();
log [ 0, 2, 4, 6, 7, 5, 3, 1 ].sort(_Main.reverse_cmp).join();
}
}
<file_sep>// https://github.com/jsx/JSX/issues/84
class A {
var f : function(:variant);
}
<file_sep>THIS FILE SHOULD NOT BE READ
<file_sep>/*EXPECTED
hello
*/
native __fake__ class Foo {
var name : string;
}
class _Main {
static function main(args : string[]) : void {
var f : Foo = { name: "hello" } as __noconvert__ Foo;
log f.name;
}
}
<file_sep>class _Main {
static function main (args : string[]) : void {
var a : int = [];
}
}<file_sep>/*EXPECTED
ok
ok
ok
*/
class C.<T, U> {
}
class _Main {
static function f(o : C.<string, number>) : void {
log "ok";
}
static function f(o : C.<C.<string, number>, number>) : void {
log "ok";
}
static function f(o : C.<string, C.<string, number>>) : void {
log "ok";
}
static function main(args : string[]) : void {
_Main.f(new C.<string, number>());
_Main.f(new C.<C.<string, number>, number>());
_Main.f(new C.<string, C.<string, number>>());
}
}
<file_sep>class C {
static function f() : C[] {
return [new C, new C];
}
}
class _Test {
function testFoo() : void {
this.
var a = C.f();
var x = a[0];
}
}
/*EXPECTED
["???"]
*/
/*JSX_OPTS
--complete 9:9
*/
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>/*EXPECTED
25
*/
class Base {
function constructor() { }
function calculate(x : number) : number {
return x + 5;
}
}
class Derived extends Base {
override function calculate(x : number) : number {
return super.calculate(x) + 10;
}
}
class _Main {
static function main(args : string[]) : void {
var d = new Derived();
log d.calculate(10);
}
}
<file_sep>/*EXPECTED
1
1
*/
class _Main {
static function main(args : string[]) : void {
var x = [1, null, "string"];
var y = {"a" : 1, "b" : null, "c" : "string"};
log x[0];
log y["a"];
}
}<file_sep>import "./lib/foo.jsx" into foo;
import "./lib/bar.jsx" into bar;
class _Main {
static function main(args : string[]) : void {
log foo.MyClass.getName(); // "<EMAIL>"
log bar.MyClass.getName(); // "<EMAIL>"
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>class Test {
static function run() : void {
var a = "abc";
a -= "a";
}
}
<file_sep>/*EXPECTED
true
*/
class _Main {
static function main(args : string[]) : void {
var a = [ "abc".match(/de/) ]; // produce null by not using the literal
log a[1] == a[0];
}
}
<file_sep>/*EXPECTED
1
1
2
3
5
8
13
*/
class _Main {
static function fib(n : number) : number {
var ret;
switch (n) {
case 1:
case 1 + 1:
ret = 1;
break;
default:
ret = _Main.fib(n - 1) + _Main.fib(n - 2);
break;
}
return ret;
}
static function main(args : string[]) : void {
log _Main.fib(1);
log _Main.fib(2);
log _Main.fib(3);
log _Main.fib(4);
log _Main.fib(5);
log _Main.fib(6);
log _Main.fib(7);
}
}
<file_sep>/*EXPECTED
1
*/
class _Main {
static const n = 0;
static function main(args : string[]) : void {
var x = Hoge.<int>.n;
log x;
}
}
class Hoge.<T> {
static const n = _Main.n + 1;
}
<file_sep>/*EXPECTED
foo
42
*/
native class G.<T> {
class I1 {
class I2 {
var foo : T;
function constructor(value : T);
}
}
} = "{ I1: function(value) { this.foo = value; } }";
class _Main {
static function f(o : G.<string>.I1.I2) : void {
log o.foo;
}
static function g(o : G.<number>.I1.I2) : void {
log o.foo;
}
static function main(args : string[]) : void {
var x = new G.<string>.I1.I2("foo");
_Main.f(x);
var y = new G.<number>.I1.I2(42);
_Main.g(y);
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>/*EXPECTED
0
1
3
*/
class _Main {
var n = 0;
function adder() : function (: number) : void {
return function (x : number) : void {
this.n += x;
};
}
static function main(args : string[]) : void {
var t = new _Main();
log t.n;
var adder = t.adder();
adder(1);
log t.n;
adder(2);
log t.n;
}
}
<file_sep>/*EXPECTED
number
string
*/
class _Main {
static function f(n : number) : void {
log "number";
}
static function f(s : string) : void {
log "string";
}
static function g(f : function ( : number) : void) : void {
f(0);
}
static function g(f : function ( : string) : void) : void {
f("");
}
static function main(args : string[]) : void {
_Main.g(_Main.f as function ( : number) : void);
_Main.g(_Main.f as function ( : string) : void);
}
}
<file_sep>/*EXPECTED
true
false
*/
class _Main {
static function f(b : boolean) : boolean {
try {
if (b) throw new Error("Hmm");
} catch (e : Error) {
return false;
}
return true;
}
static function main(args : string[]) : void {
var b = _Main.f(false);
log b;
var b = _Main.f(true);
log b;
}
}
<file_sep>class Test {
var d : string = new Date();
}
<file_sep>/*EXPECTED
-1
*/
/*JSX_OPTS
--optimize fold-const
*/
class _Main {
static function main (args : string[]) : void {
log Math.cos(Math.PI);;
}
}
<file_sep>/*EXPECTED
A.f
_Main.f
A.g
_Main.f
A.g
*/
class A {
static function f(a : number = 42) : void {
log "A.f";
_Main.f();
}
static function g() : void {
log "A.g";
}
}
class _Main {
static function f(a : number = 42) : void {
log "_Main.f";
A.g();
}
static function main(args : string[]) : void {
A.f();
_Main.f();
}
}
<file_sep>/*EXPECTED
true
*/
/*JSX_OPTS
--optimize unclassify
*/
final class Foo {
function constructor() {
}
}
class _Main {
static function main(args : string[]) : void {
var o = new Foo();
log o.toString().length != 0;
}
}
<file_sep>/*EXPECTED
10
*/
class Foo {
var a : number = 0;
function bar () : void {
this.a = 10;
function constructor () : void {
}
constructor();
log this.a;
}
}
class _Main {
static function main (args : string[]) : void {
new Foo().bar();
}
}<file_sep>/*EXPECTED
hello
*/
class _Main {
static function f() : void {
log "hello";
}
static function main(args : string[]) : void {
var a = [ _Main.f ];
a[0]();
}
}
<file_sep>
update-SKS:
rm -rf kingyo
git clone git://github.com/thaga/SuperKingyoSukui-JSX.git kingyo
rm -rf kingyo/.git
<file_sep>
native __fake__ class A { }
class _Main {
static function main(args : string[]) : void {
var o = new Object;
log o instanceof A;
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>class Hello {
function say() : void {
log "hello";
}
}
<file_sep>class Base {
}
class Derived extends Base {
static function f(v : Base) : Derived {
return v;
}
}
<file_sep>class _Main {
var a = "Hello, world";
static function main(args : string[]) :void {
var o = new _Main;
log o.a;
}
}
<file_sep>/*EXPECTED
true
false
true
false
true
false
true
false
*/
/*JSX_OPTS
--optimize fold-const
*/
class _Main {
static function main (args : string[]) : void {
log 0 < 1;
log 1 < 1;
log 1 <= 1;
log 2 <= 1;
log 1 > 0;
log 1 > 1;
log 1 >= 1;
log 1 >= 2;
}
}
<file_sep>class A {
var n = 1;
static var s = "abc";
function f() : void {}
}
class B {
static function f() : void {
var a = new A;
a.
/*EXPECTED
[
{
"word" : "n",
"definedClass" : "A",
"type" : "number"
},
{
"word" : "f",
"definedClass" : "A",
"args" : [],
"returnType" : "void",
"type" : "A.function () : void"
},
{
"word" : "toString",
"definedClass" : "Object",
"args" : [],
"returnType" : "string",
"type" : "Object.function () : string"
}
]
*/
/*JSX_OPTS
--complete 9:5
*/
<file_sep>/*EXPECTED
1
undefined
1
2
undefined
undefined
3
*/
class _Main {
static function main(args : string[]) : void {
var m = { a: 1 };
log m["a"];
log m["b"];
m["b"] = 2;
log m["a"];
log m["b"];
(m = {} : Map.<number>)["c"] = 3;
log m["a"];
log m["b"];
log m["c"];
}
}
<file_sep>/*EXPECTED
foo
*/
class _Main {
static function main(args : string[]) : void {
if (true) {
if (true) {
log "foo";
}
else if (true) {
if (true) {
log "xxx";
}
}
else if (true) {
log "bar";
if (true) {
log "baz";
}
}
else {
log "yyy";
}
}
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>/*EXPECTED
abc
*/
class _Main {
static function main(args : string[]) : void {
try {
log "abc";
} finally {
}
}
}
<file_sep>/*EXPECTED
abc
def
*/
import "256.conflicting-arraytypes-as-args/abc.jsx" into abc;
import "256.conflicting-arraytypes-as-args/def.jsx" into def;
class _Main {
static function f(o : Array.<abc.C>) : void {
log "abc";
}
static function f(o : Array.<def.C>) : void {
log "def";
}
static function main(args : string[]) : void {
_Main.f(new Array.<abc.C>);
_Main.f(new Array.<def.C>);
}
}
<file_sep>class _Main {
static function f() : void {
}
static var a = _Main.f();
}
<file_sep>class One {
function constructor() {
log 1;
}
static function say() : void {
log "One";
}
}
<file_sep>class Foo {
function foo () : Enumerable.<number> {
yield 1;
return 1;
}
}<file_sep>/*EXPECTED
true
false
3
*/
class _Main {
static function main(args : string[]) : void {
var n = null : Nullable.<number>;
log n == null;
n = 3;
log n == null;
log n;
}
}
<file_sep>/*EXPECTED
ok
*/
class _Main {
static function main(args : string[]) : void {
var f = function (block : function():void) : void {
block();
};
f( () -> { log "ok"; } );
}
}
<file_sep>/*EXPECTED
3
4
4
3
2
2
3
3
*/
class _Main {
static function main(args : string[]) : void {
var i = 3;
log i++; // 3
log i; // 4
log i--; // 4
log i; // 3
log --i; // 2
log i; // 2
log ++i; // 3
log i; // 3
}
}
<file_sep>/*EXPECTED
foo
*/
/*JSX_OPTS
--optimize dce
*/
class _Main {
var p = "foo";
function f() : void {
var that : _Main;
that = this;
var s = that.p;
log s;
}
static function main(args : string[]) : void {
new _Main().f();
}
}
<file_sep>/*EXPECTED
undefined
null access
var y : number = a.pop();
^
*/
class _Main {
static function main(args : string[]) : void {
var a = [ 3 ];
a.pop();
var x : Nullable.<number> = a.pop();
log x;
var y : number = a.pop();
log y;
}
}
// vim: set expandtab:
<file_sep>/*EXPECTED
hello
goodbye
*/
class _Main {
function constructor() {
}
function constructor(n : number) {
}
function constructor(cb : (string) -> void) {
cb("hello");
}
function constructor(cb : () -> void) {
cb();
}
static function main(args : string[]) : void {
new _Main((s) -> { log s; });
new _Main(() -> { log "goodbye"; });
}
}
<file_sep>class Test {
var a : number;
var a : number;
}
<file_sep>/*EXPECTED
3
detected invalid cast, value is not a number
_Main.say(_Main.ng() as __noconvert__ number);
^^
*/
class _Main {
static function ok() : variant {
return 3;
}
static function ng() : variant {
return false;
}
static function say(b : number) : void {
log b;
}
static function main(args : string[]) : void {
_Main.say(_Main.ok() as __noconvert__ number);
_Main.say(_Main.ng() as __noconvert__ number);
}
}
// vim: set expandtab:
<file_sep>import "test-case.jsx";
import "js.jsx";
class _Test extends TestCase {
function testInvoke() : void {
this.expect(
js.invoke(
js.global["Math"],
"abs",
[ -10 ] : Array.<variant>)
).toBe(10);
var m = "abs";
this.expect(
js.invoke(
js.global["Math"],
m,
[ -10 ] : Array.<variant>)
).toBe(10);
var a = [ -10 ] : Array.<variant>;
this.expect(
js.invoke(
js.global["Math"],
"abs",
a)
).toBe(10);
}
function testExecScript() : void {
var value = js.eval("2 + 3") as int;
this.expect(value).toBe(2 + 3);
}
}
<file_sep>/*EXPECTED
123
abc
*/
/*JS_SETUP
function Native() {
}
Native.prototype.dump = function (s) {
console.log(s);
}
*/
native class Native.<T> {
function dump(s : T) : void;
}
class _Main {
static function doit(o : Native.<number>) : void {
o.dump(123);
}
static function doit(o : Native.<string>) : void {
o.dump("abc");
}
static function main(args : string[]) : void {
var a = new Native.<number>();
_Main.doit(a);
var b = new Native.<string>();
_Main.doit(b);
}
}
<file_sep>/*EXPECTED
foo
*/
/*JSX_OPTS
--optimize lto,unclassify
*/
class T {
var v : string;
function constructor() {
this.v = "foo";
}
function getFoo() : string {
return this.v;
}
}
class D {
var t = new T();
function f() : string {
if (this.t instanceof T) {
return this.t.getFoo();
}
else {
return "bar";
}
}
}
class _Main {
static function main(args : string[]) : void {
var o = new D();
log o.f();
}
}
<file_sep>/*EXPECTED
*/
import "135.ignore.dot-files/*.jsx";
class _Main {
static function main(args : string[]) : void {
}
}
<file_sep>/*EXPECTED
123,abc
*/
class _Main {
static function main(args : string[]) : void {
try {
throw 123;
} catch (e : variant) {
try {
throw "abc";
} catch (e2 : variant) {
log e as string + "," + e2 as string;
}
}
}
}
<file_sep>/*EXPECTED
ok
*/
class Base {
function foo () : void {}
}
interface Iface {
function foo () : void;
}
class Derived extends Base implements Iface {
override function foo () : void {
log "ok";
}
}
class _Main {
static function main (args : string[]) : void {
(new Derived).foo();
}
}<file_sep>// example for declaration and binary expression
class _Main {
static function main(args :string[]) : void {
var x = 10;
var y = 20;
log x + y;
}
}
<file_sep>/*EXPECTED
hello
*/
import "200.template-under-namespace/a.jsx" into a;
class _Main {
static function main(args : string[]) : void {
a.T.<_Main>.doit();
}
static function say() : void {
log "hello";
}
}
<file_sep>/*EXPECTED
--RegExp--
exec [0]: ar
exec [1]: r
test: true
test: false
source: a(.)
global: false
ignoreCase: false
multiline: false
lastIndex: 0
global: true
ignoreCase: true
multiline: true
*/
class _Main {
static function main(args : string[]) : void {
log "--RegExp--";
var rx = new RegExp("a(.)");
log 'exec [0]: ' + rx.exec("foobar")[0];
log 'exec [1]: ' + rx.exec("foobar")[1];
log 'test: ' + rx.test("foobar").toString();
log 'test: ' + rx.test("xxx").toString();
log 'source: ' + rx.source.toString();
log 'global: ' + rx.global.toString();
log 'ignoreCase: ' + rx.ignoreCase.toString();
log 'multiline: ' + rx.multiline.toString();
log 'lastIndex: ' + rx.lastIndex.toString();
rx = new RegExp("abc", "gim");
log 'global: ' + rx.global.toString();
log 'ignoreCase: ' + rx.ignoreCase.toString();
log 'multiline: ' + rx.multiline.toString();
}
}
<file_sep>abstract class Test {
abstract function f() : void;
static function run(t : Test) : void {
try {
t.f();
} catch (e : Error) {
}
log e;
}
}
<file_sep>interface I implements J {
}
interface J implements I {
}
<file_sep>/*EXPECTED
42
*/
/*JSX_OPTS
--optimize inline
*/
// a variation of t/optimize/040
class _Main {
static function main(args : string[]) : void {
var x = -40;
log (function (x : number) : number {
return (x >= 0 ? x : -x);
}(x - 2));
}
}
<file_sep>/*JSX_OPTS
--warn-error
*/
class T {
static function f() : void {
return;
log "Hi";
}
}
<file_sep>class T {
override function f() : void {
}
}
<file_sep>import "110.import-all-no-files/*.jsx";
<file_sep>/*EXPECTED
1
*/
/*JSX_OPTS
--profile
*/
class _Main {
static function f() : void {
return;
}
static function main(args : string[]) : void {
_Main.f();
var m = JSX.getProfileResults();
log m["_Main.main(:Array.<string>)"]["_Main.f()"]["$count"];
}
}
<file_sep>/*EXPECTED
8
1.5
3
12
4
-1
2147483647
*/
class _Main {
static function main(args : string[]) : void {
log 2 * 4;
log 3 / 2;
log 8 % 5;
log 3 << 2;
log 9 >> 1;
log -1 >> 1;
log -1 >>> 1;
}
}
<file_sep>import "test-case.jsx";
class _Test extends TestCase {
function test_Int8Array() : void {
var a = new Int8Array([10, 20, 30] : int[]);
this.expect(a.length).toBe(3);
this.expect(a[0]).toBe(10);
this.expect(a[1]).toBe(20);
this.expect(a[2]).toBe(30);
this.expect(a[3]).toBe(null);
this.expect(a.byteLength).toBe(3);
a = new Int8Array(10);
this.expect(a.length).toBe(10);
this.expect(a[0]).toBe(0);
a[0] = 20;
this.expect(a[0]).toBe(20);
a[0] = 30 as int;
this.expect(a[0]).toBe(30);
}
function test_Uint8Array() : void {
var a = new Uint8Array([10, 20, 30] : int[]);
this.expect(a.length).toBe(3);
this.expect(a[0]).toBe(10);
this.expect(a[1]).toBe(20);
this.expect(a[2]).toBe(30);
this.expect(a[3]).toBe(null);
this.expect(a.byteLength).toBe(3);
a = new Uint8Array(10);
this.expect(a.length).toBe(10);
this.expect(a[0]).toBe(0);
a[0] = 20;
this.expect(a[0]).toBe(20);
a[0] = 30 as int;
this.expect(a[0]).toBe(30);
}
function test_Int16Array() : void {
var a = new Int16Array([10, 20, 30] : int[]);
this.expect(a.length).toBe(3);
this.expect(a[0]).toBe(10);
this.expect(a[1]).toBe(20);
this.expect(a[2]).toBe(30);
this.expect(a[3]).toBe(null);
this.expect(a.byteLength).toBe(3 * 2);
a = new Int16Array(10);
this.expect(a.length).toBe(10);
this.expect(a[0]).toBe(0);
a[0] = 20;
this.expect(a[0]).toBe(20);
a[0] = 30 as int;
this.expect(a[0]).toBe(30);
}
function test_Uint16Array() : void {
var a = new Uint16Array([10, 20, 30] : int[]);
this.expect(a.length).toBe(3);
this.expect(a[0]).toBe(10);
this.expect(a[1]).toBe(20);
this.expect(a[2]).toBe(30);
this.expect(a[3]).toBe(null);
this.expect(a.byteLength).toBe(3 * 2);
a = new Uint16Array(10);
this.expect(a.length).toBe(10);
this.expect(a[0]).toBe(0);
a[0] = 20;
this.expect(a[0]).toBe(20);
a[0] = 30 as int;
this.expect(a[0]).toBe(30);
}
function test_Int32Array() : void {
var a = new Int32Array([10, 20, 30] : int[]);
this.expect(a.length).toBe(3);
this.expect(a[0]).toBe(10);
this.expect(a[1]).toBe(20);
this.expect(a[2]).toBe(30);
this.expect(a[3]).toBe(null);
this.expect(a.byteLength).toBe(3 * 4);
a = new Int32Array(10);
this.expect(a.length).toBe(10);
this.expect(a[0]).toBe(0);
a[0] = 20;
this.expect(a[0]).toBe(20);
a[0] = 30 as int;
this.expect(a[0]).toBe(30);
}
function test_Uint32Array() : void {
var a = new Uint32Array([10, 20, 30] : int[]);
this.expect(a.length).toBe(3);
this.expect(a[0]).toBe(10);
this.expect(a[1]).toBe(20);
this.expect(a[2]).toBe(30);
this.expect(a[3]).toBe(null);
this.expect(a.byteLength).toBe(3 * 4);
a = new Uint32Array(10);
this.expect(a.length).toBe(10);
this.expect(a[0]).toBe(0);
a[0] = 20;
this.expect(a[0]).toBe(20);
a[0] = 30 as int;
this.expect(a[0]).toBe(30);
}
function test_Float32Array() : void {
var a = new Float32Array([10, 20, 30]);
this.expect(a.length).toBe(3);
this.expect(a[0]).toBe(10);
this.expect(a[1]).toBe(20);
this.expect(a[2]).toBe(30);
this.expect(a[3]).toBe(null);
this.expect(a.byteLength).toBe(3 * 4);
a = new Float32Array(10);
this.expect(a.length).toBe(10);
this.expect(a[0]).toBe(0);
a[0] = 20;
this.expect(a[0]).toBe(20);
a[0] = 30 as int;
this.expect(a[0]).toBe(30);
}
function test_Float64Array() : void {
var a = new Float64Array([10, 20, 30]);
this.expect(a.length).toBe(3);
this.expect(a[0]).toBe(10);
this.expect(a[1]).toBe(20);
this.expect(a[2]).toBe(30);
this.expect(a[3]).toBe(null);
this.expect(a.byteLength).toBe(3 * 8);
a = new Float64Array(10);
this.expect(a.length).toBe(10);
this.expect(a[0]).toBe(0);
a[0] = 20;
this.expect(a[0]).toBe(20);
a[0] = 30 as int;
this.expect(a[0]).toBe(30);
}
function test_DataView() : void {
var b = new Uint8Array([0x10, 0x20, 0x30, 0x40, 0, 0, 0, 0] : int[]);
var v = new DataView(b.buffer);
this.expect(v.getInt8(0), 'getInt8').toBe(0x10);
this.expect(v.getUint8(0), 'getUint8').toBe(0x10);
this.expect(v.getInt16(0), 'getInt16/BE').toBe(0x1020);
this.expect(v.getInt16(0, true), 'getInt16/LE').toBe(0x2010);
this.expect(v.getUint16(0), 'getUint16/BE').toBe(0x1020);
this.expect(v.getUint16(0, true), 'getUint16/LE').toBe(0x2010);
this.expect(v.getInt32(0), 'getInt32/BE').toBe(0x10203040);
this.expect(v.getInt32(0, true), 'getInt32/LE').toBe(0x40302010);
this.expect(v.getUint32(0), 'getUint32/BE').toBe(0x10203040);
this.expect(v.getUint32(0, true), 'getUint32/LE').toBe(0x40302010);
v.setFloat32(0, 123.456);
this.expect( Math.abs(v.getFloat32(0) - 123.456 ), 'getFloat32').toBeLT(0.001);
v.setFloat64(0, 123.456);
this.expect(v.getFloat64(0), 'getFloat64').toBe(123.456);
}
}
<file_sep>/*EXPECTED
false
true
false
true
false
true
*/
class _Main {
static function main(args : string[]) : void {
log false;
log !false;
log !!false;
log true;
log !true;
log !!true;
}
}
<file_sep>/*EXPECTED
1
2
3
*/
class _Main {
static function main(args : string[]) : void {
var a = [ 1, 2, 3];
for (var i = 0, len = a.length; i < len; ++i)
log a[i];
}
}
<file_sep>/*EXPECTED
a,1
b,2
c,3
a,b,c
*/
class _Main {
static function main(args : string[]) : void {
var m = { a: 1, b : 2, c : 3 };
for (var k in m)
log k + "," + m[k] as string;
var a = [] : string[];
var i = 0;
for (a[i++] in m)
;
log a.sort().join(",");
}
}
<file_sep>interface I {
function f() : void;
}
mixin M1 implements I {
override function f() : void {
}
}
mixin M2 implements I {
override function f() : void {
}
}
class T implements M1, M2 {
}
<file_sep>class Test {
static function run() : void {
switch (3) {
case "a":
break;
}
}
}
<file_sep>/*EXPECTED
I am Alice
I am Bob
*/
interface Say {
abstract function say() : void;
}
mixin SayName {
abstract var _name : string;
override function say() : void {
log "I am " + this._name;
}
}
class Human implements Say, SayName {
var _name : string;
function constructor(name : string) {
this._name = name;
}
}
class _Main {
static function main(args : string[]) : void {
var o : Say = new Human("Alice");
o.say();
new Human("Bob").say();
}
}
<file_sep>/*EXPECTED
Error: hi
*/
class C.<T> {
function constructor() {
try {
throw new Error("hi");
} catch (e : Error) {
log e.toString();
}
}
}
class _Main {
static function main(args : string[]) : void {
new C.<number>;
}
}
<file_sep>/*EXPECTED
0
1
*/
/*JSX_OPTS
--optimize inline
*/
final class _Main {
var n = 0;
function incr() : void {
++this.n;
}
static function main(args : string[]) : void {
var that = new _Main;
log that.n;
that.incr();
log that.n;
}
}
<file_sep>/*EXPECTED
2
*/
class _Main {
static function main(args : string[]) : void {
var a = [10, 20];
log a.length;
}
}
<file_sep>/*EXPECTED
hello
world
*/
class _Main {
var foo = "hello";
function constructor() {
(function () : void {
(function() : void {
log this.foo;
this.foo = "world";
})();
})();
log this.foo;
}
static function main(args : string[]) : void {
new _Main();
}
}
<file_sep>/*EXPECTED
bar
*/
native class Native {
class Inner {
static var foo : string;
}
} = "{ Inner: { foo: 'bar' } }";
class _Main {
static function main(args : string[]) : void {
log Native.Inner.foo;
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>/*EXPECTED
abc
undefined
*/
class _Main {
static function main(args : string[]) : void {
var a = [ new String("abc") ];
log (a[0] as String).toString();
log a[1] as String;
}
}
<file_sep>/*EXPECTED
zero
undefined
zero
one
undefined
undefined
two
*/
class _Main {
static function main(args : string[]) : void {
var a = [ "zero" ];
log a[0];
log a[1];
a[1] = "one";
log a[0];
log a[1];
(a = [] : string[])[2] = "two";
log a[0];
log a[1];
log a[2];
}
}
<file_sep>/*EXPECTED
Hi!
*/
/*JS_SETUP
function Native() {
this.say();
}
*/
native class Native {
function say() : void;
}
class _Main extends Native {
static function main(args : string[]) : void {
new _Main;
}
override function say() : void {
log "Hi!";
}
}
<file_sep>/*EXPECTED
a
*/
class _Main {
static function main(args : string[]) : void {
log 1 ? "a" : "b";
}
}
<file_sep>/*EXPECTED
abc
true
*/
class _Main {
static var b = true;
static function main(args : string[]) : void {
var a = _Main.b ? new String("abc") : null;
log a.toString();
a = _Main.b ? (null) : a;
log a == null;
}
}
<file_sep>/*EXPECTED
1,4,9
1,2,3
*/
class _Main {
static function main (args : string[]) : void {
var a = [1,2,3];
log a.map(function (i : number) {
return i * i;
}).join(",");
log a.reduce(function (prev : string, i : number) {
return prev == "" ? i as string : prev + "," + i;
}, "");
}
}
<file_sep>/*JSX_OPTS
--optimize lto,unclassify
*/
/*EXPECTED
0,0
0,0
0,0
*/
class Point {
var x = 0;
var y = 0;
function dump() : void {
log this.x as string + "," + this.y as string;
}
}
class _Main {
static var sf = function (p : Point) : void {
p.dump();
};
var mf = function (p : Point) : void {
p.dump();
};
static function main(args : string[]) : void {
var p = new Point;
p.dump();
_Main.sf(p);
(new _Main).mf(p);
}
}
<file_sep>/*EXPECTED
Hi!
*/
import "js.jsx";
__export__ class _Main {
function constructor() {
log "Hi!";
}
static function main(args : string[]) : void {
js.eval("new (JSX.require('t/run/257.export-class.jsx')._Main)");
}
}
<file_sep>/*EXPECTED
true
*/
class _Main {
static function f() : Map.<number> {
return {
"a": [1][-1]
};
}
static function main(args : string[]) : void {
var a = _Main.f();
log a["a"] == null;
}
}
<file_sep>/*EXPECTED
str0
0str
*/
class _Main {
static function main (args : string[]) : void {
log "str" + 0;
log 0 + "str";
}
}<file_sep>import "./fib.jsx";
import "test-case.jsx";
class _Main {
static function main(args : string[]) : void {
log "fib(10)=" + Fib.fib1(10).toString();
}
}
class _Test extends TestCase {
function testFib1() : void {
this.expect(Fib.fib1(10)).toBe(55);
}
function testFib2() : void {
this.expect(Fib.fib2(10)).toBe(55);
}
function testFib3() : void {
this.expect(Fib.fib3(10)).toBe(55);
}
function testFib4() : void {
this.expect(Fib.fib4(10)).toBe(55);
}
}
<file_sep>// JSX_TEST
import "test-case.jsx";
import _Lexer from "../../src/parser.jsx";
class _Test extends TestCase {
function lexerTest(rx : RegExp, good : string[], bad : string[]) : void {
this.note("matched");
var i;
var matched;
for(i = 0; i < good.length; ++i) {
matched = good[i].match(rx);
this.expect(matched, JSON.stringify(good[i])).notToBe(null);
if(matched) {
this.expect(matched[0]).toBe(good[i]);
}
}
this.note("not matched");
for(i = 0; i < bad.length; ++i) {
matched = bad[i].match(rx);
this.expect(matched, JSON.stringify(bad[i])).toBe(null);
}
}
function testRxIdent() : void {
this.diag('tokenize identifiers');
var good = [
"foo",
"bar",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"f",
"_foo",
"_",
"foo_",
"foo123",
"foo_123",
"varfoo",
"var_foo",
"var123"
];
var bad = [
"123",
"$foo",
" ",
".",
"/",
"+",
"-",
"-foo",
" ",
"\n"
];
this.lexerTest(_Lexer.rxIdent, good, bad);
}
function testRxNumberLiteral() : void {
this.diag('tokenize numbers');
var good = [
"123456789.0",
"3.14",
".012",
"0.012",
"0.012e8",
"0.e8",
"0.e+8",
"0.e-8",
"1e32",
"1E32",
"0E0",
"NaN",
"Infinity",
"0.0"
];
var bad = [
"1a2",
"1x2",
"foo",
"..2",
"2..",
"x2",
"!42",
"+",
"nan",
"infinity",
" "
];
this.lexerTest(_Lexer.rxNumberLiteral, good, bad);
}
function testRxIntegerLiteral() : void {
this.diag('tokenize integers');
var good = [
"1",
"42",
"1234567890",
"0xabcdef123",
"0XABCDEF123",
"0"
// TODO: list ECMA 262 compatible
];
var bad = [
"3.14",
".012",
"0.012",
"0.012e8",
"0.e8",
"1e32",
"1E32",
"0E0",
"0xGG",
"0xZZ",
"088",
"0b1212",
"+"
];
this.lexerTest(_Lexer.rxIntegerLiteral, good, bad);
}
function testRxStringLiteral() : void {
this.diag('tokenize strings');
var good = [
'"foo"',
'"foo bar"',
'"foo\\"bar"',
'"foo\\n"',
'""',
"'foo'",
"'foo bar'",
"'foo\\'bar'",
"'foo\\n'",
"''"
];
var bad = [
'"',
"'",
''
];
this.lexerTest(_Lexer.rxStringLiteral, good, bad);
}
function testRxRegExpLiteral() : void {
this.diag("tokenize regular expressions");
var good = [
'/foo/',
'/foo\\/bar/',
'/[a-zA-Z]/',
'/foo/i',
'/foo/m',
'/foo/g',
'/foo/img',
'/foo/igm',
'/foo/mgi',
'/foo/mgi',
'/foo/gim',
'/foo/gmi',
'/./'
];
var bad = [
"/",
" "
];
this.lexerTest(_Lexer.rxRegExpLiteral, good, bad);
}
}
<file_sep>/*EXPECTED
20
*/
/*JSX_OPTS
--optimize dce
*/
class _Main {
function constructor(n : number) {}
static function main(args : string[]) : void {
var x = 10;
new _Main(x = 20);
log x;
}
}
<file_sep>/*EXPECTED
123
*/
/*JSX_OPTS
--optimize unbox
*/
final class K {
var x = 123;
}
class _Main {
static function main(args : string[]) : void {
var k = new K;
function f() : number {
return k.x;
}
log f();
}
}
<file_sep>/*EXPECTED
42
assertion failure
assert i == 0;
^^
*/
class _Main {
static function main(args : string[]) : void {
var i = 42;
assert i == 42;
log i;
assert i == 0;
log i;
}
}
// vim: set expandtab:
<file_sep>native class Foo {
static var name : string;
} = "{ name: 'a.jsx' }";
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>class A {
static var pi = M
/*EXPECTED
[
{
"word" : "Math",
"partialWord" : "ath"
},
{
"word" : "Map",
"partialWord" : "ap"
}
]
*/
/*JSX_OPTS
--complete 2:19
*/
<file_sep>// from shibukawa:Octavia
/*EXPECTED
foo
*/
/*JSX_OPTS
--optimize unclassify
*/
final class Char
{
var whitespace : Map.<boolean>;
function constructor()
{
this.whitespace = this._charClass();
}
function _charClass () : Map.<boolean>
{
return new Map.<boolean>;
}
}
class _Main {
static function main(args : string[]) : void {
var c = new Char;
log "foo";
}
}
<file_sep>/*EXPECTED
100
*/
/*JSX_OPTS
--optimize lto,unclassify
*/
class MyObject {
var x : int;
function constructor (x : int) {
this.x = x;
}
}
class _Main {
static function f() : Object {
return new MyObject(100);
}
static function main(args : string[]) : void {
log (_Main.f() as MyObject).x;
}
}
<file_sep>/*EXPECTED
A0B0C
*/
class _Main {
static function main(args : string[]) : void {
var s = "a0b0c".replace(/[a-z]/g, (m) -> m.toUpperCase());
log s;
}
}
<file_sep>class A {
static var pi = Math.
/*EXPECTED
[
{
"word" : "<"
},
{
"word" : "E",
"definedClass" : "Math",
"type" : "number"
},
{
"word" : "LN10",
"definedClass" : "Math",
"type" : "number"
},
{
"word" : "LN2",
"definedClass" : "Math",
"type" : "number"
},
{
"word" : "LOG2E",
"definedClass" : "Math",
"type" : "number"
},
{
"word" : "LOG10E",
"definedClass" : "Math",
"type" : "number"
},
{
"word" : "PI",
"definedClass" : "Math",
"type" : "number"
},
{
"word" : "SQRT1_2",
"definedClass" : "Math",
"type" : "number"
},
{
"word" : "SQRT2",
"definedClass" : "Math",
"type" : "number"
},
{
"word" : "abs",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "acos",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "asin",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "atan",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "atan2",
"definedClass" : "Math",
"args" : [
{
"name" : "y",
"type" : "number"
},
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number, : number) : number"
},
{
"word" : "ceil",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "cos",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "exp",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "floor",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "log",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "max",
"definedClass" : "Math",
"args" : [
{
"name" : "value1",
"type" : "number"
},
{
"name" : "value2",
"type" : "number"
},
{
"name" : "value3",
"type" : "number"
},
{
"name" : "valueN",
"type" : "...number"
}
],
"returnType" : "number",
"type" : "function (: number, : number, : number, ... : number) : number"
},
{
"word" : "max",
"definedClass" : "Math",
"args" : [
{
"name" : "value1",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "min",
"definedClass" : "Math",
"args" : [
{
"name" : "value1",
"type" : "number"
},
{
"name" : "value2",
"type" : "number"
},
{
"name" : "value3",
"type" : "number"
},
{
"name" : "valueN",
"type" : "...number"
}
],
"returnType" : "number",
"type" : "function (: number, : number, : number, ... : number) : number"
},
{
"word" : "min",
"definedClass" : "Math",
"args" : [
{
"name" : "value1",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "pow",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
},
{
"name" : "y",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number, : number) : number"
},
{
"word" : "random",
"definedClass" : "Math",
"args" : [],
"returnType" : "number",
"type" : "function () : number"
},
{
"word" : "round",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "sin",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "sqrt",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "tan",
"definedClass" : "Math",
"args" : [
{
"name" : "x",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number) : number"
},
{
"word" : "max",
"definedClass" : "Math",
"args" : [
{
"name" : "value1",
"type" : "number"
},
{
"name" : "value2",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number, : number) : number"
},
{
"word" : "min",
"definedClass" : "Math",
"args" : [
{
"name" : "value1",
"type" : "number"
},
{
"name" : "value2",
"type" : "number"
}
],
"returnType" : "number",
"type" : "function (: number, : number) : number"
}
]
*/
/*JSX_OPTS
--complete 2:23
*/
<file_sep>class Test {
static function f(a : number, a : number) : void {
}
}
<file_sep>/*JSX_OPTS
--minify
*/
/*EXPECTED
abc
123
*/
import "js.jsx";
__export__ class _Main {
__export__ var longlong = 123;
__export__ static var longlong = "abc";
static function main(args : string[]) : void {
js.eval("console.log(JSX.require('t/run/262.export-vars.jsx')._Main.longlong)");
js.eval("console.log((new (JSX.require('t/run/262.export-vars.jsx')._Main)).longlong)");
}
}
<file_sep>
class _Main {
static function main (args : string[]) : void {
foo: for (;0;) {
foo: for (;1;) {
break foo;
}
}
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>class _Main {
static function main(args : string[]) : void {
switch ("foo") {
case "fo\x6f": log "a"; break;
case "foo": log "b"; break;
}
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>class Test {
static var foo = Test.foo;
}
<file_sep>/*EXPECTED
3
true
false
true
true
false
true
*/
class _Main {
static function main(args : string[]) : void {
var a = [ null, 3 ] : Array.<variant>;
log a[1];
log a[0] == null;
log a[1] == null;
log a[2] == null;
log a.shift() == null;
log a.shift() == null;
log a.shift() == null;
}
}
<file_sep>class Foo {
var bar : Array.<Foo>;
}
<file_sep>/*EXPECTED
hello
*/
class _Main {
static function f() : void {
log "hello";
}
static function main(args : string[]) : void {
var m = { a: _Main.f };
m["a"]();
}
}
<file_sep>class T {
function f() : void {
1 in { a: 0 };
}
}
<file_sep>class Base {
function f() : void {}
}
class Derived extends Base {
function f() : void {}
}
<file_sep>/*EXPECTED
true
error
error
true
*/
class Base {
}
interface I {
}
class D1 extends Base implements I {
function say() : void {
log "D1";
}
}
class D2 extends Base implements I {
function say() : void {
log "D2";
}
}
class _Main {
static function main(args : string[]) : void {
var b : Base = new D1();
var d1 = b as D1;
log d1 != null;
try {
var d2 = b as D2;
} catch (e : Error) {
log "error";
}
var i : I = new D2();
try {
d1 = i as D1;
} catch (e : Error) {
log "error";
}
d2 = i as D2;
log d2 != null;
}
}
<file_sep>/*EXPECTED
1
*/
class _Main {
static function f(n : number) : number {
try {
return 1 / n;
} catch (e : Error) {
return NaN;
}
}
static function main(args : string[]) : void {
log _Main.f(1);
}
}
<file_sep>/*EXPECTED
rgb(25,30,35)
*/
/*JSX_OPTS
--optimize inline
*/
// taken from jsx-v8bench/raitrace.jsx
final class Color {
var red = 0.0;
var green = 0.0;
var blue = 0.0;
function constructor() {
this(0.0, 0.0, 0.0);
}
function constructor(r : number, g : number, b : number) {
this.red = r;
this.green = g;
this.blue = b;
}
static function add(c1 : Color, c2 : Color) : Color {
var result = new Color(0,0,0);
result.red = c1.red + c2.red;
result.green = c1.green + c2.green;
result.blue = c1.blue + c2.blue;
return result;
}
static function addScalar(c1 : Color, s : number) : Color {
var result = new Color(0,0,0);
result.red = c1.red + s;
result.green = c1.green + s;
result.blue = c1.blue + s;
result.limit();
return result;
}
static function subtract(c1 : Color, c2 : Color) : Color {
var result = new Color(0,0,0);
result.red = c1.red - c2.red;
result.green = c1.green - c2.green;
result.blue = c1.blue - c2.blue;
return result;
}
static function multiply(c1 : Color, c2 : Color) : Color {
var result = new Color(0,0,0);
result.red = c1.red * c2.red;
result.green = c1.green * c2.green;
result.blue = c1.blue * c2.blue;
return result;
}
static function multiplyScalar(c1 : Color, f : number) : Color {
_Main.global.color = new Color(0.5, 0.5, 0.5); // XXX affects global env
var result = new Color(0,0,0);
result.red = c1.red * f;
result.green = c1.green * f;
result.blue = c1.blue * f;
return result;
}
static function divideFactor(c1 : Color, f : number) : Color {
var result = new Color(0,0,0);
result.red = c1.red / f;
result.green = c1.green / f;
result.blue = c1.blue / f;
return result;
}
function limit() : void {
this.red = (this.red > 0.0) ? ( (this.red > 1.0) ? 1.0 : this.red ) : 0.0;
this.green = (this.green > 0.0) ? ( (this.green > 1.0) ? 1.0 : this.green ) : 0.0;
this.blue = (this.blue > 0.0) ? ( (this.blue > 1.0) ? 1.0 : this.blue ) : 0.0;
}
function distance(color : Color) : number {
var d = Math.abs(this.red - color.red) + Math.abs(this.green - color.green) + Math.abs(this.blue - color.blue);
return d;
}
static function blend(c1 : Color, c2 : Color, w : number) : Color {
var result = new Color(0,0,0);
result = Color.add(
Color.multiplyScalar(c1, 1 - w),
Color.multiplyScalar(c2, w)
);
return result;
}
function brightness() : number {
var r = Math.floor(this.red*255);
var g = Math.floor(this.green*255);
var b = Math.floor(this.blue*255);
return (r * 77 + g * 150 + b * 29) >> 8;
}
override function toString() : string {
var r = Math.floor(this.red*255);
var g = Math.floor(this.green*255);
var b = Math.floor(this.blue*255);
return "rgb("+ r as string +","+ g as string +","+ b as string +")";
}
}
final class _Main {
var color = new Color(0.10, 0.20, 0.30);
var reflection = 0.1;
static var global : _Main;
static function main(args : string[]) : void {
var o = new _Main;
_Main.global = o;
var color = new Color(0.10, 0.11, 0.12);
color = Color.blend(
color,
o.color,
o.reflection
);
log color.toString();
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>/*EXPECTED
102
111
111
*/
/*JSX_OPTS
--optimize fold-const
*/
class _Main {
static function main (args : string[]) : void {
log "foo".charCodeAt(0);
log "foo".charCodeAt(1);
log "foo".charCodeAt(2);
}
}
<file_sep>class Test {
static function run() : void {
var t = null;
}
}
<file_sep>/*EXPECTED
importing:say
imported:say
importing:constructor
importing:constructor
imported:constructor
imported:constructor
*/
import "060.private-class/imported.jsx";
class _Private {
function constructor() {
log "importing:constructor";
}
static function say() : void {
log "importing:say";
}
}
class _Main extends _Private {
static function main(args : string[]) : void {
_Private.say();
Imported.say();
new _Private();
new _Main();
Imported.instantiatePrivate();
new Imported();
}
}
<file_sep>
class Foo {
function instanceMemberMethod() : void {
}
static function staticMemberMethod() : void {
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>/*EXPECTED
hello
*/
class _Main {
static function f() : number {
throw new Error("hello");
}
static function main(args : string[]) : void {
try {
_Main.f();
} catch (e : Error) {
log e.message;
}
}
}
<file_sep>/*EXPECTED
1
*/
/*JSX_OPTS
--profile
*/
class _Main {
static function f() : void {
try {
throw new Error("Hmm");
} catch (e : Error) {
}
}
static function main(args : string[]) : void {
_Main.f();
var m = JSX.getProfileResults();
log m["_Main.main(:Array.<string>)"]["_Main.f()"]["$count"];
}
}
<file_sep>/*EXPECTED
foo
bar0
foo
bar1
*/
class _Main {
static function foo() : void {
log "foo";
}
static function bar() : void {
log "bar0";
}
static function bar(i : int) : void {
log "bar1";
}
static function main(args : string[]) : void {
var f = _Main.foo;
f();
f = _Main.bar;
f();
var g : function () : void = _Main.foo;
g();
var h : function (:int):void = _Main.bar;
h(0);
}
}
<file_sep>/*EXPECTED
abc
def
*/
/*JSX_OPTS
--optimize inline
*/
class Base {
var value : string = "abc";
function constructor() {
}
function constructor(value : string) {
this.value = value;
}
}
class _Main extends Base {
function constructor() {
}
function constructor(value : string) {
super(value);
}
static function main(args : string[]) : void {
var b = new _Main();
log b.value;
b = new _Main("def");
log b.value;
}
}
<file_sep>/*EXPECTED
1
*/
class Test {
static function run() : void {
var t = newTest();
}
}
<file_sep>/*EXPECTED
60
*/
/*JSX_OPTS
--optimize dce
*/
class _Main {
static function main(args : string[]) : void {
var x = 1;
var y = 2;
var z = 3;
(x == y) && (x == z) && (z == y) ? x : y;
x = 10;
y = 20;
z = 30;
log x + y + z;
}
}
<file_sep>import "062.import-file-not-found/foo.jsx";
<file_sep>/*EXPECTED
1,2,
,2,
1,2,
,2,
1,2,
,2,
*/
class _Main {
static function main(args : string[]) : void {
var a = [ 1, 2, null ];
log a.join(",");
a[0] = null;
log a.join(",");
a = [ 1, 2, null ] : number[];
log a.join(",");
a[0] = null;
log a.join(",");
a = [ 1, 2, null ] : Array.<number>;
log a.join(",");
a[0] = null;
log a.join(",");
}
}
<file_sep>/*EXPECTED
10
24
*/
class _Main {
static function main(args : string[]) : void {
var a = [ 1, 2, 3, 4 ];
var sum = 0;
a.forEach(function (e) {
sum += e;
});
log sum;
var prod = 1;
a.forEach((e, i) -> { prod *= e; });
log prod;
}
}
<file_sep>
class Test {
var member = null;
function f() : void {
this.member = function() : void {};
}
}
<file_sep>import "js/phantomjs/test-case.jsx";
class _Test extends PhantomTestCase {
function testHello() : void {
var got = "Hello, world!";
this.expect(got).toBe("Hello, world!");
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>/*EXPECTED
-1
0.5
*/
class _Main {
static function main(args : string[]) : void {
log 1 - (1 + 1);
log 2 / (2 * 2);
}
}
<file_sep>/*EXPECTED
0
1
2
3
end
*/
class _Main {
static function main (args : string[]) : void {
function iota (n : number) : Enumerable.<number> {
var i = 0;
do {
yield i;
i++;
} while (i < n);
}
var g = iota(4);
try {
while (true) {
log g.next();
}
} catch (e : StopIteration) {
log "end";
}
}
}<file_sep>/*EXPECTED
foo
bar
*/
native class A {
static __readonly__ var propWithSideEffect : string;
} = "{ get propWithSideEffect() { console.log('foo'); return 'xxx'; } }";
class _Main {
static function main (args : string[]) : void {
A.propWithSideEffect;
log "bar";
}
}
<file_sep>import "054.import-self.jsx";
class T {
}
<file_sep>/*EXPECTED
123
*/
class _Main {
static function main(args : string[]) : void {
try {
throw 123;
} catch (e : variant) {
(function () : void {
log e as string;
})();
}
}
}
<file_sep>/*EXPECTED
ok
ok
*/
class _Main {
static const foo = "ok";
static const bar = (function() : string {
return _Main.foo;
}());
static function main(args : string[]) : void {
log _Main.foo;
log _Main.bar;
}
}
<file_sep>class _Private {
static function say() : void {
log "imported#say";
}
}
<file_sep>/*EXPECTED
foo,bar
*/
import "./131.assign-array-of-imported-class/module.jsx";
class _Main {
static function main(args : string[]) : void {
var a : string[] = C.foo;
log a.join(",");
}
}
<file_sep>/*EXPECTED
foo
bar
*/
/*JSX_OPTS
--optimize inline
*/
class _Main {
static inline function f(n : number) : void {
if (n == 0) _Main.g("foo");
else _Main.g("bar");
}
static function g(s : string) : void {
log s;
}
static function main(args : string[]) : void {
_Main.f(0);
_Main.f(1);
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>class Base {
function constructor(n : number) {
}
}
class Derived extends Base {
}
<file_sep>/*EXPECTED
hello
goodbye
*/
import "059.import/hello.jsx";
import "059.import/sub/goodbye.jsx";
class _Main {
static function main(args : string[]) : void {
new Hello().say();
new Goodbye().say();
}
}
<file_sep>
class _Main {
static function heavyFunc() : number {
var n = 0;
for (var i = 0; i < 1000000; ++i) {
n += Math.sin(i);
}
return n;
}
static function main(args : string[]) : void {
var port = (args.length > 0 ? args[0] as int : 2012);
log _Main.heavyFunc();
JSX.postProfileResults("http://localhost:" + port as string + "/post-profile", (error, response) -> {
log error;
log response;
});
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>class Test {
function main() : void {
var key : variant = null;
var obj : variant = null;
obj[key];
}
}
<file_sep>/*EXPECTED
[
{
"word" : "import"
},
{
"word" : "class"
},
{
"word" : "interface"
},
{
"word" : "mixin"
},
{
"word" : "abstract"
},
{
"word" : "final"
},
{
"word" : "native"
}
]
*/
/*JSX_OPTS
--complete 1:1
*/
<file_sep>/*EXPECTED
hello from static function
hello from method
*/
import "js.jsx";
class _Main {
__export__ static function say() : void {
log "hello from static function";
}
__export__ function say() : void {
log "hello from method";
}
static function main(args : string[]) : void {
js.eval("JSX.require('t/run/258.export-funcs.jsx')._Main.say()");
js.eval("(new (JSX.require('t/run/258.export-funcs.jsx')._Main)).say()");
}
}
<file_sep>class _Foo {
}
<file_sep>/*EXPECTED
1,2,3,1
*/
class _Main {
static function main(args : string[]) : void {
var a1 = [ 1, 2, 3 ];
var a2 = [ a1[0] ]; // should not become Array.<MBU.<number>>
var a3 = a1.concat(a2); // a1 and a2 are Array.<number>
log a3.join(",");
}
}
<file_sep>/*EXPECTED
ok
*/
class Node.<T> {
var value : T;
var _next : Node.<T>;
function constructor(value:T) {
this.value = value;
this._next = null;
}
function next() : Node.<T> {
return this._next;
}
}
class List.<T> {
var head : Node.<T>;
var length : int;
function constructor() {
this.head = null;
this.length = 0;
}
override function toString() : string {
var str = '';
for (var n = this.head; n!=null; n=n.next()) {
str += (n.value as string) + ',';
}
return str;
}
}
class _Main {
final static function main(args : string[]) : void {
var list = new List.<int>();
log "ok";
}
}
<file_sep>/*EXPECTED
foo
*/
import "132.import-alias-in-type-decl/foo.jsx" into foo;
class _Main {
static function f() : foo.Foo {
return new foo.Foo();
}
static function main(args : string[]) : void {
var f = _Main.f();
}
}
<file_sep>/*EXPECTED
A
B
*/
native class A {
class Foo {
var bar : string;
}
} = "{ Foo: function () { this.bar = 'A' } }";
native class B {
class Foo {
var bar : string;
}
} = "{ Foo: function () { this.bar = 'B' } }";
class _Main {
static function main(args : string[]) : void {
log new A.Foo().bar;
log new B.Foo().bar;
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>/*EXPECTED
30
4
*/
/*JSX_OPTS
--optimize dce
*/
class _Main {
static function main (args : string[]) : void {
var x : number;
var y : number;
(y = 2, y = 3, y = 4) && (x = 10, x = 20, x = 30);
log x;
log y;
}
}
<file_sep>/*EXPECTED
42
*/
class _Main {
static function main(args : string[]) : void {
log (function fma (a : number, b : number, c : number) {
return a * b + c;
})(6, 6, 6);
}
}<file_sep>/*EXPECTED
1
hello
3
hello,,
[["hello",null,null],null]
*/
class _Main {
static function main(args : string[]) : void {
var sa = new string[];
sa[0] = "hello";
log sa.length;
log sa.join(",");
sa = new string[3];
sa[0] = "hello";
log sa.length;
log sa.join(",");
var saa = new string[][2];
saa[0] = sa;
log JSON.stringify(saa);
}
}
<file_sep>/***
XMLHttpRequest example
*/
import 'js/web.jsx';
import 'console.jsx';
class _Main {
static function main(args : string[]) : void {
var xhr = new XMLHttpRequest();
var path = dom.document.location.pathname;
xhr.open("GET", path.replace(/\/[^\/]*$/, "") + "/hello.txt");
xhr.onreadystatechange = function (e) {
if (xhr.readyState == xhr.DONE) {
_Main.update(xhr.responseText);
}
};
xhr.onerror = function (e) {
console.error("XHR error");
};
xhr.send();
}
static function update(text : string) : void {
var output = dom.id("output");
var textNode = dom.document.createTextNode(text);
output.appendChild(textNode);
}
}
// vim: set expandtab:
<file_sep>class F {
static function foo() : number {
return 0;
}
static function run() : void {
F.foo()++;
}
}
<file_sep>/*EXPECTED
16
10
100
false
true
true
false
*/
class _Main {
static function main(args : string[]) : void {
// local variable named parseInt() etc. are allowed
var parseInt = 0;
var parseFloat = 0;
var isNaN = 0;
var isFinite = 0;
log Number.parseInt("0x10");
log Number.parseInt("010", 10);
log Number.parseFloat("1e2");
log Number.isNaN(42);
log Number.isNaN(NaN);
log Number.isFinite(42);
log Number.isFinite(Infinity);
}
}
<file_sep>interface I {
}
class Test {
static function run() : void {
new I();
}
}
<file_sep>/*EXPECTED
foo
bar
*/
class _Main {
static function f(x : () -> void = () -> { log "foo"; }) : void {
x();
}
static function main(args : string[]) : void {
_Main.f();
_Main.f(() -> { log "bar"; });
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>/*EXPECTED
foo
*/
/*JSX_OPTS
--optimize staticize
*/
class _Main {
final function foo () : void {
log 'foo';
}
static function main(args : string[]) : void {
var m = new _Main;
m.foo();
}
}
<file_sep>/*EXPECTED
abc
*/
/*JSX_OPTS
--optimize inline
*/
class _Main {
var s = "ab";
static function f(s : string) : string {
return s + "c";
}
static function main(args : string[]) : void {
var s = _Main.f(new _Main().s);
log s;
}
}
<file_sep>/*EXPECTED
A
*/
/*JSX_OPTS
--disable-type-check
*/
class A {
override function toString() : string {
return "A";
}
}
class B {
override function toString() : string {
return "B";
}
}
class _Main {
static function main(args : string[]) : void {
var o : Object = new A;
log (o as B).toString();
}
}
<file_sep>import 'timer.jsx';
import 'js/web.jsx';
class _Main {
static function main(args : string[]) : void {
Hello.main();
}
}
class Hello {
static var gl:WebGLRenderingContext = null;
static var program:WebGLProgram = null;
static var tex:WebGLTexture = null;
static var vbuf:WebGLBuffer = null;
static var tbuf:WebGLBuffer = null;
static var ibuf:WebGLBuffer = null;
static var angle:number = 0;
static function getGL(canvas : HTMLCanvasElement) : WebGLRenderingContext {
var names = ["webgl", "experimental-webgl"];
for (var i = 0; i < names.length; ++i) {
var gl = canvas.getContext(names[i]) as WebGLRenderingContext;
if (gl) {
return gl;
}
}
return null;
}
static function main() : void {
var canvas = dom.id('webgl-canvas') as HTMLCanvasElement;
var gl = Hello.getGL(canvas);
if (gl == null) {
dom.window.alert("This browser does not support WebGL :(");
return;
}
// points of vertices
var vertices = [
-0.9, -0.9,
0.9, -0.9,
0.9, 0.9,
-0.9, 0.9
];
var vbuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// texture coordinates of verteces
var texcs = [
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0
];
var tbuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, tbuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texcs), gl.STATIC_DRAW);
var indices = [
0, 1, 2,
2, 3, 0
];
var ibuf = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibuf);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
// shader of verteces
var vshader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vshader, dom.id('vshader').innerHTML);
gl.compileShader(vshader);
var shederp = gl.getShaderParameter(vshader, gl.COMPILE_STATUS);
if (!(gl.getShaderParameter(vshader, gl.COMPILE_STATUS) as boolean)) {
dom.window.alert(gl.getShaderInfoLog(vshader));
return;
}
// shader of fragments
var fshader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fshader, dom.id('fshader').innerHTML);
gl.compileShader(fshader);
if (!(gl.getShaderParameter(fshader, gl.COMPILE_STATUS) as boolean)) {
dom.window.alert(gl.getShaderInfoLog(fshader));
return;
}
// build program
var program = gl.createProgram();
gl.attachShader(program, vshader);
gl.attachShader(program, fshader);
gl.bindAttribLocation(program, 0, 'position');
gl.bindAttribLocation(program, 1, 'color');
gl.linkProgram(program);
if (!(gl.getProgramParameter(program, gl.LINK_STATUS) as boolean)) {
dom.window.alert(gl.getProgramInfoLog(program));
return;
}
// texture
var tex = gl.createTexture();
var image = dom.window.document.createElement('img') as HTMLImageElement;
image.onload = function(e:Event):void{
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
};
image.src = 'teko.jpg';
Hello.gl = gl;
Hello.program = program;
Hello.vbuf = vbuf;
Hello.tbuf = tbuf;
Hello.ibuf = ibuf;
Timer.setInterval(Hello.draw, 30);
}
static function draw(): void {
var gl = Hello.gl;
Hello.angle -= 0.005;
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST);
gl.useProgram(Hello.program);
gl.uniform1f(gl.getUniformLocation(Hello.program, 'angle'), Hello.angle);
gl.bindBuffer(gl.ARRAY_BUFFER, Hello.vbuf);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(0);
gl.bindBuffer(gl.ARRAY_BUFFER, Hello.tbuf);
gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(1);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Hello.ibuf);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
gl.flush();
}
}
<file_sep>// works on only Chrome (as of 2013/2)
import "js/web.jsx";
class _Main {
static function main(args : string[]) : void {
log "application start";
var nav : variant = dom.window.navigator;
if (!nav["getUserMedia"]) {
nav["getUserMedia"] = nav["webkitGetUserMedia"]
?: nav["mozGetUserMedia"];
}
// WebRTC video
try {
dom.window.navigator.getUserMedia(
{ video : true } : Map.<variant>,
function (stream) {
log "MediaStream start";
var v = dom.id("video") as HTMLVideoElement;
v.src = URL.createObjectURL(stream);
}, function (error) {
log error;
});
}
catch (e : Error) {
log e;
}
}
}
<file_sep>
(function (exports) {
"use strict";
var DEBUG = false;
function makeAlt(patterns) {
return "(?: \n" + patterns.join("\n | \n") + "\n)\n";
}
function quoteMeta(pattern) {
return pattern.replace(/([^0-9A-Za-z_])/g, '\\$1');
}
function rx(pat, flags) {
return RegExp(pat.replace(/[ \t\r\n]/g, ""), flags);
}
var ident = " [\\$a-zA-Z_] [\\$a-zA-Z0-9_]* ";
var doubleQuoted = ' " [^"\\n\\\\]* (?: \\\\. [^"\\n\\\\]* )* " ';
var singleQuoted = doubleQuoted.replace(/"/g, "'");
var stringLiteral = makeAlt([singleQuoted, doubleQuoted]);
var regexpLiteral = doubleQuoted.replace(/"/g, "/") + "[mgi]*";
var decimalIntegerLiteral = "(?: 0 | [1-9][0-9]* )";
var exponentPart = "(?: [eE] [+-]? [0-9]+ )";
var numberLiteral = makeAlt([
"(?: " + decimalIntegerLiteral + " \\. " +
"[0-9]* " + exponentPart + "? )",
"(?: \\. [0-9]+ " + exponentPart + "? )",
"(?: " + decimalIntegerLiteral + exponentPart + " )"
]) + "\\b";
var integerLiteral = makeAlt([
"(?: 0 [xX] [0-9a-fA-F]+ )", // hex
decimalIntegerLiteral
]) + "(?![\\.0-9eE])\\b";
var multiLineComment = "(?: /\\* (?: [^*] | (?: \\*+ [^*\\/]) )* \\*+/)";
var singleLineComment = "(?: // [^\\r\\n]* )";
var comment = makeAlt([multiLineComment, singleLineComment]);
var whiteSpace = "[\\x20\\t\\r\\n]+";
var keywords = [
"null", "true", "false",
"break", "do", "instanceof", "typeof",
"case", "else", "new", "var",
"catch", "finally", "return", "void",
"continue", "for", "switch", "while",
"function", "this",
"default", "if", "throw",
"delete", "in", "try",
"class", "extends", "super",
"import", "implements",
"debugger", "with",
"const", "export",
"let", "private", "public", "yield",
"protected"
];
var rxSpace = rx("^" + makeAlt([comment, whiteSpace]) + "+");
var rxIdent = rx("^" + ident);
var rxStringLiteral = rx("^" + stringLiteral);
var rxNumberLiteral = rx("^" + makeAlt([numberLiteral, integerLiteral]) + "\\b");
var rxRegExpLiteral = rx("^" + regexpLiteral);
var rxKeyword = rx("^" + makeAlt(keywords.map(quoteMeta)) + "\\b");
var endOfPrimaryExpr = {
"null": true,
"false": true,
"true": true,
")": true,
"]": true
};
function lastIsPrimaryExpr(tokens) {
var i = tokens.length - 1;
while(i >= 0 && tokens[i].type === "space") {
--i;
}
if(tokens[i].token in endOfPrimaryExpr) {
return true;
}
var t = tokens[i].type;
return t === "identifier" ||
t === "string" ||
t === "regexp" ||
t === "number";
}
function tokenize(fileName, src) {
var tokens = [];
var line = 1;
var col = 0;
var id = 0;
while( src.length > 0 ) {
var matched;
var type;
if( (matched = src.match(rxSpace)) !== null ) {
type = "space";
}
else if( src.charAt(0) === "/" ) {
if( lastIsPrimaryExpr(tokens) ) {
matched = src.match(/^./);
type = "keyword";
}
else if( (matched = src.match(rxRegExpLiteral)) !== null ) {
type = "regexp";
}
else {
throw new SyntaxError("jslexer: ["+fileName+":"+line+":"+col+"] "+
"Unexpected character '" +
src.charAt(0) + "'");
}
}
else if( (matched = src.match(rxKeyword)) !== null ) {
type = "keyword";
}
else if( (matched = src.match(rxIdent)) !== null ) {
type = "identifier";
}
else if( (matched = src.match(rxStringLiteral)) !== null ) {
type = "string";
}
else if( (matched = src.match(rxNumberLiteral)) !== null ) {
type = "number";
}
else if( (matched = src.match(/^./)) !== null ) {
type = "keyword";
}
else {
throw new SyntaxError("jslexer: ["+fileName+":"+line+":"+col+"] "+
"Unexpected character '" +
src.charAt(0) + "'");
}
var token = matched[0];
if (DEBUG) {
console.info(matched);
}
src = src.slice(token.length);
tokens.push({
type: type,
token: token,
column: col,
line: line,
id: ++id
});
if(token.match(/\n/)) {
var lines = token.split(/\n/);
line += lines.length - 1;
col = lines[lines.length - 1].length;
}
else {
col += matched[0].length;
}
}
return tokens;
}
exports.tokenize = tokenize;
}( typeof(exports) !== "undefined" ? exports : window ));
if(typeof(process) !== "undefined" && process.argv[1] === __filename) { // node
process.argv.slice(2).forEach(function (file) {
var buff= require("fs").readFileSync(file).toString();
var tokens = exports.tokenize(file, buff);
console.log(tokens);
});
}
<file_sep>/*EXPECTED
false
true
false
false
true
true
*/
class _Main {
static function main(args : string[]) : void {
var bV : boolean = false.valueOf();
log bV;
bV = true.valueOf();
log bV.valueOf();
var b = new Boolean();
var bV : boolean = b.valueOf();
log bV;
b = new Boolean(false);
bV = b.valueOf();
log bV;
b = new Boolean(true);
bV = b.valueOf();
log bV;
b = null;
log b == null;
}
}
<file_sep>/*EXPECTED
hello
goodbye
*/
class Base.<T> {
function doit() : void {
(this as T).hello();
}
function doit_noconvert() : void {
(this as __noconvert__ T).goodbye();
}
}
class _Main extends Base.<_Main> {
static function main(args : string[]) : void {
(new _Main).doit();
(new _Main).doit_noconvert();
}
function hello() : void {
log "hello";
}
function goodbye() : void {
log "goodbye";
}
}
<file_sep>import "common.jsx";
class Klass {
static function doit() : void {
Template.<Klass>.doit();
}
static function say() : void {
log "a";
}
}
<file_sep>/*EXPECTED
1,2,3
detected invalid cast, value is not an Array or null
_Main.say(_Main.ng() as __noconvert__ number[]);
^^
*/
class _Main {
static function ok() : variant {
return [ 1, 2, 3 ];
}
static function ng() : variant {
return {} : Map.<string>;
}
static function say(a : number[]) : void {
log a.join(",");
}
static function main(args : string[]) : void {
_Main.say(_Main.ok() as __noconvert__ number[]);
_Main.say(_Main.ng() as __noconvert__ number[]);
}
}
// vim: set expandtab:
<file_sep>/*EXPECTED
hello
*/
abstract class Base {
function self() : Base {
return this;
}
abstract function hello() : void;
}
class _Main extends Base {
override function self() : _Main {
return this;
}
override function hello() : void {
log "hello";
}
static function f(b : Base) : void {
b.self().hello();
}
static function main(args : string[]) : void {
_Main.f(new _Main);
}
}
<file_sep>/*EXPECTED
1
2
One
Two
*/
import "119.import-all-into/*.jsx" into N;
class _Main {
static function main(args : string[]) : void {
new N.One();
new N.Two();
N.One.say();
N.Two.say();
}
}
<file_sep>/*EXPECTED
# simple test
check()
true
true
1
true
true
1
0
# reset and test
check()
true
true
1
true
true
1
0
# check that callees are being reset
undefined
# check reset in callee
true
true
1
undefined
*/
/*JSX_OPTS
--profile
*/
class _Main {
static function spendTime() : void {
var until = Date.now() + 10;
while (Date.now() < until)
;
}
static function g(reset : boolean) : void {
if (reset) {
JSX.resetProfileResults();
}
_Main.spendTime();
// spend time inline
var until = Date.now() + 10;
while (Date.now() < until)
;
}
static function h() : void {
// spend time inline and in callee
_Main.spendTime();
var until = Date.now() + 10;
while (Date.now() < until)
;
// reset in callee
(function () : void {
JSX.resetProfileResults();
})();
}
static function main(args : string[]) : void {
function check() : void {
log "check()";
var m = JSX.getProfileResults();
var exclusive = m["_Main.main(:Array.<string>)"]["_Main.g(:boolean)"]["_Main.spendTime()"]["$exclusive"] as number;
log 10 <= exclusive;
var inclusive = m["_Main.main(:Array.<string>)"]["_Main.g(:boolean)"]["_Main.spendTime()"]["$inclusive"] as number;
log 10 <= inclusive;
log m["_Main.main(:Array.<string>)"]["_Main.g(:boolean)"]["_Main.spendTime()"]["$count"];
exclusive = m["_Main.main(:Array.<string>)"]["_Main.g(:boolean)"]["$exclusive"] as number;
log 10 <= exclusive;
inclusive = m["_Main.main(:Array.<string>)"]["_Main.g(:boolean)"]["$inclusive"] as number;
log 20 <= inclusive;
log m["_Main.main(:Array.<string>)"]["_Main.g(:boolean)"]["$count"];
log m["_Main.main(:Array.<string>)"]["$count"]; // should be zero, since it has not exitted
}
log "# simple test";
_Main.g(false);
check();
log "# reset and test";
_Main.g(true);
check();
log "# check that callees are being reset";
JSX.resetProfileResults();
var m = JSX.getProfileResults();
log m["_Main.main(:Array.<string>)"]["_Main.g()"]; // should be undefine
log "# check reset in callee";
_Main.h();
var m = JSX.getProfileResults();
log m["_Main.main(:Array.<string>)"]["_Main.h()"]["$exclusive"] as number <= 1;
log m["_Main.main(:Array.<string>)"]["_Main.h()"]["$inclusive"] as number <= 1;
log m["_Main.main(:Array.<string>)"]["_Main.h()"]["$count"];
log m["_Main.main(:Array.<string>)"]["_Main.h()"]["_Main.spendTime()"]; // undefined
}
}
<file_sep>
class Foo {
function constructor(a : number, b : number) {}
function constructor(c : string[]) { }
}
class C {
function f() : void {
new Fo
/*EXPECTED
[
"TODO: should includes both Foo(:number, :number) and Foo(:strin[])"
]
*/
/*JSX_OPTS
--complete 9:11
*/
// vim: set expandtab tabstop=2 shiftwidth=2:
<file_sep>(function (exports) {
"use strict";
var Config = {
quantity : 360,
size : 2.0,
decay : 0.98,
gravity : 2.0,
speed : 6.0
};
var Class = function () {
};
Class.extend = function (properties) {
var ctor = properties.constructor;
if (ctor === Object) {
var superCtor = this.prototype.constructor;
ctor = properties.constructor = function () {
superCtor.call(this);
};
}
function tmp() {}
tmp.prototype = this.prototype;
ctor.prototype = new tmp();
ctor.extend = Class.extend;
// assign properties
for (var k in properties) {
if (k.charAt(0) == '$') {
ctor[k.substring(1)] = properties[k];
} else {
ctor.prototype[k] = properties[k];
}
}
if (typeof ctor.constructor === "function") {
ctor.constructor();
}
return ctor;
};
Class.prototype.constructor = function () {
};
var Spark = Class.extend({
$rad: Math.PI * 2,
constructor: function (posX, posY, size, color) {
this.state = 0;
this.posX = posX;
this.posY = posY;
this.size = size;
this.color = color;
var angle = Math.random() * Spark.rad;
var velocity = Math.random() * Config.speed;
this.velX = Math.cos(angle) * velocity;
this.velY = Math.sin(angle) * velocity;
},
_decay: function () {
this.velX *= Config.decay;
this.velY *= Config.decay;
this.size *= Config.decay;
if(this.size < 0.5 && this.state == 0) {
this.color = Firework.randomColor();
this.size = Config.size;
this.state++;
}
},
_move: function () {
this.posX += this.velX + (Math.random() - 0.5);
this.posY += this.velY + (Math.random() - 0.5) + Config.gravity;
},
_render: function (view) {
view.cx.beginPath();
view.cx.arc(this.posX, this.posY, this.size, 0, Spark.rad, true);
view.cx.fillStyle = Math.random() > 0.2 ? this.color : "white";
view.cx.fill();
},
_isLiving: function (view) {
if(this.size <= 0.01) return false;
if(this.posX <= 0) return false;
if(this.posX >= view.width || this.posY >= view.height) return false;
return true;
},
draw: function (view) {
this._decay();
this._move();
this._render(view);
return this._isLiving(view);
},
});
var Firework = Class.extend({
$randomColor: function () {
var blightness = 60;
var rgb = [];
for (var i = 0; i < 3; ++i) {
rgb[i] = Math.min( (Math.random() * 0xFF + blightness) | 0, 255 );
}
return "rgb(" +
rgb[0] + "," +
rgb[1] + "," +
rgb[2] + ")";
},
constructor: function (view, x, y ) {
this.sparks = [];
this.view = view;
var color = "lime";
for (var i = 0; i < Config.quantity; ++i) {
this.sparks.push(new Spark(x, y, Config.size, color));
}
},
update: function() {
for(var i = 0; i < this.sparks.length; ++i) {
var s = this.sparks[i];
if (! s.draw(this.view)) {
this.sparks.splice(i, 1);
}
}
return this.sparks.length > 0;
}
});
var FireworkView = Class.extend({
constructor: function (canvas) {
this.fireworks = [];
this.numSparks = 0;
this.cx = canvas.getContext("2d");
this.width = canvas.width;
this.height = canvas.height;
var rect = canvas.getBoundingClientRect();
this.left = rect.left;
this.top = rect.top;
var $this = this;
canvas.addEventListener("mousedown", function (e) {
$this.explode(e.clientX, e.clientY);
});
canvas.addEventListener("touchstart", function (e) {
$this.explode(e.touches[0].pageX, e.touches[0].pageY);
});
},
explode: function (x, y) {
this.fireworks.push(new Firework(this, x - this.left, y - this.top));
},
update: function () {
if (this.fireworks.length == 0) {
// first one
this.explode(this.width / 2 + this.left, this.height / 3);
}
this.numSparks = 0;
for (var i = 0; i < this.fireworks.length; ++i) {
var fw = this.fireworks[i];
if(fw.update()) {
this.numSparks += fw.sparks.length;
}
else {
this.fireworks.splice(i, 1);
}
}
this.cx.fillStyle = "rgba(0, 0, 0, 0.3)";
this.cx.fillRect(0, 0, this.width, this.height);
},
});
var FPSWatcher = Class.extend({
constructor: function (elementId) {
this.start = Date.now();
this.frameCount = 0;
this.elementId = elementId;
},
update: function(numSparks) {
++this.frameCount;
if(this.frameCount % 100 == 0) {
var message = "FPS: " + ((this.frameCount / (Date.now() - this.start) * 1000) | 0) +
" (sparks: " + numSparks + ")";
document.getElementById(this.elementId).innerHTML = message;
}
}
});
exports.FireworkApplication = Class.extend({
$main: function (canvasId, fpsId, quantity) {
Config.quantity = quantity;
var canvas = document.getElementById(canvasId);
if(!canvas) {
throw new Error("No such element: " + canvasId);
}
var view = new FireworkView(canvas);
var watcher = new FPSWatcher(fpsId);
window.setInterval( function() {
view.update();
watcher.update(view.numSparks);
}, 0);
}
});
}(window));
<file_sep>/*EXPECTED
got error
got error
got error
got error
*/
/*JSX_OPTS
*/
class _T.<type> {
function constructor(v : variant) {
try {
v as __noconvert__ type;
log "function suceeded unexpected";
} catch (e : Error) {
log "got error";
}
}
}
class _Main {
static function main(args : string[]) : void {
new _T.<boolean>(null);
new _T.<number>(null);
new _T.<int>(null);
new _T.<string>(null);
}
}
<file_sep>/*EXPECTED
1
abc
undefined
*/
class _Main {
static function main(args : string[]) : void {
var a = { a: 1, b: "abc" } : variant;
log a["a"];
log a["b"];
log a["c"];
}
}
<file_sep>class Test {
delete function constructor() {
}
static function main() : void {
new Test;
}
}
<file_sep>/*EXPECTED
0
3
a
b
A
B
!
@
*/
class _Main {
static function _for() : void {
l: for (var i = 0; i < 2; ++i) {
log i;
if (true) break l;
}
l2: for (var i = 0; i < 2; ++i) {
for (var j = 3; j < 4; ++j) {
log j;
if (true) break l2;
}
}
}
static function _dowhile() : void {
l: do {
log "a";
if (true) break l;
} while (true);
l2: do {
do {
log "b";
if (true) break l2;
} while (true);
} while (true);
}
static function _while() : void {
l: while (true) {
log "A";
break l;
}
l2: while (true) {
while (true) {
log "B";
break l2;
}
}
}
static function _switch() : void {
l: switch (1) {
default:
log "!";
break l;
}
l2: while (true) {
switch (1) {
default:
log "@";
break l2;
}
}
}
static function main(args : string[]) : void {
_Main._for();
_Main._dowhile();
_Main._while();
_Main._switch();
}
}
<file_sep>class C extends String /* this is the error */ {
static function f() : void {
"abc".substring(0).c
/*EXPECTED
[
{
"word" : "charAt",
"partialWord" : "harAt",
"definedClass" : "String",
"args" : [
{
"name" : "pos",
"type" : "number"
}
],
"returnType" : "string",
"type" : "String.function (: number) : string"
},
{
"word" : "charCodeAt",
"partialWord" : "harCodeAt",
"definedClass" : "String",
"args" : [
{
"name" : "pos",
"type" : "number"
}
],
"returnType" : "number",
"type" : "String.function (: number) : number"
},
{
"word" : "concat",
"partialWord" : "oncat",
"definedClass" : "String",
"args" : [
{
"name" : "stringN",
"type" : "...string"
}
],
"returnType" : "string",
"type" : "String.function (... : string) : string"
}
]
*/
/*JSX_OPTS
--complete 3:23
*/
<file_sep>class _Main {
static function run() : void {
var x = new Variant.<int, string>();
var y = new Variant.<int, string, boolean>();
}
}
class Variant.<t1, t2> {
}
class Variant.<t1, t2, t3> {
}
<file_sep>/*EXPECTED
false
false
false
true
false
false
true
true
true
*/
class C {
}
interface I {
}
class _Main extends C implements I {
static function main(args : string[]) : void {
var n : Object = null;
log n instanceof C;
log n instanceof I;
log n instanceof _Main;
log new C() instanceof C;
log new C() instanceof I;
log new C() instanceof _Main;
log new _Main() instanceof C;
log new _Main() instanceof I;
log new _Main() instanceof _Main;
}
}
<file_sep>/*EXPECTED
10
*/
/*JSX_OPTS
--optimize fold-const
*/
class _Main {
static function main (args : string[]) : void {
var a = 10;
log a * 1.0;
}
}
<file_sep>class Test {
static function f(v : int) : void {
}
static function f(v : Array.<int>) : void {
}
static function run() :void {
Test.f("abc");
}
}
<file_sep>/*EXPECTED
true
error
*/
interface I1 {
}
interface I2 implements I1 {
}
class CTrue implements I2 {
}
class CFalse implements I1 {
}
class _Main {
static function main(args : string[]) : void {
var i1 : I1 = new CTrue();
var i2 : I2 = i1 as I2;
log i2 != null;
i1 = new CFalse();
try {
i2 = i1 as I2;
} catch (e : Error) {
log "error";
}
}
}
<file_sep>class _Private {
function constructor() {
log "imported:constructor";
}
static function say() : void {
log "imported:say";
}
}
class Imported extends _Private {
static function instantiatePrivate() : void {
new _Private();
}
static function say() : void {
_Private.say();
}
}
<file_sep>import 'js/web.jsx';
import 'mvq.jsx';
import 'webgl-util.jsx';
class Water {
static var gl = null:WebGLRenderingContext;
static var progDisp = null:WebGLProgram;
static var progVelo = null:WebGLProgram;
static var vbuf = null:WebGLBuffer;
static var drawProg = null:WebGLProgram;
static var drawVBuf = null:WebGLBuffer;
static var drawTBuf = null:WebGLBuffer;
static const tsize = 64;
static const time_step = 0.02;
static function initWithGL(gl:WebGLRenderingContext) : void {
Water.gl = gl;
Water.progDisp = Util.getProgram('water.vs', 'waterd.fs');
Water.progVelo = Util.getProgram('water.vs', 'waterv.fs');
Water.vbuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, Water.vbuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0,0, 1,0, 1,1, 0,1]), gl.STATIC_DRAW);
Water.drawProg = Util.getProgram('vt.vs', 'refr.fs');
Water.drawVBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, Water.drawVBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-20,-20, 20,-20, 20,20, -20,20]), gl.STATIC_DRAW);
Water.drawTBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, Water.drawTBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0,0, 1,0, 1,1, 0,1]), gl.STATIC_DRAW);
}
var texture = null:WebGLTexture;
var framebuffer = null:WebGLFramebuffer;
var texturebuffer = null:WebGLTexture;
var depthbuffer = null:WebGLRenderbuffer;
var width = 0;
var height = 0;
var _ix = -1;
var _iy = -1;
var _ir = 0;
var _iz = 0;
var _next_step_time = 0;
function constructor() {
var gl = Water.gl;
var w = Water.tsize;
var h = Water.tsize;
var framebuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
for (var i = 0; i < 2; ++i) {
var timg = new Uint8Array(w * h * 4);
for (var y = 0; y < h; ++y) for (var x = 0; x < w; ++x) {
var b = (y*w+x)*4;
timg[b] = 128;
timg[b + 1] = 128;
timg[b + 2] = 0;
timg[b + 3] = 0;
}
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, timg);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.bindTexture(gl.TEXTURE_2D, null);
if (i == 0) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
this.texturebuffer = texture;
} else {
this.texture = texture;
}
}
var depthbuffer = gl.createRenderbuffer();
//gl.bindRenderbuffer(gl.RENDERBUFFER, depthbuffer);
//gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, w, h);
//gl.bindRenderbuffer(gl.RENDERBUFFER, null);
//gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthbuffer);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
this.framebuffer = framebuffer;
this.depthbuffer = depthbuffer;
this.width = w;
this.height = h;
}
function destroy() : void {
var gl = Water.gl;
gl.deleteFramebuffer(this.framebuffer);
gl.deleteTexture(this.texturebuffer);
gl.deleteRenderbuffer(this.depthbuffer);
gl.deleteTexture(this.texture);
}
function step(t:number) : void {
if (!this._next_step_time) this._next_step_time = t;
if (t < this._next_step_time) return;
this._next_step_time += Water.time_step;
if (this._next_step_time < t) this._next_step_time = t;
var gl = Water.gl;
// get viewport
//var vp = gl.getParameter(gl.VIEWPORT) as Int32Array;
// XXX: workaround fod Firefox
var vp = null:Int32Array;
var tmp_vp = gl.getParameter(gl.VIEWPORT);
if (tmp_vp instanceof Int32Array) {
vp = tmp_vp as __noconvert__ Int32Array;
} else {
vp = new Int32Array(tmp_vp as __noconvert__ Array.<int>);
}
gl.disable(gl.BLEND);
gl.disable(gl.DEPTH_TEST);
this._step(Water.progDisp); // displacement step
this._step(Water.progVelo); // velocity step
// restore viewport
gl.viewport(vp[0], vp[1], vp[2], vp[3]);
gl.enable(gl.BLEND);
gl.enable(gl.DEPTH_TEST);
// reset down pos
if (this._ir > 0) this._ir = 0;
}
function _step(prog:WebGLProgram) : void {
var gl = Water.gl;
var vloc = gl.getAttribLocation(prog, 'vertex');
// draw begin
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
gl.viewport(0, 0, this.width, this.height);
gl.useProgram(prog);
var impLoc = gl.getUniformLocation(prog, 'impulse');
if (impLoc) {
gl.uniform4f(impLoc, this._ix, this._iy, this._iz, this._ir);
}
gl.uniformMatrix4fv(gl.getUniformLocation(prog, 'projectionMatrix'), false, new M44().setOrtho(0, 1, 0, 1, -1, 1).array());
gl.uniform2f(gl.getUniformLocation(prog, 'sampleStep'), 1/this.width, 1/this.height);
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.bindBuffer(gl.ARRAY_BUFFER, Water.vbuf);
gl.vertexAttribPointer(vloc, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vloc);
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
gl.disableVertexAttribArray(vloc);
gl.bindTexture(gl.TEXTURE_2D, null);
// draw end
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
// swap textures
var tmpTex = this.texturebuffer;
this.texturebuffer = this.texture;
this.texture = tmpTex;
}
function debugDraw() : void {
var gl = Water.gl;
var prog = Water.progDisp;
var vloc = gl.getAttribLocation(prog, 'vertex');
gl.useProgram(prog);
gl.uniformMatrix4fv(gl.getUniformLocation(prog, 'projectionMatrix'), false, new M44().setOrtho(0, 1, 0, 1, -1, 1).array());
gl.uniform2f(gl.getUniformLocation(prog, 'sampleStep'), 1/this.width, 1/this.height);
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.bindBuffer(gl.ARRAY_BUFFER, Water.vbuf);
gl.vertexAttribPointer(vloc, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vloc);
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
gl.disableVertexAttribArray(vloc);
}
function draw(projMat:M44, viewMat:M44, bgTex:WebGLTexture, w:number, h:number) : void {
var gl = Water.gl;
var prog = Water.drawProg;
var vloc = gl.getAttribLocation(prog, 'vertex');
var tloc = gl.getAttribLocation(prog, 'texcoord');
gl.useProgram(prog);
gl.uniformMatrix4fv(gl.getUniformLocation(prog, 'projectionMatrix'), false, projMat.array());
gl.uniformMatrix4fv(gl.getUniformLocation(prog, 'modelviewMatrix'), false, viewMat.array());
gl.uniform2f(gl.getUniformLocation(prog, 'texSize'), w, h);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.uniform1i(gl.getUniformLocation(prog, 'waveTexture'), 1);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, bgTex);
gl.uniform1i(gl.getUniformLocation(prog, 'bgTexture'), 0);
gl.bindBuffer(gl.ARRAY_BUFFER, Water.drawVBuf);
gl.vertexAttribPointer(vloc, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vloc);
gl.bindBuffer(gl.ARRAY_BUFFER, Water.drawTBuf);
gl.vertexAttribPointer(tloc, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(tloc);
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
gl.disableVertexAttribArray(vloc);
gl.disableVertexAttribArray(tloc);
}
function setImpulse(x:number, y:number, r:number, z:number) : void {
this._ix = x;
this._iy = y;
this._ir = r;
this._iz = z;
}
}
<file_sep>class Test {
var n : MayBeUndefined.<MayBeUndefined.<number>> = 3;
}
<file_sep>/*EXPECTED
3
*/
/*JSX_OPTS
--optimize inline
*/
class _Main {
var n = 3;
function f() : number {
return function () : number {
return this.n;
}();
}
static function main(args : string[]) : void {
var n = (new _Main).f();
log n;
}
}
<file_sep>
class Test {
static function run() : void {
log "s" / 100;
}
}
<file_sep>class A {
}
class B {
static function run() : void {
var a : A = new B();
}
}
<file_sep>
#OPTIMIZE=--optimize lto,no-assert,no-log,fold-const,return-if,inline,unbox,fold-const,lcse,fold-const,array-length,unclassify
all:
jsx --release --executable web --output game.jsx.js game.jsx
debug:
jsx --executable web --output game.jsx.js game.jsx
debug-with-source-map:
jsx --enable-source-map --executable web --output game.jsx.js game.jsx
update-mvq:
curl -LO https://raw.github.com/thaga/mvq.jsx/master/lib/mvq.jsx
chmod -w mvq.jsx # make read only
<file_sep>/*EXPECTED
1
2
*/
/*JSX_OPTS
--optimize inline
*/
class _Main {
static function min(x : number, y : number) : number {
return Math.min(x, y);
}
static function main(args : string[]) : void {
log _Main.min(1, 2);
log Math.max(1, 2);
}
}
<file_sep>class C {
static function f() : number {
return "abc";
}
}
<file_sep>/*EXPECTED
true
false
true
false
false
true
false
true
*/
class _Main {
static function main(args : string[]) : void {
log "a" < "b";
log "b" < "a";
log "a" <= "b";
log "b" <= "a";
log "a" > "b";
log "b" > "a";
log "a" >= "b";
log "b" >= "a";
}
}
<file_sep>/*EXPECTED
-42
*/
class _Main {
static function f(x : number) : number {
log x;
return x;
}
static function f(x : string) : string {
log x;
return x;
}
static function main(args : string[]) : void {
_Main.f(-42);
}
}
<file_sep>/*EXPECTED
1
2
3
end
*/
class _Main {
static function main (args : string[]) : void {
function foo (ary : number[]) : Enumerable.<number> {
for (var i in ary) {
yield i;
}
}
var g = foo([1, 2, 3]);
try {
while (true) {
log g.next();
}
} catch (e : StopIteration) {
log "end";
}
}
}<file_sep>/*EXPECTED
Hi!
*/
/*JSX_OPTS
--optimize strip
*/
native class Native {
} = "(console.log('Hi!'), function () {})";
class _Main {
static function main(args : string[]) : void {
var a = [ new Object ];
try {
log (a[0] as Native) != null;
} catch (e : Error) {
}
}
}
<file_sep>/*EXPECTED
42
*/
class _Main {
static function f(a : int[]) : void {
log a[0];
}
static function main(args : string[]) : void {
var a : int = 42;
_Main.f([a]);
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>import "test-case.jsx";
class _Main {
static function main(args : string[]) : void {
function foo(a : string = "bar") : void { }
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>/*EXPECTED
a
b
*/
import "199.template-arg-namespace/a.jsx" into A;
import "199.template-arg-namespace/b.jsx" into B;
class _Main {
static function main(args : string[]) : void {
A.Klass.doit();
B.Klass.doit();
}
}
<file_sep># Release Engineering
## Edit Changes and package.json
See 3921ce620c213b9a52c4f355b1557258b6dd4ecb (v0.9.17) for example.
## make publish
Type `make publish`, which builds JSX compiler, tests it,
makes a dist, and uploads the dist to npmjs.org.
This command also creates a tag and pushes the tag to github.
<file_sep># JSX completion
The JSX compiler has the completion mode for text editors / IDEs,
triggered by `jsx --complete`.
# CAVEAT
This feature is alpha quality. Project to change.
# USAGE
`jsx --complete 15:7 complete/example.jsx` will shows the following JSON array:
```json
[
{
"word" : "window",
"definedFilename" : "/path/to/jsx/lib/js/js/web.jsx",
"definedClass" : "dom",
"doc" : "The top-level Window object.",
"type" : "Window",
"definedLineNumber" : 18
},
{
"args" : [
{
"name" : "id",
"type" : "string"
}
],
"word" : "getElementById",
"definedClass" : "dom",
"definedFilename" : "/path/to/jsx/lib/js/js/web.jsx",
"type" : "function (: string) : HTMLElement",
"doc" : "same as <code>dom.document.getElement(id)</code>, except returns <code>HTMLElement</code>.",
"returnType" : "HTMLElement",
"definedLineNumber" : 35
}
]
```
[jsx.vim](https://github.com/jsx/jsx.vim/blob/master/autoload/jsx.vim) uses this feature.
<file_sep>/*EXPECTED
bar
*/
native class Native {
class Inner {
var foo : string;
}
} = "{ Inner: function() { this.foo = 'bar'; } }";
class _Main {
static function main(args : string[]) : void {
_Main.f(new Native.Inner);
}
static function f(ni : Native.Inner) : void {
log ni.foo;
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>
class Base {
function f(a : number = 10, b : number = 20) : void {
log a;
log b;
}
}
class Derived extends Base {
override function f(a : number = 100, b : number = 200) : void {
log a;
log b;
}
}
class _Main {
static function main(args : string[]) : void {
new Base().f(42);
(new Derived() as Base).f(42);
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>/*EXPECTED
foo
bar
*/
class _Main {
static function main(args : string[]) : void {
(function() : void { log "foo"; }());
(function() : void { log "bar"; })();
}
}
<file_sep>class Test {
static function run() : void {
null as string;
}
}
<file_sep>class Test {
static function run() : void {
var m = { a: 1 };
m[0];
}
}
<file_sep>class _Main {
function toString(a : number = 42) : string {
log "should not override Object#toString() without 'override' attribute";
}
}
<file_sep>class Test {
static function run() : void {
var a : variant = 0;
1 += 1;
}
}
<file_sep>/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1(the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is GCLI.
*
* The Initial Developer of the Original Code is
* The Mozilla Foundation
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* <NAME> <<EMAIL>> (Original Author)
* <NAME> <<EMAIL>>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Define a module along with a payload.
* @param {string} moduleName Name for the payload
* @param {ignored} deps Ignored. For compatibility with CommonJS AMD Spec
* @param {function} payload Function with (require, exports, module) params
*/
function define(moduleName, deps, payload) {
if (typeof moduleName != "string") {
throw new TypeError('Expected string, got: ' + moduleName);
}
if (arguments.length == 2) {
payload = deps;
}
if (moduleName in define.modules) {
throw new Error("Module already defined: " + moduleName);
}
define.modules[moduleName] = payload;
};
/**
* The global store of un-instantiated modules
*/
define.modules = {};
/**
* We invoke require() in the context of a Domain so we can have multiple
* sets of modules running separate from each other.
* This contrasts with JSMs which are singletons, Domains allows us to
* optionally load a CommonJS module twice with separate data each time.
* Perhaps you want 2 command lines with a different set of commands in each,
* for example.
*/
function Domain() {
this.modules = {};
this._currentModule = null;
}
(function () {
/**
* Lookup module names and resolve them by calling the definition function if
* needed.
* There are 2 ways to call this, either with an array of dependencies and a
* callback to call when the dependencies are found (which can happen
* asynchronously in an in-page context) or with a single string an no callback
* where the dependency is resolved synchronously and returned.
* The API is designed to be compatible with the CommonJS AMD spec and
* RequireJS.
* @param {string[]|string} deps A name, or names for the payload
* @param {function|undefined} callback Function to call when the dependencies
* are resolved
* @return {undefined|object} The module required or undefined for
* array/callback method
*/
Domain.prototype.require = function(deps, callback) {
if (Array.isArray(deps)) {
var params = deps.map(function(dep) {
return this.lookup(dep);
}, this);
if (callback) {
callback.apply(null, params);
}
return undefined;
}
else {
return this.lookup(deps);
}
};
function normalize(path) {
var bits = path.split('/');
var i = 1;
while (i < bits.length) {
if (bits[i] === '..') {
bits.splice(i-1, 1);
} else if (bits[i] === '.') {
bits.splice(i, 1);
} else {
i++;
}
}
return bits.join('/');
}
function join(a, b) {
a = a.trim();
b = b.trim();
if (/^\//.test(b)) {
return b;
} else {
return a.replace(/\/*$/, '/') + b;
}
}
function dirname(path) {
var bits = path.split('/');
bits.pop();
return bits.join('/');
}
/**
* Lookup module names and resolve them by calling the definition function if
* needed.
* @param {string} moduleName A name for the payload to lookup
* @return {object} The module specified by aModuleName or null if not found.
*/
Domain.prototype.lookup = function(moduleName) {
if (/^\./.test(moduleName)) {
moduleName = normalize(join(dirname(this._currentModule), moduleName));
}
if (moduleName in this.modules) {
var module = this.modules[moduleName];
return module;
}
if (!(moduleName in define.modules)) {
throw new Error("Module not defined: " + moduleName);
}
var module = define.modules[moduleName];
if (typeof module == "function") {
var exports = {};
var previousModule = this._currentModule;
this._currentModule = moduleName;
module(this.require.bind(this), exports, { id: moduleName, uri: "" });
this._currentModule = previousModule;
module = exports;
}
// cache the resulting module object for next time
this.modules[moduleName] = module;
return module;
};
}());
define.Domain = Domain;
define.globalDomain = new Domain();
var require = define.globalDomain.require.bind(define.globalDomain);
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
define('lib/source-map/source-map-generator', ['require', 'exports', 'module' , 'lib/source-map/base64-vlq', 'lib/source-map/util', 'lib/source-map/array-set'], function(require, exports, module) {
var base64VLQ = require('./base64-vlq');
var util = require('./util');
var ArraySet = require('./array-set').ArraySet;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. To create a new one, you must pass an object
* with the following properties:
*
* - file: The filename of the generated source.
* - sourceRoot: An optional root for all URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
this._file = util.getArg(aArgs, 'file');
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = [];
}
SourceMapGenerator.prototype._version = 3;
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
this._validateMapping(generated, original, source, name);
if (source && !this._sources.has(source)) {
this._sources.add(source);
}
if (name && !this._names.has(name)) {
this._names.add(name);
}
this._mappings.push({
generated: generated,
original: original,
source: source,
name: name
});
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping.');
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var mapping;
// The mappings must be guarenteed to be in sorted order before we start
// serializing them or else the generated line numbers (which are defined
// via the ';' separators) will be all messed up. Note: it might be more
// performant to maintain the sorting as we insert them, rather than as we
// serialize them, but the big O is the same either way.
this._mappings.sort(function (mappingA, mappingB) {
var cmp = mappingA.generated.line - mappingB.generated.line;
return cmp === 0
? mappingA.generated.column - mappingB.generated.column
: cmp;
});
for (var i = 0, len = this._mappings.length; i < len; i++) {
mapping = this._mappings[i];
if (mapping.generated.line !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generated.line !== previousGeneratedLine) {
result += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
result += ',';
}
}
result += base64VLQ.encode(mapping.generated.column
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generated.column;
if (mapping.source && mapping.original) {
result += base64VLQ.encode(this._sources.indexOf(mapping.source)
- previousSource);
previousSource = this._sources.indexOf(mapping.source);
// lines are stored 0-based in SourceMap spec version 3
result += base64VLQ.encode(mapping.original.line - 1
- previousOriginalLine);
previousOriginalLine = mapping.original.line - 1;
result += base64VLQ.encode(mapping.original.column
- previousOriginalColumn);
previousOriginalColumn = mapping.original.column;
if (mapping.name) {
result += base64VLQ.encode(this._names.indexOf(mapping.name)
- previousName);
previousName = this._names.indexOf(mapping.name);
}
}
}
return result;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
var map = {
version: this._version,
file: this._file,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._sourceRoot) {
map.sourceRoot = this._sourceRoot;
}
return JSON.stringify(map);
};
exports.SourceMapGenerator = SourceMapGenerator;
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
define('lib/source-map/base64-vlq', ['require', 'exports', 'module' , 'lib/source-map/base64'], function(require, exports, module) {
var base64 = require('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string.
*/
exports.decode = function base64VLQ_decode(aStr) {
var i = 0;
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (i >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charAt(i++));
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
return {
value: fromVLQSigned(result),
rest: aStr.slice(i)
};
};
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
define('lib/source-map/base64', ['require', 'exports', 'module' ], function(require, exports, module) {
var charToIntMap = {};
var intToCharMap = {};
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
.split('')
.forEach(function (ch, index) {
charToIntMap[ch] = index;
intToCharMap[index] = ch;
});
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function base64_encode(aNumber) {
if (aNumber in intToCharMap) {
return intToCharMap[aNumber];
}
throw new TypeError("Must be between 0 and 63: " + aNumber);
};
/**
* Decode a single base 64 digit to an integer.
*/
exports.decode = function base64_decode(aChar) {
if (aChar in charToIntMap) {
return charToIntMap[aChar];
}
throw new TypeError("Not a valid base 64 digit: " + aChar);
};
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
define('lib/source-map/util', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
function join(aRoot, aPath) {
return aPath.charAt(0) === '/'
? aPath
: aRoot.replace(/\/*$/, '') + '/' + aPath;
}
exports.join = join;
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
define('lib/source-map/array-set', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = {};
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i]);
}
return set;
};
/**
* Add the given string to this set.
*
* @param String str
*/
ArraySet.prototype.add = function ArraySet_add(aStr) {
if (this.has(aStr)) {
// Already a member; nothing to do.
return;
}
var idx = this._array.length;
this._array.push(aStr);
this._set[aStr] = idx;
};
/**
* Is the given string a member of this set?
*
* @param String str
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
return Object.prototype.hasOwnProperty.call(this._set, aStr);
};
/**
* What is the index of the given string in the array?
*
* @param String str
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (this.has(aStr)) {
return this._set[aStr];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number idx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
define('lib/source-map/source-map-consumer', ['require', 'exports', 'module' , 'lib/source-map/util', 'lib/source-map/binary-search', 'lib/source-map/array-set', 'lib/source-map/base64-vlq'], function(require, exports, module) {
var util = require('./util');
var binarySearch = require('./binary-search');
var ArraySet = require('./array-set').ArraySet;
var base64VLQ = require('./base64-vlq');
// TODO: bug 673487
//
// Sometime in the future, if we decide we need to be able to query where in
// the generated source a peice of the original code came from, we may want to
// add a slot `_originalMappings` which would be an object keyed by the
// original source and whose value would be an array of mappings ordered by
// original line/col rather than generated (which is what we have now in
// `_generatedMappings`).
/**
* A SourceMapConsumer instance represents a parsed source map which we can
* query for information about the original file positions by giving it a file
* position in the generated source.
*
* The only parameter is the raw source map (either as a JSON string, or
* already parsed to an object). According to the spec, source maps have the
* following attributes:
*
* - version: Which version of the source map spec this map is following.
* - sources: An array of URLs to the original source files.
* - names: An array of identifiers which can be referrenced by individual mappings.
* - sourceRoot: Optional. The URL root from which all sources are relative.
* - mappings: A string of base64 VLQs which contain the actual mappings.
* - file: The generated file this source map is associated with.
*/
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap);
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
var names = util.getArg(sourceMap, 'names');
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file');
if (version !== this._version) {
throw new Error('Unsupported version: ' + version);
}
this._names = ArraySet.fromArray(names);
this._sources = ArraySet.fromArray(sources);
this._generatedMappings = [];
this._parseMappings(mappings, sourceRoot);
}
/**
* The version of the source mapping spec that we are consuming.
*/
SourceMapConsumer.prototype._version = 3;
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (an ordered list in this._generatedMappings).
*/
SourceMapConsumer.prototype._parseMappings =
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var mappingSeparator = /^[,;]/;
var str = aStr;
var mapping;
var temp;
while (str.length > 0) {
if (str.charAt(0) === ';') {
generatedLine++;
str = str.slice(1);
previousGeneratedColumn = 0;
}
else if (str.charAt(0) === ',') {
str = str.slice(1);
}
else {
mapping = {};
mapping.generatedLine = generatedLine;
// Generated column.
temp = base64VLQ.decode(str);
mapping.generatedColumn = previousGeneratedColumn + temp.value;
previousGeneratedColumn = mapping.generatedColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original source.
temp = base64VLQ.decode(str);
if (aSourceRoot) {
mapping.source = util.join(aSourceRoot, this._sources.at(previousSource + temp.value));
}
else {
mapping.source = this._sources.at(previousSource + temp.value);
}
previousSource += temp.value;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source, but no line and column');
}
// Original line.
temp = base64VLQ.decode(str);
mapping.originalLine = previousOriginalLine + temp.value;
previousOriginalLine = mapping.originalLine;
// Lines are stored 0-based
mapping.originalLine += 1;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source and line, but no column');
}
// Original column.
temp = base64VLQ.decode(str);
mapping.originalColumn = previousOriginalColumn + temp.value;
previousOriginalColumn = mapping.originalColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original name.
temp = base64VLQ.decode(str);
mapping.name = this._names.at(previousName + temp.value);
previousName += temp.value;
str = temp.rest;
}
}
this._generatedMappings.push(mapping);
}
}
};
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
SourceMapConsumer.prototype.originalPositionFor =
function SourceMapConsumer_originalPositionFor(aArgs) {
// To return the original position, we must first find the mapping for the
// given generated position and then return the original position it
// points to. Because the mappings are sorted by generated line/column, we
// can use binary search to find the best mapping.
// To perform a binary search on the mappings, we must be able to compare
// two mappings.
function compare(mappingA, mappingB) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
return cmp === 0
? mappingA.generatedColumn - mappingB.generatedColumn
: cmp;
}
// This is the mock of the mapping we are looking for: the needle in the
// haystack of mappings.
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
if (needle.generatedLine <= 0) {
throw new TypeError('Line must be greater than or equal to 1.');
}
if (needle.generatedColumn < 0) {
throw new TypeError('Column must be greater than or equal to 0.');
}
var mapping = binarySearch.search(needle, this._generatedMappings, compare);
if (mapping) {
return {
source: util.getArg(mapping, 'source', null),
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: util.getArg(mapping, 'name', null)
};
}
return {
source: null,
line: null,
column: null,
name: null
};
};
exports.SourceMapConsumer = SourceMapConsumer;
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
define('lib/source-map/binary-search', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the next
// closest element that is less than that element.
//
// 3. We did not find the exact element, and there is no next-closest
// element which is less than the one we are searching for, so we
// return null.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid]);
if (cmp === 0) {
// Found the element we are looking for.
return aHaystack[mid];
}
else if (cmp > 0) {
// aHaystack[mid] is greater than our needle.
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
}
// We did not find an exact match, return the next closest one
// (termination case 2).
return aHaystack[mid];
}
else {
// aHaystack[mid] is less than our needle.
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (2) or (3) and return the appropriate thing.
return aLow < 0
? null
: aHaystack[aLow];
}
}
/**
* This is an implementation of binary search which will always try and return
* the next lowest value checked if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
*/
exports.search = function search(aNeedle, aHaystack, aCompare) {
return aHaystack.length > 0
? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
: null;
};
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
define('lib/source-map/source-node', ['require', 'exports', 'module' , 'lib/source-map/source-map-generator'], function(require, exports, module) {
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
*/
function SourceNode(aLine, aColumn, aSource, aChunks) {
this.children = [];
this.line = aLine;
this.column = aColumn;
this.source = aSource;
if (aChunks != null) this.add(aChunks);
}
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
this.children.push(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
this.children.forEach(function (chunk) {
if (chunk instanceof SourceNode) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source, line: this.line, column: this.column });
}
}
}, this);
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild instanceof SourceNode) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.lenth - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source != null
&& original.line != null
&& original.column != null) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
}
});
}
chunk.split('').forEach(function (char) {
if (char === '\n') {
generated.line++;
generated.column = 0;
} else {
generated.column++;
}
});
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;
});
/* -*- Mode: js; js-indent-level: 2; -*- */
///////////////////////////////////////////////////////////////////////////////
window.sourceMap = {
SourceMapConsumer: require('lib/source-map/source-map-consumer').SourceMapConsumer,
SourceMapGenerator: require('lib/source-map/source-map-generator').SourceMapGenerator,
SourceNode: require('lib/source-map/source-node').SourceNode
};
<file_sep>/*EXPECTED
C#constructor
M#constructor
*/
class C {
function constructor() {
log "C#constructor";
}
}
interface I {
}
mixin M {
function constructor() {
log "M#constructor";
}
}
class _Main extends C implements I, M {
static function main(args : string[]) : void {
new _Main();
}
}
<file_sep>import "timer.jsx";
class _Main {
static function main(args : string[]) : void {
var i = 0;
var id : Nullable.<TimerHandle> = null;
id = Timer.setInterval(function() : void {
log ++i;
if(i == 4) {
Timer.clearInterval(id);
}
}, 500);
}
}
<file_sep>/*EXPECTED
1,2,red
3,4,black
*/
class Point {
var _x : number;
var _y : number;
function constructor(x : number, y : number) {
this._x = x;
this._y = y;
}
override function toString() : string {
return this._x.toString() + "," + this._y.toString();
}
}
class Pixel extends Point {
var _color : string;
function constructor(x : number, y : number, color : string) {
super(x, y); // call-by-keyword
this._color = color;
}
function constructor(x : number, y : number) {
Point(x, y); // call-by-name
this._color = "black";
}
override function toString() : string {
return super.toString() + "," + this._color;
}
}
class _Main {
static function main(args : string[]) : void {
var p = new Pixel(1, 2, "red");
log p.toString();
p = new Pixel(3, 4);
log p.toString();
}
}
<file_sep>// https://github.com/jsx/JSX/issues/50
/*EXPECTED
ok
*/
class _Main {
static function takeArray(args : string[]) : void { }
static function main(args : string[]) : void {
_Main.takeArray([]);
log "ok";
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>class Test {
static function run() : void {
var a = [] : Array.<MayBeUndefined.<number>>;
}
}
<file_sep>/*EXPECTED
42
*/
class _Main {
static function takeInt(i : int) : void {
log i;
}
static function main(args : string[]) : void {
_Main.takeInt(42.5);
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>/*EXPECTED
number
string
*/
class Test {
static function f(n : number) : void {
log "number";
}
static function f(s : string) : void {
log "string";
}
static function g(f : function () : string) : void {
f("");
}
static function run() : void {
Test.g(Test.f);
}
}
<file_sep>// the origina AOBench
// http://code.google.com/p/aobench/
"use strict";
var NSUBSAMPLES = 2
var NAO_SAMPLES = 8
function vec(x, y, z)
{
this.x = x;
this.y = y;
this.z = z;
}
function vadd(a, b)
{
return new vec(a.x + b.x, a.y + b.y, a.z + b.z);
}
function vsub(a, b)
{
return new vec(a.x - b.x, a.y - b.y, a.z - b.z);
}
function vcross(a, b)
{
return new vec(a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x);
}
function vdot(a, b)
{
return (a.x * b.x + a.y * b.y + a.z * b.z);
}
function vlength(a)
{
return Math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z);
}
function vnormalize(a)
{
var len = vlength(a);
var v = new vec(a.x, a.y, a.z);
if (Math.abs(len) > 1.0e-17) {
v.x /= len;
v.y /= len;
v.z /= len;
}
return v;
}
function Sphere(center, radius)
{
this.center = center;
this.radius = radius;
this.intersect = function (ray, isect) {
// rs = ray.org - sphere.center
var rs = vsub(ray.org, this.center);
var B = vdot(rs, ray.dir);
var C = vdot(rs, rs) - (this.radius * this.radius);
var D = B * B - C;
if (D > 0.0) {
var t = -B - Math.sqrt(D);
if ( (t > 0.0) && (t < isect.t) ) {
isect.t = t;
isect.hit = true;
isect.p = new vec(ray.org.x + ray.dir.x * t,
ray.org.y + ray.dir.y * t,
ray.org.z + ray.dir.z * t);
// calculate normal.
var n = vsub(isect.p, this.center);
isect.n = vnormalize(n);
}
}
}
}
function Plane(p, n)
{
this.p = p;
this.n = n;
this.intersect = function (ray, isect) {
var d = -vdot(this.p, this.n);
var v = vdot(ray.dir, this.n);
if (Math.abs(v) < 1.0e-17) return; // no hit
var t = -(vdot(ray.org, n) + d) / v;
if ( (t > 0.0) && (t < isect.t) ) {
isect.hit = true;
isect.t = t;
isect.n = this.n;
isect.p = new vec( ray.org.x + t * ray.dir.x,
ray.org.y + t * ray.dir.y,
ray.org.z + t * ray.dir.z );
}
}
}
function Ray(org, dir)
{
this.org = org;
this.dir = dir;
}
function Isect()
{
this.t = 1000000.0; // far away
this.hit = false;
this.p = new vec(0.0, 0.0, 0.0)
this.n = new vec(0.0, 0.0, 0.0)
}
function clamp(f)
{
var i = f * 255.5;
if (i > 255.0) i = 255.0;
if (i < 0.0) i = 0.0;
return Math.round(i)
}
function orthoBasis(basis, n)
{
basis[2] = new vec(n.x, n.y, n.z)
basis[1] = new vec(0.0, 0.0, 0.0)
if ((n.x < 0.6) && (n.x > -0.6)) {
basis[1].x = 1.0;
} else if ((n.y < 0.6) && (n.y > -0.6)) {
basis[1].y = 1.0;
} else if ((n.z < 0.6) && (n.z > -0.6)) {
basis[1].z = 1.0;
} else {
basis[1].x = 1.0;
}
basis[0] = vcross(basis[1], basis[2]);
basis[0] = vnormalize(basis[0]);
basis[1] = vcross(basis[2], basis[0]);
basis[1] = vnormalize(basis[1]);
}
var spheres;
var plane;
function init_scene()
{
spheres = new Array(3);
spheres[0] = new Sphere(new vec(-2.0, 0.0, -3.5), 0.5);
spheres[1] = new Sphere(new vec(-0.5, 0.0, -3.0), 0.5);
spheres[2] = new Sphere(new vec(1.0, 0.0, -2.2), 0.5);
plane = new Plane(new vec(0.0, -0.5, 0.0), new vec(0.0, 1.0, 0.0));
}
function ambient_occlusion(isect)
{
var basis = new Array(3);
orthoBasis(basis, isect.n);
var ntheta = NAO_SAMPLES;
var nphi = NAO_SAMPLES;
var eps = 0.0001;
var occlusion = 0.0;
var p = new vec(isect.p.x + eps * isect.n.x,
isect.p.y + eps * isect.n.y,
isect.p.z + eps * isect.n.z);
for (var j = 0; j < nphi; j++) {
for (var i = 0; i < ntheta; i++) {
var r = Math.random();
var phi = 2.0 * Math.PI * Math.random();
var x = Math.cos(phi) * Math.sqrt(1.0 - r);
var y = Math.sin(phi) * Math.sqrt(1.0 - r);
var z = Math.sqrt(r);
// local -> global
var rx = x * basis[0].x + y * basis[1].x + z * basis[2].x;
var ry = x * basis[0].y + y * basis[1].y + z * basis[2].y;
var rz = x * basis[0].z + y * basis[1].z + z * basis[2].z;
var raydir = new vec(rx, ry, rz);
var ray = new Ray(p, raydir);
var occIsect = new Isect();
spheres[0].intersect(ray, occIsect);
spheres[1].intersect(ray, occIsect);
spheres[2].intersect(ray, occIsect);
plane.intersect(ray, occIsect);
if (occIsect.hit) occlusion += 1.0;
}
}
// [0.0, 1.0]
occlusion = (ntheta * nphi - occlusion) / (ntheta * nphi);
return new vec(occlusion, occlusion, occlusion);
}
function render(fill, w, h, nsubsamples)
{
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var rad = new vec(0.0, 0.0, 0.0);
// subsampling
for (var v = 0; v < nsubsamples; v++) {
for (var u = 0; u < nsubsamples; u++) {
var px = (x + (u / nsubsamples) - (w / 2.0))/(w / 2.0);
var py = -(y + (v / nsubsamples) - (h / 2.0))/(h / 2.0);
var eye = vnormalize(new vec(px, py, -1.0));
var ray = new Ray(new vec(0.0, 0.0, 0.0), eye);
var isect = new Isect();
spheres[0].intersect(ray, isect);
spheres[1].intersect(ray, isect);
spheres[2].intersect(ray, isect);
plane.intersect(ray, isect);
if (isect.hit) {
var col = ambient_occlusion(isect);
rad.x += col.x;
rad.y += col.y;
rad.z += col.z;
}
}
}
var r = clamp(rad.x / (nsubsamples * nsubsamples));
var g = clamp(rad.y / (nsubsamples * nsubsamples));
var b = clamp(rad.z / (nsubsamples * nsubsamples));
// use fill rect
fill(x, y, r, g, b);
}
}
}
if (typeof window !== "undefined") {
window.onload = function aobench_start()
{
var canvas = document.getElementById("world");
var ctx = canvas.getContext("2d");
var start = Date.now();
init_scene();
render(function (x, y, r, g, b) {
ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
ctx.fillRect (x, y, 1, 1);
}, canvas.width, canvas.height, 1)
var elapsed = Date.now() - start;
document.getElementById("status").innerHTML = "Time = " + elapsed + "[ms]";
//img = ctx.getImageData(10, 10, 50, 50)
//document.write(img.data[41]);
//ret = ctx.putImagedata(img, 10, 10);
//print(ret);
}
}
else {
exports.render = render;
}
<file_sep>/*EXPECTED
11
22
*/
class Point {
var x : number;
var y : number;
function constructor(x : number, y : number) {
this.x = x;
this.y = y;
this.y = y; // twice
}
}
class _Main {
static function main(args : string[]) : void {
var p = new Point(5 + 5, 10 + 10);
p.x += 1;
p.y += 2;
log p.x;
log p.y;
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>/*EXPECTED
Hello
JSX
World
*/
/*JSX_OPTS
--optimize dce
*/
class _Main {
static function main(args : string[]) : void {
if (true) {
log 'Hello';
log 'JSX';
}
if (false) {
log 'blah blah';
log 'blah blah';
}
if (false) {
log 'JSX';
} else {
log 'World';
}
}
}
<file_sep>import "import-twice/foo.jsx";
import "import-twice/foo.jsx";
<file_sep>/*EXPECTED
123
*/
/*JS_SETUP
function Native() {
this._ = 123;
}
*/
native class Native {
var _ : number;
}
class Derived extends Native {
var foo = "abc";
}
class _Main {
static function main(args : string[]) : void {
var d = new Derived;
log d._;
}
}
<file_sep>class Test {
static function run() : void {
var a = [ 1, 2 ];
delete a[0];
}
}
<file_sep>/*EXPECTED
foo
bar
*/
/*JSX_OPTS
--optimize inline
*/
final class _Main {
static inline function f(s : string) : void {
var x = s;
log x;
if (!x) _Main.f(x);
}
static function main(args : string[]) : void {
_Main.f("foo");
_Main.f("bar");
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>mixin M {
abstract var n : number;
}
class T implements M {
// must have n defined
}
<file_sep>// usage: jsx --complete 15:7 complete/example.jsx
import "js/web.jsx";
/**
* The application main class.
*/
class _Main {
/**
* The application entry point.
* @param args arguments of process
*/
static function main(args : string[]) :void {
log "Hello, world!";
dom.
}
}
<file_sep>/*EXPECTED
-1
-2
-1
*/
class _Main {
static function main(args : string[]) : void {
var x : int = ~ 0; // return type is number
log ~ 0;
log ~ 1.5;
log ~ ([] : number[]).pop(); // test op against maybeundefined<number>
}
}
<file_sep>class _Main {
static function main(args : string[]) : void {
switch (1) {
case 1: log "a"; break;
case 2: log "b"; break;
case 1: log "c"; break;
}
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>class C {
}
interface II {
}
interface JJ {
}
class B implements I
/*EXPECTED
[
{
"word" : "II",
"partialWord" : "I"
}
]
*/
/*JSX_OPTS
--complete 7:21
*/
<file_sep>/*EXPECTED
for
while
do-while
*/
class _Main {
static function main(args : string[]) : void {
for (var i = 1; i; i = 0)
log "for";
i = 1;
while (i--)
log "while";
i = 0;
do
log "do-while";
while (i);
}
}
<file_sep>/*EXPECTED
1
2
3
4
*/
class _Main {
static function main (args : string[]) : void {
function foo () : Enumerable.<number> {
yield 1;
function bar () : Enumerable.<number> {
yield 2;
yield 3;
}
var b = bar();
yield b.next();
yield b.next();
yield 4;
}
var f = foo();
log f.next();
log f.next();
log f.next();
log f.next();
}
}<file_sep>/*EXPECTED
0
9800000000000
*/
/*JSX_OPTS
--optimize inline
*/
/*BENCHMARK
2
*/
final class _Main {
var n = 0;
function add(value : number) : void {
this.n += value;
}
static function loop(cnt : number) : void {
var that = new _Main;
log that.n;
for (var i = 0; i < 2000; ++i) {
for (var j = 0; j < cnt; ++j) {
that.add(j);
that.add(-i);
}
}
log that.n;
}
static function main(args : string[]) : void {
_Main.loop(("100" + "000") as number);
}
}
<file_sep>/*EXPECTED
f
g1
*/
class _Main {
static function f(x : number[]) : void {
log "f";
}
static function g(x : number, y : number[]) : void {
log "g1";
}
static function g(x : number, y : number) : void {
log "g2";
}
static function main(args : string[]) : void {
_Main.f([]);
_Main.g(0, []);
}
}<file_sep>#!/usr/bin/env node
"use strict";
var path = require('path');
function indent(level) {
var s = ""
for (var i = 0; i < level; ++i) {
s += " ";
}
return s;
}
process.argv.slice(2).forEach(function (file) {
var module = require(file);
var s = "";
s += "/***\n";
s += " * JSX interface to '" + file +"' module\n";
s += " */\n";
s += "\n";
s += "native class " + path.basename(file, ".js") + " {\n";
s += " delete function constructor();\n\n";
(function dumpModule(module, prefix, level) {
for (var name in module) {
if (/^_/.test(name) || /_$/.test(name)) {
return;
}
if (/^[A-Z]/.test(name) && typeof module[name] === "function") {
// class constructor
s += "\n";
s += indent(level) + "native class " + name + " {\n\n";
dumpModule(module[name], "static ", level + 1);
dumpModule(module[name].prototype, "", level + 1);
s += "\n";
s += indent(level) + "}\n\n";
}
else if (typeof module[name] == "function") {
// class method
var matched = module[name].toString().match(/function(?: \w*)\s*\(([^\)]*)\)/);
var args = (matched != null ? matched[1] : "");
if (!args && module[name].length != 0) {
var a = [];
for (var i = 0; i < module[name].length; ++i) {
a.push("arg" + i);
}
args = a.join(", ");
}
s += indent(level) + prefix + "function " + name + "(" + args + ") : void;\n";
}
else {
s += indent(level) + "// value = " + JSON.stringify(module[name]) + "\n";
s += indent(level) + prefix + "var " + name + " : " + typeof(module[name]) + ";\n";
}
}
}(module, "static ", 1));
s += "\n";
s += "} = \"require('" + file + "')\";\n\n";
s += "// vim: set tabstop=2 shiftwidth=2 expandtab:\n";
console.log(s);
});
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>class Test {
static function run() : void {
true + 1;
}
}
<file_sep>/*EXPECTED
4
abcdef
*/
class Adder.<T> {
var result : T;
function constructor(x : T, y : T) {
var r = x + y;
this.result = r;
}
}
class _Main {
static function main(args : string[]) : void {
var f = new Adder.<number>(1, 3);
log f.result;
var g = new Adder.<string>("abc", "def");
log g.result;
}
}
<file_sep>/***
* Simple JavaScript lexer (not completely ECMA-262 compatible, but good enough now)
*/
class JSToken {
var type : string;
var token : string;
var column : number;
var line : number;
var id : number;
function constructor(type : string, token : string, column : number, line : number, id : number) {
this.type = type;
this.token = token;
this.column = column;
this.line = line;
this.id = id;
}
}
class JSLexer {
static var DEBUG = false;
static function makeAlt(patterns : string[]) : string {
return "(?: \n" + patterns.join("\n | \n") + "\n)\n";
}
static function quoteMeta(pattern : string) : string {
return pattern.replace(/([^0-9A-Za-z_])/g, '\\$1');
}
static function rx(pat : string) : RegExp {
return new RegExp(pat.replace(/[ \t\r\n]/g, ""));
}
static function rx(pat : string, flags : string) : RegExp {
return new RegExp(pat.replace(/[ \t\r\n]/g, ""), flags);
}
static var ident = " [\\$a-zA-Z_] [\\$a-zA-Z0-9_]* ";
static var doubleQuoted = ' " [^"\\n\\\\]* (?: \\\\. [^"\\n\\\\]* )* " ';
static var singleQuoted = JSLexer.doubleQuoted.replace(/"/g, "'");
static var stringLiteral = JSLexer.makeAlt([JSLexer.singleQuoted, JSLexer.doubleQuoted]);
static var regexpLiteral = JSLexer.doubleQuoted.replace(/"/g, "/") + "[mgi]*";
static var decimalIntegerLiteral = "(?: 0 | [1-9][0-9]* )";
static var exponentPart = "(?: [eE] [+-]? [0-9]+ )";
static var numberLiteral = JSLexer.makeAlt([
"(?: " + JSLexer.decimalIntegerLiteral + " \\. " +
"[0-9]* " + JSLexer.exponentPart + "? )",
"(?: \\. [0-9]+ " + JSLexer.exponentPart + "? )",
"(?: " + JSLexer.decimalIntegerLiteral + JSLexer.exponentPart + " )"
]) + "\\b";
static var integerLiteral = JSLexer.makeAlt([
"(?: 0 [xX] [0-9a-fA-F]+ )", // hex
JSLexer.decimalIntegerLiteral
]) + "(?![\\.0-9eE])\\b";
static var multiLineComment = "(?: /\\* (?: [^*] | (?: \\*+ [^*\\/]) )* \\*+/)";
static var singleLineComment = "(?: // [^\\r\\n]* )";
static var comment = JSLexer.makeAlt([JSLexer.multiLineComment, JSLexer.singleLineComment]);
static var whiteSpace = "[\\x20\\t\\r\\n]+";
static var keywords = [
"null", "true", "false",
"break", "do", "instanceof", "typeof",
"case", "else", "new", "var",
"catch", "finally", "return", "void",
"continue", "for", "switch", "while",
"function", "this",
"default", "if", "throw",
"delete", "in", "try",
"class", "extends", "super",
"import", "implements",
"debugger", "with",
"const", "export",
"let", "private", "public", "yield",
"protected"
];
static var rxSpace = JSLexer.rx("^" + JSLexer.makeAlt([JSLexer.comment, JSLexer.whiteSpace]) + "+");
static var rxIdent = JSLexer.rx("^" + JSLexer.ident);
static var rxStringLiteral = JSLexer.rx("^" + JSLexer.stringLiteral);
static var rxNumberLiteral = JSLexer.rx("^" + JSLexer.makeAlt([JSLexer.numberLiteral, JSLexer.integerLiteral]) + "\\b");
static var rxRegExpLiteral = JSLexer.rx("^" + JSLexer.regexpLiteral);
static var rxKeyword = JSLexer.rx("^" + JSLexer.makeAlt(JSLexer.keywords.map.<string>(function (s) { return JSLexer.quoteMeta(s); })) + "\\b");
static var endOfPrimaryExpr = {
"null": true,
"false": true,
"true": true,
")": true,
"]": true
};
static function lastIsPrimaryExpr(tokens : JSToken[]) : boolean {
var i = tokens.length - 1;
while(i >= 0 && tokens[i].type == "space") {
--i;
}
if(tokens[i].token in JSLexer.endOfPrimaryExpr) {
return true;
}
var t = tokens[i].type;
return t == "identifier" ||
t == "string" ||
t == "regexp" ||
t == "number";
}
static function tokenize(fileName : string, src : string) : JSToken[] {
var tokens = new JSToken[];
var line = 1;
var col = 0;
var id = 0;
while( src.length > 0 ) {
var matched;
var type;
if( (matched = src.match(JSLexer.rxSpace)) != null ) {
type = "space";
}
else if( src.charAt(0) == "/" ) {
if( JSLexer.lastIsPrimaryExpr(tokens) ) {
matched = src.match(/^./);
type = "keyword";
}
else if( (matched = src.match(JSLexer.rxRegExpLiteral)) != null ) {
type = "regexp";
}
else {
throw new SyntaxError("jslexer: ["+fileName+":"+line as string+":"+col as string+"] "+
"Unexpected character '" +
src.charAt(0) + "'");
}
}
else if( (matched = src.match(JSLexer.rxKeyword)) != null ) {
type = "keyword";
}
else if( (matched = src.match(JSLexer.rxIdent)) != null ) {
type = "identifier";
}
else if( (matched = src.match(JSLexer.rxStringLiteral)) != null ) {
type = "string";
}
else if( (matched = src.match(JSLexer.rxNumberLiteral)) != null ) {
type = "number";
}
else if( (matched = src.match(/^./)) != null ) {
type = "keyword";
}
else {
throw new SyntaxError("jslexer: ["+fileName+":"+line as string+":"+col as string+"] "+
"Unexpected character '" +
src.charAt(0) + "'");
}
var token = matched[0];
if (JSLexer.DEBUG) {
log matched;
}
src = src.slice(token.length);
tokens.push(new JSToken(type, token, col, line, ++id));
if(token.match(/\n/)) {
var lines = token.split(/\n/);
line += lines.length - 1;
col = lines[lines.length - 1].length;
}
else {
col += matched[0].length;
}
}
return tokens;
}
}
<file_sep>/*EXPECTED
B
A
*/
import "061.import-paths/a/a.jsx";
import "061.import-paths/b/b.jsx";
class _Main {
static function main(args : string[]) : void {
A.callB();
B.callA();
}
}
<file_sep>/*EXPECTED
true
*/
class _Main {
static function main(args : string[]) : void {
var m = { 'a' : 1 };
log ! ('b' in m);
}
}
<file_sep>/*EXPECTED
hello
*/
class _Main {
static function f() : number {
log "hello";
return 0;
}
static function main(args : string[]) : void {
void _Main.f();
}
}
<file_sep>/*EXPECTED
false
true
true
true
false
0
1
1
1
1
0
0
1
1
1.5
1.5
NaN
f,a,l,s,e
t,r,u,e
1,.,5
a,b,c
*/
class _Main {
static function main(args : string[]) : void {
log false as boolean;
log true as boolean;
log 1.5 as boolean;
log "a" as boolean;
log "" as boolean;
log "";
log false as int;
log true as int;
log 1 as int;
log 1.5 as int;
log "1.5" as int;
log "aaa" as int;
log "";
log false as number;
log true as number;
log 1 as number;
log 1.5 as number;
log "1.5" as number;
log "aaa" as number;
log "";
log (false as string).split("").join(",");
log (true as string).split("").join(",");
log (1.5 as string).split("").join(",");
log ("abc" as string).split("").join(",");
}
}
<file_sep>/*EXPECTED
1
1
2
3
5
8
13
*/
class _Main {
static function fib(n : number) : number {
if (n <= 2)
return 1;
var value = 1;
var prevValue = 1;
for (var i = 3; i <= n; i++) {
var t = value + prevValue;
prevValue = value;
value = t;
}
return value;
}
static function main(args : string[]) : void {
log _Main.fib(1);
log _Main.fib(2);
log _Main.fib(3);
log _Main.fib(4);
log _Main.fib(5);
log _Main.fib(6);
log _Main.fib(7);
}
}
<file_sep>/*JSX_OPTS
--minify
*/
/*EXPECTED
function
undefined
undefined
function
number
undefined
undefined
number
function
undefined
undefined
function
number
undefined
undefined
number
*/
import "js.jsx";
__export__ class C {
function mf() : void {
}
__noexport__ function mf2() : void {
}
function _mf() : void {
}
__export__ function _mf2() : void {
}
var mv = 123;
__noexport__ var mv2 = "not accessible";
var _mv = "not accessible";
__export__ var _mv2 = 456;
static function sf() : void {
}
__noexport__ function sf2() : void {
}
static function _sf() : void {
}
__export__ static function _sf2() : void {
}
static var sv = 123;
__noexport__ static var sv2 = "not accessible";
static var _sv = "not accessible";
__export__ static var _sv2 = 123;
}
class _Main {
static function main(args : string[]) : void {
var o = js.eval("new (JSX.require('t/run/261.export-rule.jsx').C)");
log typeof o["mf"];
log typeof o["mf2"];
log typeof o["_mf"];
log typeof o["_mf2"];
log typeof o["mv"];
log typeof o["mv2"];
log typeof o["_mv"];
log typeof o["_mv2"];
var c = js.eval("JSX.require('t/run/261.export-rule.jsx').C");
log typeof c["sf"];
log typeof c["sf2"];
log typeof c["_sf"];
log typeof c["_sf2"];
log typeof c["sv"];
log typeof c["sv2"];
log typeof c["_sv"];
log typeof c["_sv2"];
}
}
<file_sep>/*EXPECTED
Hi!
hello
string:all your base are belongs to us
in finally
finally after rethrow
from the deepness
*/
class MyError1 extends Error {
function constructor(message : string) {
super(message);
}
}
class MyError2 extends MyError1 {
function constructor() {
super("MyError2");
}
}
class _Main {
static function main(args : string[]) : void {
// simple
try {
throw new Error();
} catch (e: Error) {
log e.message;
}
try {
throw new Error("Hi!");
} catch (e : Error) {
log e.message;
}
// should catch MyError1
try {
throw new MyError1("hello");
} catch (e : MyError2) {
log "unreachable:MyError2";
} catch (e : MyError1) {
log e.message; // hello
} catch (e : Error) {
log "unreachable:Error";
} catch (e : variant) {
log "unreachable:variant";
}
// variant only
try {
throw "all your base are belongs to us";
} catch (e : variant) {
log typeof e + ":" + e as string;
}
// try-finally
var a;
try {
} finally {
a = "in finally";
}
log a;
// rethrow
try {
try {
throw new Error("from the deepness");
} catch (e : Error) {
throw e;
} finally {
log "finally after rethrow";
}
} catch (e : Error) {
log e.message;
}
}
}
<file_sep>/*EXPECTED
undefined
*/
class _Main {
static function main(args : string[]) : void {
var a = new Map.<number>();
log a["a"];
for (var k in a) {
log "never reached";
}
}
}
<file_sep>/*EXPECTED
3
1
4
a
b
3
1
4
3
1
4
*/
class _Main {
static function main(args : string[]) : void {
var a = [ 3, 1, 4 ];
log a[0];
log a[1];
log a[2];
var b = [ "a", "b" ];
log b[0];
log b[1];
var c = [ 3, 1, 4 ] : number[];
log c[0];
log c[1];
log c[2];
var d = [ 3, 1, 4 ] : Array.<number>;
log d[0];
log d[1];
log d[2];
}
}
<file_sep>/*EXPECTED
42
*/
native class Foo {
static const bar : number;
} = "{ bar: 42 }";
class _Main {
static function main (args : string[]) : void {
log Foo.bar;
}
}
<file_sep>/*EXPECTED
abc
*/
/*JSX_OPTS
--optimize lto,inline
*/
class _Main {
var s = "ab";
function f() : string {
return this.s + "c";
}
static var s : _Main;
static function main(args : string[]) : void {
_Main.s = new _Main();
var s = _Main.s.f();
log s;
}
}
<file_sep>/*EXPECTED
number
string
*/
class _Main {
static function f(f : function() : number) : void {
log 'number';
}
static function f(f : function() : string) : void {
log 'string';
}
static function main(args : string[]) : void {
_Main.f(function() : number { return 0; });
_Main.f(function() : string { return 's'; });
}
}
<file_sep>/*EXPECTED
0
*/
class Outer.<T> {
var m1 : T;
class Inner.<U> {
var m2 : T;
var m3 : U;
}
}
class _Main {
static function main(args : string[]) : void {
var outer = new Outer.<number>;
var inner = new Outer.<number>.Inner.<string>; // Outer.<number> has already been instantiated
log inner.m2;
log inner.m3;
}
}<file_sep>/*EXPECTED
*/
class F {
static function f(n : number) : void {
}
static function f(v : number) : void {
}
}
<file_sep>/*EXPECTED
true
true
true
true
true
false
false
false
1.5
false
3
false
abc
*/
class _Main {
static function main(args : string[]) : void {
var a : variant = null;
log (a as __noconvert__ Nullable.<boolean>) == null;
log (a as __noconvert__ Nullable.<number>) == null;
log (a as __noconvert__ Nullable.<int>) == null;
log (a as __noconvert__ Nullable.<string>) == null;
a = false;
log (a as __noconvert__ Nullable.<boolean>) == false;
log (a as __noconvert__ Nullable.<boolean>) == null;
log (a as __noconvert__ Nullable.<boolean>) == true;
a = 1.5;
log (a as __noconvert__ Nullable.<number>) == null;
var n : number = a as __noconvert__ Nullable.<number>;
log n;
a = 3;
log (a as __noconvert__ Nullable.<int>) == null;
var i : int = a as __noconvert__ Nullable.<int>;
log i;
a = "abc";
log (a as __noconvert__ Nullable.<string>) == null;
var s : string = a as __noconvert__ Nullable.<string>;
log s;
}
}
<file_sep>class T {
function constructor() {
this.constructor(1);
}
function constructor(i : number) {
}
}
<file_sep>class T {
static function f(n : number) : number {
var ret;
switch (n) {
case 1:
ret = 1;
break;
case 2:
ret = 2;
break;
}
return ret;
}
}
<file_sep>/*EXPECTED
*/
/*JSX_OPTS
--optimize inline
*/
class _Main {
static function main(args : string[]) : void {
function f():void {
(function():void {
"foo".slice(0);
}());
}
}
}
<file_sep>class Test {
static function f() : void {
(function(elem : number) : void { log elem; })();
}
}
<file_sep>/*EXPECTED
hello
hell
hel
he
h
*/
class _Main {
static function main(args : string[]) : void {
var f = function (s : string) : void {
log s;
if (s.length != 0)
f(s.substring(0, s.length - 1));
};
f("hello");
}
}
<file_sep>/*EXPECTED
false
false
false
*/
class _Main {
static var sv = 0 && 0;
var mv = 0 && 0;
static function main(args : string[]) : void {
var l = 0 && 0;
log l;
log _Main.sv;
log (new _Main).mv;
}
}
<file_sep>import "js/nodejs.jsx";
import "console.jsx";
class _Main {
static function main(args : string[]) : void {
var p = node.require(process.cwd() + "/package.json");
var tag = "v" + p["version"] as string;
var dry_run = (args.length > 0 && args[0] == "--dry-run");
var tasks = [
["git", "tag", tag],
["git", "push", "origin", tag],
["git", "push", "origin", "master"]
];
if (dry_run) {
tasks.forEach((item) -> {
item.unshift("echo");
});
}
function runNext(tasks : string[][]) : void {
if (tasks.length) {
var task = tasks.shift().slice(0);
console.log("> " + task.join(" "));
var cmd = task.shift();
var args = task;
node.child_process.execFile(cmd, args, (err, stdout, stderr) -> {
if (err) {
console.error(err.toString());
process.exit(0);
}
if(stdout) {
process.stdout.write(stdout);
}
if (stderr) {
process.stderr.write(stderr);
}
runNext(tasks);
});
}
}
runNext(tasks);
}
}
// vim: set expandtab:
<file_sep>class A {
var m : () -> void;
}
class B extends A {
function foo () : void {
super.m();
}
}
<file_sep>class Test {
static function run() : void {
var a = 1;
delete a;
}
}
<file_sep>/*EXPECTED
*/
class Base {
}
interface Interface {
}
class _Main extends Base implements Interface {
function constructor() {
Base();
Interface();
}
static function main(args : string[]) : void {
new _Main();
}
}
<file_sep>/*EXPECTED
2
2
-1
4
0.5
*/
/*JSX_OPTS
--optimize fold-const
*/
class _Main {
static const ZERO = 0;
static const ONE = _Main.ZERO + 1;
static const TWO = _Main.ONE + 1;
static function main(args : string[]) : void {
log _Main.TWO;
log _Main.ONE + _Main.ONE;
log _Main.ONE - _Main.TWO;
log _Main.TWO * _Main.TWO;
log _Main.ONE / _Main.TWO;
}
}
<file_sep>/*EXPECTED
42
*/
class Base {
var x = 0;
}
class _Main extends Base {
static function main(args : string[]) : void {
var o : Nullable.<_Main> = new _Main;
o.x = 42;
log o.x;
}
}
<file_sep>/*EXPECTED
1
*/
class _Main {
static var n : int = 1.3;
static function main(args : string[]) : void {
log _Main.n;
}
}
<file_sep>/*EXPECTED
world
detected invalid cast, value is not a Map or null
_Main.say(_Main.ng() as __noconvert__ Map.<string>);
^^
*/
class _Main {
static function ok() : variant {
return { hello: "world" };
}
static function ng() : variant {
return "good bye";
}
static function say(h : Map.<string>) : void {
log h["hello"];
}
static function main(args : string[]) : void {
_Main.say(_Main.ok() as __noconvert__ Map.<string>);
_Main.say(_Main.ng() as __noconvert__ Map.<string>);
}
}
// vim: set expandtab:
<file_sep>/*EXPECTED
a
0
0
b
10
20
*/
/*JSX_OPTS
--optimize lto,inline,unclassify
*/
class Point {
var x : number;
var y : number;
function constructor(x : number = 0, y : number = 0) {
this.x = x;
this.y = y;
}
}
class _Main {
static function main(args : string[]) : void {
var p = new Point;
log "a";
log p.x;
log p.y;
p = new Point(10, 20);
log "b";
log p.x;
log p.y;
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>class Test {
function f() : void {
}
static function g() : void {
var f = new Test().f; // should generate compile error
}
}
<file_sep>
class C {
static const foo : string[] = ["foo", "bar"];
}
<file_sep>import "058.import-as-conflict-with-class/foo.jsx" into Foo;
class Foo {
}
<file_sep>class T {
function constructor(a1 : number, a2 : number) {
var a3;
a
/*EXPECTED
[
{
"word" : "assert",
"partialWord" : "ssert"
},
{
"word" : "a3",
"partialWord" : "3"
},
{
"word" : "a1",
"partialWord" : "1",
"type" : "number"
},
{
"word" : "a2",
"partialWord" : "2",
"type" : "number"
}
]
*/
/*JSX_OPTS
--complete 4:4
*/
<file_sep>/*EXPECTED
15
*/
/*JSX_OPTS
--optimize dce
*/
class _Main {
static function main(args : string[]) : void {
// should be converted into `log 1 + ((10 + 2) + 2`
var y = 10 + 2;
var z = 1 + (y + 2);
log z;
}
}
<file_sep>class Test {
static function run() : void {
var a = new Test();
var b : int = a;
}
}
<file_sep>/*EXPECTED
*/
class K {
/**
* @param a the parameter
*/
static function f(a : number = 0) : void {
}
}
class _Main {
static function main(args : string[]) : void {
K.f();
}
}
<file_sep>/*EXPECTED
foo
42
*/
class Hoge.<T> {
var a: T;
var b: Map.<string>;
function constructor(a: T, option: Map.<string> = {}) {
this.a = a;
this.b = option;
}
}
class _Main {
static function main(args: string[]) : void {
var fuga = new Hoge.<string>("foo");
log fuga.a;
var hoge = new Hoge.<number>(42);
log hoge.a;
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>/*EXPECTED
1
2
*/
class _Main {
static function main(args : string[]) : void {
var x;
var t = true;
t ? x = 1 : x = 2;
log x;
!t ? x = 1 : x = 2;
log x;
}
}
// vim: set expandtab tabstop=2:
<file_sep>// https://github.com/jsx/JSX/issues/99
/*EXPECTED
ok
*/
/*///
Here is commented out.
///*/
class _Main {
static function main(args : string[]) : void {
log "ok";
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>/*EXPECTED
1
*/
/*JSX_OPTS
--optimize fold-const
*/
class _Main {
static const i = 1;
static function main(args : string[]) : void {
log _Main.i;
}
}
<file_sep>class Test {
static function run() : void {
this.foo = 1;
}
}
<file_sep>/*EXPECTED
foo
bar
*/
class Foo {
class Inner {
static var C = "foo";
}
}
class Bar {
class Inner {
static var C = "bar";
}
}
class _Main {
static function main(args : string[]) : void {
log Foo.Inner.C;
log Bar.Inner.C;
}
}
<file_sep>/*EXPECTED
1
2
2
*/
class _Main {
static function a(x : number) : number {
log x;
return x;
}
static function main(args : string[]) : void {
log ("abc", _Main.a(1), _Main.a(2));
}
}
<file_sep>/*EXPECTED
null
*/
class _Main {
static function main(args : string[]) : void {
var a = new string[];
a.push(_Main.b());
log a[0];
}
static function b() : Nullable.<string> {
return null;
}
}
// vim: set expandtab:
<file_sep>/*EXPECTED
0
*/
// static vars must be initialized only once
class _Main {
static const value = Math.random();
static function main(args : string[]) : void {
var v0 = _Main.value;
var v1 = _Main.value;
log v0 - v1;
}
}
<file_sep>/*EXPECTED
true
*/
class _Main {
static function main(args : string[]) : void {
function foobar(i : number) : number {
return i + i;
}
var x = foobar;
log !!x;
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>// https://github.com/jsx/JSX/issues/88
/*EXPECTED
false
false
*/
class _Main {
static function main(args : string[]) : void {
log true == (1 != 1);
log true == (true == (1 != 1));
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>/*EXPECTED
mixin
base
mixin
*/
class Base {
function message() : string {
return "base";
}
}
mixin Mixin {
override function message() : string {
return "mixin";
}
}
class _Main extends Base implements Mixin {
static function main(args : string[]) : void {
var t = new _Main;
var m = t.message(); // "mixin"
log m;
var b = new Base;
m = b.message(); // "base"
log m;
b = t;
m = b.message(); // "mixin"
log m;
}
}
<file_sep>/*EXPECTED
42
*/
/*JSX_OPTS
--optimize fold-const,dce
*/
class _Main {
static const V : int = 42;
static function main (args : string[]) : void {
if (_Main.V as string) {
log _Main.V as string;
}
}
}
<file_sep>/*
This program is originated from http://nmi.jp/archives/386
Copyright (c) 2012, <NAME>. All rights reserved.
Image resources are copied from the following web site:
http://homepage2.nifty.com/hamcorossam/
Copyright (c) 2012, HamCorossam. All rights reserved.
*/
var Config = {
cols: 10,
rows: 15,
cellWidth : 32,
cellHeight: 32,
bulletWidth : 4,
bulletHeight: 4,
bulletSpeed: 20,
reloadCount: 3,
initialNumRocks: 5,
FPS: 30,
imagePath: "img"
};
Config.width = Config.cols * Config.cellWidth;
Config.height = Config.rows * Config.cellHeight;
var Class = function () { };
Class.extend = function (properties) {
var ctor = properties.constructor;
if (ctor === Object) {
var superCtor = this.prototype.constructor;
ctor = properties.constructor = function () {
superCtor.call(this);
};
}
function tmp() {}
tmp.prototype = this.prototype;
ctor.prototype = new tmp();
ctor.extend = Class.extend;
// assign properties
for (var k in properties) {
if (k.charAt(0) == '$') {
ctor[k.substring(1)] = properties[k];
} else {
ctor.prototype[k] = properties[k];
}
}
if (typeof ctor.constructor === "function") {
ctor.constructor();
}
return ctor;
};
Class.prototype.constructor = function () { };
var Sprite = Class.extend({
x : 0,
y : 0,
width : 0,
height : 0,
image : null,
detectCollision: function (other) {
return Math.abs(this.x - other.x) < (Config.cellWidth >> 1)
&& Math.abs(this.y - other.y) < (Config.cellHeight >> 1);
},
draw : function (context) {
context.drawImage(this.image,
this.x - (this.width >> 1),
this.y - (this.height >> 1));
}
});
var MovingObject = Sprite.extend({
x : 0,
y : 0,
dx : 0,
dy : 0,
image : null,
constructor : function (x, y, dx, dy, image) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.image = image;
},
update : function () {
this.x += this.dx;
this.y += this.dy;
return this._inDisplay();
},
_inDisplay : function () {
return !( this.x <= 0 || this.x >= Config.width
|| this.y <= 0 || this.y >= Config.height);
},
});
var Bullet = MovingObject.extend({
width : 0,
height : 0,
constructor : function (x, y, dx, dy, image) {
MovingObject.call(this, x, y, dx, dy, image);
},
update : function (st) {
var inDisplay = MovingObject.prototype.update.call(this);
this.draw(st.ctx);
for(var rockKey in st.rocks) {
var rock = st.rocks[rockKey];
if(this.detectCollision(rock)) {
if(rock.hp == 0) return false;
inDisplay = false;
if(--rock.hp == 0) {
st.score = Math.min(st.score + rock.score, 999999999);
st.updateScore();
rock.dx = rock.dy = 0;
rock.setState(st, "bomb1");
}
else {
var newState = (rock.state + "w").substring(0, 6);
rock.setState(st, newState);
}
}
}
return inDisplay;
}
});
var Rock = MovingObject.extend({
width : Config.cellWidth,
height : Config.cellHeight,
hp : 0,
score : 0,
state : "",
constructor : function (
x, y, dx, dy,
hp, score, state,
image
) {
MovingObject.call(this, x, y, dx, dy, image);
this.hp = hp;
this.score = score;
this.state = state;
},
update : function (st) {
var inDisplay = MovingObject.prototype.update.call(this);
this.draw(st.ctx);
if(this.hp == 0) {
var next = (this.state.substring(4) | 0) + 1;
if(next > 10) {
return false;
}
else {
this.setState(st, "bomb" + next);
}
}
else {
this.setState(st, this.state.substring(0, 5));
if(st.isGaming() && this.detectCollision(st.ship)) {
st.changeStateToBeDying();
st.dying = 1;
}
}
return inDisplay;
},
setState : function (stage, state) {
this.state = state;
this.image = stage.images[state];
}
});
var SpaceShip = Sprite.extend({
x : 0,
y : 0,
width : Config.cellWidth,
height : Config.cellHeight,
image : null,
constructor : function (x, y, image) {
this.x = x;
this.y = y;
this.image = image;
}
});
var Stage = Class.extend({
imageName : null,
images : null,
state : "loading",
ship : null,
dying : 0,
lastX : -1,
lastY : -1,
frameCount : 0,
currentTop : 0,
ctx : null,
bgCtx : null,
bullets : null,
rocks : null,
numRocks : 0,
score : 0,
scoreElement : null,
changeStateToBeLoading : function () {
this.state = "loading";
},
isLoading : function () {
return this.state == "loading";
},
changeStateToBeGaming : function () {
this.state = "gaming";
},
isGaming : function () {
return this.state == "gaming";
},
changeStateToBeDying : function () {
this.state = "dying";
},
isDying : function () {
return this.state == "dying";
},
changeStateToBeGameOver : function () {
this.state = "gameover";
},
isGameOver : function () {
return this.state == "gameover";
},
level : function () {
return this.frameCount / 500;
},
drawBackground : function () {
var bottom = Config.height + Config.cellHeight - this.currentTop;
if(bottom > 0) {
this.ctx.drawImage(this.bgCtx.canvas, 0, this.currentTop,
Config.width, bottom, 0, 0, Config.width, bottom);
}
if(Math.abs(Config.height - bottom) > 0) {
this.ctx.drawImage(this.bgCtx.canvas, 0, bottom);
}
},
draw : function () {
this.drawBackground();
var ship = this.ship;
if(this.isGaming()) {
ship.draw(this.ctx);
}
else if(this.isDying()) {
ship.image = this.images["bomb" + this.dying];
ship.draw(this.ctx);
if(++this.dying > 10) {
this.initialize(); // restart the game
//this.changeStateToBeGameOver();
}
}
},
drawSpace : function (px, py) {
var spaceType = (Math.random() * 10 + 1) | 0;
var image = this.images["space" + spaceType];
this.bgCtx.drawImage(image,
px * Config.cellWidth,
py * Config.cellHeight);
},
createBullet : function (dx, dy) {
return new Bullet(
this.ship.x, this.ship.y,
dx * Config.bulletSpeed,
dy * Config.bulletSpeed,
this.images["bullet"]
);
},
createRock : function () {
var level = this.level();
var px = this.ship.x + Math.random() * 100 - 50;
var py = this.ship.y + Math.random() * 100 - 50;
var fx = Math.random() * Config.width;
var fy = (level >= 4) ? (Math.random() * 2) * Config.height : 0;
var r = Math.atan2(py - fy, px - fx);
var d = Math.max(Math.random() * (5.5 + level) + 1.5, 10);
var hp = (Math.random() * Math.random() * ((5 + level / 4) | 0)) | 1;
var rockId = (Math.random() * 3 + 1) | 0;
return new Rock(
fx,
fy,
Math.cos(r) * d,
Math.sin(r) * d,
hp,
hp * hp * 100,
"rock" + rockId,
this.images["rock" + rockId]
);
},
tick : function () {
++this.frameCount;
window.setTimeout(function() {
this.tick();
}.bind(this), (1000 / Config.FPS) | 0);
this.watchFPS();
if(this.isLoading()) {
return;
}
if(--this.currentTop == 0) {
this.currentTop = Config.height + Config.cellHeight;
}
if( (this.currentTop % Config.cellHeight) == 0) {
var line = this.currentTop / Config.cellHeight - 1;
for(var px = 0; px < Config.cols; ++px) {
this.drawSpace(px, line);
}
}
this.draw();
var fc = this.frameCount;
if(this.isGaming() && (this.frameCount % Config.reloadCount) == 0) {
this.bullets[fc + "a"] = this.createBullet(-1, -1);
this.bullets[fc + "b"] = this.createBullet( 0, -1);
this.bullets[fc + "c"] = this.createBullet( 1, -1);
this.bullets[fc + "d"] = this.createBullet(-1, 1);
this.bullets[fc + "e"] = this.createBullet( 1, 1);
}
if(this.numRocks < (Config.initialNumRocks + this.level())) {
this.rocks[fc + "r"] = this.createRock();
++this.numRocks;
}
for(var bulletKey in this.bullets) {
if(!this.bullets[bulletKey].update(this)) {
delete this.bullets[bulletKey];
}
}
for(var rockKey in this.rocks) {
if(!this.rocks[rockKey].update(this)) {
delete this.rocks[rockKey];
--this.numRocks;
}
}
},
initialize : function () {
for(var px = 0; px < Config.cols; ++px) {
for(var py = 0; py < Config.rows + 1; ++py) {
this.drawSpace(px, py);
}
}
for(var i = 0; i < 3; ++i) {
var canvas = window.document.createElement("canvas");
canvas.width = Config.cellWidth;
canvas.height = Config.cellHeight;
// prepare flashing rock images
var rctx = canvas.getContext("2d");
var k = "rock" + (i+1);
rctx.drawImage(this.images[k], 0, 0);
rctx.globalCompositeOperation = "source-in";
rctx.fillStyle = "#fff";
rctx.fillRect(0, 0, canvas.width, canvas.height);
this.images[k + "w"] = canvas;
}
this.currentTop = Config.height + Config.cellHeight;
this.ship = new SpaceShip(
Config.width >> 2,
(Config.height * 3/4) | 0,
this.images["my"]);
this.score = 0;
this.bullets = {};
this.rocks = {};
this.numRocks = 0;
this.changeStateToBeGaming();
window.setTimeout(function() {
window.scrollTo(0, 0);
}, 250);
},
constructor : function (stageCanvas, scoreboard) {
// initialize properties
this.changeStateToBeLoading();
this.imageName = ["my", "bullet", "rock1", "rock2", "rock3"];
this.images = {};
scoreboard.style.width = Config.width + "px";
this.scoreElement = scoreboard;
stageCanvas.width = Config.width;
stageCanvas.height = Config.height;
this.ctx = stageCanvas.getContext("2d");
var bg = window.document.createElement("canvas");
bg.width = Config.width;
bg.height = Config.height + Config.cellHeight;
this.bgCtx = bg.getContext("2d");
for(var i = 0; i < 10; ++i) {
this.imageName.push("space" + (i + 1));
this.imageName.push("bomb" + (i + 1));
}
// preload
var loadedCount = 0;
var checkLoad = function(e) {
var image = e.target;
var canvas = window.document.createElement("canvas");
var cx = canvas.getContext("2d");
cx.drawImage(image, 0, 0);
this.images[image.name] = canvas;
if(++loadedCount == this.imageName.length) {
this.initialize();
}
}.bind(this);
for(var i = 0; i < this.imageName.length; ++i) {
var name = this.imageName[i];
var image = window.document.createElement("img");
image.addEventListener("load", checkLoad);
image.src = Config.imagePath + "/" + name + ".png";
image.name = name;
}
var touchStart = function(e) {
e.preventDefault();
var p = this.getPoint(e);
this.lastX = p[0];
this.lastY = p[1];
if(this.isGameOver()) {
this.initialize();
}
}.bind(this);
var body = window.document.body;
body.addEventListener("mousedown", touchStart);
body.addEventListener("touchstart", touchStart);
var touchMove = function(e) {
e.preventDefault();
var p = this.getPoint(e);
if(this.isGaming() && this.lastX != -1) {
var ship = this.ship;
ship.x += ((p[0] - this.lastX) * 2.5) | 0;
ship.y += ((p[1] - this.lastY) * 3.0) | 0;
ship.x = Math.max(ship.x, 0);
ship.x = Math.min(ship.x, Config.width);
ship.y = Math.max(ship.y, 0);
ship.y = Math.min(ship.y, Config.height);
}
this.lastX = p[0];
this.lastY = p[1];
}.bind(this);
body.addEventListener("mousemove", touchMove);
body.addEventListener("touchmove", touchMove);
},
getPoint : function (e) {
var px = 0;
var py = 0;
if(e instanceof MouseEvent) {
px = e.clientX;
py = e.clientY;
}
else if(e instanceof TouchEvent) {
px = e.touches[0].pageX;
py = e.touches[0].pageY;
}
return [ px, py ];
},
start : Date.now(),
fps : 0,
watchFPS : function () {
if((this.frameCount % Config.FPS) == 0) {
this.fps = (this.frameCount / (Date.now() - this.start) * 1000) | 0;
this.updateScore();
}
},
updateScore : function () {
var scoreStr = this.score + "";
var fillz = "000000000".substring(
0, 9 - scoreStr.length
);
this.scoreElement.innerHTML = fillz + scoreStr + "<br/>\n" + this.fps + " FPS";
}
});
var _Main = Class.extend({
$main : function (args) {
console.log("shooting.js");
var stageCanvas = document.getElementById(args[0]);
var scoreboard = document.getElementById(args[1]);
var stage = new Stage(stageCanvas, scoreboard);
stage.tick();
}
});
// vim: set expandtab:
<file_sep>/*EXPECTED
0,abc
*/
class _Main {
static function say(a : Array.<variant>) : void {
log a.join(",");
}
static function main(args : string[]) : void {
var a = [ 0, "abc" ] : variant[]; // test type
_Main.say(a); // test variant[] === Array.<variant>
}
}
<file_sep>/*EXPECTED
10
20
30
*/
class _Main {
static function main (args : string[]) : void {
var lambdas = {
"foo" : () -> 10,
"bar" : () -> (0, 20),
"baz" : () -> 30
};
log lambdas["foo"]();
log lambdas["bar"]();
log lambdas["baz"]();
}
}
<file_sep>class Test {
static function run() : void {
log [] : variant;
}
}
<file_sep>class _Main {
static function main(args : string[]) : void {
assert false, 1;
}
}<file_sep>/*
* Point class
*
* Usage:
* var p = new Point(10, 20);
* log p.getX(); // 10
* log p.getY(); // 20
*/
class Point {
var _x = 0;
var _y = 0;
function constructor() {
}
function constructor(x : number, y : number) {
this._x = x;
this._y = y;
}
// getters
function getX() : number {
return this._x;
}
function getY() : number {
return this._y;
}
// setters
function setX(value : number) : void {
this._x = value;
}
function setY(value : number) : void {
this._y = value;
}
}
class _Main {
static function main(args : string[]) : void {
log "by default constructor:";
var p = new Point;
log "x=" + p.getX() as string;
log "y=" + p.getY() as string;
log "by new Point(10, 20):";
p = new Point(10, 20);
log "x=" + p.getX() as string;
log "y=" + p.getY() as string;
}
}
<file_sep>/*EXPECTED
[object Object]
*/
class _Main {
static function main(args : string[]) : void {
var m = {
toString: 1
};
log m.toString();
}
}
<file_sep>mixin M1 {
function constructor() {
}
}
mixin M2 {
function constructor() {
}
}
class T implements M1, M2 {
function constructor() {
M2();
M1();
}
}
<file_sep>/*EXPECTED
123
*/
class _Main {
class Box {
var _value : number;
function constructor (value : number) {
this._value = value;
}
function getValue () : number {
return this._value;
}
}
static function box (value : number) : _Main.Box {
return new _Main.Box(value);
}
static function unbox (box : _Main.Box) : number {
return box.getValue();
}
static function main (args : string[]) : void {
var box = _Main.box(123);
log _Main.unbox(box);
}
}<file_sep>/*EXPECTED
3
4
*/
class _Main {
static var n : number = 3;
static function main(args : string[]) : void {
log _Main.n;
_Main.n = 4;
log _Main.n;
}
}
<file_sep>import "js.jsx";
import "test-case.jsx";
import "../../src/jsx-command.jsx";
import "../../src/jsx-node-front.jsx";
class _Test extends TestCase {
function testJSXDoc() : void {
var platform = new NodePlatform(".");
var statusCode = JSXCommand.main(platform, ["--mode", "doc", "--output", "t/src/jsxdoc/", "t/src/jsxdoc/hello.jsx"]);
this.expect(statusCode, "status code").toBe(0);
if(statusCode != 0) {
return;
}
var file = "t/src/jsxdoc/t/src/jsxdoc/hello.jsx.html";
this.expect(platform.fileExists(file), "HTML file has been generated").toBe(true);
var content = platform.load(file);
this.expect(content).toMatch(/Module Description/);
this.expect(content).toMatch(/Class Description/);
this.expect(content).toMatch(/MyClass/);
this.expect(content).toMatch(/Instance Variable/);
this.expect(content).toMatch(/instanceVariable/);
this.expect(content).toMatch(/Class Variable/);
this.expect(content).toMatch(/classVariable/);
this.expect(content).toMatch(/Constructor/);
this.expect(content).toMatch(/Static Method/);
this.expect(content).toMatch(/List of Strings/);
this.expect(content).toMatch(/staticMethod/);
this.expect(content).toMatch(/Instance Method/);
this.expect(content).toMatch(/List of Numbers/);
this.expect(content).toMatch(/instanceMethod/);
}
}
// vim: set noexpandtab:
<file_sep>class T {
static var fld = "bar.jsx";
function constructor() {
log "bar.jsx";
}
static function f() : void {
log "bar.jsx";
}
}
<file_sep>/*EXPECTED
3
*/
/*JSX_OPTS
--optimize lto,unclassify
*/
class Foo {
var n = 3;
function f() : Foo {
return this;
}
static function main(args : string[]) : void {
log (new Foo).f().f().n;
}
}
class _Main {
static function main(args : string[]) : void {
log (new Foo).f().f().n;
}
}
<file_sep>/*EXPECTED
45
*/
class _Main {
static function main(args : string[]) : void {
var sum = 0;
for (var i = 0; i < 10; ++i)
sum += i;
log sum;
}
}
<file_sep>/*EXPECTED
bar
*/
/*JSX_OPTS
--optimize staticize --minify
*/
class _Main {
final function foo () : void {
function bar () : void {
log "bar";
}
bar();
}
static function main (args : string[]) : void {
(new _Main).foo();
}
}<file_sep>/*EXPECTED
0,a
1,b
2,c
*/
class _Main {
static function main(args : string[]) : void {
var a = [ "a", "b", "c" ];
for (var i in a)
log i as string + "," + a[i];
}
}
<file_sep>/*EXPECTED
foo
*/
/*JSX_OPTS
--optimize staticize
*/
class Base {
final function foo () : string {
return 'foo';
}
}
class _Main {
static var x = new Base().foo();
static function main(args : string[]) : void {
log _Main.x;
}
}
<file_sep>class Test {
static function run() : void {
["abc"] : int[];
}
}
<file_sep>/*EXPECTED
*/
class _Main {
static function main (args : string[]) : void {
var a : function (:boolean) : void;
var b : function (:boolean) : void;
a = b = function (recurse:boolean) : void {
log "Hi";
if (recurse) a(false);
};
}
}
<file_sep>class Test {
static function f() : void {
}
static function run() : void {
var t = Test.f();
}
}
<file_sep>/*EXPECTED
static
*/
class _Main {
static const STATIC_VAR = "static";
static function main(args : string[]) : void {
log _Main.STATIC_VAR;
}
}
<file_sep>import "test-case.jsx";
class _Test extends TestCase {
function testTCEqualsTrue() : void {
this.expect(this.equals(
"foo",
"foo"
)).toBe(true);
this.expect(this.equals(
null,
null
)).toBe(true);
this.expect(this.equals(
[1, 2, 3],
[1, 2, 3]
)).toBe(true);
this.expect(this.equals(
[ [1], [2], [3]],
[ [1], [2], [3]]
)).toBe(true);
this.expect(this.equals(
{ foo: 10, bar: 20 },
{ foo: 10, bar: 20 }
)).toBe(true);
this.expect(this.equals(
{ foo: 10, bar: 20 },
{ bar: 20, foo: 10 }
)).toBe(true);
this.expect(this.equals(
[{ foo: 10, bar: 20 }],
[{ foo: 10, bar: 20 }]
)).toBe(true);
this.expect(this.equals(
[new Date(0)],
[new Date(0)]
)).toBe(true);
}
function testTCEqualsFalse() : void {
this.expect(this.equals(
0,
null
)).toBe(false);
this.expect(this.equals(
"",
null
)).toBe(false);
this.expect(this.equals([1, 2, 3, 0], [1, 2, 3])).toBe(false);
this.expect(this.equals([1, 2, 3], [1, 2, 3, 0])).toBe(false);
this.expect(this.equals([1, 2, 4], [1, 2, 3])).toBe(false);
this.expect(this.equals(
{ foo: 10, bar: 20 },
{ foo: 10, bar: 21 }
)).toBe(false);
this.expect(this.equals(
{ foo: 10, bar: 20 },
{ foo: 10, baz: 20 }
)).toBe(false);
this.expect(this.equals(
[new Date(0)],
[new Date(1)]
)).toBe(true);
}
}
<file_sep>/*EXPECTED
true
true
false
false
*/
class _Main {
static function main(args : string[]) : void {
var h = { a: 1 };
log "a" in h;
var s = "a";
log s in h;
log "b" in h;
log "a" in { e: 0 };
}
}
<file_sep>Super Kingyo Sukui in JSX
======================================
This is a JSX port of X68000 Super Kingyo Sukui.
Notes
======================================
This application uses `requestAnimationFrame()` emulation.
If you want to use native RAF, add `#raf` to the end of the URL.
* http://thaga.github.com/SuperKingyoSukui-JSX/ (emulated RAF)
* http://thaga.github.com/SuperKingyoSukui-JSX/#raf (native RAF)
Author
======================================
<NAME> (thaga)
License
======================================
The MIT License
<file_sep>class Test {
function f() : void {
}
class F {
}
<file_sep>/*EXPECTED
true
false
0
0
n,u,l,l
false
false
0
0
f,a,l,s,e
false
true
1
1
t,r,u,e
false
true
1
1.5
1,.,5
false
true
0
NaN
abc
*/
class _Main {
static function main(args : string[]) : void {
var v : variant = null;
log v == null;
log v as boolean;
log v as int;
log v as number; // may become 0 or NaN
log (v as string).split("").join(","); // null may be "null" or "undefined"
log "";
v = false;
log v == null;
log v as boolean;
log v as int;
log v as number;
log (v as string).split("").join(",");
log "";
v = true;
log v == null;
log v as boolean;
log v as int;
log v as number;
log (v as string).split("").join(",");
log "";
v = 1.5;
log v == null;
log v as boolean;
log v as int;
log v as number;
log (v as string).split("").join(",");
log "";
v = "abc";
log v == null;
log v as boolean;
log v as int;
log v as number;
log v as string;
}
}
<file_sep>/*EXPECTED
a x
a y
a z
b x
b y
b z
c x
c y
c z
3
9
*/
class _Main {
static function main(args : string[]) : void {
var s = 0;
var t = 0;
var a = [ "a", "b", "c" ];
var b = [ "x", "y", "z" ];
for (var i in a) {
s += i;
for (var j in b) {
log a[i], " ", b[j];
t += j;
}
}
log s; // 0 + 1 + 2
log t; // (0 + 1 + 2) * 3
}
}
<file_sep>class _Main {
static function foo.<T>(a : T, b : T) : void {
}
static function bar.<T,U>(a : T) : void {
}
static function main(args : string[]) : void {
_Main.foo(1, "2");
_Main.bar(1);
}
}
<file_sep>class C {
static function f() : number {
}
}
<file_sep>/*EXPECTED
string
*/
class _Main {
static function main(args : string[]) : void {
var a : variant = _Main.main.toString();
log typeof a;
}
}
<file_sep>class Test {
}
class Test {
}
<file_sep>class T {
static function test() : void {
log ~ "abc";
}
}
<file_sep>/*EXPECTED
0
1
0
3
1
3
0
default
1
default
*/
class _Main {
static function _for() : void {
l: for (var i = 0; i < 2; ++i) {
log i;
if (true) continue l;
log "bad";
}
l2: for (var i = 0; i < 2; ++i) {
for (var j = 3; j < 4; ++j) {
log i;
log j;
if (true) continue l2;
log "bad";
}
}
}
static function _switch() : void {
l: for (var i = 0; i < 2; ++i) {
log i;
switch (1) {
default:
log "default";
if (true) continue l;
}
}
}
static function main(args : string[]) : void {
_Main._for();
_Main._switch();
}
}
<file_sep>class T {
static var fld = "foo.jsx";
function constructor() {
log "foo.jsx";
}
static function f() : void {
log "foo.jsx";
}
}
<file_sep>class Test {
static function run() : void {
true + false;
}
}
<file_sep>/*EXPECTED
true
*/
/*JSX_OPTS
--optimize fold-const,dce
*/
class _Main {
static function main (args : string[]) : void {
if (true as string) {
log true as string;
}
}
}
<file_sep>/*EXPECTED
10
20
10
20
*/
class _Main {
static function main(args : string[]) : void {
var a = [
10,
20,
];
var m = {
a: 10,
b: 20,
};
log a[0];
log a[1];
log m['a'];
log m['b'];
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>/*EXPECTED
1
2
3
4
5
10
*/
class _Main {
static function a(x : number) : number {
log x;
return x;
}
static function main(args : string[]) : void {
log _Main.a(1) + _Main.a(2) * (_Main.a(3) + _Main.a(4)) - _Main.a(5);
}
}
<file_sep>/***
* Module Description
*/
/**
* Class Description
*/
class MyClass {
/**
* Instance Variable
*/
var instanceVariable = "x";
/**
* Class Variable
*/
static var classVariable = "x";
/**
* Constructor
*/
function constructor() {
}
/**
* Static Method
* @param args List of Strings
*/
static function staticMethod(args : string[] = null) : void {
log "Hello, world!";
}
/**
* Instance Method
* @param args List of Numbers
*/
function instanceMethod(args : number[]) : void {
log "Hello, world!";
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>class Two {
function constructor() {
log 2;
}
static function say() : void {
log "Two";
}
}
<file_sep>class T {
function constructor() {
super(555);
}
}
<file_sep>class T {
static function f() : void {
var i;
do {
break;
} while ((i = 0) != 0);
log i;
}
}
<file_sep>mixin M {
}
class Base implements M {
}
class Derived extends Base implements M {
}
<file_sep>import 'js/web.jsx';
import 'mvq.jsx';
import 'webgl-util.jsx';
class RenderTexture {
static var gl = null:WebGLRenderingContext;
static function initWithGL(gl:WebGLRenderingContext) : void {
RenderTexture.gl = gl;
}
var framebuffer = null:WebGLFramebuffer;
var texturebuffer = null:WebGLTexture;
var depthbuffer = null:WebGLRenderbuffer;
var width = 0;
var height = 0;
var _viewport = null:Int32Array;
function constructor(w:int, h:int) {
var gl = RenderTexture.gl;
var framebuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
var texturebuffer = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texturebuffer);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(w * h * 4));
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.bindTexture(gl.TEXTURE_2D, null);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texturebuffer, 0);
var depthbuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, depthbuffer);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, w, h);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthbuffer);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
this.framebuffer = framebuffer;
this.texturebuffer = texturebuffer;
this.depthbuffer = depthbuffer;
this.width = w;
this.height = h;
}
function destroy() : void {
var gl = RenderTexture.gl;
gl.deleteFramebuffer(this.framebuffer);
gl.deleteTexture(this.texturebuffer);
gl.deleteRenderbuffer(this.depthbuffer);
}
function begin() : void {
var gl = RenderTexture.gl;
//this._viewport = gl.getParameter(gl.VIEWPORT) as Int32Array;
// XXX: workaround fod Firefox
this._viewport = null;
var tmp_vp = gl.getParameter(gl.VIEWPORT);
if (tmp_vp instanceof Int32Array) {
this._viewport = tmp_vp as __noconvert__ Int32Array;
} else {
this._viewport = new Int32Array(tmp_vp as __noconvert__ Array.<int>);
}
// draw begin
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
gl.viewport(0, 0, this.width, this.height);
gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);
}
function end() : void {
var gl = RenderTexture.gl;
// draw end
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
var vp = this._viewport;
gl.viewport(vp[0], vp[1], vp[2], vp[3]);
}
function texture() : WebGLTexture {
return this.texturebuffer;
}
}
<file_sep>/*EXPECTED
[1],[2],[3]
2,3,4
*/
class C.<From, To> {
static function mymap(a : From[], cb : function (:Nullable.<From>):Nullable.<To>) : To[] {
return a.map.<To>(cb);
}
}
class _Main {
static function main(args : string[]) : void {
var c : string[] = C.<number, string>.mymap([1, 2, 3], (v) -> "[" + v as string + "]");
log c.join(",");
var d : number[] = C.<string, number>.mymap(["1", "2", "3"], (v) -> v as number + 1);
log d.join(",");
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>/*EXPECTED
hello
*/
class _Main {
function constructor() {
log "hello";
}
static function main(args : string[]) : void {
new _Main;
}
}
<file_sep>/***
* Experimental generator
*/
import "timer.jsx";
class Async {
static function sleep(durationMS : number) : (variant) -> void {
return (g) -> {
Timer.setTimeout(() -> {
Async.go(g);
}, durationMS);
};
}
static function run(coro : () -> Enumerable.<(variant)->void>) : void {
Async.go(coro());
}
static function go(v : variant) : void {
var g = v as Enumerable.<(variant)->void>;
try {
var cb = g.next();
cb(g);
}
catch (si : StopIteration) {
return; // nothing
}
}
}
class _Main {
static function main(args : string[]) : void {
Async.run(() -> {
log "H";
yield Async.sleep(100);
log "e";
yield Async.sleep(100);
log "l";
yield Async.sleep(100);
log "l";
yield Async.sleep(100);
log "o";
});
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>import "../hello.jsx";
class Goodbye {
function say() : void {
log "goodbye";
}
}
<file_sep>class FooClass {
function constructor() {
log "FooClass#constructor";
}
static function say() : void {
log "FooClass#say";
}
}
interface FooInterface {
}
<file_sep>class Base {
final function f() : void {}
}
class Derived extends Base {
override function f() : void {}
}
<file_sep>window.addEventListener('load', function (e) {
"use strict";
var Lexer = require("jslexer");
require("source-map");
var SOURCE = "source"; // should have data-file="..."
var ORIG = "original";
var GEN = "generated";
var colorMap = {
space: "#ccc", // includes comments
identifier: "#333",
keyword: "#09d",
string: "#d70",
number: "#f60",
regexp: "#660"
};
var skipMap = {
"(": true,
")": true,
",": true
};
var DEBUG = false;
function element(id) {
var item = document.getElementById(id);
if(!item) {
throw new Error("Element not found for id " + id);
}
return item;
}
function elementOffset(elem) {
// point to the center
var valueL = elem.offsetWidth >> 1;
var valueT = elem.offsetHeight >> 1;
// accumulate
do {
valueT += elem.offsetTop | 0;
valueL += elem.offsetLeft | 0;
elem = elem.offsetParent;
} while (elem);
return { x: valueL, y: valueT };
}
function load(name) {
var xhr = new XMLHttpRequest();
xhr.open("GET", name, false);
xhr.send(null);
return xhr.responseText;
}
function format(fmt, __va_args__) {
var args = arguments;
return fmt.replace(/%([0-9]+)/g, function (_unused, n) {
return args[ n | 0 ];
});
}
function asHTML(prefix, tokens) {
var elements = tokens.map(function (tokenObject) {
var s = tokenObject.token.
replace(/&/g, "&").
replace(/</g, "<").
replace(/>/g, ">");
var t = tokenObject.type;
var style = t in colorMap ? "color:" + colorMap[t] : "";
return format('<span id="%1%2" style="%3;" class="%4">%5</span>',
prefix, tokenObject.id, style, t, s);
});
return "<code>" + elements.join("") + "</code>";
}
function initSourcePane(s, p) {
p.style.padding = "0px";
p.style.margin = "1px";
p.style.width = format("%1px", (s.offsetWidth >> 1) - 4);
// TODO: make panes scrollable
//p.style.maxHeight = "800px";
//p.style.overflowY = "scroll";
}
var source = element(SOURCE);
console.assert(source.dataset.file, "source.dataset.file");
initSourcePane(source, element(ORIG));
initSourcePane(source, element(GEN));
var gen = Lexer.tokenize(source.dataset.file, load(source.dataset.file));
var mappingURL;
if(gen[gen.length-1].type === "space") {
var m = gen[gen.length-1].token.
match(/[#@] *sourceMappingURL=([^ \t\r\n]+)/);
if(!m) {
return;
}
mappingURL = m[1];
}
console.assert(mappingURL, "sourceMappingURL");
var mapping = JSON.parse(load(mappingURL));
var mainFile = mapping.sourceRoot != null ? mapping.sourceRoot + "/" + mapping.sources[1] : mapping.sources[1];
mainFile = mainFile.replace(/^example\//, "");
var orig = Lexer.tokenize(mainFile, mapping.sourcesContent[1] || load(mainFile));
element(ORIG).innerHTML = asHTML(ORIG, orig);
element(GEN).innerHTML = asHTML(GEN, gen);
var consumer = new sourceMap.SourceMapConsumer(mapping);
var basePos = {
x: source.offsetLeft,
y: source.offsetTop
};
var cx = (function () {
var c = document.createElement('canvas');
if(DEBUG) {
c.style.border = "solid 1px black";
}
c.style.position = "absolute";
c.style.margin = "0px";
c.style.padding = "0px";
c.style.left = source.offsetLeft + "px";
c.style.top = source.offset + "px";
c.width = source.offsetWidth;
c.height = source.offsetHeight;
source.appendChild(c);
return c.getContext("2d");
}());
console.assert(cx, "cx");
var original = [];
orig.forEach(function (tokenObject) {
if(!original[tokenObject.line]) {
original[tokenObject.line] = [];
}
original[tokenObject.line][tokenObject.column] = tokenObject;
});
function getOriginalToken(genToken) {
if(genToken.type === "space") {
return null;
}
if(genToken.token in skipMap) {
return null;
}
var p = consumer.originalPositionFor(genToken);
if(! (original[p.line] && original[p.line][p.column])) {
return null;
}
return original[p.line][p.column];
}
var t0 = Date.now();
var i = 0;
function drawLine() {
var genToken;
var origToken;
do {
if(i >= gen.length) {
if(DEBUG) {
console.debug("finish drawLine by %s ms.", Date.now() - t0);
}
return;
}
genToken = gen[i++];
origToken = getOriginalToken(genToken);
} while (origToken=== null);
setTimeout(drawLine);
if(origToken.done) {
return;
}
origToken.done = true;
cx.beginPath();
// left pane
var elem = element(ORIG + origToken.id);
var p = elementOffset(elem);
cx.moveTo(p.x - basePos.x, p.y - basePos.y);
cx.strokeStyle = elem.style.color;
// to right pane
elem = element(GEN + genToken.id);
p = elementOffset(elem);
cx.lineTo(p.x - basePos.x, p.y - basePos.y);
cx.stroke();
}
setTimeout(drawLine);
});
<file_sep>class Foo {
function g() : void {
yield 42;
}
}<file_sep>class T {
static function f() : void {
if (T.f())
;
}
}
<file_sep>class Outer {
class Inner {
function say() : void {
log "inner#say";
}
static function say() : void {
log "inner.say";
}
}
}
<file_sep>/*EXPECTED
2
*/
class _Main {
static function f(n : number) : number {
return (n ? true : false) ? 2 : 1;
}
static function main(args : string[]) : void {
log _Main.f(3);
}
}
<file_sep>class T {
static function f(n : number) : boolean {
var ret;
do {
if (n != 0)
break;
ret = true;
} while (false);
return ret;
}
}
<file_sep>/*EXPECTED
1
*/
class _Main {
function myMethod() : int {
var x = 1;
try {
return x;
} finally {
}
}
static function main(args : string[]) : void {
log (new _Main).myMethod();
}
}
<file_sep>/*EXPECTED
hello
*/
class _Main {
static var f = function() : string {
return "hello";
};
static function main(args : string[]) : void {
log _Main.f();
}
}
<file_sep>
class _Main {
static function main(args : string[]) : void {
log JSON.stringify(args);
}
}
<file_sep>/*EXPECTED
1
1 2
1 2 3
*/
class _Main {
static function f(x:int):void {
log x;
}
static function f(x:int, y:int):void {
log x, y;
}
static function f(x:int, y:int, z:int):void {
log x, y, z;
}
static function main(args : string[]) : void {
_Main.f(1);
_Main.f(1, 2);
_Main.f(1, 2, 3);
}
}
<file_sep>/*EXPECTED
false
*/
class A.<T> {
static function test(a:variant):boolean {
return a instanceof T;
}
}
class _Main {
static function main(args:string[]):void {
var some_object = 0;
log A.<_Main>.test(some_object);
}
}
// vim: set expandtab:
<file_sep>class Named.<T> {
static function say() : void {
log "named";
}
}
// used to check that it is not imported
class _Hidden.<T> {
}
<file_sep>/*EXPECTED
a.jsx
b.jsx
*/
// multipie In-line Native Definitions should be allowed
import "./306.multi-ind/a.jsx" into a;
import "./306.multi-ind/b.jsx" into b;
class _Main {
static function main(args : string[]) : void {
log a.Foo.name;
log b.Foo.name;
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>import "./lib/foo.jsx";
class C {
function f() : void {
Foo.
/*EXPECTED
[
{
"word" : "<"
},
{
"word" : "staticMemberMethod",
"args" : [],
"definedClass" : "Foo",
"returnType" : "void",
"type" : "function () : void"
}
]
*/
/*JSX_OPTS
--complete 5:9
*/
// vim: set expandtab tabstop=2 shiftwidth=2:
<file_sep>class Test {
static function run() : void {
"answer" < 42;
}
}
<file_sep>/*EXPECTED
Hi!
Ciao!
*/
/*JSX_OPTS
--optimize strip
*/
native class Console {
delete function constructor();
static function log(s : string) : void {
log s;
}
} = "(console.log('Hi!'), console)";
class _Main {
static function main(args : string[]) : void {
Console.log("Ciao!");
}
}
<file_sep>/*EXPECTED
5
*/
/*JSX_OPTS
--optimize dce
*/
class _Main {
static function main(args : string[]) : void {
var x = 0;
// boolean
if (true) {
++x;
}
if (false) {
x = NaN;
}
// number
if (1) {
++x;
}
if (0) {
x = NaN;
}
// string
if ('a') {
++x;
}
if ('') {
x = NaN;
}
// array
if ([] : number[]) {
++x;
}
// map
if ({} : Map.<number>) {
++x;
}
log x;
}
}
<file_sep>/*EXPECTED
yes
yes
1
1
Infinity
yes
1
hi
*/
class _Main {
static function main(args : string[]) : void {
log "" ?: "yes";
log "yes" ?: "no";
log 0 ?: 1;
log NaN ?: 1;
log Infinity ?: 0;
log ((null : String) ?: new String("yes")).toString();
log [ 0 ][1] ?: 1;
log [ "abc" ][1] ?: "hi";
}
}
<file_sep>/*EXPECTED
3
2
1
*/
class Stack.<T> {
var _contents : Stack.<T>.Cons;
function constructor () {
this._contents = null;
}
function push (x : T) : void {
this._contents = new Stack.<T>.Cons(x, this._contents);
}
function pop () : T {
var x = this._contents.head;
this._contents = this._contents.tail;
return x;
}
function peek () : T {
return this._contents.head;
}
class Cons {
var head : T;
var tail : Stack.<T>.Cons;
function constructor(head : T, tail : Stack.<T>.Cons) {
this.head = head;
this.tail = tail;
}
}
}
class _Main {
static function main (args : string[]) : void {
var stack = new Stack.<number>;
stack.push(1);
stack.push(2);
stack.push(3);
log stack.pop();
log stack.pop();
log stack.pop();
}
}
<file_sep>import "../b/b.jsx";
class A {
static function callB() : void {
B.say();
}
static function say() : void {
log "A";
}
}
<file_sep>/*EXPECTED
_Private1
_Private2
_Private3
*/
import "063.import-by-name/foo.jsx";
import _Private1, _Private2 from "063.import-by-name/foo.jsx";
import _Private3 from "063.import-by-name/foo.jsx" into foo;
class _Main {
static function main(args : string[]) : void {
_Private1.say();
_Private2.say();
foo._Private3.say();
}
}
<file_sep>// FIXME checkthat all lines are report as errors
class T {
static function run() : void {
undefined as __noconvert__ boolean;
undefined as __noconvert__ int;
undefined as __noconvert__ number;
undefined as __noconvert__ string;
undefined as __noconvert__ Object;
undefined as __noconvert__ number[];
undefined as __noconvert__ function () : void;
null as __noconvert__ boolean;
null as __noconvert__ int;
null as __noconvert__ number;
null as __noconvert__ string;
}
}
<file_sep>/*EXPECTED
undefined
null access
_Main.g(a.pop());
^
*/
class _Main {
static function f(n : Nullable.<number>) : void {
log n;
}
static function g(n : number) : void {
log n;
}
static function main(args : string[]) : void {
var a = [ 3 ];
a.pop();
_Main.f(a.pop());
_Main.g(a.pop());
}
}
// vim: set expandtab:
<file_sep>/*JSX_OPTS
--warn-error
*/
class T {
static function f(n : number) : void {
while (true) {
switch (n) {
default:
continue;
}
log 1;
}
}
}
<file_sep>class T {
static function f() : void {
t
/*EXPECTED
[
{
"word" : "throw",
"partialWord" : "hrow"
},
{
"word" : "try",
"partialWord" : "ry"
},
{
"word" : "true",
"partialWord" : "rue"
},
{
"word" : "typeof",
"partialWord" : "ypeof"
}
]
*/
/*JSX_OPTS
--complete 3:4
*/
<file_sep>/*EXPECTED
42
*/
class _Main {
static function main (args : string[]) : void {
log (function g() {
yield 42;
})().next();
}
}<file_sep>class C {
__export__ function f() : void {
}
function f(s : string) : void {
}
}
interface I {
__export__ function f(n : number) : void;
}
class D extends C implements I {
override function f(n : number) : void {
}
}
<file_sep>/*EXPECTED
foo
*/
/*JSX_OPTS
--optimize staticize --minify
*/
import "console.jsx";
class _Main {
final function foo () : void {
try {
log "foo";
} catch (e : Error) {
log e;
}
}
static function main (args : string[]) : void {
(new _Main).foo();
}
}<file_sep>/*EXPECTED
A
false
A
true
*/
/*JSX_OPTS
--optimize inline
*/
final class A {
var b = new B;
function constructor() {
log "A";
}
}
final class B {
function not(value : boolean) : boolean {
return !value;
}
}
// a variation of t/optimize/040
class _Main {
static function main(args : string[]) : void {
log new A().b.not(true);
log new A().b.not(false);
}
}
<file_sep>/*EXPECTED
60
*/
class _Main {
static function hoge(f: (int) -> (int) -> (int) -> int): int {
return f(10)(20)(30);
}
static function main(args : string[]) : void {
log _Main.hoge((x) -> (y) -> (z) -> x + y + z);
}
}
<file_sep>/*EXPECTED
10
10
3
9
*/
/*JSX_OPTS
--disable-type-check --optimize inline
*/
class _Main {
static function main(args : string[]) : void {
var sum = 0;
[ 1, 2, 3, 4 ].forEach((n) -> { sum += n; });
log sum;
var closures = new Array.<() -> number>;
[ 1, 2, 3, 4 ].forEach((n) -> {
closures.push(() : number -> n);
});
sum = 0;
closures.forEach((f) -> { sum += f(); });
log sum;
sum = 0;
["foo", "bar", "baz"].forEach((item, i) -> { sum += i; });
log sum;
sum = 0;
["foo", "bar", "baz"].forEach((item, i, a) -> { sum += a.length; });
log sum;
}
}
<file_sep>/*EXPECTED
Derived#say:123
*/
/*JS_SETUP
function newDerived() {
var Base = JSX.require("t/run/270.extend-in-js.jsx").Base;
var Derived = function () {
Base.call(this); // call super class ctor
console.log("Derived#new");
};
Derived.prototype = (function () {
function f() {}
f.prototype = Base.prototype;
return new f();
})();
Derived.prototype.say = function () {
console.log("Derived#say:" + this.n);
}
return new Derived;
}
*/
import "js.jsx";
__export__ class Base {
// n and say are automatically exported
var n = 123;
function say() : void {
log "should never see this";
}
}
class _Main {
static function main(args : string[]) : void {
var derived = js.eval("newDerived()") as Base;
derived.say();
}
}
<file_sep>import "056.import-as-conflict/a.jsx" into foo;
import "056.import-as-conflict/b.jsx" into foo;
<file_sep>class Test {
static function run() : void {
var f : number = undefined;
}
}
<file_sep>/*EXPECTED
woof
mew
woof
mew
*/
abstract class Animal {
abstract function say() : void;
}
class Dog extends Animal {
override function say() : void {
log "woof";
}
}
class Cat extends Animal {
override function say() : void {
log "mew";
}
}
class _Main {
static function main(args : string[]) : void {
new Dog().say();
new Cat().say();
var animal : Animal = new Dog();
animal.say();
animal = new Cat();
animal.say();
}
}
<file_sep>/*JSX_OPTS
--warn-error
*/
class T {
static function f() : void {
while (true) {
continue;
log "Hi";
}
}
}
<file_sep>/*EXPECTED
Hello, world!
*/
class _Main {
static var foo = function bar() : string {
return "Hello, world!";
};
static function main(args : string[]) : void {
log _Main.foo();
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>/*EXPECTED
1
*/
class _Main {
var _n : number;
function constructor(n : number) {
this._n = n;
}
static function main(args : string[]) : void {
var t = new _Main(1);
log t._n;
}
}
<file_sep>/*EXPECTED
true
true
false
true
false
true
false
true
false
true
*/
class _Main {
static function main(args : string[]) : void {
log ! 0;
log ! NaN;
log ! 1;
log ! "";
log ! "abc";
log ! null;
log ! new String();
log 1 || 0;
log 0 || "";
log 1 && "abc";
}
}
<file_sep>/*EXPECTED
ok
*/
/*JSX_OPTS
--optimize no-assert
*/
class _Main {
var m = (function () : number {
assert !"seven";
return 123;
})();
var mf = function () : void {
assert !"eight";
};
function f() : void {
assert !"one";
(function () : void {
assert !"two";
})();
function g() : void {
assert !"three";
}
g();
}
static var s = (function () : number {
assert !"nine";
return 123;
})();
static var sf = function (n : number) : void {
assert !"ten";
};
static function f() : void {
assert !"four";
(function () : void {
assert !"five";
})();
function g() : void {
assert !"six";
}
g();
}
static function main(args : string[]) : void {
var m = new _Main;
m.f();
m.mf();
_Main.f();
_Main.sf(_Main.s); // _use_ the variable since initialization is delayed
log "ok";
}
}
<file_sep>/*EXPECTED
true
*/
class _Main {
static function main(args : string[]) : void {
var a = [ 0 ][-1];
log a == null;
}
}
<file_sep>import "./153.native-class-conflict/a.jsx" into a;
import "./153.native-class-conflict/b.jsx" into b;
class Test {
static function run() : void {
a.console.log("foo");
b.console.log("bar");
}
}
<file_sep>/*EXPECTED
foo
42
[1],[2],[3]
*/
class C {
function f.<T>(value : T) : T[] {
var a = new T[];
a.push(value);
return a;
}
function mymap.<From, To>(a : From[], cb : function (:Nullable.<From>):To) : To[] {
var result = new To[];
for (var i = 0; i < a.length; ++i) {
result.push(cb(a[i]));
}
return result;
}
}
class _Main {
static function main(args : string[]) : void {
var x = new C;
var a : string[] = x.f.<string>("foo");
log a[0];
var b : number[] = x.f.<number>(42);
log b[0];
var c : string[] = x.mymap.<number, string>([1, 2, 3], (v) -> "[" + v as string + "]");
log c.join(",");
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
<file_sep>/*EXPECTED
10
*/
class C.<T> {
static const f = function (a : T) : T {
return a;
};
}
class _Main {
static function main(args : string[]) : void {
log C.<number>.f(10);
}
}
<file_sep>/*EXPECTED
A
B#f
x
*/
/*JSX_OPTS
--optimize inline
*/
final class A {
var b = new B;
function constructor() {
log "A";
}
}
final class B {
function f() : boolean {
log "B#f";
return true;
}
function not(value : boolean) : boolean {
return !value && this.f();
}
}
// a variation of t/optimize/040
class _Main {
static function main(args : string[]) : void {
var x = args.length >= 0; // true
if (x && new A().b.not(false)) {
log "x";
}
if (!x && new A().b.not(false)) {
log "y";
}
}
}
<file_sep>/*EXPECTED
null
null
null
null
*/
class P.<T> {
static function f(a : Nullable.<T>) : void {
log a;
}
}
class _Main {
static function main(args : string[]) : void {
P.<variant>.f(null);
P.<variant[]>.f(null);
P.<Object>.f(null);
P.<Object[]>.f(null);
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<file_sep>/*EXPECTED
true
true
*/
interface I {
}
mixin M {
}
class _Main {
static function main(args : string[]) : void {
var i : I = null;
var o : Object = i;
log o == null;
var m : M = null;
o = m;
log o == null;
}
}
<file_sep>/*EXPECTED
55
11
*/
class _Main {
static function main(args : string[]) : void {
var sum = 0;
var i = 0;
while (i++ < 10)
sum += i;
log sum;
log i;
}
}
| 9fd4c0a7f6b56678ee3042071dc5ef1fb8dc852d | [
"JavaScript",
"Makefile",
"Markdown",
"Shell"
] | 466 | JavaScript | yosuke-furukawa/JSX | 55e68a8e42cd3b58edfb4691903240cec8566c2e | 81323677a64df8b1cb9a84ca1d4ea80acff68ade |
refs/heads/master | <file_sep>package com.bakarvin.klinikhp.admin.fragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bakarvin.klinikhp.Preferences;
import com.bakarvin.klinikhp.R;
import com.bakarvin.klinikhp.databinding.FragmentHomeStaffBinding;
public class HomeStaffFragment extends Fragment {
FragmentHomeStaffBinding homeStaffBinding;
public HomeStaffFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
homeStaffBinding = FragmentHomeStaffBinding.inflate(inflater, container, false);
View v = homeStaffBinding.getRoot();
String uname = Preferences.getLoginUname(getContext());
String id = Preferences.getUserLogin(getContext());
homeStaffBinding.txtNamaStaff.setText(uname);
homeStaffBinding.txtIDStaff.setText(id);
return v;
}
}<file_sep>include ':app'
rootProject.name = "Klinik HP"<file_sep>package com.bakarvin.klinikhp.dokter.fragment;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bakarvin.klinikhp.R;
import com.bakarvin.klinikhp.databinding.FragmentDaftarStaffBinding;
import com.bakarvin.klinikhp.databinding.FragmentHomeDokterBinding;
import com.bakarvin.klinikhp.dokter.rekmedis.DaftarRekamMedisActivity;
import com.bakarvin.klinikhp.dokter.rekmedis.DetailRekamMedisDokterActivity;
import com.bakarvin.klinikhp.dokter.rekmedis.ListRekamMedisActivity;
public class HomeDokterFragment extends Fragment {
FragmentHomeDokterBinding homeDokterBinding;
public HomeDokterFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
homeDokterBinding = FragmentHomeDokterBinding.inflate(inflater, container, false);
View v = homeDokterBinding.getRoot();
homeDokterBinding.btnRekamMedis.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getContext(), ListRekamMedisActivity.class));
}
});
return v;
}
}<file_sep>package com.bakarvin.klinikhp.admin.fragment;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bakarvin.klinikhp.R;
import com.bakarvin.klinikhp.admin.crud.dokter.DaftarDokterActivity;
import com.bakarvin.klinikhp.admin.crud.pasien.DaftarPasienActivity;
import com.bakarvin.klinikhp.databinding.FragmentDaftarStaffBinding;
public class DaftarStaffFragment extends Fragment {
FragmentDaftarStaffBinding daftarStaffBinding;
public DaftarStaffFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
daftarStaffBinding = FragmentDaftarStaffBinding.inflate(inflater, container, false);
View v = daftarStaffBinding.getRoot();
daftarStaffBinding.btnDaftarPasien.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getContext(), DaftarPasienActivity.class));
}
});
daftarStaffBinding.btnDaftarDokter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getContext(), DaftarDokterActivity.class));
}
});
return v;
}
}<file_sep>package com.bakarvin.klinikhp.admin.crud.dokter.fragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bakarvin.klinikhp.R;
import com.bakarvin.klinikhp.databinding.FragmentDaftarDataDokterBinding;
import com.bakarvin.klinikhp.databinding.FragmentDaftarJadwalDokterBinding;
import com.bakarvin.klinikhp.databinding.FragmentDaftarStaffBinding;
import java.util.ArrayList;
import java.util.List;
public class DaftarDataDokterFragment extends Fragment {
FragmentDaftarDataDokterBinding daftarDataDokterBinding;
public DaftarDataDokterFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
daftarDataDokterBinding = FragmentDaftarDataDokterBinding.inflate(inflater, container, false);
View v = daftarDataDokterBinding.getRoot();
daftarDataDokterBinding.btnNextDaftarDokter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendDataDokter();
}
});
return v;
}
void sendDataDokter(){
Bundle args = new Bundle();
args.putString("no_ktp",daftarDataDokterBinding.txtDaftarKTPDokter.getText().toString());
args.putString("nama",daftarDataDokterBinding.txtDaftarNamaDokter.getText().toString());
args.putString("alamat",daftarDataDokterBinding.txtDaftarAlamatDokter.getText().toString());
args.putString("poli",daftarDataDokterBinding.txtDaftarPoliDokter.getText().toString());
args.putString("telp",daftarDataDokterBinding.txtDaftarTelpDokter.getText().toString());
args.putString("uname",daftarDataDokterBinding.txtDaftarUnameDokter.getText().toString());
args.putString("pass",daftarDataDokterBinding.txtDaftarPassDokter.getText().toString());
Fragment nextFrag = new DaftarJadwalDokterFragment();
nextFrag.setArguments(args);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fragDaftarDokter, nextFrag)
.addToBackStack(null)
.commit();
}
}<file_sep>package com.bakarvin.klinikhp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.bakarvin.klinikhp.admin.LoginStaffActivity;
import com.bakarvin.klinikhp.admin.MainMenuStaffActivity;
import com.bakarvin.klinikhp.databinding.ActivityMainBinding;
import com.bakarvin.klinikhp.dokter.LoginDokterActivity;
import com.bakarvin.klinikhp.dokter.MainMenuDokterActivity;
import com.google.firebase.database.DatabaseReference;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding activityMainBinding;
int kodeLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(activityMainBinding.getRoot());
checkPref();
activityMainBinding.btnLoginStaff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), LoginStaffActivity.class));
}
});
activityMainBinding.btnLoginDokter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), LoginDokterActivity.class));
}
});
}
private void checkPref(){
if (Preferences.getLoginStatus(getBaseContext())){
kodeLogin = Integer.parseInt(Preferences.getLoginKode(getBaseContext()));
masukMenu();
} else {
Toast.makeText(this, "Gaada user yang Login", Toast.LENGTH_SHORT).show();
}
}
private void masukMenu(){
if (kodeLogin == 1){
startActivity(new Intent(this, MainMenuDokterActivity.class));
} else {
startActivity(new Intent(this, MainMenuStaffActivity.class));
}
}
}<file_sep>package com.bakarvin.klinikhp.admin.crud.rekmedis;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.view.View;
import android.widget.Toast;
import com.bakarvin.klinikhp.adapter.PdfDocumentAdapter;
import com.bakarvin.klinikhp.admin.MainMenuStaffActivity;
import com.bakarvin.klinikhp.databinding.ActivityDetailRekamMedisStaffBinding;
import com.bakarvin.klinikhp.model.Common;
import com.bakarvin.klinikhp.model.RekamMedis;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DetailRekamMedisStaffActivity extends AppCompatActivity {
ActivityDetailRekamMedisStaffBinding rekamMedisStaffBinding;
DatabaseReference dbMedis;
String getIdMedis;
String getNamaDokter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rekamMedisStaffBinding = ActivityDetailRekamMedisStaffBinding.inflate(getLayoutInflater());
setContentView(rekamMedisStaffBinding.getRoot());
dbMedis = FirebaseDatabase.getInstance().getReference("RekamMedis");
getIdMedis = getIntent().getStringExtra("idMedis");
rekamMedisStaffBinding.btnBackDetailMedis.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(DetailRekamMedisStaffActivity.this, MainMenuStaffActivity.class));
}
});
init(getIdMedis);
// exportPdf();
}
private void init(String getIdMedis) {
dbMedis.child(getIdMedis).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
RekamMedis rekamMedis = snapshot.getValue(RekamMedis.class);
rekamMedisStaffBinding.txtTitleDetailMedis.setText(rekamMedis.getId_Medis());
rekamMedisStaffBinding.txtDetailIdRekamMedis.setText(rekamMedis.getId_Medis());
rekamMedisStaffBinding.txtDetailIdDokterMedis.setText(rekamMedis.getId_dokter());
rekamMedisStaffBinding.txtDetailIdPasienMedis.setText(rekamMedis.getId_pasien());
rekamMedisStaffBinding.txtDetailNamaPasienMedis.setText(rekamMedis.getNama_pasien());
rekamMedisStaffBinding.txtDetailAnasMedis.setText(rekamMedis.getAnastesa());
rekamMedisStaffBinding.txtDetailDiagMedis.setText(rekamMedis.getDiagnosa());
rekamMedisStaffBinding.txtDetailTerapiMedis.setText(rekamMedis.getTerapi());
rekamMedisStaffBinding.txtDetailResepMedis.setText(rekamMedis.getResep());
rekamMedisStaffBinding.txtDetailTanggalMedis.setText(rekamMedis.getTgl_medis());
getNamaDokter = rekamMedis.getNama_dokter();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void exportPdf(){
Dexter.withActivity(this)
.withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
rekamMedisStaffBinding.btnPrintRekamMedis.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
createPDF(Common.getAppPath(DetailRekamMedisStaffActivity.this)+"test_pdf.pdf");
Toast.makeText(DetailRekamMedisStaffActivity.this, "test pencet", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
});
}
void createPDF(String path) {
if (new File(path).exists())
new File(path).delete();
try {
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream(path));
doc.open();
doc.setPageSize(PageSize.A4);
doc.addCreationDate();
doc.addAuthor("Baka");
doc.addCreator("Arvin");
BaseColor CA = new BaseColor(0, 153, 204, 255);
float fontSize = 16.0f;
float valueFontSize = 26.0f;
BaseFont baseFont = BaseFont.createFont("res/font/roboto_black.ttf", "UTF-8", BaseFont.EMBEDDED);
//Title
Font titleFont = new Font(baseFont, 36.0f, Font.NORMAL, BaseColor.BLACK);
addNewItem(doc, "Order Details", Element.ALIGN_CENTER, titleFont);
//Body
Font orderNumber = new Font(baseFont, fontSize, Font.NORMAL, CA);
addNewItem(doc, "Order No:", Element.ALIGN_LEFT, orderNumber);
addLineSeparator(doc);
doc.close();
printPDF();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
private void printPDF() {
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
try {
PrintDocumentAdapter printDocumentAdapter = new PdfDocumentAdapter(DetailRekamMedisStaffActivity.this, Common.getAppPath(DetailRekamMedisStaffActivity.this)+"test_pdf.pdf");
printManager.print("Document", printDocumentAdapter, new PrintAttributes.Builder().build());
} catch (Exception e) {
e.printStackTrace();
}
}
private void addLineSeparator(Document doc) throws DocumentException {
LineSeparator lineSeparator = new LineSeparator();
lineSeparator.setLineColor(new BaseColor(0,0,0,68));
addLineSpace(doc);
doc.add(new Chunk(lineSeparator));
addLineSpace(doc);
}
private void addLineSpace(Document doc) throws DocumentException {
doc.add(new Paragraph(""));
}
private void addNewItem(Document doc, String text, int alignCenter, Font font) throws DocumentException {
Chunk chunk = new Chunk(text, font);
Paragraph paragraph = new Paragraph(chunk);
paragraph.setAlignment(alignCenter);
doc.add(paragraph);
}
}<file_sep>package com.bakarvin.klinikhp.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bakarvin.klinikhp.databinding.ItemRekamMedisBinding;
import com.bakarvin.klinikhp.model.RekamMedis;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MedisAdapter extends RecyclerView.Adapter<MedisAdapter.MedisHolder>{
private final ArrayList<RekamMedis> medisList;
private onAction action;
public MedisAdapter(ArrayList<RekamMedis> medisList) {
this.medisList = medisList;
}
@NonNull
@Override
public MedisHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
ItemRekamMedisBinding itemRekamMedisBinding = ItemRekamMedisBinding.inflate(layoutInflater,parent, false);
return new MedisHolder(itemRekamMedisBinding);
}
@Override
public void onBindViewHolder(@NonNull MedisHolder holder, int position) {
RekamMedis rekamMedis = medisList.get(position);
holder.itemRekamMedisBinding.txtTgl.setText(rekamMedis.getTgl_medis());
holder.itemRekamMedisBinding.txtNamaDokter.setText(rekamMedis.getNama_dokter());
holder.itemRekamMedisBinding.txtNamaPasien.setText(rekamMedis.getNama_pasien());
holder.itemRekamMedisBinding.cardItemMedis.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
action.onActionClick(view, position);
}
});
}
@Override
public int getItemCount() {
return medisList.size();
}
public class MedisHolder extends RecyclerView.ViewHolder {
private final ItemRekamMedisBinding itemRekamMedisBinding;
public MedisHolder(@NonNull ItemRekamMedisBinding itemRekamMedisBinding) {
super(itemRekamMedisBinding.getRoot());
this.itemRekamMedisBinding = itemRekamMedisBinding;
}
}
public interface onAction{
void onActionClick(View v, int position);
}
public void ActionClick(onAction onAction){
action = onAction;
}
}<file_sep>package com.bakarvin.klinikhp.dokter.rekmedis;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.bakarvin.klinikhp.adapter.JadwalDokterAdapter;
import com.bakarvin.klinikhp.adapter.MedisAdapter;
import com.bakarvin.klinikhp.adapter.PasienAdapter;
import com.bakarvin.klinikhp.admin.crud.dokter.DetailDokterActivity;
import com.bakarvin.klinikhp.admin.crud.pasien.DetailPasienActivity;
import com.bakarvin.klinikhp.databinding.ActivityListRekamMedisBinding;
import com.bakarvin.klinikhp.model.JadwalDokter;
import com.bakarvin.klinikhp.model.Pasien;
import com.bakarvin.klinikhp.model.RekamMedis;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import static java.security.AccessController.getContext;
public class ListRekamMedisActivity extends AppCompatActivity {
ActivityListRekamMedisBinding listRekamMedisBinding;
ArrayList<RekamMedis> medisList;
MedisAdapter medisAdapter;
DatabaseReference dbRekam;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listRekamMedisBinding = ActivityListRekamMedisBinding.inflate(getLayoutInflater());
setContentView(listRekamMedisBinding.getRoot());
dbRekam = FirebaseDatabase.getInstance().getReference("RekamMedis");
medisList = new ArrayList<>();
getDataMedis();
// medisList = new ArrayList<>();
// getDataMedis();
listRekamMedisBinding.fabDaftarRekamMedis.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), DaftarRekamMedisActivity.class));
}
});
}
private void getDataMedis() {
dbRekam.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()){
RekamMedis rekamMedis = ds.getValue(RekamMedis.class);
medisList.add(rekamMedis);
}
medisAdapter = new MedisAdapter(medisList);
listRekamMedisBinding.rvListMedis.setAdapter(medisAdapter);
medisAdapter.ActionClick(new MedisAdapter.onAction() {
@Override
public void onActionClick(View v, int position) {
RekamMedis rekamMedis = medisList.get(position);
Intent i = new Intent(getApplicationContext(), DetailRekamMedisDokterActivity.class);
i.putExtra("idMedis",rekamMedis.getId_Medis());
startActivity(i);
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getApplicationContext(), "WTF DB Error", Toast.LENGTH_SHORT).show();
}
});
}
}<file_sep>package com.bakarvin.klinikhp.admin.crud.pasien;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.bakarvin.klinikhp.databinding.ActivityEditPasienBinding;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
public class EditPasienActivity extends AppCompatActivity {
ActivityEditPasienBinding editPasienBinding;
DatabaseReference dbPasien;
DatabaseReference dbEditPasien;
String getKtp;
String getNamaPasien;
String getAlamat;
String getJenkel;
String getUmur;
String getStatus;
String getTelp;
String getIbu;
String getPasangan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editPasienBinding = ActivityEditPasienBinding.inflate(getLayoutInflater());
setContentView(editPasienBinding.getRoot());
dbPasien = FirebaseDatabase.getInstance().getReference().child("Pasien");
getIntentExtra();
editPasienBinding.btnEdtPasien.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditPasien();
}
});
editPasienBinding.imgBackEditPasien.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
private void getIntentExtra() {
getKtp = getIntent().getStringExtra("no_ktp");
getNamaPasien = getIntent().getStringExtra("nama_pasien");
getAlamat = getIntent().getStringExtra("alamat_pasien");
getJenkel = getIntent().getStringExtra("jenkel_pasien");
getUmur = getIntent().getStringExtra("umur_pasien");
getStatus = getIntent().getStringExtra("status_pasien");
getTelp = getIntent().getStringExtra("telp_pasien");
getIbu = getIntent().getStringExtra("ibu_pasien");
getPasangan = getIntent().getStringExtra("pasangan_pasien");
init();
}
private void init() {
editPasienBinding.txtEditKtpPasien.setText(getKtp);
editPasienBinding.txtEditNamaPasien.setText(getNamaPasien);
editPasienBinding.txtEditAlamatPasien.setText(getAlamat);
if (getJenkel.equals("Laki - laki")){
editPasienBinding.spinEditJenkelPasien.setSelection(0);
} else {
editPasienBinding.spinEditJenkelPasien.setSelection(1);
}
editPasienBinding.txtEditUmurPasien.setText(getUmur);
if (getStatus.equals("Menikah")){
editPasienBinding.spinEditStatusPasien.setSelection(0);
}else{
editPasienBinding.spinEditStatusPasien.setSelection(1);
}
editPasienBinding.txtEditTelpPasien.setText(getTelp);
editPasienBinding.txtEditIbuPasien.setText(getIbu);
editPasienBinding.txtEditPasanganPasien.setText(getPasangan);
}
private void EditPasien() {
String no_ktp = editPasienBinding.txtEditKtpPasien.getText().toString();
String nama_pasien = editPasienBinding.txtEditNamaPasien.getText().toString();
String alamat_pasien = editPasienBinding.txtEditAlamatPasien.getText().toString();
String jenkel = editPasienBinding.spinEditJenkelPasien.getSelectedItem().toString();
String umur = editPasienBinding.txtEditUmurPasien.getText().toString();
String status = editPasienBinding.spinEditStatusPasien.getSelectedItem().toString();
String no_hp = editPasienBinding.txtEditTelpPasien.getText().toString();
String nama_ibu = editPasienBinding.txtEditIbuPasien.getText().toString();
String nama_pasangan = editPasienBinding.txtEditPasanganPasien.getText().toString();
if (no_ktp.isEmpty()||nama_pasien.isEmpty()||alamat_pasien.isEmpty()||jenkel.isEmpty()||umur.isEmpty()||
status.isEmpty()||no_hp.isEmpty()||nama_ibu.isEmpty()||nama_pasangan.isEmpty()){
Toast.makeText(getApplicationContext(), "Ada yang Kosong", Toast.LENGTH_SHORT).show();
} else {
dbEditPasien = dbPasien.child(getKtp);
HashMap<String, String> pasienMap = new HashMap<>();
pasienMap.put("no_ktp", no_ktp);
pasienMap.put("nama_pasien", nama_pasien);
pasienMap.put("alamat_pasien", alamat_pasien);
pasienMap.put("jenkel", jenkel);
pasienMap.put("umur", umur);
pasienMap.put("status", status);
pasienMap.put("no_hp", no_hp);
pasienMap.put("nama_ibu", nama_ibu);
if (status.equals("Belum Menikah")){
pasienMap.put("nama_pasangan","-");
} else {
pasienMap.put("nama_pasangan", nama_pasangan);
}
dbEditPasien.setValue(pasienMap).addOnCompleteListener(task -> {
if (task.isSuccessful()){
Log.d("Masuk", "Data berhasil diubah No. KTP = " + no_ktp);
finish();
}
});
}
}
}<file_sep>package com.bakarvin.klinikhp.admin;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.Toast;
import com.bakarvin.klinikhp.Preferences;
import com.bakarvin.klinikhp.R;
import com.bakarvin.klinikhp.admin.fragment.DaftarStaffFragment;
import com.bakarvin.klinikhp.admin.fragment.DokterStaffFragment;
import com.bakarvin.klinikhp.admin.fragment.HomeStaffFragment;
import com.bakarvin.klinikhp.admin.fragment.PasienStaffFragment;
import com.bakarvin.klinikhp.admin.fragment.RekamStaffFragment;
import com.bakarvin.klinikhp.databinding.ActivityMainMenuStaffBinding;
import com.bakarvin.klinikhp.databinding.ItemFilterMedisBinding;
import com.bakarvin.klinikhp.dokter.LoginDokterActivity;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MainMenuStaffActivity extends AppCompatActivity implements View.OnClickListener {
ActivityMainMenuStaffBinding mainMenuStaffBinding;
boolean drawerOpen;
boolean filterMedis;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainMenuStaffBinding = ActivityMainMenuStaffBinding.inflate(getLayoutInflater());
setContentView(mainMenuStaffBinding.getRoot());
drawerOpen = false;
mainMenuStaffBinding.txtTitle.setText("Home");
mainMenuStaffBinding.staffHomeFrag.setOnClickListener(this);
mainMenuStaffBinding.staffDaftarFrag.setOnClickListener(this);
mainMenuStaffBinding.staffDokterFrag.setOnClickListener(this);
mainMenuStaffBinding.staffPasienFrag.setOnClickListener(this);
mainMenuStaffBinding.staffMedisFrag.setOnClickListener(this);
mainMenuStaffBinding.staffLogoutFrag.setOnClickListener(this);
mainMenuStaffBinding.btnFilterRekam.setOnClickListener(this);
mainMenuStaffBinding.btnDrawer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
drawerState();
}
});
loadFrag(new HomeStaffFragment());
}
private boolean loadFrag(Fragment fragment){
if (fragment !=null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.mainFragStaff, fragment)
.addToBackStack(null)
.commit();
return true;
}
return false;
}
void drawerState() {
if (!drawerOpen) {
mainMenuStaffBinding.drawerStaff.openDrawer(Gravity.LEFT);
drawerOpen = true;
} else {
mainMenuStaffBinding.drawerStaff.closeDrawers();
drawerOpen = false;
}
}
void setFilterMedis(){
if (!filterMedis){
mainMenuStaffBinding.btnFilterRekam.setActivated(false);
mainMenuStaffBinding.btnFilterRekam.setVisibility(View.INVISIBLE);
} else {
mainMenuStaffBinding.btnFilterRekam.setActivated(true);
mainMenuStaffBinding.btnFilterRekam.setVisibility(View.VISIBLE);
}
}
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.staffHomeFrag:
loadFrag(new HomeStaffFragment());
mainMenuStaffBinding.txtTitle.setText("Home");
drawerState();
filterMedis = false;
setFilterMedis();
break;
case R.id.staffDaftarFrag:
loadFrag(new DaftarStaffFragment());
mainMenuStaffBinding.txtTitle.setText("Pendaftaran");
drawerState();
filterMedis = false;
setFilterMedis();
break;
case R.id.staffDokterFrag:
loadFrag(new DokterStaffFragment());
mainMenuStaffBinding.txtTitle.setText("List Dokter");
drawerState();
filterMedis = false;
setFilterMedis();
break;
case R.id.staffPasienFrag:
loadFrag(new PasienStaffFragment());
mainMenuStaffBinding.txtTitle.setText("List Pasien");
drawerState();
filterMedis = false;
setFilterMedis();
break;
case R.id.staffMedisFrag:
loadFrag(new RekamStaffFragment());
mainMenuStaffBinding.txtTitle.setText("List Rekam Medis");
drawerState();
filterMedis = true;
setFilterMedis();
break;
case R.id.staffLogoutFrag:
Preferences.clearLoginUser(getBaseContext());
startActivity(new Intent(getApplicationContext(), LoginDokterActivity.class));
break;
}
}
// void openFilter(){
// AlertDialog builder = new AlertDialog.Builder(context).create();
// LayoutInflater layoutInflater = LayoutInflater.from(context);
// ItemFilterMedisBinding filterMedisBinding = ItemFilterMedisBinding.inflate(layoutInflater);
// builder.setView(filterMedisBinding.getRoot());
// builder.show();
// filterMedisBinding.btnMin.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
// @Override
// public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// calendar.set(year, month, dayOfMonth);
// filterMedisBinding.btnMin.setText(simpleDateFormat.format(calendar.getTime()));
// date_minimal = calendar.getTime();
//
// String input1 = filterMedisBinding.btnMin.getText().toString();
// String input2 = filterMedisBinding.btnMax.getText().toString();
// if (input1.isEmpty() || input2.isEmpty()){
// filterMedisBinding.btnApplyFilter.setClickable(false);
// }else {
// filterMedisBinding.btnApplyFilter.setClickable(true);
// }
// }
// }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
// datePickerDialog.show();
// }
// });
// filterMedisBinding.btnMax.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
// @Override
// public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// calendar.set(year, month, dayOfMonth);
// filterMedisBinding.btnMax.setText(simpleDateFormat.format(calendar.getTime()));
// date_maximal = calendar.getTime();
//
// String input1 = filterMedisBinding.btnMin.getText().toString();
// String input2 = filterMedisBinding.btnMax.getText().toString();
// if (input1.isEmpty() || input2.isEmpty()){
// filterMedisBinding.btnApplyFilter.setClickable(false);
// }else {
// filterMedisBinding.btnApplyFilter.setClickable(true);
// }
// }
// }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
// datePickerDialog.show();
// }
// });
// filterMedisBinding.btnApplyFilter.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// String dateMin = filterMedisBinding.btnMin.getText().toString();
// String dateMax = filterMedisBinding.btnMax.getText().toString();
// Bundle bundle = new Bundle();
// bundle.putString(dateMin, "date_minimal");
// bundle.putString(dateMax, "date_maximal");
// RekamStaffFragment medisFrag = new RekamStaffFragment();
// medisFrag.setArguments(bundle);
// Toast.makeText(context, dateMin+" & "+dateMax, Toast.LENGTH_SHORT).show();
//// builder.dismiss();
// }
// });
// }
} | 8358be39c2581d78c47a2f33133458a2def55406 | [
"Java",
"Gradle"
] | 11 | Java | bakarvin/klinikhp | a9afc14bfdb7a9f0487851faf408310a1609f864 | b9298399f65fcf527e607c5538ee3acfd40d20a6 |
refs/heads/master | <file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$hoy = date("Y-m-d H:i:s");
$index = $request->index;
$phy1 = $request->phy1;
$phy2 = $request->phy2;
$phy3 = $request->phy3;
$phy4 = $request->phy4;
$phy5 = $request->phy5;
$phy6 = $request->phy6;
$phy7 = $request->phy7;
$phy8 = $request->phy8;
$phy9 = $request->phy9;
$phy10 = $request->phy10;
$phy11 = $request->phy11;
$phy12 = $request->phy12;
$phy13 = $request->phy13;
$response = mysql_query("UPDATE physics_table
SET
phy1 = '$phy1',
phy2 = '$phy2',
phy3 = '$phy3',
phy4 = '$phy4',
phy5 = '$phy5',
phy6 = '$phy6',
phy7 = '$phy7',
phy8 = '$phy8',
phy9 = '$phy9',
phy10 = '$phy10',
phy11 = '$phy11',
phy12 = '$phy12',
phy13 = '$phy13'
WHERE id = $index");
mysql_close($connection); // Connection Closed
echo $response;
?><file_sep>-- MySQL dump 10.13 Distrib 5.6.24, for osx10.8 (x86_64)
--
-- Host: 127.0.0.1 Database: saludholisticadb
-- ------------------------------------------------------
-- Server version 5.6.21
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `medicamentos`
--
DROP TABLE IF EXISTS `medicamentos`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `medicamentos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(20) DEFAULT NULL,
`medicamento` text,
`date` datetime DEFAULT NULL,
`lastUpdate` datetime DEFAULT NULL,
`medstatus` int(11) DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `medicamentos`
--
LOCK TABLES `medicamentos` WRITE;
/*!40000 ALTER TABLE `medicamentos` DISABLE KEYS */;
INSERT INTO `medicamentos` VALUES (1,'GE10006','ksdc kjdc ksdjcnsuhciwnck djscnkjscksdjcsd update2','2015-08-31 07:21:25','2015-10-01 06:35:23',1,0),(2,'GE10006','acetaminofen update 1','2015-09-04 06:33:04','2015-10-01 06:37:59',1,0),(3,'GE10006','acetaminofen sdcbds jhsbdc jshdbcjhbdsjs','2015-09-04 06:33:18','2015-09-04 06:33:18',1,0),(4,'GE10006','jsbd jcj sdcjhdck jsdckjsdcjsdkcj nksdcs','2015-09-04 06:35:29','2015-10-01 06:38:00',1,0),(5,'GE10006','hcdjcsk jdksjcnksdncksjndckskmdlc dscsdkclsc','2015-09-04 06:39:07','2015-09-04 06:39:07',1,0),(6,'GE10006','qjwn sjqwn sjq shbw ejs qej sjewb sw','2015-09-29 07:24:11','2015-09-29 07:24:11',1,0);
/*!40000 ALTER TABLE `medicamentos` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-10-14 8:14:27
<file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$hoy = date("Y-m-d H:i:s");
$HCId = $request->HCId;
$status = 0;
$result = mysql_query("SELECT * FROM motive_table WHERE HCId = '$HCId' AND status=$status", $connection);
if(!$result || mysql_num_rows($result)==0){
$response = mysql_query("INSERT INTO motive_table
(HCId,
date,
status)
VALUES
('$HCId',
'$hoy',
'$status')"
);
$result = mysql_query("SELECT * FROM motive_table WHERE HCId = '$HCId' AND status=$status", $connection);
}
$row = mysql_fetch_row($result);
mysql_close($connection); // Connection Closed
echo json_encode($row);
?><file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$HCId=$request->HCId;
$Exa=$request->Exa;
$hoy = date("Y-m-d H:i:s");
$status = 0;
$response = mysql_query("INSERT INTO examinations
(HCID,
name,
date,
lastUpdate,
status)
VALUES
('$HCId',
'$Exa',
'$hoy',
'$hoy',
'$status')"
);
$query = mysql_query("SELECT * FROM examinations WHERE HCID= '$HCId'", $connection);
$myarray = array();
while($row = mysql_fetch_assoc($query)){
$id=$row['id'];
$exa = $row['name'];
$res = $row['result'];
$date = $row['date'];
$resdate = $row['resultDate'];
$lastdate = $row['lastUpdate'];
$status = $row['status'];
$myarray[]=array('id'=>$id, 'HCId' =>$HCId, 'name' => $exa, 'res' => $res, 'date' => $date, 'resdate' => $resdate, 'lastdate' => $lastdate, "status" => $status);
}
mysql_close($connection); // Connection Closed
echo json_encode($myarray);
?><file_sep><?php
$connection = mysql_connect ( "localhost", "root", "" ); // Establishing Connection with Server..
$db = mysql_select_db ( "saludholisticadb", $connection ); // Selecting Database
// Fetching Values from URL
$postdata = file_get_contents ( "php://input" );
$request = json_decode ( $postdata );
$Iddocument = $request->Iddocument;
$Idtype = $request->Idtype;
$query = mysql_query("SELECT * FROM personal_data WHERE document = $Iddocument AND documentType = $Idtype ", $connection);
$row = mysql_fetch_row($query);
mysql_close($connection); // Connection Closed
echo json_encode($row);
?><file_sep>SHapp.controller('userCtrl',['$http','$scope','$interval','$q',function($http, $scope, $interval, $q) {
$scope.init = function() {
$scope.Iddocument = null;
$scope.Idtype = null;
$scope.name = null;
$scope.borndate = null;
$scope.bornplace = null;
$scope.civilstate = null;
$scope.gender = null;
$scope.ocupation = null;
$scope.procedencia = null;
$scope.address = null;
$scope.phone = null;
$scope.cellphone = null;
$scope.company = null;
$scope.companyphone = null;
$scope.eps = null;
$scope.religion = null;
$scope.reference = null;
};
$scope.saveData = function() {
if ($scope.Iddocument != null
&& $scope.Iddocument != undefined
&& $scope.Idtype != null
&& $scope.Idtype != undefined
&& $scope.name != null
&& $scope.name != undefined
&& $scope.borndate != null
&& $scope.borndate != undefined
&& $scope.bornplace != null
&& $scope.bornplace != undefined) {
$http.post('datamethods/insertUser.php',{
Iddocument : $scope.Iddocument,
Idtype : $scope.Idtype,
name : $scope.name,
borndate : $scope.borndate,
bornplace : $scope.bornplace,
civilstate : $scope.civilstate,
gender : $scope.gender,
ocupation : $scope.ocupation,
procedencia : $scope.procedencia,
address : $scope.address,
phone : $scope.phone,
cellphone : $scope.cellphone,
company : $scope.company,
companyphone : $scope.companyphone,
eps : $scope.eps,
religion : $scope.religion,
reference : $scope.reference
}).success(function(data, status,headers, config) {
if(data){
$('#UserRegisteredAlert').show();
$scope.DisableFields();
}else{
alert("El Paciente ya existe");
}
}).error(function(data, status,headers, config) {
});
} else {
if ($scope.Iddocument == null
|| $scope.Iddocument == undefined) {
$("#docinput").addClass("has-error");
}
if ($scope.Idtype == null
|| $scope.Idtype == undefined) {
$("#doctypeinput")
.addClass("has-error");
}
if ($scope.name == null
|| $scope.name == undefined) {
$("#nameinput").addClass("has-error");
}
if ($scope.borndate == null
|| $scope.borndate == undefined) {
$("#borndateinput").addClass(
"has-error");
}
if ($scope.bornplace == null
|| $scope.bornplace == undefined) {
$("#bornplaceinput").addClass(
"has-error");
}
}
}
$scope.UpdateData = function() {
$http.post('datamethods/UpdateUser.php',{
Iddocument : $scope.Iddocument,
Idtype : $scope.Idtype,
name : $scope.name,
borndate : $scope.borndate,
bornplace : $scope.bornplace,
civilstate : $scope.civilstate,
gender : $scope.gender,
ocupation : $scope.ocupation,
procedencia : $scope.procedencia,
address : $scope.address,
phone : $scope.phone,
cellphone : $scope.cellphone,
company : $scope.company,
companyphone : $scope.companyphone,
eps : $scope.eps,
religion : $scope.religion,
reference : $scope.reference
}).success(function(data, status,headers, config) {
if(data){
$('#UserUpdatedAlert').show();
$scope.DisableFields();
}else{
alert("qwertye");
}
}).error(function(data, status,headers, config) {
});
}
$scope.SearchPatient = function() {
$http.post('datamethods/SearchUser.php',{
Iddocument : $scope.Iddocument,
Idtype : $scope.Idtype
}).success(function(data, status,headers, config) {
if(data == "false" || data == null || data == undefined){
$('#UserNotFoundAlert').show();
}else{
$scope.FillPatientData(data);
$scope.DisableFields();
}
}).error( function(data, status,headers, config) {
});
}
$scope.FillPatientData = function(data) {
var BornDate = new Date(data[4]);
$scope.name = data[3];
$scope.bornday = BornDate.getDate()+1;
$scope.bornmonth = BornDate.getMonth()+1;
$scope.bornyear = BornDate.getFullYear();
$scope.bornplace = data[5];
$scope.civilstate = data[6];
$scope.gender = data[7];
if($scope.gender == 0){
$("#GenreBtn").text("Masculino");
}
else
{
$("#GenreBtn").text("Femenino");
}
$scope.ocupation = data[8];
$scope.procedencia = data[9];
$scope.address = data[10];
$scope.phone = data[11];
$scope.cellphone = data[12];
$scope.company = data[13];
$scope.companyphone = data[14];
$scope.eps = data[15];
$scope.religion = data[16];
$scope.reference = data[17];
$scope.regdate = data[18];
$scope.update = data[19];
$('#regdates').css('display', 'block');
}
$scope.DisableFields = function(){
$('#pac-doc').attr('disabled', true);
$('#DocTypeDD').attr('disabled', true);
$('#pac-name').attr('disabled', true);
$('#hc-bornday').attr('disabled', true);
$('#hc-bornmonth').attr('disabled', true);
$('#hc-bornyear').attr('disabled', true);
$('#hc-age').attr('disabled', true);
$('#hc-bornplace').attr('disabled', true);
$('#pac-civil').attr('disabled', true);
$('#GenreDD').attr('disabled', true);
$('#Savebtn').css('display', 'none');
$('#Updatebtn').css('display', 'block');
$('#hisclinic').css('display', 'block');
$scope.GetHcInfo();
}
$scope.GetHcInfo = function(){
$http.post('datamethods/GetHcInfo.php',{
Iddocument : $scope.Iddocument,
Idtype : $scope.Idtype
}).success(function(data, status,headers, config) {
$scope.hcdata=data;
}).error( function(data, status,headers, config) {
});
}
$scope.AddHC = function(){
$http.post('datamethods/AddHC.php',{
Iddocument : $scope.Iddocument,
Idtype : $scope.Idtype
}).success(function(data, status,headers, config) {
window.location.href = "HClinicaGeneral.php?id=" + $scope.Iddocument +"&type="+$scope.Idtype+"&HCId="+data;
}).error( function(data, status,headers, config) {
});
}
$scope.OpenHC = function(id){
window.location.replace("http://localhost/saludholistica/HClinicaGeneral.php?id=" + $scope.Iddocument +"&type="+$scope.Idtype+"&HCId="+id);
}
$scope.$watch('bornday', function() {
if ($scope.bornday != null
&& $scope.bornday != undefined
&& $scope.bornmonth != null
&& $scope.bornmonth != undefined
&& $scope.bornyear != null
&& $scope.bornyear != undefined) {
$scope.calcAge();
$scope.borndate = new Date($scope.bornyear,
$scope.bornmonth, $scope.bornday);
}
;
});
$scope.$watch('bornmonth', function() {
if ($scope.bornday != null
&& $scope.bornday != undefined
&& $scope.bornmonth != null
&& $scope.bornmonth != undefined
&& $scope.bornyear != null
&& $scope.bornyear != undefined) {
$scope.calcAge();
$scope.borndate = new Date($scope.bornyear,
$scope.bornmonth, $scope.bornday);
}
;
});
$scope.$watch('bornyear', function() {
if ($scope.bornday != null
&& $scope.bornday != undefined
&& $scope.bornmonth != null
&& $scope.bornmonth != undefined
&& $scope.bornyear != null
&& $scope.bornyear != undefined) {
$scope.calcAge();
$scope.borndate = new Date($scope.bornyear,
$scope.bornmonth - 1,
$scope.bornday);
}
;
});
$scope.calcAge = function() {
var now = new Date();
var yearNow = now.getYear() + 1900;
var monthNow = now.getMonth() + 1;
var dateNow = now.getDate();
var years = yearNow - parseInt($scope.bornyear);
var months = monthNow
- parseInt($scope.bornmonth);
var days = dateNow - parseInt($scope.bornday);
var bdays = parseInt($scope.bornday);
var byears = parseInt($scope.bornyear);
var bmonths = parseInt($scope.bornmonth) - 1;
var bdate = new Date(byears, bmonths, bdays);
$scope.borndate = String(bdate);
if (months < 0) {
$scope.age = years - 1;
} else if (months == 0) {
if (days < 0) {
$scope.age = years - 1;
} else {
$scope.age = years;
}
} else if (months > 0) {
$scope.age = years;
}
}
} ]);<file_sep><?php
echo "test test test test";
phpinfo();
?><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Historia Clinica - Salud Holistica</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/HCGeneral.css">
<?php
$document = $_GET["id"];
$type = $_GET["type"];
$hcid = $_GET["HCId"];
?>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body ng-app="SHapp">
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> <span
class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="user.php">Salud Holistica</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse"
id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-expanded="false">Agenda<span
class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="index.php">General</a></li>
<li><a href="agendaodonto.php">Odontologia</a></li>
<!-- <li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
<li class="divider"></li>
<li><a href="#">One more separated link</a></li> -->
</ul></li>
<li class="active"><a href="user.php">Historia Clinica</a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<div class="container" ng-controller="HCCtrl" ng-init="init('<?php echo $document?>', '<?php echo $type?>', '<?php echo $hcid?>')">
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><a href="#motivetab" aria-controls="home" role="tab" data-toggle="tab">Motivo de consulta</a></li>
<li role="presentation"><a href="#systemstab" aria-controls="profile" role="tab" data-toggle="tab">Revision por sistemas</a></li>
<li role="presentation"><a href="#symptomstab" aria-controls="messages" role="tab" data-toggle="tab">Sintomas generales</a></li>
<li role="presentation"><a href="#backgroundtab" aria-controls="settings" role="tab" data-toggle="tab">Antecedentes</a></li>
<li role="presentation"><a href="#physictab" aria-controls="settings" role="tab" data-toggle="tab">Examen fisico</a></li>
<li role="presentation"><a href="#analisystab" aria-controls="analisys" role="tab" data-toggle="tab">Analisis de sintomas</a></li>
<li role="presentation"><a href="#diagtab" aria-controls="analisys" role="tab" data-toggle="tab">Diagnostico</a></li>
<li role="presentation"><a href="#conductab" aria-controls="analisys" role="tab" data-toggle="tab">Conducta</a></li>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="motivetab">
<div class="container">
<div class="row fieldrow">
<div class="col-sm-11 form-group" id="Motivetext">
<label for="pac-name" class="control-label">Motivo de la consulta</label>
<textarea class="form-control" rows="5" id="Motive" ng_model="motive" ng_change="UpdateMotive()"></textarea>
</div>
<div class="col-sm-11 form-group" id="Symptomtext">
<label for="pac-name" class="control-label">Sintomas</label>
<textarea class="form-control" rows="5" id="Motive" ng_model="symptom" ng_change="UpdateMotive()"></textarea>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="systemstab">
<div class="container">
<div class="row fieldrow">
<div class="col-sm-3 form-group" id="headtext">
<label for="pac-name" class="control-label">Cabeza</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys1" ng_change="UpdateSystem()"></textarea>
</div>
<div class="col-sm-3 form-group" id="eyestext">
<label for="pac-name" class="control-label">Ojos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys2" ng_change="UpdateSystem()"></textarea>
</div>
<div class="col-sm-3 form-group" id="orltext">
<label for="pac-name" class="control-label">ORL</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys3" ng_change="UpdateSystem()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-3 form-group" id="mouthtext">
<label for="pac-name" class="control-label">Boca</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys4" ng_change="UpdateSystem()"></textarea>
</div>
<div class="col-sm-3 form-group" id="necktext">
<label for="pac-name" class="control-label">Cuello</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys5" ng_change="UpdateSystem()"></textarea>
</div>
<div class="col-sm-3 form-group" id="cptext">
<label for="pac-name" class="control-label">C/P</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys6" ng_change="UpdateSystem()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-3 form-group" id="digesttext">
<label for="pac-name" class="control-label">Digestivo</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys7" ng_change="UpdateSystem()"></textarea>
</div>
<div class="col-sm-3 form-group" id="gutext">
<label for="pac-name" class="control-label">G/U</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys8" ng_change="UpdateSystem()"></textarea>
</div>
<div class="col-sm-3 form-group" id="endotext">
<label for="pac-name" class="control-label">Endocrino</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys9" ng_change="UpdateSystem()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-3 form-group" id="neurotext">
<label for="pac-name" class="control-label">Neurologico</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys10" ng_change="UpdateSystem()"></textarea>
</div>
<div class="col-sm-3 form-group" id="osteotext">
<label for="pac-name" class="control-label">Osteoarticular</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys11" ng_change="UpdateSystem()"></textarea>
</div>
<div class="col-sm-3 form-group" id="muscletext">
<label for="pac-name" class="control-label">Musculo - esqueletico</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="sys12" ng_change="UpdateSystem()"></textarea>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="symptomstab">
<div class="container">
<div class="row fieldrow">
<div class="col-sm-3 form-group" id="wishestext">
<label for="pac-name" class="control-label">Deseos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="symptom1" ng_change="UpdateSymptom()"></textarea>
</div>
<div class="col-sm-3 form-group" id="averstext">
<label for="pac-name" class="control-label">Aversiones</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="symptom2" ng_change="UpdateSymptom()"></textarea>
</div>
<div class="col-sm-3 form-group" id="thirsttext">
<label for="pac-name" class="control-label">Sed</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="symptom3" ng_change="UpdateSymptom()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-3 form-group" id="heathtext">
<label for="pac-name" class="control-label">Calor Vital</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="symptom4" ng_change="UpdateSymptom()"></textarea>
</div>
<div class="col-sm-3 form-group" id="transptext">
<label for="pac-name" class="control-label">Transpiracion</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="symptom5" ng_change="UpdateSymptom()"></textarea>
</div>
<div class="col-sm-3 form-group" id="dreamstext">
<label for="pac-name" class="control-label">Sue�o y sue�os</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="symptom6" ng_change="UpdateSymptom()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-6 form-group" id="mental">
<label for="pac-name" class="control-label">Sintomas mentales</label>
<textarea class="form-control" rows="4" id="Motive" ng_model="symptom7" ng_change="UpdateSymptom()"></textarea>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="backgroundtab">
<div class="container">
<div class="row fieldrow">
<h3>PERSONALES</h3>
<div class="col-sm-3 form-group" id="medicaltext">
<label for="pac-name" class="control-label">Medico - quirurjicos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back1" ng_change="UpdateBackGround()"></textarea>
</div>
<div class="col-sm-3 form-group" id="ginecotext">
<label for="pac-name" class="control-label">Gineco - obstetricos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back2" ng_change="UpdateBackGround()"></textarea>
</div>
<div class="col-sm-3 form-group" id="traumatext">
<label for="pac-name" class="control-label">Traumaticos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back3" ng_change="UpdateBackGround()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-3 form-group" id="habitstext">
<label for="pac-name" class="control-label">Habitos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back4" ng_change="UpdateBackGround()"></textarea>
</div>
<div class="col-sm-3 form-group" id="venerealtext">
<label for="pac-name" class="control-label">Venereas</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back5" ng_change="UpdateBackGround()"></textarea>
</div>
<div class="col-sm-3 form-group" id="pharmatext">
<label for="pac-name" class="control-label">Farmacologicos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back6" ng_change="UpdateBackGround()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-3 form-group" id="toxictext">
<label for="pac-name" class="control-label">Toxicoalergicos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back7" ng_change="UpdateBackGround()"></textarea>
</div>
<div class="col-sm-3 form-group" id="psicotext">
<label for="pac-name" class="control-label">Psicologicos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back8" ng_change="UpdateBackGround()"></textarea>
</div>
</div>
<div class="row fieldrow">
<h3>FAMILIARES</h3>
<div class="col-sm-4 form-group" id="parentstext">
<label for="pac-name" class="control-label">Padres</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back9" ng_change="UpdateBackGround()"></textarea>
</div>
<div class="col-sm-4 form-group" id="grandstext">
<label for="pac-name" class="control-label">Abuelos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back10" ng_change="UpdateBackGround()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-4 form-group" id="unclestext">
<label for="pac-name" class="control-label">Tios</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back11" ng_change="UpdateBackGround()"></textarea>
</div>
<div class="col-sm-4 form-group" id="brotherstext">
<label for="pac-name" class="control-label">Hermanos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back12" ng_change="UpdateBackGround()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-6 form-group" id="biopattext">
<label for="pac-name" class="control-label">BIOPATOGRAFIA</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="back13" ng_change="UpdateBackGround()"></textarea>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="physictab">
<div class="container">
<div class="row fieldrow">
<div class="col-sm-2 form-group" id="tatext">
<label for="pac-name" class="control-label">TA</label>
<input type="text" class="form-control" placeholder="" name="" id="pac-doc" ng-model="phy1" ng-change="UpdatePhysic()">
</div>
<div class="col-sm-2 form-group" id="fctext">
<label for="pac-name" class="control-label">FC</label>
<input type="text" class="form-control" placeholder="" name="" id="pac-doc" ng-model="phy2" ng-change="UpdatePhysic()">
</div>
<div class="col-sm-2 form-group" id="frtext">
<label for="pac-name" class="control-label">FR</label>
<input type="text" class="form-control" placeholder="" name="" id="pac-doc" ng-model="phy3" ng-change="UpdatePhysic()">
</div>
<div class="col-sm-2 form-group" id="ttext">
<label for="pac-name" class="control-label">T</label>
<input type="text" class="form-control" placeholder="" name="" id="pac-doc" ng-model="phy4" ng-change="UpdatePhysic()">
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-2 form-group" id="pstext">
<label for="pac-name" class="control-label">Ps</label>
<input type="text" class="form-control" placeholder="" name="" id="pac-doc" ng-model="phy5" ng-change="UpdatePhysic()">
</div>
<div class="col-sm-2 form-group" id="tltext">
<label for="pac-name" class="control-label">Tl</label>
<input type="text" class="form-control" placeholder="" name="" id="pac-doc" ng-model="phy6" ng-change="UpdatePhysic()">
</div>
<div class="col-sm-2 form-group" id="pstext">
<label for="pac-name" class="control-label">P. abdominal</label>
<input type="text" class="form-control" placeholder="" name="" id="pac-doc" ng-model="phy7" ng-change="UpdatePhysic()">
</div>
<div class="col-sm-2 form-group" id="tltext">
<label for="pac-name" class="control-label">P. cadera</label>
<input type="text" class="form-control" placeholder="" name="" id="pac-doc" ng-model="phy8" ng-change="UpdatePhysic()">
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-2 form-group" id="imctext">
<label for="pac-name" class="control-label">IMC</label>
<input type="text" class="form-control" placeholder="" name="" id="pac-doc" ng-model="phy12" ng-change="UpdatePhysic()">
</div>
<div class="col-sm-2 form-group" id="icctext">
<label for="pac-name" class="control-label">ICC</label>
<input type="text" class="form-control" placeholder="" name="" id="pac-doc" ng-model="phy13" ng-change="UpdatePhysic()">
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-3 form-group" id="generaltext">
<label for="pac-name" class="control-label">Estado general</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="phy9" ng_change="UpdatePhysic()"></textarea>
</div>
<div class="col-sm-3 form-group" id="acttext">
<label for="pac-name" class="control-label">Actitud del enfermo</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="phy10" ng_change="UpdatePhysic()"></textarea>
</div>
<div class="col-sm-3 form-group" id="findtext">
<label for="pac-name" class="control-label">Hallazgos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="phy11" ng_change="UpdatePhysic()"></textarea>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="analisystab">
<div class="container">
<div class="row fieldrow">
<div class="col-sm-6 form-group" id="restext">
<label for="pac-name" class="control-label">Resumen de sintomas caracteristicos</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="ana1" ng_change="UpdateAnalisys()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-6 form-group" id="reperttext">
<label for="pac-name" class="control-label">Sintomas a repertorizar</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="ana2" ng_change="UpdateAnalisys()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-6 form-group" id="repertresultext">
<label for="pac-name" class="control-label">Resultado de la repertorizacion</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="ana3" ng_change="UpdateAnalisys()"></textarea>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="diagtab">
<div class="container">
<div class="row fieldrow">
<div class="col-sm-5 form-group" id="restext">
<label for="pac-name" class="control-label">Nosologico</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="diag1" ng_change="UpdateDiag()"></textarea>
</div>
<div class="col-sm-5 form-group" id="reperttext">
<label for="pac-name" class="control-label">Miasmatico</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="diag2" ng_change="UpdateDiag()"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-5 form-group" id="reperttext">
<label for="pac-name" class="control-label">Integral</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="diag3" ng_change="UpdateDiag()"></textarea>
</div>
<div class="col-sm-5 form-group" id="reperttext">
<label for="pac-name" class="control-label">Medicamentoso</label>
<textarea class="form-control" rows="2" id="Motive" ng_model="diag4" ng_change="UpdateDiag()"></textarea>
</div>
</div>
<div class="row fieldrow">
<h3>CIE 10</h3>
<div class="col-sm-12">
<div class="col-sm-1 form-group" id="docinput">
<label for="pac-name" class="control-label">Codigo</label> <input
type="text" class="form-control" placeholder="" name="name"
id="pac-doc" ng-model="ciecode" required>
</div>
<div class="col-sm-4 form-group" id="docinput">
<label for="pac-name" class="control-label">Nombre</label> <input
type="text" class="form-control" placeholder="" name="name"
id="pac-doc" ng-model="ciename" required>
</div>
<button type="button" class="btn btn-default" id="SearchDoc"
ng-click="SearchCie()">
<span class="glyphicon glyphicon-search"></span>
</button>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-6">
<table class="table">
<tr>
<th></th>
<th>CODIGO</th>
<th>DESCRIPCION</th>
<th>SEXO</th>
<th>MIN</th>
<th>MAX</th>
<th>NOMAIN</th>
<th>OBSERVACIONES</th>
</tr>
<tr ng-repeat="model in Ciedata">
<td><input type="checkbox" ></td>
<td>{{model.code}}</td>
<td>{{model.name}}</td>
<td>{{model.sex}}</td>
<td>{{model.min}}</td>
<td>{{model.max}}</td>
<td>{{model.nomain}}</td>
<td>{{model.obs}}</td>
<td></td>
</tr>
</table>
</div>
</div>
<div class="col-sm-6">
<ul>
<li ng-repeat="model in Ciecodes">
</ul>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="conductab">
<div class="row fieldrow">
<div class="col-sm-12">
<div class="container">
<!-- row medicamentos -->
<div class="row">
<div class="col-sm-9 col-sm-offset-1">
<div class="panel panel-default medpanel">
<div class="panel-heading">
<h3 class="panel-title">Medicamentos</h3>
</div>
<div class="panel-body">
<div class="row">
<table class="table">
<tr>
<th>DESCRIPCION</th>
<th>FECHA FORMULACION</th>
<th>FECHA ULTIMA MODIFICACION</th>
<th>ESTADO</th>
<th class="col-sm-3">ACCIONES</th>
</tr>
<tr ng-repeat="model in meddata">
<td>{{model.med}}</td>
<td>{{model.date}}</td>
<td>{{model.lastdate}}</td>
<td>{{model.wordstatus}}</td>
<td><button type="button" class="btn btn-warning btn-xs medstat" ng-click="UpdMedStt(model.id, 0)" ng-show="model.medstatus==1">
Suspender
</button>
<button type="button" class="btn btn-success btn-xs medstat" ng-click="UpdMedStt(model.id, 1)" ng-show="model.medstatus==0">
Activar
</button>
<button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#medModalUpdate" data-id="{{model.id}}" data-med="{{model.med}}">
Modificar
</button>
</td>
</tr>
</table>
</div>
<div class="col-sm-3 col-sm-offset-2">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#medModal">
Agregar
</button>
</div>
<div class="col-sm-3 col-sm-offset-2">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#medModal">
imprimir
</button>
</div>
</div>
</div>
</div>
</div>
<!-- row examenes -->
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="panel panel-default medpanel">
<div class="panel-heading">
<h3 class="panel-title">Examenes Medicos</h3>
</div>
<div class="panel-body">
<div class="row">
<table class="table">
<tr>
<th>EXAMEN</th>
<th>RESULTADO</th>
<th>FECHA FORMULACION</th>
<th>FECHA RESULTADO</th>
<th>FECHA ULTIMA MODIFICACION</th>
<th>ACCIONES</th>
</tr>
<tr ng-repeat="model in exadata">
<td>{{model.name}}</td>
<td>{{model.res}}</td>
<td>{{model.date}}</td>
<td>{{model.resdate}}</td>
<td>{{model.lastdate}}</td>
<td><button type="button" class="btn btn-warning btn-xs" ng-show="model.res=='' || model.res == null" data-toggle="modal" data-target="#exaupdModal" ng-click="setexachange(model.id,model.name,model.res)">
Agregar Resultado
</button>
<button type="button" class="btn btn-primary btn-xs" ng-hide="model.res=='' || model.res == null" data-toggle="modal" data-target="#exaupdModal" ng-click="setexachange(model.id,model.name,model.res)">
Actualizar
</button>
</td>
</tr>
</table>
</div>
<div class="col-sm-3 col-sm-offset-2">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#exaModal">
Agregar
</button>
</div>
<div class="col-sm-3 col-sm-offset-2">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exaModal">
imprimir
</button>
</div>
</div>
</div>
</div>
</div>
<!-- row Recomendaciones -->
<div class="row">
<div class="col-sm-9 col-sm-offset-1">
<div class="panel panel-default medpanel">
<div class="panel-heading">
<h3 class="panel-title">Recomendaciones</h3>
</div>
<div class="panel-body">
<div class="row">
<table class="table">
<tr>
<th>DESCRIPCION</th>
<th>FECHA FORMULACION</th>
<th>FECHA ULTIMA MODIFICACION</th>
<th>ESTADO</th>
<th class="col-sm-3">ACCIONES</th>
</tr>
<tr ng-repeat="model in recdata">
<td>{{model.rec}}</td>
<td>{{model.date}}</td>
<td>{{model.lastdate}}</td>
<td>{{model.wordstatus}}</td>
<td><button type="button" class="btn btn-warning btn-xs recstat" ng-click="UpdRecStt(model.id, 0)" ng-show="model.recstatus==1">
Suspender
</button>
<button type="button" class="btn btn-success btn-xs recstat" ng-click="UpdRecStt(model.id, 1)" ng-show="model.recstatus==0">
Activar
</button>
<button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#recModalUpdate" data-id="{{model.id}}" data-rec="{{model.rec}}">
Modificar
</button>
</td>
</tr>
</table>
</div>
<div class="col-sm-3 col-sm-offset-2">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#recModal">
Agregar
</button>
</div>
<div class="col-sm-3 col-sm-offset-2">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#recModal">
imprimir
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-3 col-sm-offset-2">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">
Finalizar
</button>
</div>
<div class="col-sm-3 col-sm-offset-3" >
<button type="button" class="btn btn-primary" ng-click="Imprimir()">
Imprimir
</button>
</div>
</div>
</div>
</div>
</div>
<!-- medmodal -->
<div class="modal fade" id="medModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Agregar Medicamento</h4>
</div>
<div class="modal-body">
<div class="row fieldrow">
<div class="col-sm-11 form-group" id="">
<textarea class="form-control" rows="2" id="addmedtxt" ng_model="medAdded"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" ng-click="AddMed()">Agregar</button>
</div>
</div>
</div>
</div>
<!-- medmodalUpdate -->
<div class="modal fade" id="medModalUpdate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Actualizar Medicamento</h4>
</div>
<div class="modal-body">
<div class="row fieldrow">
<div class="col-sm-11 form-group" id="">
<textarea class="form-control" rows="2" id="medtxtupt" ng-model="medtxtupt"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<input type="hidden" id="medIdupt" value="" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" ng-click="UpdMed()">Actualizar</button>
</div>
</div>
</div>
</div>
<!-- recmodal -->
<div class="modal fade" id="recModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Agregar Recomendación</h4>
</div>
<div class="modal-body">
<div class="row fieldrow">
<div class="col-sm-11 form-group" id="">
<textarea class="form-control" rows="2" id="addrectxt" ng_model="recAdded"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" ng-click="AddRec()">Agregar</button>
</div>
</div>
</div>
</div>
<!-- recmodalUpdate -->
<div class="modal fade" id="recModalUpdate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Actualizar Recomendación</h4>
</div>
<div class="modal-body">
<div class="row fieldrow">
<div class="col-sm-11 form-group" id="">
<textarea class="form-control" rows="2" id="rectxtupt" ng-model="rectxtupt"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<input type="hidden" id="recIdupt" value="" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" ng-click="UpdRec()">Actualizar</button>
</div>
</div>
</div>
</div>
<!-- examodal -->
<div class="modal fade" id="exaModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Agregar examen medico</h4>
</div>
<div class="modal-body">
<div class="row fieldrow">
<div class="col-sm-11 form-group" id="">
<label for="addexanametxt" class="control-label">Nombre</label>
<textarea class="form-control" rows="2" id="addexanametxt" ng_model="exaname"></textarea>
</div>
</div>
<!-- <div class="row fieldrow"> -->
<!-- <div class="col-sm-11 form-group" id=""> -->
<!-- <label for="addexarestxt" class="control-label">Resultado</label> -->
<!-- <textarea class="form-control" rows="2" id="addexarestxt" ng_model="exares"></textarea> -->
<!-- </div> -->
<!-- </div> -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" ng-click="AddExa()">Agregar</button>
</div>
</div>
</div>
</div>
<!-- exaupdmodal -->
<div class="modal fade" id="exaupdModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Actualizar examen medico</h4>
</div>
<div class="modal-body">
<div class="row fieldrow">
<div class="col-sm-11 form-group" id="">
<label for="addexanametxt" class="control-label">Nombre</label>
<textarea class="form-control" rows="2" id="addexanametxt" ng_model="exaname"></textarea>
</div>
</div>
<div class="row fieldrow">
<div class="col-sm-11 form-group" id="">
<label for="addexarestxt" class="control-label">Resultado</label>
<textarea class="form-control" rows="2" id="addexarestxt" ng_model="exares"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" ng-click="UpdExa()">Actualizar</button>
</div>
</div>
</div>
</div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/messages_es.min.js"></script>
<script src="js/angular.min.js"></script>
<script src="js/general.js"></script>
<script src="js/app/HCCtrl.js"></script>
<script src="js/user.js"></script>
<script src="js/HC.js"></script>
<script>
$("#commentForm").validate();
</script>
</body>
</html><file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect ( "localhost", "root", "" ); // Establishing Connection with Server..
$db = mysql_select_db ( "saludholisticadb", $connection ); // Selecting Database
// Fetching Values from URL
$postdata = file_get_contents ( "php://input" );
$request = json_decode ( $postdata );
$HCId = $request->HCId;
$id = $request->id;
$res = $request->res;
$name = $request->name;
$hoy = date("Y-m-d H:i:s");
$result = mysql_query("UPDATE examinations SET
name = '$name',
result = '$res',
resultDate = '$hoy',
lastUpdate = '$hoy'
WHERE id = '$id'");
$query = mysql_query("SELECT * FROM examinations WHERE HCID= '$HCId'", $connection);
$myarray = array();
while($row = mysql_fetch_assoc($query)){
$id=$row['id'];
$exa = $row['name'];
$res = $row['result'];
$date = $row['date'];
$resdate = $row['resultDate'];
$lastdate = $row['lastUpdate'];
$status = $row['status'];
$myarray[]=array('id'=>$id, 'HCId' =>$HCId, 'name' => $exa, 'res' => $res, 'date' => $date, 'resdate' => $resdate, 'lastdate' => $lastdate, "status" => $status);
}
mysql_close($connection); // Connection Closed
echo json_encode($myarray);
?><file_sep>-- MySQL dump 10.13 Distrib 5.6.24, for osx10.8 (x86_64)
--
-- Host: 127.0.0.1 Database: saludholisticadb
-- ------------------------------------------------------
-- Server version 5.6.21
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `symptons_table`
--
DROP TABLE IF EXISTS `symptons_table`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `symptons_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(20) NOT NULL,
`symptom1` text,
`symptom2` text,
`symptom3` text,
`symptom4` text,
`symptom5` text,
`symptom6` text,
`symptom7` text,
`date` datetime DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `symptons_table`
--
LOCK TABLES `symptons_table` WRITE;
/*!40000 ALTER TABLE `symptons_table` DISABLE KEYS */;
INSERT INTO `symptons_table` VALUES (2,'GE10001','normales','ascddscsc','csdcsdc','vvfgbf','dwqdqw','xas asd asd asd as asd a','dscs sdfsfd sdfsjkdf skjdnf ksjdnfk sndkfjn ksdjsd','2015-08-18 10:50:36',0),(3,'',NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-18 14:20:45',0),(4,'GE10002',NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-18 14:22:09',0),(5,'GE10003',NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-18 17:22:23',0),(6,'GE10004','xbjadhsbx','','','','asjhbx jabhsjsx','','jahbsx jabjxhadbxjdghciwuehi wekjkwjeb djwbe weew','2015-08-18 18:33:12',0),(7,'GE10005',NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-18 18:45:40',0),(8,'GE10006',NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-31 05:55:57',0),(9,'GE10008',NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-09-04 05:20:19',0);
/*!40000 ALTER TABLE `symptons_table` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-10-14 8:14:28
<file_sep><?php
$connection = mysql_connect ( "localhost", "root", "" ); // Establishing Connection with Server..
$db = mysql_select_db ( "saludholisticadb", $connection ); // Selecting Database
// Fetching Values from URL
$postdata = file_get_contents ( "php://input" );
$request = json_decode ( $postdata );
if (!empty($request->code)) {
$code = "%".$request->code."%";
}else{
$code="%%";
}
if (!empty($request->ciename)) {
$nametxt = "%".$request->ciename."%";
}else{
$nametxt = "%%";
}
if($code != "%%" && $nametxt != "%%"){
$query = mysql_query("SELECT * FROM cie10 WHERE codigo LIKE '$code' OR descripcion LIKE '$nametxt' ", $connection);
}
if($code == "%%" && $nametxt != "%%"){
$query = mysql_query("SELECT * FROM cie10 WHERE descripcion LIKE '$nametxt' ", $connection);
}elseif ($nametxt =="%%" && $code != "%%"){
$query = mysql_query("SELECT * FROM cie10 WHERE codigo LIKE '$code' ", $connection);
}
$myarray = array();
while($row = mysql_fetch_assoc($query)){
$codigo=$row['codigo'];
$nombre = $row['descripcion'];
$sexo = $row['sexo'];
$min = $row['min'];
$max = $row['max'];
$nomain = $row['no_main'];
$obs = $row['obs'];
$myarray[]=array('code'=>$codigo, 'name' =>$nombre, 'sex' => $sexo, 'min' => $min, "max" => $max, "nomain" => $nomain, 'obs'=>$obs);
}
mysql_close($connection); // Connection Closed
echo json_encode($myarray);
?><file_sep><?php
require_once('connector/scheduler_connector.php');
include ('config.php');
$scheduler = new schedulerConnector($res, $dbtype);
$scheduler->render_table("schedule_odonto","id","start_date,end_date,text,name,phone");
?><file_sep>-- MySQL dump 10.13 Distrib 5.6.24, for osx10.8 (x86_64)
--
-- Host: 127.0.0.1 Database: saludholisticadb
-- ------------------------------------------------------
-- Server version 5.6.21
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `recomendaciones`
--
DROP TABLE IF EXISTS `recomendaciones`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recomendaciones` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(20) DEFAULT NULL,
`recomendacion` text,
`date` datetime DEFAULT NULL,
`lastUpdate` datetime DEFAULT NULL,
`recstatus` int(11) DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `recomendaciones`
--
LOCK TABLES `recomendaciones` WRITE;
/*!40000 ALTER TABLE `recomendaciones` DISABLE KEYS */;
INSERT INTO `recomendaciones` VALUES (7,'GE10006','jhabsx jbdhsjch sdjbchjsdcs','2015-10-01 07:42:54','2015-10-01 08:01:12',1,0),(8,'GE10006','frb jdfvbdhjvbd hfvdfvdf','2015-10-01 07:45:25','2015-10-01 08:01:34',0,0),(9,'GE10006','agfscxhsg vchxsdgv chgsdvcsd','2015-10-01 07:46:35','2015-10-01 08:03:46',1,0),(10,'GE10006','jahsbxjabh sxahjxabhsjbhx ajhsbx jasx update 1','2015-10-01 07:49:12','2015-10-01 08:03:33',1,0);
/*!40000 ALTER TABLE `recomendaciones` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-10-14 8:14:27
<file_sep>-- MySQL dump 10.13 Distrib 5.6.24, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: saludholisticadb
-- ------------------------------------------------------
-- Server version 5.6.25
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `physics_table`
--
DROP TABLE IF EXISTS `physics_table`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `physics_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(20) NOT NULL,
`phy1` text,
`phy2` text,
`phy3` text,
`phy4` text,
`phy5` text,
`phy6` text,
`phy7` text,
`phy8` text,
`phy9` text,
`phy10` text,
`phy11` text,
`phy12` text,
`phy13` text,
`date` datetime DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-08-18 12:21:24
<file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect ( "localhost", "root", "" ); // Establishing Connection with Server..
$db = mysql_select_db ( "saludholisticadb", $connection ); // Selecting Database
// Fetching Values from URL
$postdata = file_get_contents ( "php://input" );
$request = json_decode ( $postdata );
$medId = $request->MedId;
$medtxt = $request->medtxt;
$HCId = $request->HCId;
$hoy = date("Y-m-d H:i:s");
$result = mysql_query("UPDATE medicamentos SET
medicamento = '$medtxt',
lastUpdate = '$hoy'
WHERE id = '$medId'");
$query = mysql_query("SELECT * FROM medicamentos WHERE HCId = '$HCId'", $connection);
$myarray = array();
while($row = mysql_fetch_assoc($query)){
$medId=$row['id'];
$medicamento=$row['medicamento'];
$date = $row['date'];
$lastdate = $row['lastUpdate'];
$medstatus = $row['medstatus'];
$status = $row['status'];
if($medstatus==0){
$wordstatus = "Suspendido";
}else{
$wordstatus = "Activo";
}
$myarray[]=array('id' => $medId, 'med'=>$medicamento, 'date' =>$date, 'lastdate' => $lastdate, 'medstatus' => $medstatus , "wordstatus" => $wordstatus , 'status' => $status);
}
mysql_close($connection); // Connection Closed
echo json_encode($myarray);
?><file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$hoy = date("Y-m-d H:i:s");
$index = $request->index;
$ana1 = $request->ana1;
$ana2 = $request->ana2;
$ana3 = $request->ana3;
$response = mysql_query("UPDATE analisys_table
SET
ana1 = '$ana1',
ana2 = '$ana2',
ana3 = '$ana3'
WHERE id = $index");
mysql_close($connection); // Connection Closed
echo $response;
?><file_sep>$(".DocType li a").click(function() {
$("#DocTypeBtn").text($(this).text());
});
$(".Genre li a").click(function() {
$("#GenreBtn").text($(this).text());
});
<file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$hoy = date("Y-m-d H:i:s");
$Motive = $request->Motive;
$Symptom = $request->Symptom;
$index = $request->index;
$response = mysql_query("UPDATE motive_table
SET
motive = '$Motive',
symptom = '$Symptom'
WHERE `index`=$index");
mysql_close($connection); // Connection Closed
echo $response;
?><file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$hoy = date("Y-m-d H:i:s");
$index = $request->index;
$diag1 = $request->diag1;
$diag2 = $request->diag2;
$diag3 = $request->diag3;
$diag4 = $request->diag4;
$response = mysql_query("UPDATE diag_table
SET
diag1 = '$diag1',
diag2 = '$diag2',
diag3 = '$diag3',
diag4 = '$diag4'
WHERE id = $index");
mysql_close($connection); // Connection Closed
echo $response;
?><file_sep>CREATE TABLE `personal_data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`document` int(11) NOT NULL,
`documentType` int(1) NOT NULL,
`name` varchar(255) NOT NULL,
`bornDate` date NOT NULL,
`bornPlace` varchar(255) NOT NULL,
`civilState` varchar(255) NOT NULL,
`gender` int(1) NOT NULL,
`ocupation` varchar(255) DEFAULT NULL,
`procedencia` varchar(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`phone` varchar(255) DEFAULT NULL,
`cellphone` varchar(255) DEFAULT NULL,
`company` varchar(255) DEFAULT NULL,
`companyPhone` varchar(255) DEFAULT NULL,
`eps` varchar(255) DEFAULT NULL,
`religion` varchar(255) DEFAULT NULL,
`reference` varchar(255) DEFAULT NULL,
`createDate` datetime NOT NULL,
`updateDate` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
<file_sep><?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name=$request->name;
$section = $request->section;
$status = 0;
//Insert query
$query = mysql_query("UPDATE waiting_general SET status='$status' WHERE name = '$name' AND section = '$section'");
mysql_close($connection); // Connection Closed
echo $query;
?><file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$HCId=$request->HCId;
$Med=$request->Med;
$hoy = date("Y-m-d H:i:s");
$MedStatus = 1;
$status = 0;
$response = mysql_query("INSERT INTO medicamentos
(HCId,
medicamento,
date,
lastUpdate,
medstatus,
status)
VALUES
('$HCId',
'$Med',
'$hoy',
'$hoy',
'$MedStatus',
'$status')"
);
$query = mysql_query("SELECT * FROM medicamentos WHERE HCId = '$HCId'", $connection);
$myarray = array();
while($row = mysql_fetch_assoc($query)){
$medId=$row['id'];
$medicamento=$row['medicamento'];
$date = $row['date'];
$lastdate = $row['lastUpdate'];
$medstatus = $row['medstatus'];
$status = $row['status'];
if($medstatus==0){
$wordstatus = "Suspendido";
}else{
$wordstatus = "Activo";
}
$myarray[]=array('id' => $medId, 'med'=>$medicamento, 'date' =>$date, 'lastdate' => $lastdate, 'medstatus' => $medstatus , "wordstatus" => $wordstatus , 'status' => $status);
}
mysql_close($connection); // Connection Closed
echo json_encode($myarray);
?><file_sep>CREATE TABLE `motive_table` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(45) NOT NULL,
`motive` text,
`symptom` text,
`date` datetime DEFAULT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`index`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
<file_sep>-- MySQL dump 10.13 Distrib 5.6.24, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: saludholisticadb
-- ------------------------------------------------------
-- Server version 5.6.25
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `systems_table`
--
DROP TABLE IF EXISTS `systems_table`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `systems_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(20) NOT NULL,
`sys1` text,
`sys2` text,
`sys3` text,
`sys4` text,
`sys5` text,
`sys6` text,
`sys7` text,
`sys8` text,
`sys9` text,
`sys10` text,
`sys11` text,
`sys12` text,
`date` datetime DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-08-18 12:21:24
<file_sep><?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$section = $request->section;
$query = mysql_query("SELECT name as nombre, phone as telefono, text as description, priority as priority, status as status
FROM waiting_general
WHERE status = 1
AND section = '$section'
ORDER BY priority", $connection);
$waitings = array();
while ($row = mysql_fetch_row($query)){
$aux = array('name' => $row[0],
'phone' => $row[1],
'description' => $row[2],
'priority' => $row[3],
'status' => $row[4] );
array_push($waitings, $aux);
}
$json = json_encode($waitings);
echo $json;
mysql_close($connection); // Connection Closed
?><file_sep><?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name=$request->name;
$phone=$request->phone;
$desc=$request->desc;
$priority=$request->priority;
$section = $request->section;
$status = 1;
//Insert query
$query = mysql_query("insert into waiting_general(name, phone, text, priority, status, section) values ('$name', '$phone', '$desc','$priority','$status', '$section')");
mysql_close($connection); // Connection Closed
echo $query;
?><file_sep>CREATE TABLE `schedule_general` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`start_date` datetime NOT NULL,
`end_date` datetime NOT NULL,
`name` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`text` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
<file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$hoy = date("Y-m-d H:i:s");
$HCId = $request->HCId;
$status = 0;
$result = mysql_query("SELECT * FROM backgrounds_table WHERE HCId = '$HCId' AND status=$status", $connection);
if(!$result || mysql_num_rows($result)==0){
$response = mysql_query("INSERT INTO backgrounds_table
(HCId,
date,
status)
VALUES
('$HCId',
'$hoy',
'$status')"
);
$result = mysql_query("SELECT * FROM backgrounds_table WHERE HCId = '$HCId' AND status=$status", $connection);
}
$row = mysql_fetch_row($result);
mysql_close($connection); // Connection Closed
echo json_encode($row);
?><file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$Iddocument=$request->Iddocument;
$Idtype=$request->Idtype;
$name=$request->name;
$borndate=$request->borndate;
$bornplace=$request->bornplace;
$civilstate=$request->civilstate;
$gender=$request->gender;
$ocupation=$request->ocupation;
$procedencia=$request->procedencia;
$address=$request->address;
$phone=$request->phone;
$cellphone=$request->cellphone;
$company=$request->company;
$companyphone=$request->companyphone;
$eps=$request->eps;
$religion=$request->religion;
$reference=$request->reference;
$hoy = date("Y-m-d H:i:s");
$response = mysql_query("UPDATE personal_data
SET
civilState = '$civilstate',
ocupation = '$ocupation',
procedencia = '$procedencia',
address = '$address',
phone = '$phone',
cellphone = '$cellphone',
company = '$company',
companyPhone = '$companyphone',
eps = '$eps',
religion = '$religion',
reference = '$reference',
updateDate = '$hoy'
WHERE document = '$Iddocument' AND documentType = '$Idtype'");
mysql_close($connection); // Connection Closed
echo $response;
?><file_sep><?php
$connection = mysql_connect ( "localhost", "root", "" ); // Establishing Connection with Server..
$db = mysql_select_db ( "saludholisticadb", $connection ); // Selecting Database
// Fetching Values from URL
$postdata = file_get_contents ( "php://input" );
$request = json_decode ( $postdata );
$Iddocument = $request->Iddocument;
$Idtype = $request->Idtype;
$query = mysql_query("SELECT * FROM hcindex WHERE document = $Iddocument AND documentType = $Idtype ", $connection);
$myarray = array();
while($row = mysql_fetch_assoc($query)){
$id=$row['HCId'];
$date = $row['creationDate'];
$myarray[]=array('id'=>$id, 'date' =>$date);
}
mysql_close($connection); // Connection Closed
echo json_encode($myarray);
?><file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$hoy = date("Y-m-d H:i:s");
$HCId = $request->HCId;
$HCindex= $request->HCindex;
$systemindex = $request->systemindex;
$symptomindex = $request->symptomindex;
$backindex = $request->backindex;
$physicindex = $request->physicindex;
$analisysindex = $request->analisysindex;
$diagindex = $request->diagindex;
?><file_sep>-- MySQL dump 10.13 Distrib 5.6.24, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: saludholisticadb
-- ------------------------------------------------------
-- Server version 5.6.25
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `backgrounds_table`
--
DROP TABLE IF EXISTS `backgrounds_table`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `backgrounds_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(20) NOT NULL,
`back1` text,
`back2` text,
`back3` text,
`back4` text,
`back5` text,
`back6` text,
`back7` text,
`back8` text,
`back9` text,
`back10` text,
`back11` text,
`back12` text,
`back13` text,
`date` datetime DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `hcindex`
--
DROP TABLE IF EXISTS `hcindex`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `hcindex` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`document` int(11) NOT NULL,
`documentType` int(11) NOT NULL,
`HCId` varchar(50) NOT NULL,
`creationDate` datetime NOT NULL,
PRIMARY KEY (`index`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `motive_table`
--
DROP TABLE IF EXISTS `motive_table`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `motive_table` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(45) NOT NULL,
`motive` text,
`symptom` text,
`date` datetime DEFAULT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`index`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `personal_data`
--
DROP TABLE IF EXISTS `personal_data`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `personal_data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`document` int(11) NOT NULL,
`documentType` int(1) NOT NULL,
`name` varchar(255) NOT NULL,
`bornDate` date NOT NULL,
`bornPlace` varchar(255) NOT NULL,
`civilState` varchar(255) NOT NULL,
`gender` int(1) NOT NULL,
`ocupation` varchar(255) DEFAULT NULL,
`procedencia` varchar(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`phone` varchar(255) DEFAULT NULL,
`cellphone` varchar(255) DEFAULT NULL,
`company` varchar(255) DEFAULT NULL,
`companyPhone` varchar(255) DEFAULT NULL,
`eps` varchar(255) DEFAULT NULL,
`religion` varchar(255) DEFAULT NULL,
`reference` varchar(255) DEFAULT NULL,
`createDate` datetime NOT NULL,
`updateDate` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `physics_table`
--
DROP TABLE IF EXISTS `physics_table`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `physics_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(20) NOT NULL,
`phy1` text,
`phy2` text,
`phy3` text,
`phy4` text,
`phy5` text,
`phy6` text,
`phy7` text,
`phy8` text,
`phy9` text,
`phy10` text,
`phy11` text,
`phy12` text,
`phy13` text,
`date` datetime DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `schedule_general`
--
DROP TABLE IF EXISTS `schedule_general`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `schedule_general` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`start_date` datetime NOT NULL,
`end_date` datetime NOT NULL,
`name` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`text` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `schedule_odonto`
--
DROP TABLE IF EXISTS `schedule_odonto`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `schedule_odonto` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`start_date` datetime NOT NULL,
`end_date` datetime NOT NULL,
`name` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`text` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `symptons_table`
--
DROP TABLE IF EXISTS `symptons_table`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `symptons_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(20) NOT NULL,
`symptom1` text,
`symptom2` text,
`symptom3` text,
`symptom4` text,
`symptom5` text,
`symptom6` text,
`symptom7` text,
`date` datetime DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `systems_table`
--
DROP TABLE IF EXISTS `systems_table`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `systems_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(20) NOT NULL,
`sys1` text,
`sys2` text,
`sys3` text,
`sys4` text,
`sys5` text,
`sys6` text,
`sys7` text,
`sys8` text,
`sys9` text,
`sys10` text,
`sys11` text,
`sys12` text,
`date` datetime DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `waiting_general`
--
DROP TABLE IF EXISTS `waiting_general`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `waiting_general` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`text` varchar(255) NOT NULL,
`priority` int(1) NOT NULL,
`status` int(1) NOT NULL,
`section` int(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `waiting_odonto`
--
DROP TABLE IF EXISTS `waiting_odonto`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `waiting_odonto` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`text` varchar(255) NOT NULL,
`priority` int(1) NOT NULL,
`status` int(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-08-18 12:21:33
<file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$hoy = date("Y-m-d H:i:s");
$index = $request->index;
$symptom1 = $request->symptom1;
$symptom2 = $request->symptom2;
$symptom3 = $request->symptom3;
$symptom4 = $request->symptom4;
$symptom5 = $request->symptom5;
$symptom6 = $request->symptom6;
$symptom7 = $request->symptom7;
$response = mysql_query("UPDATE symptons_table
SET
symptom1 = '$symptom1',
symptom2 = '$symptom2',
symptom3 = '$symptom3',
symptom4 = '$symptom4',
symptom5 = '$symptom5',
symptom6 = '$symptom6',
symptom7 = '$symptom7'
WHERE id = $index");
mysql_close($connection); // Connection Closed
echo $response;
?><file_sep>-- MySQL dump 10.13 Distrib 5.6.24, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: saludholisticadb
-- ------------------------------------------------------
-- Server version 5.6.25
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `personal_data`
--
DROP TABLE IF EXISTS `personal_data`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `personal_data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`document` int(11) NOT NULL,
`documentType` int(1) NOT NULL,
`name` varchar(255) NOT NULL,
`bornDate` date NOT NULL,
`bornPlace` varchar(255) NOT NULL,
`civilState` varchar(255) NOT NULL,
`gender` int(1) NOT NULL,
`ocupation` varchar(255) DEFAULT NULL,
`procedencia` varchar(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`phone` varchar(255) DEFAULT NULL,
`cellphone` varchar(255) DEFAULT NULL,
`company` varchar(255) DEFAULT NULL,
`companyPhone` varchar(255) DEFAULT NULL,
`eps` varchar(255) DEFAULT NULL,
`religion` varchar(255) DEFAULT NULL,
`reference` varchar(255) DEFAULT NULL,
`createDate` datetime NOT NULL,
`updateDate` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-08-18 12:21:23
<file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$hoy = date("Y-m-d H:i:s");
$index = $request->index;
$sys1 = $request->sys1;
$sys2 = $request->sys2;
$sys3 = $request->sys3;
$sys4 = $request->sys4;
$sys5 = $request->sys5;
$sys6 = $request->sys6;
$sys7 = $request->sys7;
$sys8 = $request->sys8;
$sys9 = $request->sys9;
$sys10 = $request->sys10;
$sys11 = $request->sys11;
$sys12 = $request->sys12;
$response = mysql_query("UPDATE systems_table
SET
sys1 = '$sys1',
sys2 = '$sys2',
sys3 = '$sys3',
sys4 = '$sys4',
sys5 = '$sys5',
sys6 = '$sys6',
sys7 = '$sys7',
sys8 = '$sys8',
sys9 = '$sys9',
sys10 = '$sys10',
sys11 = '$sys11',
sys12 = '$sys12'
WHERE id = $index");
mysql_close($connection); // Connection Closed
echo $response;
?><file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect ( "localhost", "root", "" ); // Establishing Connection with Server..
$db = mysql_select_db ( "saludholisticadb", $connection ); // Selecting Database
// Fetching Values from URL
$postdata = file_get_contents ( "php://input" );
$request = json_decode ( $postdata );
$recId = $request->RecId;
$rectxt = $request->rectxt;
$HCId = $request->HCId;
$hoy = date("Y-m-d H:i:s");
$result = mysql_query("UPDATE recomendaciones SET
recomendacion = '$rectxt',
lastUpdate = '$hoy'
WHERE id = '$recId'");
$query = mysql_query("SELECT * FROM recomendaciones WHERE HCId = '$HCId'", $connection);
$myarray = array();
while($row = mysql_fetch_assoc($query)){
$recId=$row['id'];
$recomendacion=$row['recomendacion'];
$date = $row['date'];
$lastdate = $row['lastUpdate'];
$recstatus = $row['recstatus'];
$status = $row['status'];
if($recstatus==0){
$wordstatus = "Suspendido";
}else{
$wordstatus = "Activo";
}
$myarray[]=array('id' => $recId, 'rec'=>$recomendacion, 'date' =>$date, 'lastdate' => $lastdate, 'recstatus' => $recstatus , "wordstatus" => $wordstatus , 'status' => $status);
}
mysql_close($connection); // Connection Closed
echo json_encode($myarray);
?><file_sep>-- MySQL dump 10.13 Distrib 5.6.24, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: saludholisticadb
-- ------------------------------------------------------
-- Server version 5.6.25
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `personal_data`
--
DROP TABLE IF EXISTS `personal_data`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `personal_data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`document` int(11) NOT NULL,
`documentType` int(1) NOT NULL,
`name` varchar(255) NOT NULL,
`bornDate` date NOT NULL,
`bornPlace` varchar(255) NOT NULL,
`civilState` varchar(255) NOT NULL,
`gender` int(1) NOT NULL,
`ocupation` varchar(255) DEFAULT NULL,
`procedencia` varchar(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`phone` varchar(255) DEFAULT NULL,
`cellphone` varchar(255) DEFAULT NULL,
`company` varchar(255) DEFAULT NULL,
`companyPhone` varchar(255) DEFAULT NULL,
`eps` varchar(255) DEFAULT NULL,
`religion` varchar(255) DEFAULT NULL,
`reference` varchar(255) DEFAULT NULL,
`createDate` datetime NOT NULL,
`updateDate` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `personal_data`
--
LOCK TABLES `personal_data` WRITE;
/*!40000 ALTER TABLE `personal_data` DISABLE KEYS */;
INSERT INTO `personal_data` VALUES (1,1032366065,1,'<NAME>','1986-04-11','Bogota','soltero',0,'ingeniero','sdcdfvdfvsd','calle 123 skdjsdcsdcsdc','234567','1234567890','sjdhcbsj cjsb djcb sjdcb sjb','123456','cb','none','pepe','2015-08-17 17:45:05','0000-00-00 00:00:00'),(2,1070955993,1,'<NAME>','1989-11-12','Villavicencio','soltera',1,'enfermera jefe','colombiana','cale 123 sjkd8998','1234567','3203983976','<NAME>','3123280021','compensar','cristiana','<NAME>','2015-08-17 13:05:49','2015-08-17 13:42:03'),(3,123456789,1,'qwebw eubqw bejqbhwjq','1988-12-12','bogota','asdbasjdhba',0,'jsdn ksjcn ksjdcsdcsjk','jsdhcbjsd bhcsh csjbh','jcbsjdcbh sdjhdcbjsbhd','jhbcsdjchbsjhd','hsdcbsjbhcs','jhxbsjdbhcsjbh','cbhdsjcbhsj','jhjbhdjbhd','','','2015-08-18 07:02:32','2015-08-18 07:02:32');
/*!40000 ALTER TABLE `personal_data` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-08-18 17:09:30
<file_sep>-- MySQL dump 10.13 Distrib 5.6.24, for osx10.8 (x86_64)
--
-- Host: 127.0.0.1 Database: saludholisticadb
-- ------------------------------------------------------
-- Server version 5.6.21
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `systems_table`
--
DROP TABLE IF EXISTS `systems_table`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `systems_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(20) NOT NULL,
`sys1` text,
`sys2` text,
`sys3` text,
`sys4` text,
`sys5` text,
`sys6` text,
`sys7` text,
`sys8` text,
`sys9` text,
`sys10` text,
`sys11` text,
`sys12` text,
`date` datetime DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `systems_table`
--
LOCK TABLES `systems_table` WRITE;
/*!40000 ALTER TABLE `systems_table` DISABLE KEYS */;
INSERT INTO `systems_table` VALUES (1,'GE10001','asd','negros','asdasc','ghng','wefwef','xcvxcvx','qwqeweqw','sd fsdf sdf sd\n- sdsdcs\n-c csdcscs','ascakscnacjksdcsd','sdcsdc','sdcsdc','sdcsdcsdcsd','2015-08-18 10:24:43',0),(2,'',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-18 14:20:45',0),(3,'GE10002',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-18 14:22:09',0),(4,'GE10003',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-18 17:22:23',0),(5,'GE10004','sddsc\ndsvcdfvdf\ndvfvdf\ndfvdfv\ndfvdf\nvdf\nv\ndf','','','','sdvfdvf','','','','dfvdfvdscd','sd cjsdhbcjs cjd','','','2015-08-18 18:33:12',0),(6,'GE10005',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-18 18:45:40',0),(7,'GE10006',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-31 05:55:57',0),(8,'GE10008',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-09-04 05:20:17',0);
/*!40000 ALTER TABLE `systems_table` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-10-14 8:14:29
<file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$hoy = date("Y-m-d H:i:s");
$index = $request->index;
$back1 = $request->back1;
$back2 = $request->back2;
$back3 = $request->back3;
$back4 = $request->back4;
$back5 = $request->back5;
$back6 = $request->back6;
$back7 = $request->back7;
$back8 = $request->back8;
$back9 = $request->back9;
$back10 = $request->back10;
$back11 = $request->back11;
$back12 = $request->back12;
$back13 = $request->back13;
$response = mysql_query("UPDATE backgrounds_table
SET
back1 = '$back1',
back2 = '$back2',
back3 = '$back3',
back4 = '$back4',
back5 = '$back5',
back6 = '$back6',
back7 = '$back7',
back8 = '$back8',
back9 = '$back9',
back10 = '$back10',
back11 = '$back11',
back12 = '$back12',
back13 = '$back13'
WHERE id = $index");
mysql_close($connection); // Connection Closed
echo $response;
?><file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$Iddocument=$request->Iddocument;
$Idtype=$request->Idtype;
$name=$request->name;
$borndate=$request->borndate;
$bornplace=$request->bornplace;
$civilstate=$request->civilstate;
$gender=$request->gender;
$ocupation=$request->ocupation;
$procedencia=$request->procedencia;
$address=$request->address;
$phone=$request->phone;
$cellphone=$request->cellphone;
$company=$request->company;
$companyphone=$request->companyphone;
$eps=$request->eps;
$religion=$request->religion;
$reference=$request->reference;
$hoy = date("Y-m-d H:i:s");
//Insert query
$result = mysql_query("SELECT document FROM personal_data WHERE document = $Iddocument AND documentType = $Idtype", $connection);
if(mysql_num_rows($result)==0){
$response = mysql_query("INSERT INTO personal_data
(document,
documentType,
name,
bornDate,
bornPlace,
civilState,
gender,
ocupation,
procedencia,
address,
phone,
cellphone,
company,
companyPhone,
eps,
religion,
reference,
createDate,
updateDate)
VALUES
('$Iddocument',
'$Idtype',
'$name',
'$borndate',
'$bornplace',
'$civilstate',
'$gender',
'$ocupation',
'$procedencia',
'$address',
'$phone',
'$cellphone',
'$company',
'$companyphone',
'$eps',
'$religion',
'$reference',
'$hoy',
'$hoy')
");
}
else
{
$response = false;
}
mysql_close($connection); // Connection Closed
echo $response;
?><file_sep>var SHapp = angular.module('SHapp', []);
$('#addPac').on('hide.bs.modal', function () {
$('#addPac').removeData();
})<file_sep>
$("#medModalUpdate").on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var id = button.data('id');
var med = button.data('med');
var modal = $(this);
modal.find('#medtxtupt').val(med);recModalUpdate
modal.find('#medIdupt').val(id);
})
$("#recModalUpdate").on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var id = button.data('id');
var red = button.data('rec');
var modal = $(this);
modal.find('#rectxtupt').val(red);
modal.find('#recIdupt').val(id);
})<file_sep>-- MySQL dump 10.13 Distrib 5.6.24, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: saludholisticadb
-- ------------------------------------------------------
-- Server version 5.6.25
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `systems_table`
--
DROP TABLE IF EXISTS `systems_table`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `systems_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`HCId` varchar(20) NOT NULL,
`sys1` text,
`sys2` text,
`sys3` text,
`sys4` text,
`sys5` text,
`sys6` text,
`sys7` text,
`sys8` text,
`sys9` text,
`sys10` text,
`sys11` text,
`sys12` text,
`date` datetime DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `systems_table`
--
LOCK TABLES `systems_table` WRITE;
/*!40000 ALTER TABLE `systems_table` DISABLE KEYS */;
INSERT INTO `systems_table` VALUES (1,'GE10001','asd','negros','asdasc','ghng','wefwef','xcvxcvx','qwqeweqw','sd fsdf sdf sd\n- sdsdcs\n-c csdcscs','ascakscnacjksdcsd','sdcsdc','sdcsdc','sdcsdcsdcsd','2015-08-18 10:24:43',0),(2,'',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-18 14:20:45',0),(3,'GE10002',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2015-08-18 14:22:09',0);
/*!40000 ALTER TABLE `systems_table` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-08-18 17:09:31
<file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$hoy = date("Y-m-d H:i:s");
$HCId = $request->HDId;
$code = $request->code;
$status = 0;
$response = mysql_query("INSERT INTO hccie
(HCId,
code,
date,
status)
VALUES
('$HCId',
'$code',
'$hoy',
'$status')"
);
$query = mysql_query("SELECT * FROM hccie WHERE code = $code AND HCId = $HCId", $connection);
$myarray = array();
while($row = mysql_fetch_assoc($query)){
$codigo=$row['code'];
$myarray[]=array('code'=>$codigo);
}
mysql_close($connection); // Connection Closed
echo json_encode($myarray);
?><file_sep><?php
date_default_timezone_set('America/Bogota');
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("saludholisticadb", $connection); // Selecting Database
//Fetching Values from URL
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$Iddocument=$request->Iddocument;
$Idtype=$request->Idtype;
$hoy = date("Y-m-d H:i:s");
$HCId = "";
$result = mysql_query("SELECT MAX(`index`) FROM hcindex", $connection);
if(!$result){
$HCId = "GE10001";
}else{
$row = mysql_fetch_row($result);
$index= 10001 + $row[0];
$HCId= "GE".$index;
}
$response = mysql_query("INSERT INTO hcindex
(document,
documentType,
HCId,
creationDate)
VALUES
('$Iddocument',
'$Idtype',
'$HCId',
'$hoy')"
);
mysql_close($connection); // Connection Closed
echo $HCId;
?><file_sep>CREATE TABLE `hcindex` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`document` int(11) NOT NULL,
`documentType` int(11) NOT NULL,
`HCId` varchar(50) NOT NULL,
`creationDate` datetime NOT NULL,
PRIMARY KEY (`index`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
| 767fb180325d80ff049cba90987b9c95fa567210 | [
"JavaScript",
"SQL",
"PHP"
] | 46 | PHP | hortasoft/saludholistica | 0275d5006fb4100d84f80e562e95e47c5bd34522 | b36ef5da5833673aaad627254b00fb1f9b46f95f |
refs/heads/master | <repo_name>AlecJY/OcSocks<file_sep>/src/main/java/com/alebit/ocsocks/Main.java
package com.alebit.ocsocks;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class Main {
public Main() {
try {
new ProxyServer();
URLClassLoader sockslibLoader = new URLClassLoader(new URL[]{new URL("https://raw.githubusercontent.com/AlecJY/OcSocks/master/libs/sockslib-1.0.0-SNAPSHOT.jar")}, this.getClass().getClassLoader());
Class socksProxyServerFactory = Class.forName("sockslib.server.SocksProxyServerFactory", false, sockslibLoader);
Method newNoAuthenticationServer = socksProxyServerFactory.getDeclaredMethod("newNoAuthenticationServer", int.class);
Object instance = socksProxyServerFactory.newInstance();
Object socksProxyServer = newNoAuthenticationServer.invoke(instance, 8080);
Class socksProxyServerClass = Class.forName("sockslib.server.SocksProxyServer", true, sockslibLoader);
Method start = socksProxyServerClass.getDeclaredMethod("start");
start.invoke(socksProxyServer);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Main();
}
}
| af61f33e8e5c52b27e7dd1f6deb3044333ce2e08 | [
"Java"
] | 1 | Java | AlecJY/OcSocks | 9ef9a774e2552f3a06b603b2fff3be186dc4fa2f | 9b317f54782247da407ceebbbbe7921e9527c345 |
refs/heads/master | <repo_name>YooSunYoung/YCommonUI<file_sep>/src/ycommonUI/panel/monitor/YMonitorOutputStream.java
// writer : <NAME>
// writer's e-mail : <EMAIL>
// version : 0
package ycommonUI.panel.monitor;
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
public class YMonitorOutputStream extends OutputStream{
private StringBuilder sb;
private JTextArea textarea;
public YMonitorOutputStream(JTextArea textarea){
sb = new StringBuilder();
this.textarea = textarea;
}
@Override
public void write(int b) throws IOException {
// TODO Auto-generated method stub
if(b == '\r'){
return ;
}
else if (b == '\n'){
String text = sb.toString() + "\n";
textarea.append(text);
sb.setLength(0);
return;
}
sb.append((char) b);
}
}
<file_sep>/src/ycommonUI/panel/monitor/YMonitorPanel.java
// writer : <NAME>
// writer's e-mail : <EMAIL>
// version : 0
package ycommonUI.panel.monitor;
import java.awt.Color;
import java.awt.Font;
import java.io.PrintStream;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class YMonitorPanel extends JPanel{
private YMonitorOutputStream monitor_output_stream; // monitor_area's output stream
private JTextArea text_area; // where the output stream goes.
private JScrollPane monitor_scroll_pane;
private Font default_font;
public YMonitorPanel(){
init();
}
public YMonitorPanel(String name){
init();
setName(name);
}
public void init(){
// default font
default_font = new Font("Sanserif",0,20);
// create fields
text_area = new JTextArea();
monitor_output_stream = new YMonitorOutputStream(text_area);
// set monitor text area
text_area.setEditable(false);
text_area.setFont(default_font);
// add components
monitor_scroll_pane = new JScrollPane(text_area);
monitor_scroll_pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
monitor_scroll_pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.add(monitor_scroll_pane);
monitor_scroll_pane.setBounds(15,30,880,310);
this.setLayout(null);
this.setBounds(10,10,450,350);
this.setBorder(BorderFactory.createLineBorder(Color.black));
}
public YMonitorOutputStream getMonitorOutputStream(){
return this.monitor_output_stream;
}
public JScrollPane getMonitorScrollPane(){
return this.monitor_scroll_pane;
}
public PrintStream getMonitorPrintStream(){
return new PrintStream(this.monitor_output_stream);
}
public JTextArea getTextArea(){
return this.text_area;
}
// test
public static void main(String[] args){
JFrame jf = new JFrame();
jf.setLayout(null);
jf.setSize(485, 520);
YMonitorPanel cp = new YMonitorPanel("testhesthest");
System.setOut(new PrintStream(cp.getMonitorOutputStream()));
for (int i = 0 ; i < 20 ; i++){
System.out.println("zzan");
}
jf.add(cp);
jf.setContentPane(cp);
jf.setVisible(true);
}
}
| f209b7ec00247d6dc9fe1ad45bdebb91ae89aa79 | [
"Java"
] | 2 | Java | YooSunYoung/YCommonUI | 8aa7e0807667a0eefe614c602cbd7d589fd71ddb | 1953d078f775f7d8ad07b5e29dccd11f6bcd86e4 |
refs/heads/master | <repo_name>CartinhaSquadETEC/projeto-distribuidora<file_sep>/distribuidora_inserts.sql
insert into jogos (id, nome, data_lancamento, classificacao_indicativa, preco, descricao, produtora) values
(1, "Terra Mystica", "20131205", "12+", 260.00, "Terra Mystica é um jogo com pouca sorte que premia planejamento estratégico. Cada jogador controla um dos 14 grupos. Com sutileza, o jogador deve tentar governar uma área tão grande quanto possível e desenvolver habilidades desse grupo. Há também quatro cultos religiosos em que o jogador pode progredir. Para fazer tudo isso, cada grupo tem as competências e habilidades especiais.", "Mandala Jogos"),
(2, "<NAME>", "20160407", "12+", 180.00, "Os jogadores são proprietários de plantações em Porto Rico, nos tempos das grandes navegações. Crescendo com até cinco diferentes tipos de culturas (milho, índigo, tabaco, açúcar e café), os jogadores devem tentar conduzir seus negócios de forma mais eficiente do que seus concorrentes mais próximos: manter cultivo e armazenagem otimizados, desenvolver San Juan com edifícios úteis, utilizar a mão-de-obra de colonos, vender suas colheitas no tempo certo, e, mais importante ainda, transportar suas mercadorias de volta para a Europa para o máximo ganho.", "Devir Brasil"),
(3, "As Viagens de Marco Polo", "20170213", "12+", 300.00, "Em The Voyages of Marco Polo, os jogadores recriam esta jornada, com cada jogador sendo um personagem diferente com poderes especiais no jogo. O jogo é jogado ao longo de cinco rodadas. A cada rodada, os jogadores lançam seus cinco dados pessoais e podem executar uma ação com eles.", "Z-Man Games"),
(4, "Agricola", "20060127", "12+", 250.00, "Em Agricola, você é um fazendeiro em um barraco de madeira com seu cônjuge e um pouco mais. Em um turno, você começa a ter apenas duas ações, um para você e um para o cônjuge, de todas as possibilidades que você encontrará em uma fazenda: recolher barro, madeira ou pedra, cercas de construção, e assim por diante. Você pode pensar em ter filhos, a fim de conseguir mais trabalhadores, mas primeiro você precisa expandir a sua casa. E o que você vai fazer para alimentar todos os pequenos?", "Devir Brasil"),
(5, "Through The Ages: Uma Nova História da Civilização", "20090311", "14+", 320.00, "Through the Ages é um jogo de construção de civilização. Cada jogador tenta construir a melhor civilização através de uma gestão cuidadosa dos recursos, descoberta de novas tecnologias, elegendo os líderes certos, a construção de maravilhas e manutenção de poder militar. Fraqueza em qualquer área pode ser explorada por seus adversários. O jogo tem lugar ao longo dos tempos com início na idade da antiguidade e terminando na idade moderna.", "Devir Brasil"),
(6, "<NAME>: Adventure on the Cursed Island", "20030918", "8+", 270.00, "Os jogadores serão confrontados com os desafios da construção de um abrigo, encontrar comida, lutar contra animais selvagens, e se proteger das mudanças climáticas. Construção de muros em torno de suas casas, a domesticação de animais, a construção de armas e ferramentas e muito mais esperam por eles na ilha. Os jogadores decidem em qual direção o jogo vai se desenrolar e – depois de várias semanas de muito trabalho no jogo – como será sua adaptação na ilha.", "Z-Man Games"),
(7, "Mage Knight Board Game", "20161002", "14+", 390.00, "O Mage Knight Board Game da Wizkids coloca você no controle de um dos quatro poderosos cavaleiros mágicos para explorar (e conquistar) um canto do universo de Mage Knight sob o controle do Império Atlante. Construir o seu exército, encher seu deck com feitiços poderosos e ações, explorar cavernas e masmorras, e, eventualmente, conquistar cidades controladas por poderosas facções! Embora os jogadores adversários podem ser aliados poderosos, apenas um será capaz de reivindicar a terra como sua, no final de cada campanha. Combinando elementos de RPGs, jogos de tabuleiro e construção de deck tradicional, este jogo capta a rica história do universo de Mage Knight, proporcionando de tudo um pouco em uma única caixa.", "WizKids"),
(8, "<NAME>", "20000524", "13+", 190.00, "<NAME> herda seus sistemas fundamentais das clássicas campanhas por cartas dos jogos We the People e Hannibal: Rome vs Carthage. O mapa do jogo é um mapa do mundo no período, os jogadores movem unidades e exercem sua influência na tentativa de ganhar aliados e controle para sua superpotência. Tal como acontece com outros jogos de campanha de cartas da GMT, as tomadas de decisões são um desafio.", "Devir Brasil"),
(9, "Pandemic Legacy: 1ª Temporada", "20151130", "13+", 269.00, "Pandemic Legacy começa com o que será um dos piores anos da história humana. Se é o pior ano os jogadores têm de se unir para salvar o mundo. Ao contrário de Pandemic, as medidas tomadas num jogo de Pandemic Legacy afetam todos os jogos futuros. Os personagens vão mudar. Alguns podem ser perdidos. Heróis surgirão. E, claro, há as doenças, que começam sob controle, mas em breve...", "Z-Man Games"),
(10, "Eldritch Horror", " 20090331", "14+", 200.00, "Em Eldritch Horror, de um a oito jogadores assumem o papel de investigadores que andam pelo mundo, trabalhando juntos, e devem resolver mistérios relacionados aos Grandes Antigos cuja intenção é a destruição global. Nessa busca você pode reunir pistas, encontrar situações estranhas, lutar contra monstros e embarcar em expedições ousadas. Você tem a coragem de salvar o mundo?", "Galápagos Jogos"),
(11, "Mombasa", "20110104", "12+", 233.00, "Em Mombasa, os jogadores adquirem partes de companhias baseadas em Mombasa, Cape Town, Saint-Louis e Cairo, e propagarão postos de troca destas companhias através de toda África para ganharem mais dinheiro.", "Meeple BR Jogos"),
(12, "Lords of Waterdeep", "20010626", "12+", 280.00, "Waterdeep, a Cidade dos Esplendores, a jóia mais resplandecente em Forgotten Realms, é um covil de intriga política e obscuras negociações. Neste jogo, os jogadores são senhores poderosos que disputam o controle desta grande cidade.", "Wizards of the Coast"),
(13, "7 Wonders", "20080330", "10+", 204.00, "7 Wonders dura três eras. Os jogadores têm tabuleiros individuais com poderes especiais ('maravilhas'), onde são colocadas suas cartas. Em cada era, os jogadores recebem sete cartas, escolhem uma, e em seguida, passam o restante para um jogador ao lado. Os jogadores revelam suas cartas simultaneamente, podendo fazê-lo de três maneiras: descartando-a para receber ouro, usando-a para evoluir a sua 'maravilha', ou utilizando-a, e para isso deve pagar recursos (se necessário), momento em que há interação com outros jogadores de várias maneiras (interessante que esta interação é apenas com jogadores que estão exatamente ao seu lado; com os demais não se pode negociar).", "Galápagos Jogos"),
(14, "Power Grid", "20050909", "12+", 210.00, "O objetivo de Power Grid é fornecer energia para a maioria dos municípios. Os jogadores marcam rotas pré-existentes entre cidades para a conexão, e depois faz lances em um leilão para comprar as usinas que usam para alimentar suas cidades.", "Galápagos Jogos"),
(15, "The Castles of Burgundy", "20151116", "12+", 180.00, "Este jogo se passa na região de Burgundy da França na alta Idade Média. Cada jogador assume o papel de um aristocrata, originalmente controlando um pequeno principado. Assumindo o papel destes aristocratas, os jogadores podem construir assentamentos e castelos poderosos, praticar comércio ao longo do rio, explorar minas de prata, e usar o conhecimento de viajantes. O jogo é sobre a colocação de peças no tabuleiro para o principado. O mecanismo de jogo principal envolve dois dados.", "Grow Jogos e Brinquedos"),
(16, "Stone Age", "20120216", "10+", 249.00, "Os jogadores lutam para sobreviver à Idade da Pedra, trabalhando como caçadores, coletores, agricultores e fabricantes de ferramentas. Você deve reunir recursos e crescer com a sua população, construindo as ferramentas necessárias para construir sua civilização. Os jogadores usam até 10 membros da tribo em três fases. Na primeira fase, os jogadores colocam seus homens em regiões do tabuleiro que eles acham que vai beneficiá-los, incluindo a caça, a plantação ou a pedreira. Na segunda fase, o jogador inicial ativa cada uma de suas áreas escolhida em qualquer ordem, seguido pelos outros jogadores. Na terceira fase, os jogadores devem ter comida suficiente disponível para alimentar sua população, ou eles podem perder recursos ou pontos.", "Devir Brasil"),
(17, "<NAME> (Segunda Edição)", "20090405", "12+", 450.00, "Em War of the Ring, um jogador assume o controle dos Povos Livres (PL), o outro jogador controla exércitos de sombra (EA). Inicialmente, os povos livres estão relutantes em tomar armas contra Sauron, então eles devem ser atacados por Sauron ou persuadidos por Gandalf e outros companheiros, antes de começar a lutar corretamente: esta é representada pela via política, que mostra se uma nação está pronta para lutar na Guerra do Anel ou não.", "Devir Brasil"),
(18, "Alquimistas", "20060407", "13+", 320.00, "Em Alchemists, 2 a 4 alquimistas competem para descobrir os segredos de sua arte mística. Os pontos podem ser ganhos de várias maneiras, mas a maioria dos pontos são ganhos por teorias de publicação - teorias corretas - e é aí que reside o problema.", "Devir Brasil"),
(19, "A Guerra dos Tronos: Board Game", "20120316", "14+", 260.00, "Baseado na bem sucedida série de livros 'As crônicas de gelo e fogo (Guerra dos Tronos)' escrita por <NAME>, 'A Game of Thrones' é um jogo de tabuleiro épico, no qual será necessário mais do que poder militar para ganhar. Você ganhará poder através da força, usando palavras doces para coagir seu caminho até o trono, ou reunindo o povo das cidades para o seu lado? Através de planejamento estratégico, diplomacia magistral, e um inteligente uso de cartas, espalhe sua influência sobre Westeros!", "Galápagos Jogos"),
(20, "<NAME>", "20100410", "10+", 130.00, "De muitas maneiras 7 Wonders: Duel lembra seu pai 7 Wonders onde mais de três jogadores adquirem cartas que fornecem recursos ou avançam suas forças armadas e avanços científicos, a fim de desenvolver uma civilização e completar.", "Galápagos Jogos"),
(21, "Caverna: The Cave Farmers", "20160312", "14+", 400.00, "Caverna: The Cave Farmers é uma reformulação completa de Agricola que substitui os baralhos de cartas do jogo anterior, com um conjunto de edifícios ao adicionar a capacidade de comprar armas e enviar seus agricultores em missões para ganhar mais recursos. O designer <NAME> diz que o jogo inclui partes do Agricola, mas também tem novas ideias, especialmente a parte da caverna do seu tabuleiro de jogo, onde você pode construir minas e buscar por rubis. O jogo também inclui dois novos animais: cães e jumentos.", "Ludofy Creative"),
(22, "Tzolk'in: The Mayan Calendar", "20091012", "13+", 319.00, "Tzolkin: The Mayan Calendar apresenta um novo mecanismo de jogo: a colocação do trabalhador dinâmico. Jogadores que representam diferentes tribos maias colocam os seus trabalhadores em gigantes engrenagens conectadas, e as engrenagens giram com eles e levam os trabalhadores para pontos de ação diferentes. Durante um turno, os jogadores podem colocar um ou mais trabalhadores no menor ponto visível das engrenagens ou pegar um ou mais trabalhadores.", "Rio Grande Games"),
(23, "Five Tribes", "20050723", "13+", 320.00, "Cruzando na Terra de 1001 Noites, sua caravana chega ao Sultanato da fábula de Naqala. O velho sultão morreu e o controle de Naqala está vazio. Os oráculos tiveram a premonição de que estranhos manobram as cinco tribos para ganhar influência sobre a lendária cidade-estado. Você vai cumprir a profecia? Chame os velhos Gênios, mova as Tribos em posição no momento certo e o Sultanato pode tornar-se seu.", "Days of Wonder"),
(24, "Descent: Journeys in the Dark (second edition)", "20090904", "10+", 330.00, "Descent: Journeys in the Dark (Second Edition) é um jogo de tabuleiro no qual um dos jogadores faz o papel do terrível Overlord, e até outros quatro jogadores fazem o papel de heróis corajosos. Durante cada partida, os heróis realizam missões e se aventuram em cavernas perigosas, ruínas antigas, dungeons escuras e florestas amaldiçoadas para batalhar com monstros, ganhar riquezas e tentar impedir que o Overlord realize sem plano negro.Com o perigo rondando em todos os lugares, o combate é uma necessidade. Descent: Journeys in the Dark (2nd Edition) usa um sistema único de dados. Os jogadores preparam as suas reservas de dados de acordo com as habilidades e armas dos personagens, e cada dado na reserva contribui para o ataque de diferentes formas.", "Fantasy Flight Games"),
(25, "Village", "20170511", "12+", 260.00, "Vida na aldeia é difícil – mas a vida aqui também permite que os habitantes cresçam e prosperem como bem entenderem. Um morador pode querer se tornar um frade. Outro pode sentir-se ambicioso e lutar por uma carreira em cargos públicos. Um terceiro pode querer procurar a sua sorte em terras distantes. Cada jogador irá tomar as rédeas de uma família e encontrar fama e glória de muitas maneiras diferentes. Há uma coisa que você não deve esquecer, no entanto: O tempo não pára e com o tempo as pessoas vão desaparecer.", "Fire on Board Jogos"),
(26, "Cyclades", "20070630", "13+", 150.00, "Em Cyclades, os jogadores devem comprar o favor dos deuses em sua corrida para ser o primeiro jogador a construir duas metrópoles no arquipélago grego conhecido como Cyclades.", "Galápagos Jogos"),
(27 , "Istanbul", "20050626", "13+", 240.00, "Em Istanbul, você lidera um grupo de um comerciante e quatro assistentes através de 16 locais no bazar. Em cada local, você pode realizar uma ação específica. O desafio , porém, é que para tomar uma ação, você deve mover o comerciante e um assistente lá, em seguida, deixar o assistente para trás ( para lidar com todos os detalhes , enquanto você se concentra em questões maiores). Se você quiser usar esse assistente novamente mais tarde, o comerciante deve retornar ao local para buscá-lo. Assim, você deve planejar com antecedência e com cuidado para evitar ficar sem assistentes e, portanto, incapaz de fazer qualquer coisa.", "Grow Jogos"),
(28, "Space Cantina", "20160110", "12+", 80.00, "Depois que a Federação Intergaláctica aprovou a construção do maior complexo comercial conhecido no Universo, dezenas de comerciantes espaciais decidiram abrir um negócio por perto, no Space Cantina. Você é um deles, tentando ganhar mais dinheiro com seu restaurante. Porém, a concorrência é enorme.", "Ace Studios"),
(29 , "Eclipse", "20110528", "14+", 270.00, "Por muitos anos, a galáxia tem sido um lugar pacífico. Depois da implacável Guerra Terran-Hegemony (30,027-33,364), muito esforço tem sido empregado por todas as espécies de grandes sistemas para evitar a repetição dos terríveis eventos. O Conselho Galáctico foi criado para impor a paz preciosa e tomou muitos corajosos esforços para prevenir a escalada de atos maliciosos. No entanto, a tensão e discórdia estão crescendo entre as sete principais espécies e no próprio Conselho. Velhas alianças estão quebrando e apressados tratados diplomáticos são feitos em sigilo. Um confronto das superpotências parece inevitável. Qual facção sairá vitoriosa e levar a galáxia sob o seu domínio?", "Asmodee"),
(30 , "The Gallerist", "20140330", "15+", 300.00, "Esta época de arte e capitalismo criou uma necessidade de uma nova ocupação, The Gallerist, que combina elementos do negociante de arte, curador do museu, e gerente dos artistas.", "Fire on Board Jogos"),
(31 , "Blood Rage", "20160504", "16+", 340.00, "Blood Rage é um jogo de tabuleiro Viking épico de pilhagem, luta, e aventuras para 2-4 jogadores, onde cada jogador representa um poderoso clã dos Vikings, que foram liberados das salas de Valhalla e dotados com dons dos próprios deuses para pilhar os restos mortais de Midgard enquanto ela queima durante o Ragnarok.", "Galápagos Jogos"),
(32 , "Merchants & Marauders", "20100302", "12+", 180.00, "Merchants & Marauders permite aos jogadores viver a vida de um influente comerciante ou um pirata temido no Caribe durante a época dourada da pirataria.", "Conclave Editora"),
(33 , "Arcadia Quest", "20100330", "10+", 200.00, "Em Arcadia Quest, os jogadores levam alianças de heróis intrépidos em uma campanha épica para destronar o lorde vampiro e recuperar o poderoso Arcadia. Mas só uma guilda pode levá-lo no final, e os jogadores devem lutar uns contra os outros, bem como contra as forças de ocupação monstruosas.", "Galápagos Jogos"),
(34 , "Patchwork", "20110730", "11+", 190.00, "Em Patchwork, dois jogadores competem para construir a mais estética (e de alta pontuação) colcha de retalhos em um tabuleiro de jogo pessoal de 9x9. Para iniciar o jogo, coloque para fora todos os patches de forma aleatória em um círculo e coloque um marcador diretamente no patch 2-1. Cada jogador tem cinco botões - a moeda / pontos do jogo - e alguém é escolhido como o jogador inicial", "Ludofy Creative"),
(35 , "Battlestar Galactica", "20080720", "10+", 300.00, "O jogo ambienta os participantes no seriado Battlestar Galactica e consegue reproduzir as situações que os personagens da TV sofriam durante os episódios. Cada um joga com um personagem da série, divididos em 4 grupos: Líder Político, Líder Militar, Piloto e Suporte.", " Fantasy Flight Games"),
(36 , "Star Wars: Rebellion", "20160220", "14+", 350.00, "Experimente a Guerra Civil Galática como nunca antes. Em Star Wars: Rebellion, você controla todo o Império Galático ou a Aliança Rebelde. ", "Galápagos Jogos"),
(37 , "Russian Railroads", "20130203", "12+", 200.00, "Russian Railroads é um jogo tematizado em estrada de ferro, com a mecânica de alocação de trabalhadores em que você tenta gerir uma série de trilhos de trem para marcar pontos de vitória.", "Z-Man Games"),
(38 , "Star Wars: X-Wing Miniatures Game", "20120920", "14+", 230.00, "Star Wars: X-Wing é um jogo de miniaturas de combate tático espacial, no qual os jogadores assumem o controle de poderosos X-Wings rebeldes e ágeis caças imperiais, encarando-os uns contra os outros em ritmo acelerado.", "Galápagos Jogos"),
(39 , " Dead of Winter: A Crossroads Game", "20140302", "12+", 200.00, "Crossroads é uma nova série da Plaid Hat Games que testa a capacidade de um grupo de sobreviventes a trabalhar juntos e permanecer vivo enquanto enfrenta crises e desafios, tanto fora como dentro.", "Galápagos Jogos"),
(40 , "Ticket to Ride: Europa", "20050330", "8+", 120.00, "Ticket to Ride: Europe leva você em uma nova aventura de trem pela Europa. De Edimburgo a Constantinopla e de Lisboa a Moscou, você vai visitar grandes cidades da Europa. Mais do que apenas um novo mapa, Ticket to Ride: Europe dispõe de novos elementos de jogabilidade, incluindo túneis e estações de trem. O jogo também inclui cartas de maior formato e peças de jogo Estação de Trem.", "Galápagos Jogos"),
(41 , "Caylus", "20050403", "12+", 100.00, "Era uma vez…1289. Para fortalecer as fronteiras do Reino da França, o rei Philip, o Justo, decidiu construir um novo castelo. Por enquanto Caylus não passa de uma aldeia humilde, mas logo, trabalhadores e artesãos estarão se reunindo, atraídos pelas grandes perspectivas. Perto do local da construção uma cidade está lentamente surgindo.", "Rio Grande Games"),
(42 , "Ticket to Ride: 10th Anniversary", "20140604", "8+", 80.00, "Em Ticket to Ride, jogadores recolhem cartas de vários tipos de vagões de trem usados para reivindicar rotas ferroviárias na América do Norte. Quanto mais longe as rotas, mais pontos ganham. Os pontos vêm para aqueles que cumprir os Tickets de Destino - cartas de objetivo que ligam cidades distantes; e para o jogador que constrói a mais longa rota contínua.", "Galápagos Jogos"),
(43 , "Zombicide: Black Plague", "20150320", "13+", 110.00, "Zombicide: Black Plague leva o apocalipse zumbi para um cenário medieval fantástico! Os poderes arcanos dos Necromantes desencadearam uma invasão de zumbis na idade das espadas e feitiçaria, e cabe ao seu grupo de desgarrados sobreviventes ficarem não só vivos durante esses tempos sombrios, mas ter de volta o reino e punir os responsáveis pelo Apocalipse!", " CMON Limited"),
(44 , "Kemet", "20120730", "13+", 200.00, "Em Kemet, os jogadores representam uma tribo egípcia e irão usar os poderes místicos dos deuses do antigo Egito – junto com seus exércitos poderosos – para marcar pontos em batalhas gloriosas ou através de invasão de ricos territórios.", "Galápagos Jogos"),
(45 , "Star Wars: Imperial Assault", "20150210", "12+", 300.00, "Imperial Assault é um jogo de tabuleiro estratégico de combate tático e missões para dois a cinco jogadores, oferecendo duas formas de jogos distintas de batalha e aventura no universo de Star Wars.", "Fantasy Flight Games"),
(46 , "Twilight Imperium (Third Edition)", "20050920", "12+", 390.00, "Twilight Imperium Third Edition é um jogo épico de construção de impérios com conflito interestelar, comércio, e luta pelo poder. Os jogadores assumem os papéis de antigas civilizações galácticas, cada uma procurando tomar o trono imperial através da guerra, diplomacia e progressão tecnológica. Com hexágonos de tabuleiro, miniaturas de plástico requintados, centenas de cartas, e introdução de um rico conjunto de dimensões estratégicas que permite a cada jogador reorientar o seu plano de jogo.", " Fantasy Flight Games"),
(47 , "Space Cantina", "20160110", "12+", 80.00, "Depois que a Federação Intergaláctica aprovou a construção do maior complexo comercial conhecido no Universo, dezenas de comerciantes espaciais decidiram abrir um negócio por perto, no Space Cantina. Você é um deles, tentando ganhar mais dinheiro com seu restaurante. Porém, a concorrência é enorme. ", "Ace Studios"),
(48 , "Dixit", "20080912", "8+", 200.00, "Na vez de cada jogador, o jogador escolhe uma de suas 6 cartas na mão e dá uma dica sobre a arte da mesma, pode ser uma palavra, frase, mímica, cantar (ou cantarolar) um música, após isso o jogador separa esta carta virada para baixo.", "Galápagos Jogos"),
(49 , "Keyflower", "20120911", "12+", 120.00, "Keyflower é um jogo para 2-6 jogadores jogado em quatro rodadas. Cada jogada representa uma estação: primavera, verão, outono e inverno.", "Redbox Editora"),
(50 , "<NAME>", "20030101", "8+", 90.00, "Dixit Odyssey é tanto um jogo independente quanto uma expansão para o jogo Dixit, com novas 84 cartas", "Galápagos Jogos,");
insert into generos (id, genero) values
(1, "Economia"),
(2, "Civilização"),
(3, "Expansão Territorial"),
(4, "Fantasia"),
(5, "Medieval"),
(6, "Agricultura"),
(7, "Viagem"),
(8, "Jogo de Cartas"),
(9, "Aventura"),
(10, "Exploração"),
(11, "Náutico"),
(12, "Luta"),
(13, "Política"),
(14, "Guerra Moderna"),
(15, "Antiguidade"),
(16, "Mitologia"),
(17, "Árabe"),
(18, "Construção de Cidades"),
(19, "Ambiental"),
(20, "Medicina"),
(21, "Indústria"),
(22, "Horror"),
(23, "Pré-Histórico"),
(24, "Dedução"),
(25, "Negociação"),
(26, "Ação"),
(27, "Investigação"),
(28, "RPG"),
(29, "Tabuleiro"),
(30, "Cartas"),
(31, "Adulto"),
(32, "Física"),
(33, "Ciência"),
(34, "Química"),
(35, "Matemática"),
(36, "Estratégia"),
(37, "Esporte"),
(38, "Corrida"),
(39, "Simulação"),
(40, "Trívia"),
(41, "MOBA"),
(42, "Quebra-Cabeça"),
(43, "Ritmo"),
(44, "FMVs"),
(45, "Casual"),
(46, "Violência"),
(47, "Escolar"),
(48, "Informática"),
(49, "Pós-Apocalipse"),
(50, "Pré-Apocalipse");
insert into jogos_possuem_generos (jogos_id, generos_id) values
(1, 2),
(2, 6),
(3, 7),
(4, 1),
(5, 8),
(6, 11),
(7, 9),
(8, 13),
(9, 20),
(10, 22),
(11, 35),
(12, 18),
(13, 15),
(14, 21),
(15, 3),
(16, 23),
(17, 5),
(18, 24),
(19, 25),
(20, 50),
(21, 4),
(22, 16),
(23, 17),
(24, 33),
(25, 48),
(26, 32),
(27, 31),
(28, 34),
(29, 14),
(30, 36),
(31, 26),
(32, 27),
(33, 29),
(34, 49),
(35, 19),
(36, 9),
(37, 10),
(38, 46),
(39, 44),
(40, 3),
(41, 45),
(42, 28),
(43, 30),
(44, 39),
(45, 38),
(46, 37),
(47, 40),
(48, 41),
(49, 42),
(50, 43);
insert into comprador (id, nome, data_nascimento, cpf, email) values
(1, "Silvio", "1992/02/25", "648519934/98", "<EMAIL>"),
(2, "Vitor", "1965/12/01", "009127132/08", "<EMAIL>"),
(3, "<NAME>", "1979/05/30", "718348054/22", "<EMAIL>"),
(4, "<NAME>", "1999/01/01", "448779538/92", "<EMAIL>"),
(5, "<NAME>", "1967/06/04", "333154541/40", "<EMAIL>"),
(6, "<NAME>", "1969/04/04", "745569374/50", "<EMAIL>"),
(7, "Solange", "1998/09/19", "285624513/71", "<EMAIL>"),
(8, "Miguel", "1971/08/24", "748644523/93", "<EMAIL>"),
(9, "Davi", "1999/02/24", "692895533/32", "<EMAIL>"),
(10, "Vera", "1984/05/30", "833863766/14", "<EMAIL>"),
(11, "Iris", "1995/02/15", "688466613/70", "<EMAIL>"),
(12, "Caroline", "1973/01/01", "077268416/21", "<EMAIL>"),
(13, "Jéssica", "1998/01/01", "653285616/94", "<EMAIL>"),
(14, "Joana", "1975/01/01", "305226624/12", "<EMAIL>"),
(15, "Pedro", "1999/01/01", "618266512/25", "<EMAIL>"),
(16, "<NAME>", "1974/01/01", "5713684938/1", "<EMAIL>"),
(17, "Ana", "1999/01/01", "143201283/54", "<EMAIL>"),
(18, "Maria", "1972/01/01", "715513192/09", "<EMAIL>"),
(19, "Joel", "1978/01/01", "351265808/33", "<EMAIL>"),
(20, "Eliabe", "1988/01/01", "213258413/31", "<EMAIL>"),
(21, "Lucas", "2000/11/27", "733279108/04", "<EMAIL>"),
(22, "Leonardo", "1997/01/01", "308405315/40", "<EMAIL>"),
(23, "Gabriela", "1981/01/01", "267625257/76", "<EMAIL>"),
(24, "Adriana", "1992/01/01", "835429739/04", "<EMAIL>"),
(25, "Ricardo", "1994/01/01", "767810380/87", "<EMAIL>"),
(26, "André", "2001/01/01", "767810380/00", "<EMAIL>"),
(27, "Ana", "2005/01/01", "767810380/07", "<EMAIL>"),
(28, "Kevin", "2001/05/24", "767810300/87", "<EMAIL>"),
(29, "Kauan", "1999/01/01", "767814550/87", "<EMAIL>"),
(30, "Jailson", "1988/05/24", "767810380/87", "<EMAIL>"),
(31, "Binho", "1954/12/21", "767812380/87", "<EMAIL>"),
(32, "Rubens", "1939/01/20", "7678121380/87", "<EMAIL>"),
(33, "Marcelo", "1987/02/21", "767120380/87", "<EMAIL>"),
(34, "Rodrigo", "1957/06/24", "767670380/87", "<EMAIL>"),
(35, "Angelita", "1964/08/30", "767710380/87", "<EMAIL>"),
(36, "Gabriel", "1972/04/21", "767850380/87", "<EMAIL>"),
(37, "Suellen", "1987/01/05", "767830380/87", "<EMAIL>"),
(38, "Cheregati", "1954/02/04", "762810380/87", "<EMAIL>"),
(39, "Pedro", "2003/01/07", "767810180/87", "<EMAIL>"),
(40, "Reginaldo", "2006/01/01", "769810380/87", "<EMAIL>"),
(41, "Brayan", "2000/01/05", "767810880/87", "<EMAIL>"),
(42, "Nicole", "1998/05/07", "767816380/87", "<EMAIL>"),
(43, "Richard", "1985/05/05", "767840380/87", "<EMAIL>"),
(44, "Elizangela", "1999/09/09", "717810380/87", "<EMAIL>"),
(45, "Jacquin", "1966/06/06", "767800380/87", "<EMAIL>"),
(46, "Paola", "1996/06/06", "767810980/87", "<EMAIL>"),
(47, "Fogaça", "1942/02/05", "767817380/87", "<EMAIL>"),
(48, "Henrique", "1945/02/09", "767610380/87", "<EMAIL>"),
(49, "Mirian", "1952/08/18", "767814380/87", "<EMAIL>"),
(50, "Mirio", "1988/05/01", "767810180/87", "<EMAIL>");
insert into tipo_pagamento (id, descricao) values
(1, "Crédito"),
(2, "Débito"),
(3, "Boleto"),
(4, "Outros");
insert into comprador_compra_jogos (comprador_id, jogos_id, quantidade, valor_compra, tipo_pagamento_id) values
(1, 14, 2, 0, 2),
(2, 16, 1, 0, 3),
(3, 22, 1, 0, 3),
(4, 15, 1, 0, 1),
(5, 11, 1, 0, 1),
(6, 8, 1, 0, 4),
(7, 10, 1, 0, 3),
(8, 19, 1, 0, 4),
(9, 21, 1, 0, 1),
(10, 9, 1, 0, 4),
(11, 4, 1, 0, 1),
(12, 20, 1, 0, 4),
(13, 25, 1, 0, 3),
(14, 8, 5, 0, 4),
(15, 12, 3, 0, 4),
(16, 1, 1, 0, 3),
(17, 3, 1, 0, 1),
(18, 5, 1, 0, 1),
(19, 2, 8, 0, 1),
(20, 18, 1, 0, 1),
(21, 23, 1, 0, 1),
(22, 13, 1, 0, 3),
(23, 6, 1, 0, 4),
(24, 14, 1, 0, 3),
(25, 26, 1, 0, 2),
(26, 27, 4, 0, 3),
(27, 28, 1, 0, 3),
(28, 29, 1, 0, 1),
(29, 23, 3, 0, 4),
(30, 29, 1, 0, 4),
(31, 30, 1, 0, 4),
(32, 31, 6, 0, 1),
(33, 32, 1, 0, 3),
(34, 43, 1, 0, 2),
(35, 16, 5, 0, 1),
(36, 50, 1, 0, 4),
(37, 12, 2, 0, 1),
(38, 50, 3, 0, 4),
(39, 43, 5, 0, 2),
(40, 45, 6, 0, 1),
(41, 48, 7, 0, 2),
(42, 49, 9, 0, 4),
(43, 1, 1, 0, 3),
(44, 46, 1, 0, 3),
(45, 20, 1, 0, 3),
(46, 21, 2, 0, 3),
(47, 9, 1, 0, 1),
(48, 42, 2, 0, 2),
(49, 5, 1, 0, 4),
(50, 37, 2, 0, 4);
update comprador_compra_jogos
inner join jogos
on jogos.id = comprador_compra_jogos.jogos_id
set comprador_compra_jogos.valor_compra = comprador_compra_jogos.quantidade * jogos.preco
where jogos.id = comprador_compra_jogos.jogos_id;<file_sep>/README.md
# Projeto Distribuidora
Este projeto reproduz a modelagem do banco de dados do catálogo de uma ditribuidora de jogos e suas respectivas vendas.
----------
----------
**Questões:**
----------
1 - Consulte o nome, a data de lançamento e o preço do top 10 jogos com o maior número de compras feitas por clientes de idade entre 10-45 anos que foram feitos por boleto.
----------
2 - Consulte o nome e a data de lançamento do top 5 jogos mais vendidos que tenham no mínimo 5 anos desde seu lançamento, exibindo também, quantos foram comprados.
----------
3 - Consulte o nome, a data de lançamento e o preço do top 8 dos jogos mais caros na loja, e quantas pessoas com idade maior que 18 anos os compraram.
----------
4 - Consulte o nome, preço e a quantidade comprada dos 3 jogos mais comprados do gênero "Aventura" lançados entre os anos 2010/01/01 e 2016/12/31.
----------
5 - Faça uma consulta que mostre de quais formas o jogo de id 19 foi comprado e quem o comprou.
----------
6 - Consultar o total de jogos vendidos de todas as classificações indicativas.
----------
7 - Consultar quantos clientes maiores que 18 anos que compraram jogos por cartão de crédito.
----------
8 - Consulte o nome e o cpf dos compradores que compraram jogos que custam mais de R$150.00.
----------
<file_sep>/distribuidora_estrutura.sql
-- MySQL Script generated by MySQL Workbench
-- Mon Sep 18 18:03:38 2017
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema distribuidora
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema distribuidora
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `distribuidora` DEFAULT CHARACTER SET utf8 ;
USE `distribuidora` ;
-- -----------------------------------------------------
-- Table `distribuidora`.`jogos`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `distribuidora`.`jogos` (
`id` INT NOT NULL AUTO_INCREMENT,
`nome` VARCHAR(80) NOT NULL,
`data_lancamento` DATE NOT NULL,
`classificacao_indicativa` VARCHAR(3) NOT NULL,
`preco` DECIMAL(5,2) NOT NULL,
`descricao` VARCHAR(1000) NOT NULL,
`produtora` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `distribuidora`.`generos`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `distribuidora`.`generos` (
`id` INT NOT NULL AUTO_INCREMENT,
`genero` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `distribuidora`.`comprador`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `distribuidora`.`comprador` (
`id` INT NOT NULL AUTO_INCREMENT,
`nome` VARCHAR(45) NOT NULL,
`data_nascimento` DATE NOT NULL,
`cpf` VARCHAR(13) NOT NULL,
`email` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `distribuidora`.`jogos_possuem_generos`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `distribuidora`.`jogos_possuem_generos` (
`jogos_id` INT NOT NULL,
`generos_id` INT NOT NULL,
PRIMARY KEY (`jogos_id`, `generos_id`),
INDEX `fk_jogos_has_generos_generos1_idx` (`generos_id` ASC),
INDEX `fk_jogos_has_generos_jogos_idx` (`jogos_id` ASC),
CONSTRAINT `fk_jogos_has_generos_jogos`
FOREIGN KEY (`jogos_id`)
REFERENCES `distribuidora`.`jogos` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_jogos_has_generos_generos1`
FOREIGN KEY (`generos_id`)
REFERENCES `distribuidora`.`generos` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `distribuidora`.`tipo_pagamento`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `distribuidora`.`tipo_pagamento` (
`id` INT NOT NULL,
`descricao` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `distribuidora`.`comprador_compra_jogos`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `distribuidora`.`comprador_compra_jogos` (
`comprador_id` INT NOT NULL,
`jogos_id` INT NOT NULL,
`quantidade` INT NOT NULL,
`valor_compra` FLOAT(7,2) NOT NULL,
`tipo_pagamento_id` INT NOT NULL,
PRIMARY KEY (`comprador_id`, `jogos_id`, `tipo_pagamento_id`),
INDEX `fk_comprador_has_jogos_jogos1_idx` (`jogos_id` ASC),
INDEX `fk_comprador_has_jogos_comprador1_idx` (`comprador_id` ASC),
INDEX `fk_comprador_compra_jogos_tipo_pagamento1_idx` (`tipo_pagamento_id` ASC),
CONSTRAINT `fk_comprador_has_jogos_comprador1`
FOREIGN KEY (`comprador_id`)
REFERENCES `distribuidora`.`comprador` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_comprador_has_jogos_jogos1`
FOREIGN KEY (`jogos_id`)
REFERENCES `distribuidora`.`jogos` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_comprador_compra_jogos_tipo_pagamento1`
FOREIGN KEY (`tipo_pagamento_id`)
REFERENCES `distribuidora`.`tipo_pagamento` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
| b12cab14a3416e67054d48d8028dae79dec1a373 | [
"Markdown",
"SQL"
] | 3 | SQL | CartinhaSquadETEC/projeto-distribuidora | cdae47fb1d3faea30754d803d3861cf71ac2961e | 0fa1e6b2f549a6c5353d0d1988e2a3611838f562 |
refs/heads/master | <repo_name>ekylibre/beardley-charts<file_sep>/Gemfile
source 'https://rubygems.org'
# Specify your gem's dependencies in beardley-charts.gemspec
gemspec
<file_sep>/lib/beardley-charts.rb
require 'beardley/charts'
| 2b44fd436bd1c35b5efe5cd36069ffb0e8735f3b | [
"Ruby"
] | 2 | Ruby | ekylibre/beardley-charts | 2243fe37cbcdcc6ddefaaeb75f26542299caf4fe | e170d26cd061a9c69c2129db2cd7c7ee0848eb33 |
refs/heads/main | <repo_name>shayanafzal/Amazon_Vine_Analysis<file_sep>/README.md
# Amazon Vine Analysis
## Overview of the analysis
### Purpose
The purpose of this analysis was to analyze reviews written by members of the paid Amazon Vine program. The Amazon Vine program is a service that allows manufacturers as well as publishers to receive reviews for their products.
The analysis looks at a data set of reviews for books on Amazon. PySpark has been used to perform the ETL process to extract the data from this data set. The data was then transformed and connected to AWS RDS instance. From there the data was loaded into PgAdmin.
Once the data was gathered, it was analyzed to determine if there is any bias towards favourable reviews coming form the Amazon Vine Program.
## Deliverables
[Deliverable 1 Coding](https://github.com/shayanafzal/Amazon_Vine_Analysis/blob/75568f4b1dbae57415b24c77885eae99f387c560/Amazon_Reviews_ETL.ipynb)
[Deliverable 1 PgAdmin Coding and Data Tables Screen Shots](https://github.com/shayanafzal/Amazon_Vine_Analysis/tree/main/Resources)
[Deliverable 2 Coding](https://github.com/shayanafzal/Amazon_Vine_Analysis/blob/75568f4b1dbae57415b24c77885eae99f387c560/Vine_Review_Analysis.ipynb)
## Results
* Total Vine Reviews – 5,272
* Total Non-Vine Reviews - 139,467
* Vine Reviews with 5 Star – 2,192
* Non-Vine Reviews with 5 Stars – 64,248
* Percentage of 5 Star Vine Reviews – 41.6 %
* Percentage of 5 Star Non-Vine Reviews – 46.1 %
## Summary
From the results above it is evident that out of the data set of books sold by amazon, 41.6% of the reviews posted by members of the Amazon Vine program are 5 star reviews.
Where was 46.1% of the reviews posted by non vine members are 5 star reviews.
In light of the data that we have, we can conlude that the members of the Amazon Vine program do not have a bias when giving out 5 Star reveiws for the books that they are reviewing as the total percentage of 5 Star reveiws left by members of the Amazon Vine program is lower than the total percetange of 5 star reviews left by those that are not members of the Amazon Vine program.
A futher recommendation would be to look into the total of number of 1 star reviews that are left by member of the Amazon Vine program. It could be that the members are only being sent the best books to review. Hence, looking into 1 star reviews would help determine if there is any systematic bias in the quality of the books that the Amazon Vine members are being asked to post reviews for.
<file_sep>/Resources/schema.sql
CREATE TABLE review_id_table (
review_id TEXT PRIMARY KEY NOT NULL,
customer_id INTEGER,
product_id TEXT,
product_parent INTEGER,
review_date DATE
);
CREATE TABLE products_table (
product_id TEXT PRIMARY KEY NOT NULL,
product_title TEXT
);
CREATE TABLE customers_table (
customer_id INT PRIMARY KEY NOT NULL,
customer_count INT
);
CREATE TABLE vine_table (
review_id TEXT PRIMARY KEY,
star_rating INET,
helpful_votes INT,
total_votes INT,
vine TEXT,
verified_purchase TEXT
);
SELECT COUNT(*) FROM REVIEW_ID_TABLE
SELECT COUNT(*) FROM PRODUCTS_TABLE
SELECT COUNT(*) FROM CUSTOMERS_TABLE
SELECT COUNT(*) FROM VINE_TABLE
| c74e4e0cb93608b4ff1d62a3c905d10eb05de528 | [
"Markdown",
"SQL"
] | 2 | Markdown | shayanafzal/Amazon_Vine_Analysis | 798b035f6358ce92a753213a20fa3a84e74413d3 | 2d2814c0d6413c1140784f37a42a52eb3f37b402 |
refs/heads/main | <file_sep>using System;
using System.Globalization;
using System.IO;
using System.Linq;
namespace SomeCAlgorithms {
internal static class Program {
private static void GetSortReturn(string filename = "file.in") {
// Trying to get the path to the file
try {
var directoryInfo = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
if (directoryInfo == null) return;
string line;
var path = Path.Combine(directoryInfo.FullName, filename);
// Read line of numbers from file
using (var fileStream = new StreamReader(path)) { line = fileStream.ReadLine(); }
// Iterating through splitted by ' ' line
if (line != null) { // If line exist
// Collect !numbers! from the line into List
var listToSort = line.Split(' ').Select(Convert.ToDouble).ToList();
listToSort.Sort(); // Sorting the array
File.WriteAllText(path, string.Empty); // Clear all file content
// Write all sorted array content into file.in
using (var fileStream = new StreamWriter(path)) {
foreach (var number in listToSort) {
fileStream.Write(number.ToString(CultureInfo.InvariantCulture) + " ");
}
}
}
}
catch (Exception e) {
Console.WriteLine("Error occured: " + e.Message);
}
}
public static void Main(string[] args) {
// Read array array from file, sort it and put it back
Console.Write("Enter a file name (default file.in): ");
var filename = Console.ReadLine();
if (filename != "") {
GetSortReturn(filename);
}
else {
GetSortReturn();
}
}
}
}<file_sep>using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
namespace ParabolaFly {
// Subclass that store data about current state of point in space
// Also it provides main functions to calculate speed, coords etc. of the point
public class Point {
public double X, Y, MomentSpeed; // MomentSpeed = v(t) == speed at moment t
public readonly double TimeStep;
private readonly double _angle, _speed;
private const double G = 9.81;
// Constructor (by default all params equals 0)
public Point(double timeStep, double x = 0, double y = 0, double speed = 0, double angle = 0) {
X = x;
Y = y;
_speed = speed;
_angle = ConvertToRadians(angle); // To use Math.Sin(), Math.Cos()
TimeStep = timeStep;
}
// Converts given angle in degrees into radians
private static double ConvertToRadians(double a) { return a * Math.PI / 180; }
// Simple function to calculate the square of given number
private static double GetSquare(double value) { return value * value; }
// Special function to calculate the total fly time
public double GetFlyTime() { return 2 * _speed * Math.Sin(_angle) / G; }
// Calculate X coord of the point at the moment t
private double CalculateX(double time) { return _speed * Math.Cos(_angle) * time; }
// Calculate Y coord of the point at the moment t
private double CalculateY(double time) { return _speed * Math.Sin(_angle) * time - (G * GetSquare(time) / 2); }
// Calculate the speed of the point at the moment t
private double CalculateSpeed(double time) {
double speedX = _speed * Math.Cos(_angle),
speedY = _speed * Math.Sin(_angle);
return Math.Sqrt((speedY - G * time) * (speedY - G * time) + GetSquare(speedX));
}
// Calculate the fly length
private double GetFlyLength() { return GetSquare(_speed) * Math.Sin(2 * _angle); }
// Calculate the max height of the fly
private double GetMaxFlyHeight() { return GetSquare(_speed * GetSquare(Math.Sin(_angle))) / 2 * G; }
// Collect all params of the fly into one string
public string CollectAllParams() {
return $"Total fly time: {GetFlyTime()}{Environment.NewLine}Fly total length: {GetFlyLength()}{Environment.NewLine}Fly maximum height: {GetMaxFlyHeight()}";
}
// Function to execute all calculation functions
public void CalculateCoords(double time) {
Y = CalculateY(time);
X = CalculateX(time);
MomentSpeed = CalculateSpeed(time);
}
}
public partial class MainWindow {
private static void StartVisualization(Point myPoint, FrameworkElement mainGrid) {
// Variables
const string filename = "output.out"; // Filename
double currentTime = 0;
// Get the Text Block element and clear it (if exist)
var output = (TextBlock) mainGrid.FindName("Output");
if (output != null) output.Text = "";
// File manipulations
var directoryInfo = Directory.GetParent(Directory.GetCurrentDirectory()).Parent; // Get the path to the file
if (directoryInfo == null) return; // No such file in directory
var path = Path.Combine(directoryInfo.FullName, filename); // Create path variable
// Calculating position until the point reaches the ground (x, 0)
using (var fileStream = new StreamWriter(path)) {
string line;
if (output != null) {
while (currentTime < myPoint.GetFlyTime()) {
currentTime += myPoint.TimeStep;
myPoint.CalculateCoords(Math.Round(currentTime, 4));
line = $"Time (t): {Math.Round(currentTime, 3)}\tX coord: {myPoint.X}\tY coord: {myPoint.Y}\tSpeed at moment t: {myPoint.MomentSpeed}";
if (!(myPoint.Y >= 0)) continue;
fileStream.WriteLine(line);
output.Text += line + Environment.NewLine;
}
}
line = $"Touch Down! (At {myPoint.GetFlyTime()} seconds)";
fileStream.Write(line);
if (output != null) output.Text += line;
}
var paramsOutput = (TextBlock) mainGrid.FindName("ParamsOutput");
if (paramsOutput != null) paramsOutput.Text = myPoint.CollectAllParams();
}
public MainWindow() {
InitializeComponent();
// Collect the input data into subclass Point
CalculateButton.Click += (sender, args) => {
// Check if all fields are not empty
if (InputAngle.Text != string.Empty && InputSpeed.Text != string.Empty && InputTimeStep.Text != string.Empty) {
const int x = 0, y = 0;
var speed = Convert.ToDouble(InputSpeed.Text.Replace('.', ','));
var angle = Convert.ToDouble(InputAngle.Text.Replace('.', ','));
var timeStep = Convert.ToDouble(InputTimeStep.Text.Replace('.', ','));
var myPoint = new Point(timeStep, x, y, speed, angle); // Create a new Point object
StartVisualization(myPoint, MainGrid); // This method will start drawing the myPoint fly
}
else {
// If one or more fields are empty -> Error message
MessageBox.Show("Some fields are empty! Please fill them all!");
}
};
}
}
}<file_sep># WPF2021 - Windows Presentation Foundation 2021 -- Алгоритмы и структуры данных
<NAME> ПМ-201
| 3be029eea04e60049e1031c894eb88debf714747 | [
"Markdown",
"C#"
] | 3 | C# | MrRooots/WPF2021 | ff927a11a28fa54210988c14a26fa23171ad11da | 87360ac84f92b34c59fcb1cf989099e52fae58b7 |
refs/heads/main | <file_sep>Documentation : https://documenter.getpostman.com/view/12500382/TzRLmWNB
<file_sep>const authRoutes = require('express').Router()
const authControllers = require('../controllers/authControllers')
authRoutes.post('/sign-up',authControllers.signup)
authRoutes.post('/sign-in',authControllers.signin)
module.exports=authRoutes<file_sep>const { foods } = require('../models')
const response = require('../helpers/response')
module.exports = {
postFoods: (req, res) => {
let { body } = req;
foods.create(body)
.then((data) => {
response.success(res, "Succes Post Foods", 200, data)
})
.catch((err) => {
response.error(res, 500, err)
});
},
getAllFoods: (req, res) => {
foods.findAll()
.then((data) => {
response.success(res, "success Get All Foods", 200, data)
})
.catch((err) => {
response.error(res, 500, err)
});
},
getDataById: (req, res) => {
let { id } = req.params;
foods.findOne({
where: { id }
})
.then((data) => {
response.success(res, "Succes Get Data By Id", 200, data)
.catch((err) => {
response.error(res, 500, err)
});
})
},
updateFoods: (req, res) => {
let { id } = req.params;
let { body } = req
foods.update(body, {
where: {
id: id
}
}).then((data) => {
response.success(res, "Succes Update Foods", 200, data)
}).catch((err) => {
response.error(res, 500, err)
})
},
deleteFood: (req, res) => {
let { id } = req.params;
foods.destroy({
where: {
id: id
}
}).then((data) => {
response.success(res, "Succes Delete Foods", 200, data)
}).catch((err) => {
response.error(res, 500, err)
})
}
} | 5e5410c22e6b4ac327103440bfc95359985953f3 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | Zahro25/resfull-sequelize-jwt | b97b96ab39f19d9eaf8845598f06887fa73f8ee5 | a0a2970b6d2a4f7df0005a9331605eeae9924345 |
refs/heads/master | <file_sep>
# Install NPM dependencies
npm install
# Run NPM
npm start
Your app will then be running on port 5000.
<file_sep>angular
.module('materialApp.directives', [])
.directive('feedItem', feedItem);
/* @ngInject */
function feedItem() {
var directive = {
bindToController: true,
controller: feedController,
controllerAs: 'feed',
link: link,
restrict: 'EA',
require: ['feedItem'],
templateUrl: 'directives/feed/feed.html',
scope: {
url: '@',
title: '@',
loved: '@',
posted: '@',
description: '@',
posturl: '@',
artist: '@',
sitename: '@',
posturl: '@',
time: '@'
}
};
return directive;
function link(scope, element, attrs, controllers) {
var time = scope.feed.time;
var string = "";
var min = Math.floor(time/60);
var sec = Math.floor(time%60);
if(sec < 10) {
string = min + ":0"+ sec;
}
else {
string = min + ":"+ sec;
}
scope.feed.nTime = string;
// scope.apply();
// var appCtrl = controllers[0],
// feedCtrl = controllers[1];
// feedCtrl.options = appCtrl.options;
// feedCtrl.localUser = appCtrl.localUser;
}
}
/* @ngInject */
function feedController() {}
| ce6491c01d90fc1d8cf39867c5e77b5f8156971b | [
"Markdown",
"JavaScript"
] | 2 | Markdown | topmaster716/angluar-material-master6 | a76e927792da51df2943c120b1e3da1843968991 | b14d6772ab5d67fae3bf8e23d77cd10629e2c1cc |
refs/heads/master | <repo_name>HoXP/DiffDemo<file_sep>/Assets/Common/FileManager.cs
using System.IO;
public class FileCatchData
{
public bool state = true; //操作是否成功
public string message = ""; //失败之后的信息
public object data = null ; //需要返回的数据
}
/// <summary>
/// 包外文件管理器
/// </summary>
public class FileManager
{
/// <summary>
/// 删除文件
/// </summary>
public static FileCatchData DeleteFile(string path)
{
FileCatchData fileCatchData = new FileCatchData();
if(string.IsNullOrEmpty(path))
{
fileCatchData.state = false;
return fileCatchData;
}
try
{
if (File.Exists(path))
{
File.Delete(path);
}
fileCatchData.state = true;
}
catch (System.Exception e)
{
fileCatchData.state = false;
fileCatchData.message = e.Message;
}
return fileCatchData;
}
}
<file_sep>/Assets/Common/DllManager.cs
using System.Runtime.InteropServices;
public class DllManager
{
[DllImport("bsdiff")]
public static extern int StartDiff(string oldFile, string newFile, string patch);
[DllImport("bspatch")]
public static extern int StartPatch(string oldFile, string outFile, string patch);
}<file_sep>/Assets/Editor/PatchEditor.cs
using System.IO;
using UnityEditor;
using UnityEngine;
public class PatchEditor : EditorWindow
{
private const string ext = ".zip";
[MenuItem("Tools/Diff File")]
public static void DiffFile()
{
string basePath = Application.dataPath + "/../";
string oldFile = basePath + "Diff/old" + ext;
string newFile = basePath + "Diff/new" + ext;
string patchFile = basePath + "Diff/patch";
if (File.Exists(oldFile) == false || File.Exists(newFile) == false)
{
Debug.Log("cant find file oldFile=" + oldFile + ";newFile=" + newFile);
return;
}
FileManager.DeleteFile(patchFile);
string[] list = new string[4];
list[0] = "bsdiff";
list[1] = oldFile;
list[2] = newFile;
list[3] = patchFile;
Debug.Log("oldFile ===" + oldFile);
Debug.Log("newFile ===" + newFile);
Debug.Log("patchFile ===" + patchFile);
int value = DllManager.StartDiff(oldFile, newFile, patchFile);
Debug.Log("DiffFile ===" + value);
}
[MenuItem("Tools/Patch File")]
public static void PatchFile()
{
string basePath = Application.dataPath + "/../";
string oldFile = basePath + "Diff/old" + ext;
string outFile = basePath + "Diff/out" + ext;
string patchFile = basePath + "Diff/patch";
if (File.Exists(oldFile) == false || File.Exists(patchFile) == false)
{
Debug.Log("cant find file oldFile=" + oldFile + ";patchFile=" + patchFile);
return;
}
FileManager.DeleteFile(outFile);
string[] list = new string[4];
list[0] = "bspatch";
list[1] = oldFile;
list[2] = outFile;
list[3] = patchFile;
Debug.Log("oldFile ===" + oldFile);
Debug.Log("outFile ===" + outFile);
Debug.Log("patchFile ===" + patchFile);
int value = DllManager.StartPatch(oldFile, outFile, patchFile);
Debug.Log("PatchFile ===" + value);
}
} | fda319e876feda15dbc75d2ff3ba8f6c83fe8b9e | [
"C#"
] | 3 | C# | HoXP/DiffDemo | 05d8de533567e1582ad4cefa39fcf3c557df8e2b | 3e26ebeec01186667cea294178a586dfa71570fe |
refs/heads/master | <repo_name>Driver121/cv_5<file_sep>/src/cv5H.h
/*
* cv5H.h
*
* Created on: 18. 10. 2016
* Author: Peter
*/
#ifndef CV5H_H_
#define CV5H_H_
void adc_init(void);
void init_NVIC(void);
void ADC1_IRQHandler(void);
void initUSART2(void); // usart 1
void PutcUART2(char);// usart 1
void RegisterCallbackUART2(void *callback); // usart 1
void USART2_IRQHandler(void); // usart 1
double prevod();
void stav(uint16_t);
void Put(char []);
void posliPoZnaku(char , int );
void posliDoFunkcie();
char znak[];
#endif /* CV5H_H_ */
| 24d7a198cde6d5d646fabc5b121161a51a460108 | [
"C"
] | 1 | C | Driver121/cv_5 | 2651c95d87e66d1107728a305b807109f656e94b | 6f5aa8028aa889d85c4dc1a4e05c67956a43cf2d |
refs/heads/master | <repo_name>cdmihai/D3Viz<file_sep>/startServer
#!/bin/sh
serverPath=`pwd`
if [ $# -eq 1 ]
then
eval serverPath=$1
fi
echo "Starting server at:" $serverPath
echo
config="server.document-root = \"${serverPath}\"\n"
config="${config}server.port = 3000\n"
config="${config}"'mimetype.assign = (".html" => "text/html", ".css" => "text/css", ".txt" => "text/plain",".jpg" => "image/jpeg", ".png" => "image/png", ".js" => "application/javascript", ".json" => "application/json")'
echo $config > lighttpd.config
lighttpd -t -f lighttpd.config
lighttpd -D -f lighttpd.config
<file_sep>/GroupedBarChart.js
/*
Based on: http://bl.ocks.org/mbostock/3887051
*/
/*
Displays a grouped bar chart.
The chart takes as input the name of the first column (via mainGroupName()).
This is the column around which the rest of the columns are grouped by.
*/
function groupedBarChart() {
//pading around the chart
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
};
var width = 960 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
var yLabel ="";
//column name of first grouping
//the bars will be grouped by this column
var mainGroupingName = ""
//scale responsible for the main grouping
var x0 = d3.scale.ordinal()
//scale responsible for the grouped bars
//it "exists" inside x0: its range is as big as one band in X0
var x1 = d3.scale.ordinal();
var y = d3.scale.linear();
//a color scale for the grouped bars
var color = d3.scale.category20();
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
//add styling to the axis.
var styleAxis = function (element) {
element.style("fill", "none")
.style("stroke", "#000")
.style("shape-rendering", "crispEdges")
.style("font", "10px sans-serif")
return element;
}
var chart = function (selection) {
selection.each(function (data) {
//retrieve the inner grouping column names as all the column names of a node except the primary one
var secondGroupingNames = d3.keys(data[0]).filter(function (key) {
return key !== mainGroupingName;
});
//add a new field to all data objects that contains an array off all the values in a key - value format
//this is needed to be able to join the grouped data to its marks
data.forEach(function (d) {
d.secondGrouping = secondGroupingNames.map(function (name) {
return {
name: name,
value: +d[name]
};
});
});
x0.rangeRoundBands([0, width], .1);
//the domain of the primary grouping
x0.domain(data.map(function (d) {
return d[mainGroupingName];
}));
//the domain of the secondary grouping represents the values of the secondary grouped columns
//the range is the range of one of the primary groupings. This ensures that the grouped columns fit in the larger grouping
x1.domain(secondGroupingNames).rangeRoundBands([0, x0.rangeBand()]);
y.range([height, 0]);
//compute the maximum of all the nested values
y.domain([0, d3.max(data, function (d) {
return d3.max(d.secondGrouping, function (d) {
return d.value;
});
})]);
var svg = d3.select(this) //the element that contains the graph
.append("svg") //create the svg
.attr("width", width + margin.left + margin.right) //width, including margins
.attr("height", height + margin.top + margin.bottom) //height, including margins
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); //translate to margin corner
//Ox axis styling
svg.append("g")
.call(styleAxis)
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
//Oy axis styling and label
svg.append("g")
.call(styleAxis)
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text(yLabel);
//create groups for each main grouping value
var mainGrouping = svg.selectAll(".mainGrouping")
.data(data) //the top level data is joined, each row in the data gets one group
.enter().append("g")
.attr("class", "g")
.attr("transform", function (d) {
return "translate(" + x0(d[mainGroupingName]) + ",0)"; //each main grouping is translated to a position via the x0 scale
});
//create the grouped bars
mainGrouping.selectAll("rect")
.data(function (d) { //for each row, join its nested data to rectangles from inside each higher level group
return d.secondGrouping;
})
.enter().append("rect")
.attr("width", x1.rangeBand()) //use x1 to get the height of a single bar, so it fits inside the larger band defined by x0
.attr("x", function (d) {
return x1(d.name); //use x1 to obtain the position of a specific bar
})
.attr("y", function (d) {
return y(d.value); //use y to scale the actual value
})
.attr("height", function (d) {
return height - y(d.value);
})
.style("fill", function (d) {
return color(d.name); //get the color for a specific bar
});
var legend = svg.selectAll(".legend")
.data(secondGroupingNames.slice())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) {
return "translate(0," + i * 20 + ")"; //put the legend boxes vertically on top of each other
});
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function (d) {
return d;
});
});
}
//here be getters and setters
chart.mainGroupingName = function (value) {
if (!arguments.length) return dateFormat;
mainGroupingName = value;
return this;
};
chart.width = function (value) {
if (!arguments.length) return width;
width = value - margin.left - margin.right;
return this;
};
chart.height = function (value) {
if (!arguments.length) return height;
height = value - margin.top - margin.bottom;
return this;
};
chart.yLabel = function (value) {
if (!arguments.length) return yLabel;
yLabel = value;
return this;
};
chart.yLabel = function (value) {
if (!arguments.length) return yLabel;
yLabel = value;
return this;
};
return chart;
} | d307c4c75e8a5385010f52853a2c6b1217480dbe | [
"JavaScript",
"Shell"
] | 2 | Shell | cdmihai/D3Viz | c67be3f20533039accc8ce4e28c19e7d3de4bada | 133a8e8084ad69abae1824692bb74dd9bd9da007 |
refs/heads/master | <repo_name>s4heid/dpb587.me<file_sep>/content/photo/2014-barcelona-trip/83ed7ac-font-magica-de-montjuic.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 19:35:34'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.37096167
longitude: 2.15126667
next: /gallery/2014-barcelona-trip/a061586-font-magica-de-montjuic
ordering: 29
previous: /gallery/2014-barcelona-trip/7f51e46-font-magica-de-montjuic
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Font màgica de Montjuïc'
aliases:
- /gallery/2014-barcelona-trip/83ed7ac-font-magica-de-montjuic.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/507bcb2-img-1148.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-13 13:50:20'
exif:
aperture: f/2.4
exposure: 1/129
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 34.79563
longitude: -106.390525
ordering: 27
previous: /gallery/2014-albuquerque-balloon-fiesta/c60d938-img-1145
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1148
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/507bcb2-img-1148.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/468d46d-img-1199.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 19:19:02'
exif:
aperture: f/2.2
exposure: 1/1647
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44129667
longitude: 103.85865833
next: /gallery/2015-cambodia-thailand-trip/4ad3c57-img-1204
ordering: 38
previous: /gallery/2015-cambodia-thailand-trip/9a599fd-img-1196
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1199
aliases:
- /gallery/2015-cambodia-thailand-trip/468d46d-img-1199.html
---
<file_sep>/content/photo/2015-balloon-fiesta/c7a6b71-imag2233.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 06:41:25'
exif:
aperture: f/2.0
exposure: 364/1000000
make: HTC
model: HTC6500LVW
layout: gallery-photo
location:
latitude: 35.19432
longitude: -106.59864
next: /gallery/2015-balloon-fiesta/0234c12-img-0399
ordering: 9
previous: /gallery/2015-balloon-fiesta/89dbad4-img-0392
sizes:
1280:
height: 724
width: 1280
640w:
height: 362
width: 640
200x200:
height: 200
width: 200
title: IMAG2233
aliases:
- /gallery/2015-balloon-fiesta/c7a6b71-imag2233.html
---
<file_sep>/content/photo/2015-england-trip/6d56866-38a48962-13c2-419b-8273-ae7cf45c0002.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 09:07:36'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.38162167
longitude: -2.358795
next: /gallery/2015-england-trip/d702f2b-e9b69c74-3c6f-41d3-8f76-5d2aac504cae
ordering: 38
previous: /gallery/2015-england-trip/3089002-55261651-5765-4713-9bcc-445ea2bd0333
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 38A48962-13C2-419B-8273-AE7CF45C0002
aliases:
- /gallery/2015-england-trip/6d56866-38a48962-13c2-419b-8273-ae7cf45c0002.html
---
<file_sep>/content/photo/2014-london-iceland-trip/c758581-glacier-walk.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 17:22:48'
exif:
aperture: f/2.4
exposure: 1/861
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.53488667
longitude: -19.34806667
next: /gallery/2014-london-iceland-trip/5303bd3-panorama
ordering: 86
previous: /gallery/2014-london-iceland-trip/6be2794-glacier-walk
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Glacier Walk'
aliases:
- /gallery/2014-london-iceland-trip/c758581-glacier-walk.html
---
In the crevasse, there was another tour where you could climb up the glacier walls.
<file_sep>/content/photo/2015-costa-rica-trip/52fbc4f-hanging-bridges.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 08:56:46'
exif:
aperture: f/2.2
exposure: 1/573
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.34122
longitude: -84.797875
next: /gallery/2015-costa-rica-trip/b442c36-hanging-bridges
ordering: 61
previous: /gallery/2015-costa-rica-trip/2cdf51c-hanging-bridges
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Hanging Bridges'
aliases:
- /gallery/2015-costa-rica-trip/52fbc4f-hanging-bridges.html
---
There also happened to be a lot of hummingbirds hanging around the paths, like this green one.
<file_sep>/content/photo/2015-costa-rica-trip/02aeb31-el-avion.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-18 17:24:24'
exif:
aperture: f/2.2
exposure: 1/898
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.40210333
longitude: -84.15347217
next: /gallery/2015-costa-rica-trip/3078b77-el-avion
ordering: 115
previous: /gallery/2015-costa-rica-trip/5ea206c-el-avion
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'El Avión'
aliases:
- /gallery/2015-costa-rica-trip/02aeb31-el-avion.html
---
There are going to be a few of these pictures of the sun setting...
<file_sep>/README.md
This is my personal website running at [dpb587.me](https://dpb587.me/). [Hugo](https://gohugo.io/) is used to generate the site.
Unless noted, software code is licensed under [MIT License](https://github.com/dpb587/dpb587.me/blob/master/LICENSE) and all other content is licensed under [CC-BY](http://opendefinition.org/licenses/cc-by/).
<file_sep>/content/photo/2015-cambodia-thailand-trip/4d68b2e-img-1416.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 01:33:13'
exif:
aperture: f/2.2
exposure: 1/1522
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44662
longitude: 103.91981333
next: /gallery/2015-cambodia-thailand-trip/9f0162c-img-1436
ordering: 52
previous: /gallery/2015-cambodia-thailand-trip/4050aa0-img-1408
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1416
aliases:
- /gallery/2015-cambodia-thailand-trip/4d68b2e-img-1416.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/9ab9107-img-2186.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-20 00:08:55'
exif:
aperture: f/2.2
exposure: 1/107
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.74673
longitude: 100.49221167
next: /gallery/2015-cambodia-thailand-trip/e61d2c7-img-2196
ordering: 112
previous: /gallery/2015-cambodia-thailand-trip/276b568-img-2169
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2186
aliases:
- /gallery/2015-cambodia-thailand-trip/9ab9107-img-2186.html
---
<file_sep>/content/photo/2015-costa-rica-trip/f46cf80-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 09:12:57'
exif:
aperture: f/2.2
exposure: 1/1464
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.38428333
longitude: -84.1385945
next: /gallery/2015-costa-rica-trip/b89996d-manuel-antonio-national-park
ordering: 98
previous: /gallery/2015-costa-rica-trip/327d1bb-manuel-antonio-national-park
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Manuel Antonio National Park'
aliases:
- /gallery/2015-costa-rica-trip/f46cf80-manuel-antonio-national-park.html
---
Another view from one of the other viewpoints in the park. There were about 6 specific platforms/viewpoints in the park.
<file_sep>/content/photo/2014-london-iceland-trip/59809e9-tyrannosaurus-rex.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 11:24:28'
exif:
aperture: f/2.4
exposure: 1/15
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.495914
longitude: -0.176366
next: /gallery/2014-london-iceland-trip/6132b85-giraffe
ordering: 27
previous: /gallery/2014-london-iceland-trip/a8e17f9-stegosaurus
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Tyrannosaurus Rex'
aliases:
- /gallery/2014-london-iceland-trip/59809e9-tyrannosaurus-rex.html
---
They had about a dozen large skeletons set up around the exhibit. There were lots of fields trips at the museum.
<file_sep>/content/photo/2015-costa-rica-trip/e6652a0-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 07:58:53'
exif:
aperture: f/2.2
exposure: 1/1721
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.380125
longitude: -84.13964717
next: /gallery/2015-costa-rica-trip/f4bad1a-manuel-antonio-national-park
ordering: 88
previous: /gallery/2015-costa-rica-trip/917dd23-manuel-antonio-national-park
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: '<NAME>onio National Park'
aliases:
- /gallery/2015-costa-rica-trip/e6652a0-manuel-antonio-national-park.html
---
We took a break here to have breakfast... of PB&Js.
<file_sep>/content/photo/2015-cambodia-thailand-trip/2927987-img-2383.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-22 01:20:35'
exif:
aperture: f/2.2
exposure: 1/50
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.695925
longitude: 100.74758
ordering: 131
previous: /gallery/2015-cambodia-thailand-trip/5c50d93-img-2380
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2383
aliases:
- /gallery/2015-cambodia-thailand-trip/2927987-img-2383.html
---
<file_sep>/content/photo/2015-balloon-fiesta/0234c12-img-0399.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 06:43:47'
exif:
aperture: f/2.2
exposure: 1/1163
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19517833
longitude: -106.59832
next: /gallery/2015-balloon-fiesta/de8713a-img-0410
ordering: 10
previous: /gallery/2015-balloon-fiesta/c7a6b71-imag2233
sizes:
1280:
height: 276
width: 1280
640w:
height: 138
width: 640
200x200:
height: 200
width: 200
title: IMG_0399
aliases:
- /gallery/2015-balloon-fiesta/0234c12-img-0399.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/7156473-img-1132.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 18:09:36'
exif:
aperture: f/2.2
exposure: 1/1319
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.40668833
longitude: 103.864655
next: /gallery/2015-cambodia-thailand-trip/b53c895-img-1140
ordering: 27
previous: /gallery/2015-cambodia-thailand-trip/0679a96-img-1131
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1132
aliases:
- /gallery/2015-cambodia-thailand-trip/7156473-img-1132.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/b6da0c7-img-1186.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 18:57:17'
exif:
aperture: f/2.2
exposure: 1/608
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44147
longitude: 103.85955
next: /gallery/2015-cambodia-thailand-trip/3dbcc3b-img-1187
ordering: 35
previous: /gallery/2015-cambodia-thailand-trip/f9f7cbe-img-1182
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1186
aliases:
- /gallery/2015-cambodia-thailand-trip/b6da0c7-img-1186.html
---
<file_sep>/content/photo/2015-balloon-fiesta/9ee1c77-img-0503.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-08 11:49:20'
exif:
aperture: f/2.2
exposure: 1/1199
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.1872
longitude: -106.69281667
next: /gallery/2015-balloon-fiesta/0a0247c-img-0522
ordering: 22
previous: /gallery/2015-balloon-fiesta/711f1d1-img-0499
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_0503
aliases:
- /gallery/2015-balloon-fiesta/9ee1c77-img-0503.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/a92f6a2-img-1029.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 18:26:21'
exif:
aperture: f/2.2
exposure: 1/1883
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.56395
longitude: 104.93112167
next: /gallery/2015-cambodia-thailand-trip/2e84c6b-img-1031
ordering: 12
previous: /gallery/2015-cambodia-thailand-trip/cbb80b5-img-1023
sizes:
1280:
height: 390
width: 1280
640w:
height: 195
width: 640
200x200:
height: 200
width: 200
title: IMG_1029
aliases:
- /gallery/2015-cambodia-thailand-trip/a92f6a2-img-1029.html
---
<file_sep>/content/photo/2014-barcelona-trip/b4f7cf3-flying-back.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-25 11:23:38'
exif:
aperture: f/2.2
exposure: 1/5650
make: Apple
model: 'iPhone 6'
layout: gallery-photo
ordering: 93
previous: /gallery/2014-barcelona-trip/1ef572c-beach
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Flying Back'
aliases:
- /gallery/2014-barcelona-trip/b4f7cf3-flying-back.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/aca3309-img-1800.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 19:49:21'
exif:
aperture: f/2.2
exposure: 1/706
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.43449167
longitude: 103.88992167
next: /gallery/2015-cambodia-thailand-trip/52209eb-img-1815
ordering: 73
previous: /gallery/2015-cambodia-thailand-trip/97f665d-img-1738
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1800
aliases:
- /gallery/2015-cambodia-thailand-trip/aca3309-img-1800.html
---
<file_sep>/content/photo/2015-costa-rica-trip/c8f8633-monteverde-chocolate-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-13 14:08:25'
exif:
aperture: f/2.2
exposure: 1/40
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.45817
longitude: -84.65201667
next: /gallery/2015-costa-rica-trip/5f71bc8-jeep-boat-jeep
ordering: 38
previous: /gallery/2015-costa-rica-trip/0a29380-monteverde-chocolate-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Monteverde Chocolate Tour'
aliases:
- /gallery/2015-costa-rica-trip/c8f8633-monteverde-chocolate-tour.html
---
They then let us crush the nibs into a powder where they mixed it with warm water for a very strong warm chocolate. We could concoct several different spoonful flavors by adding our own spices and toppings.
<file_sep>/content/photo/2014-london-iceland-trip/c16a7b6-thames-cable-car.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-08 16:35:40'
exif:
aperture: f/2.4
exposure: 1/935
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.499772965908
longitude: 0.008321972564
next: /gallery/2014-london-iceland-trip/2c1b931-river-thames
ordering: 6
previous: /gallery/2014-london-iceland-trip/c217f20-greenwich-park
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Thames Cable Car'
aliases:
- /gallery/2014-london-iceland-trip/c16a7b6-thames-cable-car.html
---
We took the cable car across the River Thames as another unique transportation method.
<file_sep>/content/photo/2015-cambodia-thailand-trip/0119242-img-2251.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-20 01:12:06'
exif:
aperture: f/2.2
exposure: 1/33
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.74663333
longitude: 100.49337833
next: /gallery/2015-cambodia-thailand-trip/34cf764-img-2256
ordering: 116
previous: /gallery/2015-cambodia-thailand-trip/062b0a1-img-2234
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2251
aliases:
- /gallery/2015-cambodia-thailand-trip/0119242-img-2251.html
---
<file_sep>/content/photo/2015-balloon-fiesta/914279d-img-0922.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-11 17:19:14'
exif:
aperture: f/2.2
exposure: 1/120
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.68769167
longitude: -105.93876667
ordering: 41
previous: /gallery/2015-balloon-fiesta/021aeeb-img-0920
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_0922
aliases:
- /gallery/2015-balloon-fiesta/914279d-img-0922.html
---
<file_sep>/content/photo/2015-england-trip/2d3df9a-184c652a-394f-40e1-b325-b3ff0ef009e3.md
---
galleries:
- 2015-england-trip
date: '2015-03-08 05:44:54'
exif:
aperture: f/2.2
exposure: 1/1276
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.50883833
longitude: -0.07612217
next: /gallery/2015-england-trip/bab7628-9010d32f-fe0b-4648-a498-4c68cdd114de
ordering: 4
previous: /gallery/2015-england-trip/84d1f65-2f92ff97-e35e-45c1-8ac4-c01b017d0636
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 184C652A-394F-40E1-B325-B3FF0EF009E3
aliases:
- /gallery/2015-england-trip/2d3df9a-184c652a-394f-40e1-b325-b3ff0ef009e3.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/8230d10-img-1053.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 07:39:05'
exif:
aperture: f/2.4
exposure: 1/209
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.195655
longitude: -106.5981
next: /gallery/2014-albuquerque-balloon-fiesta/12895b3-img-1054
ordering: 6
previous: /gallery/2014-albuquerque-balloon-fiesta/9691dba-img-1051
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1053
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/8230d10-img-1053.html
---
<file_sep>/content/photo/2014-barcelona-trip/66cda3d-barcelona-port.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-24 14:35:37'
exif:
aperture: f/2.2
exposure: 1/989
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.37584167
longitude: 2.17906167
next: /gallery/2014-barcelona-trip/f3e1020-beach
ordering: 89
previous: /gallery/2014-barcelona-trip/f19bddd-walkway
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Barcelona Port'
aliases:
- /gallery/2014-barcelona-trip/66cda3d-barcelona-port.html
---
<file_sep>/content/photo/2014-london-iceland-trip/fbe9b12-hyde-park.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-08 12:47:03'
exif:
aperture: f/2.4
exposure: 1/5435
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.502492355028
longitude: -0.140907744457
next: /gallery/2014-london-iceland-trip/033bb54-royal-observatory
ordering: 3
previous: /gallery/2014-london-iceland-trip/b70543a-natural-history-museum
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Hyde Park'
aliases:
- /gallery/2014-london-iceland-trip/fbe9b12-hyde-park.html
---
As a part of our transportation tour, we biked through Hyde Park and past Buckingham Palace. The Queen was in, but she was too busy to say hi.
<file_sep>/content/photo/2014-london-iceland-trip/6be2794-glacier-walk.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 17:18:27'
exif:
aperture: f/2.4
exposure: 1/733
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.53487
longitude: -19.35039667
next: /gallery/2014-london-iceland-trip/c758581-glacier-walk
ordering: 85
previous: /gallery/2014-london-iceland-trip/b6db71d-glacier-walk
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Glacier Walk'
aliases:
- /gallery/2014-london-iceland-trip/6be2794-glacier-walk.html
---
It was fun hiking up and around the different glacier features.
<file_sep>/content/photo/2015-costa-rica-trip/0f5608b-tree-house-restaurant.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 21:06:34'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.31620833
longitude: -84.82524167
next: /gallery/2015-costa-rica-trip/97dc064-hanging-bridges
ordering: 58
previous: /gallery/2015-costa-rica-trip/d86ce6f-don-juan-coffee-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Tree House Restaurant'
aliases:
- /gallery/2015-costa-rica-trip/0f5608b-tree-house-restaurant.html
---
For dinner Wednesday, we found a restaurant on the second floor which had the tree top as the roof.
<file_sep>/content/photo/2014-barcelona-trip/1474689-parc-guell.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 14:46:40'
exif:
aperture: f/2.2
exposure: 1/1980
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.41486167
longitude: 2.15203883
next: /gallery/2014-barcelona-trip/3f1a4bb-parc-guell
ordering: 2
previous: /gallery/2014-barcelona-trip/9ef11bc-parc-guell
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: '<NAME>'
aliases:
- /gallery/2014-barcelona-trip/1474689-parc-guell.html
---
<file_sep>/content/photo/2014-london-iceland-trip/e1c9e55-museum-of-skogar.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 15:14:20'
exif:
aperture: f/2.4
exposure: 1/20
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.52618333
longitude: -19.49292833
next: /gallery/2014-london-iceland-trip/fc55b8c-museum-of-skogar
ordering: 79
previous: /gallery/2014-london-iceland-trip/833c1b3-museum-of-skogar
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Museum of Skógar'
aliases:
- /gallery/2014-london-iceland-trip/e1c9e55-museum-of-skogar.html
---
Iceland has *very* few trees, so most timber used for boats washed up on shore. When found, land owners would mark the wood as their own.
<file_sep>/content/photo/2014-london-iceland-trip/120fd55-countryside.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-09 12:17:14'
exif:
aperture: f/2.4
exposure: 1/467
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.94573667
longitude: -0.73051667
next: /gallery/2014-london-iceland-trip/82328eb-bletchley-codebreaking
ordering: 11
previous: /gallery/2014-london-iceland-trip/0964b34-british-library
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Countryside
aliases:
- /gallery/2014-london-iceland-trip/120fd55-countryside.html
---
Taking the train up towards Bletchley Park and getting a bit more into the country.
<file_sep>/content/photo/2015-costa-rica-trip/9606542-horse-parade.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-11 16:32:17'
exif:
aperture: f/2.2
exposure: 1/465
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.41904167
longitude: -84.51981333
next: /gallery/2015-costa-rica-trip/e3b74ac-hike-to-cerro-chato
ordering: 9
previous: /gallery/2015-costa-rica-trip/ce6a440-horse-parade
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Horse Parade'
aliases:
- /gallery/2015-costa-rica-trip/9606542-horse-parade.html
---
We didn't entirely figure out why everybody was riding their horse and meeting up at this soda in the middle of pretty much nowhere, but it kept us entertained for the ~1:30 we waited for the new bus. Oddly, some people driving through town were giving our bus group stranger looks than they gave the horses.
<file_sep>/content/photo/2014-london-iceland-trip/b70543a-natural-history-museum.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-08 11:25:08'
exif:
aperture: f/2.4
exposure: 1/20
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.495914
longitude: -0.176366
next: /gallery/2014-london-iceland-trip/fbe9b12-hyde-park
ordering: 2
previous: /gallery/2014-london-iceland-trip/7cf02b5-night
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Natural History Museum'
aliases:
- /gallery/2014-london-iceland-trip/b70543a-natural-history-museum.html
---
A quick look inside the Natural History Museum. At the upper level, far end they have a slice from a giant sequoia tree from California.
<file_sep>/content/photo/2015-balloon-fiesta/ae76c84-img-0598.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-10 06:36:32'
exif:
aperture: f/2.2
exposure: 1/280
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19581167
longitude: -106.59748833
next: /gallery/2015-balloon-fiesta/4419092-img-0619
ordering: 27
previous: /gallery/2015-balloon-fiesta/fa4c901-img-0549
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0598
aliases:
- /gallery/2015-balloon-fiesta/ae76c84-img-0598.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/4bfb671-img-1956.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-18 18:46:42'
exif:
aperture: f/2.2
exposure: 1/33
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.352645
longitude: 103.85198333
next: /gallery/2015-cambodia-thailand-trip/cad1df3-img-1958
ordering: 87
previous: /gallery/2015-cambodia-thailand-trip/6de27eb-img-1952
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1956
aliases:
- /gallery/2015-cambodia-thailand-trip/4bfb671-img-1956.html
---
<file_sep>/content/_index.md
---
title: Hello
description: My name is <NAME>.
---
Technology intrigues me. Pretty much any sort, but I enjoy web-oriented tech
the most. I like innovating, technical challenges, and learning new concepts.
This is a place to remember some of those experiences. Maybe you'll find
something interesting.
<file_sep>/content/photo/2014-london-iceland-trip/c4ff904-glacier-walk.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 18:09:10'
exif:
aperture: f/2.4
exposure: 1/191
make: Apple
model: 'iPhone 5'
layout: gallery-photo
next: /gallery/2014-london-iceland-trip/9fa3c9a-skogafoss
ordering: 92
previous: /gallery/2014-london-iceland-trip/68119f5-glacier-walk
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Glacier Walk'
aliases:
- /gallery/2014-london-iceland-trip/c4ff904-glacier-walk.html
---
There was a lot of ash across the glacier. Most of it was from an eruption in the early 1900s.
<file_sep>/content/photo/2015-costa-rica-trip/1cb087d-first-beach.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-16 10:04:36'
exif:
aperture: f/2.2
exposure: 1/4950
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.97787833
longitude: -84.82238
next: /gallery/2015-costa-rica-trip/edfd7fa-playa-espadilla
ordering: 84
previous: /gallery/2015-costa-rica-trip/7bff94b-canopy-zip-line
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'First Beach'
aliases:
- /gallery/2015-costa-rica-trip/1cb087d-first-beach.html
---
On our way from Santa Elena to <NAME>, we had a brief stopover at the Puntarenas bus station conveniently located across the street from the beach.
<file_sep>/content/photo/2015-england-trip/9606663-9befa48b-c37e-4cf6-b729-41e6d96cd3d6.md
---
galleries:
- 2015-england-trip
date: '2015-03-08 07:34:50'
exif:
aperture: f/2.2
exposure: 1/60
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.505645
longitude: -0.07521117
next: /gallery/2015-england-trip/6656c15-8c6a8abc-f5e5-4524-afcc-d3f7bba46a46
ordering: 13
previous: /gallery/2015-england-trip/c57966f-012c767e-22bb-472d-ba1b-6c0ee8717996
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 9BEFA48B-C37E-4CF6-B729-41E6D96CD3D6
aliases:
- /gallery/2015-england-trip/9606663-9befa48b-c37e-4cf6-b729-41e6d96cd3d6.html
---
<file_sep>/content/photo/2015-costa-rica-trip/263b61d-hanging-bridges.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 09:12:46'
exif:
aperture: f/2.2
exposure: 1/1522
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.338495
longitude: -84.796905
next: /gallery/2015-costa-rica-trip/621981b-hanging-bridges
ordering: 64
previous: /gallery/2015-costa-rica-trip/698af83-hanging-bridges
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Hanging Bridges'
aliases:
- /gallery/2015-costa-rica-trip/263b61d-hanging-bridges.html
---
Our shadows on the tree canopy below the bridge.
<file_sep>/content/photo/2015-costa-rica-trip/48f23d8-hanging-bridges.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 09:21:01'
exif:
aperture: f/2.2
exposure: 1/1130
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.336375
longitude: -84.796875
next: /gallery/2015-costa-rica-trip/e66a29c-hanging-bridges
ordering: 66
previous: /gallery/2015-costa-rica-trip/621981b-hanging-bridges
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Hanging Bridges'
aliases:
- /gallery/2015-costa-rica-trip/48f23d8-hanging-bridges.html
---
The bridge spans ranged from 150ft to 510ft across.
<file_sep>/content/photo/2015-cambodia-thailand-trip/31dca9d-img-1703.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 17:42:24'
exif:
aperture: f/2.2
exposure: 1/1319
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.412405
longitude: 103.86348667
next: /gallery/2015-cambodia-thailand-trip/97f665d-img-1738
ordering: 71
previous: /gallery/2015-cambodia-thailand-trip/7d5c98a-img-1674
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1703
aliases:
- /gallery/2015-cambodia-thailand-trip/31dca9d-img-1703.html
---
<file_sep>/content/photo/2015-costa-rica-trip/0880939-monteverde-chocolate-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-13 13:22:06'
exif:
aperture: f/2.2
exposure: 1/60
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.46288333
longitude: -84.64357
next: /gallery/2015-costa-rica-trip/803d85a-monteverde-chocolate-tour
ordering: 34
previous: /gallery/2015-costa-rica-trip/c732c52-monteverde-chocolate-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Monteverde Chocolate Tour'
aliases:
- /gallery/2015-costa-rica-trip/0880939-monteverde-chocolate-tour.html
---
We got a tour of some of the plants they utilize, like this vanilla vine.
<file_sep>/content/photo/2014-london-iceland-trip/b0d46ee-british-museum.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 15:26:25'
exif:
aperture: f/2.4
exposure: 1/154
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.51931667
longitude: -0.1268055
next: /gallery/2014-london-iceland-trip/632b686-rosetta-stone
ordering: 35
previous: /gallery/2014-london-iceland-trip/66e837b-hyde-park
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'British Museum'
aliases:
- /gallery/2014-london-iceland-trip/b0d46ee-british-museum.html
---
The museum had a very interesting and impressive entry.
<file_sep>/content/photo/2015-costa-rica-trip/62f33e5-img-2464.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-18 19:36:16'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.39204667
longitude: -84.14666667
next: /gallery/2015-costa-rica-trip/0f370ed-img-2465
ordering: 123
previous: /gallery/2015-costa-rica-trip/cdb87b9-el-avion
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2464
aliases:
- /gallery/2015-costa-rica-trip/62f33e5-img-2464.html
---
And, finish the night off with card games of Spoons. Or, in our case, Dull-Knives-Because-You-Can't-Find-Spoons-In-The-Kitchen.
<file_sep>/content/photo/2015-england-trip/3f5cb97-ad05b78c-0cf1-449a-a827-48b199cefce9.md
---
galleries:
- 2015-england-trip
date: '2015-03-08 07:27:03'
exif:
aperture: f/2.2
exposure: 1/40
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.50543667
longitude: -0.0754195
next: /gallery/2015-england-trip/c57966f-012c767e-22bb-472d-ba1b-6c0ee8717996
ordering: 11
previous: /gallery/2015-england-trip/ee3f59d-475fbb88-fe94-40ea-a82a-9d964340dc9d
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: AD05B78C-0CF1-449A-A827-48B199CEFCE9
aliases:
- /gallery/2015-england-trip/3f5cb97-ad05b78c-0cf1-449a-a827-48b199cefce9.html
---
<file_sep>/content/photo/2015-costa-rica-trip/a977d06-giovannis-night-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 20:22:58'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.47117833
longitude: -84.654655
next: /gallery/2015-costa-rica-trip/52e4f19-giovannis-night-tour
ordering: 27
previous: /gallery/2015-costa-rica-trip/e38b136-giovannis-night-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Giovanni''s Night Tour'
aliases:
- /gallery/2015-costa-rica-trip/a977d06-giovannis-night-tour.html
---
Also, several banana trees were growing along the path.
<file_sep>/content/photo/2015-costa-rica-trip/238588a-giovannis-night-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 21:08:31'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.47038333
longitude: -84.65065
next: /gallery/2015-costa-rica-trip/4aa865c-giovannis-night-tour
ordering: 31
previous: /gallery/2015-costa-rica-trip/fcef47e-giovannis-night-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Giovanni''s Night Tour'
aliases:
- /gallery/2015-costa-rica-trip/238588a-giovannis-night-tour.html
---
Of course, the tour wasn't complete without being able to see one of the classical green/blue, red-eyes frogs.
<file_sep>/content/photo/2015-costa-rica-trip/6a78f2e-jeep-boat-jeep.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 08:58:23'
exif:
aperture: f/2.2
exposure: 1/2198
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.47493
longitude: -84.76483833
next: /gallery/2015-costa-rica-trip/23e51bc-jeep-boat-jeep
ordering: 40
previous: /gallery/2015-costa-rica-trip/5f71bc8-jeep-boat-jeep
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: Jeep-Boat-Jeep
aliases:
- /gallery/2015-costa-rica-trip/6a78f2e-jeep-boat-jeep.html
---
The first part of the boat ride across the lake was very foggy.
<file_sep>/content/photo/2014-colorado-aspens/6e859c1-aspens-are-turning.md
---
galleries:
- 2014-colorado-aspens
date: '2014-09-27 11:52:35'
exif:
aperture: f/2.4
exposure: 1/1642
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 39.61175833
longitude: -105.95075333
next: /gallery/2014-colorado-aspens/3c21081-tall-aspens
ordering: 1
previous: /gallery/2014-colorado-aspens/3346d74-golden-aspens
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Aspens are Turning'
aliases:
- /gallery/2014-colorado-aspens/6e859c1-aspens-are-turning.html
---
<file_sep>/content/photo/2015-costa-rica-trip/67d08eb-el-avion.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-18 18:54:24'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.402275
longitude: -84.15306117
next: /gallery/2015-costa-rica-trip/cdb87b9-el-avion
ordering: 121
previous: /gallery/2015-costa-rica-trip/ae8494f-el-avion
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'El Avión'
aliases:
- /gallery/2015-costa-rica-trip/67d08eb-el-avion.html
---
The restaurant sign...
<file_sep>/content/photo/2015-cambodia-thailand-trip/00018be-img-1558.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 15:14:33'
exif:
aperture: f/2.2
exposure: 1/898
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.41341667
longitude: 103.865045
next: /gallery/2015-cambodia-thailand-trip/c3ecee4-img-1581
ordering: 62
previous: /gallery/2015-cambodia-thailand-trip/6bc9240-img-1538
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1558
aliases:
- /gallery/2015-cambodia-thailand-trip/00018be-img-1558.html
---
<file_sep>/content/photo/2015-costa-rica-trip/3bf02da-hike-to-cerro-chato.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 11:37:14'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.44275833
longitude: -84.678895
next: /gallery/2015-costa-rica-trip/b8030bb-hike-to-cerro-chato
ordering: 16
previous: /gallery/2015-costa-rica-trip/b0381c7-hike-to-cerro-chato
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Hike to Cerro Chato'
aliases:
- /gallery/2015-costa-rica-trip/3bf02da-hike-to-cerro-chato.html
---
As we got higher in elevation, we were surrounded by more and more of the very green forest.
<file_sep>/content/photo/2015-cambodia-thailand-trip/457e6e0-img-0984.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 02:30:47'
exif:
aperture: f/2.2
exposure: 1/172
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.56492
longitude: 104.93242833
next: /gallery/2015-cambodia-thailand-trip/2c0eaa2-img-0993
ordering: 6
previous: /gallery/2015-cambodia-thailand-trip/b5dafc7-img-0971
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0984
aliases:
- /gallery/2015-cambodia-thailand-trip/457e6e0-img-0984.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/af60a57-img-1308.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 23:20:15'
exif:
aperture: f/2.2
exposure: 1/100
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.46185833
longitude: 103.871475
next: /gallery/2015-cambodia-thailand-trip/2fa5b81-img-1325
ordering: 48
previous: /gallery/2015-cambodia-thailand-trip/0ecdcf8-img-1272
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1308
aliases:
- /gallery/2015-cambodia-thailand-trip/af60a57-img-1308.html
---
<file_sep>/content/photo/2014-london-iceland-trip/0964b34-british-library.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-09 11:00:08'
exif:
aperture: f/2.4
exposure: 1/423
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.52896333
longitude: -0.12743883
next: /gallery/2014-london-iceland-trip/120fd55-countryside
ordering: 10
previous: /gallery/2014-london-iceland-trip/4f82b54-fancy-building
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'British Library'
aliases:
- /gallery/2014-london-iceland-trip/0964b34-british-library.html
---
This is looking out from the main patio of the British Library.
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/12014b2-img-1102.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-11 07:42:03'
exif:
aperture: f/2.4
exposure: 1/234
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.194905
longitude: -106.596695
next: /gallery/2014-albuquerque-balloon-fiesta/924c0ae-img-1103
ordering: 19
previous: /gallery/2014-albuquerque-balloon-fiesta/2c795a3-img-1099
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1102
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/12014b2-img-1102.html
---
<file_sep>/content/photo/2015-costa-rica-trip/c312ad5-cerro-chato.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 13:18:25'
exif:
aperture: f/2.2
exposure: 1/1068
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.44978
longitude: -84.71313667
next: /gallery/2015-costa-rica-trip/bccbec3-hike-from-cerro-chato
ordering: 18
previous: /gallery/2015-costa-rica-trip/b8030bb-hike-to-cerro-chato
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Cerro Chato'
aliases:
- /gallery/2015-costa-rica-trip/c312ad5-cerro-chato.html
---
Once at the base, the clouds and fog lifted and we could see across the lake. The tour group in front of us had brought their swimsuits to take a brief break in the lake.
<file_sep>/content/photo/2015-cambodia-thailand-trip/0d2ea91-img-2271-pano.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-20 18:11:00'
exif:
aperture: null
exposure: null
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.75430333
longitude: 100.54046667
next: /gallery/2015-cambodia-thailand-trip/1c60947-img-2306
ordering: 119
previous: /gallery/2015-cambodia-thailand-trip/76f41b1-img-2288
sizes:
1280:
height: 174
width: 1280
640w:
height: 87
width: 640
200x200:
height: 200
width: 200
title: IMG_2271-PANO
aliases:
- /gallery/2015-cambodia-thailand-trip/0d2ea91-img-2271-pano.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/e19b8cf-img-2338.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-21 00:13:28'
exif:
aperture: f/2.2
exposure: 1/760
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.74386333
longitude: 100.48908833
next: /gallery/2015-cambodia-thailand-trip/f0b8ca2-img-2352
ordering: 125
previous: /gallery/2015-cambodia-thailand-trip/5bfa633-img-2333
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2338
aliases:
- /gallery/2015-cambodia-thailand-trip/e19b8cf-img-2338.html
---
<file_sep>/content/photo/2014-london-iceland-trip/881baef-sudhurland.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 14:28:09'
exif:
aperture: f/2.4
exposure: 1/243
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.57186333
longitude: -19.872495
next: /gallery/2014-london-iceland-trip/d66f55c-sudhurland
ordering: 73
previous: /gallery/2014-london-iceland-trip/c8267be-sudhurland
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Sudhurland
aliases:
- /gallery/2014-london-iceland-trip/881baef-sudhurland.html
---
Tremors and small earthquakes make it a bit dangerous due to falling rocks.
<file_sep>/content/photo/2015-costa-rica-trip/d86ce6f-don-juan-coffee-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 16:52:50'
exif:
aperture: f/2.2
exposure: 1/1014
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.32289167
longitude: -84.835105
next: /gallery/2015-costa-rica-trip/0f5608b-tree-house-restaurant
ordering: 57
previous: /gallery/2015-costa-rica-trip/ec40a9e-don-juan-coffee-tour
sizes:
1280:
height: 276
width: 1280
640w:
height: 138
width: 640
200x200:
height: 200
width: 200
title: 'Don Juan Coffee Tour'
aliases:
- /gallery/2015-costa-rica-trip/d86ce6f-don-juan-coffee-tour.html
---
At the end of the tour we were able to sample their coffees and some snacks. They had a very nice back patio which looked out over the plantation, forest, and soon-to-be sunset.
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/a2f3fee-img-1089.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 08:41:33'
exif:
aperture: f/2.4
exposure: 1/1232
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.197025
longitude: -106.59560333
next: /gallery/2014-albuquerque-balloon-fiesta/e93dd19-img-1091
ordering: 14
previous: /gallery/2014-albuquerque-balloon-fiesta/cf568c1-img-1084
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1089
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/a2f3fee-img-1089.html
---
<file_sep>/content/photo/2014-london-iceland-trip/cad4f8c-st-pauls-cathedral.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-10 12:34:13'
exif:
aperture: f/2.4
exposure: 1/797
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.513973
longitude: -0.098416
next: /gallery/2014-london-iceland-trip/d6abeff-st-pauls-cathedral
ordering: 20
previous: /gallery/2014-london-iceland-trip/bb52573-st-pauls-cathedral
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'St. Paul''s Cathedral'
aliases:
- /gallery/2014-london-iceland-trip/cad4f8c-st-pauls-cathedral.html
---
It took about 530 steps to climb up to the Golden Gallery for these great views of the city.
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/ceb86f3-img-1039.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 07:31:04'
exif:
aperture: f/2.4
exposure: 1/60
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19323667
longitude: -106.59864167
next: /gallery/2014-albuquerque-balloon-fiesta/700178d-img-1048
ordering: 2
previous: /gallery/2014-albuquerque-balloon-fiesta/f98e69a-img-1037
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1039
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/ceb86f3-img-1039.html
---
<file_sep>/content/photo/2014-london-iceland-trip/b88e820-hallgrimskirkja.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 12:58:55'
exif:
aperture: f/2.4
exposure: 1/30
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.141899108887
longitude: -21.92679977417
next: /gallery/2014-london-iceland-trip/b1ba977-church-organ
ordering: 52
previous: /gallery/2014-london-iceland-trip/d6254b6-hallgrimskirkja
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Hallgrímskirkja
aliases:
- /gallery/2014-london-iceland-trip/b88e820-hallgrimskirkja.html
---
Inside the unique church. The proportions and cement-ness were a bit confusing.
<file_sep>/content/photo/2014-barcelona-trip/1ef572c-beach.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-24 15:33:30'
exif:
aperture: f/2.2
exposure: 1/476
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.369225
longitude: 2.18914667
next: /gallery/2014-barcelona-trip/b4f7cf3-flying-back
ordering: 92
previous: /gallery/2014-barcelona-trip/ae24d7f-beach
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: Beach
aliases:
- /gallery/2014-barcelona-trip/1ef572c-beach.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/1c60947-img-2306.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-20 19:54:10'
exif:
aperture: f/2.2
exposure: 1/33
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.80266667
longitude: 100.55210833
next: /gallery/2015-cambodia-thailand-trip/ff63707-img-2314
ordering: 120
previous: /gallery/2015-cambodia-thailand-trip/0d2ea91-img-2271-pano
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2306
aliases:
- /gallery/2015-cambodia-thailand-trip/1c60947-img-2306.html
---
<file_sep>/content/photo/2015-costa-rica-trip/bccbec3-hike-from-cerro-chato.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 14:14:25'
exif:
aperture: f/2.2
exposure: 1/1647
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.443155
longitude: -84.67774167
next: /gallery/2015-costa-rica-trip/2cb76f3-hike-from-cerro-chato
ordering: 19
previous: /gallery/2015-costa-rica-trip/c312ad5-cerro-chato
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Hike from Cerro Chato'
aliases:
- /gallery/2015-costa-rica-trip/bccbec3-hike-from-cerro-chato.html
---
And a few more pictures of the view on the hike down.
<file_sep>/content/photo/2015-cambodia-thailand-trip/5341bfc-img-2166.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 22:20:56'
exif:
aperture: f/2.2
exposure: 1/100
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.750475
longitude: 100.49036333
next: /gallery/2015-cambodia-thailand-trip/276b568-img-2169
ordering: 110
previous: /gallery/2015-cambodia-thailand-trip/baae0b9-img-2141
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2166
aliases:
- /gallery/2015-cambodia-thailand-trip/5341bfc-img-2166.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/ffde6e7-img-1117.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 23:17:21'
exif:
aperture: f/2.2
exposure: 1/3968
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.57612167
longitude: 104.92285833
next: /gallery/2015-cambodia-thailand-trip/bf24d58-img-1125
ordering: 22
previous: /gallery/2015-cambodia-thailand-trip/6e79602-img-1098
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1117
aliases:
- /gallery/2015-cambodia-thailand-trip/ffde6e7-img-1117.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/c60d938-img-1145.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-11 18:52:10'
exif:
aperture: f/2.4
exposure: 1/17
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19418
longitude: -106.59716667
next: /gallery/2014-albuquerque-balloon-fiesta/507bcb2-img-1148
ordering: 26
previous: /gallery/2014-albuquerque-balloon-fiesta/1b9b6f2-img-1127
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1145
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/c60d938-img-1145.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/82c066d-img-1121.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-11 08:18:10'
exif:
aperture: f/2.4
exposure: 1/1153
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19848833
longitude: -106.59513833
next: /gallery/2014-albuquerque-balloon-fiesta/2681241-img-1122
ordering: 23
previous: /gallery/2014-albuquerque-balloon-fiesta/0e588f6-img-1110
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1121
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/82c066d-img-1121.html
---
<file_sep>/content/photo/2014-london-iceland-trip/223be54-waterfall.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 21:23:31'
exif:
aperture: f/2.4
exposure: 1/15
make: Apple
model: 'iPhone 5'
layout: gallery-photo
next: /gallery/2014-london-iceland-trip/c828133-panorama
ordering: 98
previous: /gallery/2014-london-iceland-trip/b23ccc1-night-waterfall
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Waterfall
aliases:
- /gallery/2014-london-iceland-trip/223be54-waterfall.html
---
At the waterfall, there was a path that you hike to get around behind the waterfall and look out.
<file_sep>/content/photo/2014-london-iceland-trip/5303bd3-panorama.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 17:25:01'
exif:
aperture: f/2.4
exposure: 1/1004
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.53496667
longitude: -19.34728833
next: /gallery/2014-london-iceland-trip/b6360f4-glacier-walk
ordering: 87
previous: /gallery/2014-london-iceland-trip/c758581-glacier-walk
sizes:
1280:
height: 293
width: 1280
640w:
height: 146
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Panorama
aliases:
- /gallery/2014-london-iceland-trip/5303bd3-panorama.html
---
Looking out over the glacier.
<file_sep>/content/photo/2015-costa-rica-trip/f6374cd-boat-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 14:08:43'
exif:
aperture: f/2.2
exposure: 1/2825
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.42549667
longitude: -84.16899167
next: /gallery/2015-costa-rica-trip/e7c7497-boat-tour
ordering: 106
previous: /gallery/2015-costa-rica-trip/47fd351-boat-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Boat Tour'
aliases:
- /gallery/2015-costa-rica-trip/f6374cd-boat-tour.html
---
Heading out to ocean. Some storms were predicted for the afternoon and evening, but fortunately they stayed closer to land and didn't affect us on the boat.
<file_sep>/content/photo/2015-cambodia-thailand-trip/59014a2-img-2109.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 21:48:55'
exif:
aperture: f/2.2
exposure: 1/1412
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.75112167
longitude: 100.493095
next: /gallery/2015-cambodia-thailand-trip/baae0b9-img-2141
ordering: 108
previous: /gallery/2015-cambodia-thailand-trip/0b51e42-img-2092
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2109
aliases:
- /gallery/2015-cambodia-thailand-trip/59014a2-img-2109.html
---
<file_sep>/content/photo/2015-costa-rica-trip/df11754-canopy-zip-line.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 16:10:48'
exif:
aperture: f/2.2
exposure: 1/1041
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.34532167
longitude: -84.84487167
next: /gallery/2015-costa-rica-trip/15acca5-canopy-zip-line
ordering: 81
previous: /gallery/2015-costa-rica-trip/388aa87-canopy-zip-line
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Canopy Zip Line'
aliases:
- /gallery/2015-costa-rica-trip/df11754-canopy-zip-line.html
---
While waiting, we were able to get some great views of the landscape. Sadly, it was very inconvenient to pull my camera out of my pocket with all the harnesses to take more pictures.
<file_sep>/content/photo/2015-balloon-fiesta/958ec45-img-0336.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 06:12:58'
exif:
aperture: f/2.2
exposure: 1/134
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19447833
longitude: -106.59611333
next: /gallery/2015-balloon-fiesta/a320270-imag2180
ordering: 0
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0336
aliases:
- /gallery/2015-balloon-fiesta/958ec45-img-0336.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/0a6cf42-img-2037.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 20:36:45'
exif:
aperture: f/2.2
exposure: 1/732
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.751705
longitude: 100.49288833
next: /gallery/2015-cambodia-thailand-trip/e653903-img-2038
ordering: 100
previous: /gallery/2015-cambodia-thailand-trip/15296ea-img-2032
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2037
aliases:
- /gallery/2015-cambodia-thailand-trip/0a6cf42-img-2037.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/cf568c1-img-1084.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 08:31:10'
exif:
aperture: f/2.4
exposure: 1/1355
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19680333
longitude: -106.59555833
next: /gallery/2014-albuquerque-balloon-fiesta/a2f3fee-img-1089
ordering: 13
previous: /gallery/2014-albuquerque-balloon-fiesta/f114579-img-1074
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1084
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/cf568c1-img-1084.html
---
<file_sep>/content/photo/2015-costa-rica-trip/c732c52-monteverde-chocolate-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-13 13:19:06'
exif:
aperture: f/2.2
exposure: 1/40
make: Apple
model: 'iPhone 6'
layout: gallery-photo
next: /gallery/2015-costa-rica-trip/0880939-monteverde-chocolate-tour
ordering: 33
previous: /gallery/2015-costa-rica-trip/4aa865c-giovannis-night-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Monteverde Chocolate Tour'
aliases:
- /gallery/2015-costa-rica-trip/c732c52-monteverde-chocolate-tour.html
---
On Tuesday we walked to a Chocolate tour on a young plantation.
<file_sep>/content/photo/2015-england-trip/65a4a84-662d346f-778c-41ce-8754-90744c250cb3.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 03:18:15'
exif:
aperture: f/2.2
exposure: 1/391
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.48460333
longitude: -0.60292833
next: /gallery/2015-england-trip/c562b5a-55767f0e-9154-4e92-99d3-4db88d659d0e
ordering: 21
previous: /gallery/2015-england-trip/73b85ca-1caa4214-8ca5-4168-90a8-b731645d1503
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 662D346F-778C-41CE-8754-90744C250CB3
aliases:
- /gallery/2015-england-trip/65a4a84-662d346f-778c-41ce-8754-90744c250cb3.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/12895b3-img-1054.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 07:39:43'
exif:
aperture: f/2.4
exposure: 1/201
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19581167
longitude: -106.59813667
next: /gallery/2014-albuquerque-balloon-fiesta/5cd399d-img-1055
ordering: 7
previous: /gallery/2014-albuquerque-balloon-fiesta/8230d10-img-1053
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1054
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/12895b3-img-1054.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/7d5c98a-img-1674.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 17:16:57'
exif:
aperture: f/2.2
exposure: 1/942
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.42668333
longitude: 103.86563
next: /gallery/2015-cambodia-thailand-trip/31dca9d-img-1703
ordering: 70
previous: /gallery/2015-cambodia-thailand-trip/7954a7d-img-1647
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1674
aliases:
- /gallery/2015-cambodia-thailand-trip/7d5c98a-img-1674.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/4ad3c57-img-1204.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 19:30:29'
exif:
aperture: f/2.2
exposure: 1/1364
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44074667
longitude: 103.85862
next: /gallery/2015-cambodia-thailand-trip/a408209-img-1209
ordering: 39
previous: /gallery/2015-cambodia-thailand-trip/468d46d-img-1199
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1204
aliases:
- /gallery/2015-cambodia-thailand-trip/4ad3c57-img-1204.html
---
<file_sep>/content/photo/2014-london-iceland-trip/293e193-its-an-albino-peacock.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-09 17:50:06'
exif:
aperture: f/2.4
exposure: 1/20
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.796651340364
longitude: -0.635953433065
next: /gallery/2014-london-iceland-trip/aa978b7-platform-9-3-4
ordering: 15
previous: /gallery/2014-london-iceland-trip/0c6bcfa-its-a-peacock
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'It''s an Albino Peacock'
aliases:
- /gallery/2014-london-iceland-trip/293e193-its-an-albino-peacock.html
---
There were several other peacocks, but only one special albino one.
<file_sep>/content/photo/2014-london-iceland-trip/9b3e52f-st-pauls-cathedral.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-10 11:06:11'
exif:
aperture: f/2.4
exposure: 1/2710
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.512745
longitude: -0.09724167
next: /gallery/2014-london-iceland-trip/bb52573-st-pauls-cathedral
ordering: 18
previous: /gallery/2014-london-iceland-trip/493e33e-gherkin
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'St. Paul''s Cathedral'
aliases:
- /gallery/2014-london-iceland-trip/9b3e52f-st-pauls-cathedral.html
---
Built in the late 1600s, this cathedral has hosted quite a few famous events.
<file_sep>/themes/dpb587-20181103a/layouts/taxonomy/gallery.html
{{ define "main" }}
<div class="columns is-fullheight">
<div class="column">
<section class="hero is-primary has-text-centered">
<div class="hero-body">
<div class="container">
<h1 class="title">
{{ .Title }}
</h1>
<h2 class="subtitle">
{{ dateFormat "January 2, 2006" .Date }}{{ if .Params.date_end }} – {{ dateFormat "January 2, 2006" .Params.date_end }}{{ end }}
</h2>
</div>
</div>
</section>
<div class="container">
<section class="section">
<div class="columns is-multiline">
{{ range .Paginator.Pages }}
<div class="column is-one-quarter-desktop is-half-tablet">
<a href="{{ .URL }}">
<div class="card">
<div class="card-image">
<figure class="image is-2by2">
<img src="{{ .Site.Params.assetUrl }}{{ index .Params.galleries 0 }}/{{ .File.BaseFileName }}~200x200.jpg" title="{{ .Title }}" />
</figure>
</div>
<div class="card-content has-text-centered">
{{ .Title }}
</div>
</div>
</a>
</div>
{{ end }}
</div>
</section>
</div>
{{ partial "pagination" }}
</div>
</div>
{{ end }}
<file_sep>/content/photo/2014-london-iceland-trip/56d4241-the-nereid-monument.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 16:00:21'
exif:
aperture: f/2.4
exposure: 1/17
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.51927167
longitude: -0.12765833
next: /gallery/2014-london-iceland-trip/1f869bd-sculptures
ordering: 38
previous: /gallery/2014-london-iceland-trip/f9b153c-artifacts
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'The Nereid Monument'
aliases:
- /gallery/2014-london-iceland-trip/56d4241-the-nereid-monument.html
---
An impressive reconstruction of a monument in the museum.
<file_sep>/content/photo/2014-london-iceland-trip/4f82b54-fancy-building.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-09 10:55:37'
exif:
aperture: f/2.4
exposure: 1/1178
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.5298016
longitude: -0.1262431
next: /gallery/2014-london-iceland-trip/0964b34-british-library
ordering: 9
previous: /gallery/2014-london-iceland-trip/ca1f5b9-river-thames
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Fancy Building'
aliases:
- /gallery/2014-london-iceland-trip/4f82b54-fancy-building.html
---
Was walking by this building, and it looked interesting…
<file_sep>/content/photo/2014-barcelona-trip/71bf8a4-parc-guell.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 15:16:27'
exif:
aperture: f/2.2
exposure: 1/648
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.41341167
longitude: 2.15163333
next: /gallery/2014-barcelona-trip/38b9ecd-parc-guell
ordering: 5
previous: /gallery/2014-barcelona-trip/24a6783-parc-guell
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: '<NAME>'
aliases:
- /gallery/2014-barcelona-trip/71bf8a4-parc-guell.html
---
<file_sep>/content/photo/2015-england-trip/fac9303-a5ee73bd-dff0-4ba1-9e73-a9acf32de02a.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 08:43:40'
exif:
aperture: f/2.2
exposure: 1/120
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.38086333
longitude: -2.35965333
next: /gallery/2015-england-trip/26fb32e-8b1ebc5d-128d-44e6-8407-3729726243c2
ordering: 35
previous: /gallery/2015-england-trip/af28ed2-838aee87-dd8c-49bd-9780-ed48fc47ac1c
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: A5EE73BD-DFF0-4BA1-9E73-A9ACF32DE02A
aliases:
- /gallery/2015-england-trip/fac9303-a5ee73bd-dff0-4ba1-9e73-a9acf32de02a.html
---
<file_sep>/content/photo/2015-costa-rica-trip/04b40de-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 08:04:28'
exif:
aperture: f/2.2
exposure: 1/557
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.37961667
longitude: -84.13964167
next: /gallery/2015-costa-rica-trip/4a08af3-manuel-antonio-national-park
ordering: 90
previous: /gallery/2015-costa-rica-trip/f4bad1a-manuel-antonio-national-park
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: '<NAME>onio National Park'
aliases:
- /gallery/2015-costa-rica-trip/04b40de-manuel-antonio-national-park.html
---
It was a very nice time of day because the sun wasn't shining too strongly and it was still slightly cooler from the night before. Still way too humid, of course.
<file_sep>/config.toml
languageCode = "en-us"
title = "<NAME>"
copyright = "Unless noted, software code is licensed under MIT License and all other content under CC-BY."
disqusShortname = "dpb587"
googleAnalytics = "UA-37464314-1"
theme = "dpb587-20181103a"
enableRobotsTXT = true
enableGitInfo = true
pygmentsCodefences = true
pygmentsStyle = "native"
paginate = "256"
[author]
name = "<NAME>"
email = "<EMAIL>"
[taxonomies]
tag = "tags"
gallery = "galleries"
[permalinks]
post = "/post/:year/:month/:day/:slug/"
page = "/:slug/"
gallery = "/gallery/:slug/"
photo = "/photo/:year/:month/:day/:slug/"
[[menu.main]]
name = "about"
url = "/about/"
weight = -110
[[menu.main]]
name = "posts"
url = "/post/"
weight = -130
[[menu.main]]
name = "galleries"
url = "/galleries/"
weight = -120
[params]
description = ""
assetUrl = "https://dpb587-website-us-east-1.s3.amazonaws.com/asset/gallery/"
github = "dpb587"
twitter = "dpb587"
mainSections = ["post" ,"gallery"]
[params.logo]
url = "dpb587.png"
width = 50
height = 50
alt = "dpb587"
<file_sep>/content/photo/2015-cambodia-thailand-trip/411da1f-img-1526.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 14:49:30'
exif:
aperture: f/2.2
exposure: 1/33
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.412945
longitude: 103.86411333
next: /gallery/2015-cambodia-thailand-trip/6bc9240-img-1538
ordering: 60
previous: /gallery/2015-cambodia-thailand-trip/2d3679e-img-1229
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1526
aliases:
- /gallery/2015-cambodia-thailand-trip/411da1f-img-1526.html
---
<file_sep>/content/photo/2015-costa-rica-trip/0a29380-monteverde-chocolate-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-13 14:00:19'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.45803667
longitude: -84.65213
next: /gallery/2015-costa-rica-trip/c8f8633-monteverde-chocolate-tour
ordering: 37
previous: /gallery/2015-costa-rica-trip/7cd8fdf-monteverde-chocolate-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Monteverde Chocolate Tour'
aliases:
- /gallery/2015-costa-rica-trip/0a29380-monteverde-chocolate-tour.html
---
Once they're dried, the beans can be skinned and lightly crushed into "nibs" which have the extremely strong chocolate taste.
<file_sep>/content/photo/2014-barcelona-trip/ffd7d37-christmasy-walkways.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-22 21:31:20'
exif:
aperture: f/2.2
exposure: 1/17
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.38267167
longitude: 2.17715
next: /gallery/2014-barcelona-trip/baf4bfd-mirador-de-colom
ordering: 38
previous: /gallery/2014-barcelona-trip/af00008-palau-de-la-generalitat
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: '<NAME>'
aliases:
- /gallery/2014-barcelona-trip/ffd7d37-christmasy-walkways.html
---
<file_sep>/content/photo/2015-costa-rica-trip/1362d41-canopy-zip-line.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 14:31:39'
exif:
aperture: f/2.2
exposure: 1/2083
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.34681667
longitude: -84.840355
next: /gallery/2015-costa-rica-trip/de9981c-canopy-zip-line
ordering: 76
previous: /gallery/2015-costa-rica-trip/0817658-canopy-zip-line
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Canopy Zip Line'
aliases:
- /gallery/2015-costa-rica-trip/1362d41-canopy-zip-line.html
---
Some of the zip lines were shorter, crossing a bit further down the hill.
<file_sep>/content/photo/2014-london-iceland-trip/f9f25f0-narwhal.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 12:09:23'
exif:
aperture: f/2.4
exposure: 1/20
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.495914
longitude: -0.176366
next: /gallery/2014-london-iceland-trip/ca834b8-buckingham-palace
ordering: 31
previous: /gallery/2014-london-iceland-trip/43e714a-missouri-monster
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Narwhal
aliases:
- /gallery/2014-london-iceland-trip/f9f25f0-narwhal.html
---
Did you know that some of them have double tusks?
<file_sep>/content/photo/2015-balloon-fiesta/e6b56db-img-0647.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-10 06:52:05'
exif:
aperture: f/2.2
exposure: 1/898
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19671667
longitude: -106.59719667
next: /gallery/2015-balloon-fiesta/8326351-img-0697
ordering: 30
previous: /gallery/2015-balloon-fiesta/9cd0322-img-0631
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_0647
aliases:
- /gallery/2015-balloon-fiesta/e6b56db-img-0647.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/15296ea-img-2032.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 20:30:03'
exif:
aperture: f/2.2
exposure: 1/33
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.75166667
longitude: 100.49295
next: /gallery/2015-cambodia-thailand-trip/0a6cf42-img-2037
ordering: 99
previous: /gallery/2015-cambodia-thailand-trip/368bbdb-img-2031
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2032
aliases:
- /gallery/2015-cambodia-thailand-trip/15296ea-img-2032.html
---
<file_sep>/content/photo/2014-london-iceland-trip/340d0ac-cured-shark.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 14:53:13'
exif:
aperture: f/2.4
exposure: 1/120
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.15008617
longitude: -21.94287
next: /gallery/2014-london-iceland-trip/1e88721-saga-museum
ordering: 64
previous: /gallery/2014-london-iceland-trip/bd9f003-weather
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Cured Shark'
aliases:
- /gallery/2014-london-iceland-trip/340d0ac-cured-shark.html
---
It’s apparently a specialty… but not quite my favorite snack.
<file_sep>/content/photo/2015-costa-rica-trip/0f370ed-img-2465.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-19 19:53:24'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.93750833
longitude: -84.0954055
ordering: 124
previous: /gallery/2015-costa-rica-trip/62f33e5-img-2464
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2465
aliases:
- /gallery/2015-costa-rica-trip/0f370ed-img-2465.html
---
Back in San José for a short night's sleep before the early morning flight we found a nearby place for dinner. Somebody there enjoyed The Shining. Redrum.
<file_sep>/content/photo/2015-cambodia-thailand-trip/00ae52c-img-2070.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 21:05:15'
exif:
aperture: f/2.2
exposure: 1/581
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.75174667
longitude: 100.492255
next: /gallery/2015-cambodia-thailand-trip/b410619-img-2075
ordering: 104
previous: /gallery/2015-cambodia-thailand-trip/b6df529-img-2059
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2070
aliases:
- /gallery/2015-cambodia-thailand-trip/00ae52c-img-2070.html
---
<file_sep>/content/photo/2014-london-iceland-trip/f2e51f5-the-national-gallery.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-10 13:55:24'
exif:
aperture: f/2.4
exposure: 1/1153
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.50798833
longitude: -0.12789717
next: /gallery/2014-london-iceland-trip/ef30149-trafalgar-lunch
ordering: 24
previous: /gallery/2014-london-iceland-trip/3bb5ad8-trafalgar-square
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'The National Gallery'
aliases:
- /gallery/2014-london-iceland-trip/f2e51f5-the-national-gallery.html
---
Walked through The National Gallery and saw *lots* of paintings and artwork. It’s an impressive collection.
<file_sep>/content/photo/2015-costa-rica-trip/99e190d-lookout.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 10:39:12'
exif:
aperture: f/2.2
exposure: 1/2475
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.4458
longitude: -84.67424667
next: /gallery/2015-costa-rica-trip/904620b-hike-to-cerro-chato
ordering: 12
previous: /gallery/2015-costa-rica-trip/a3b1d00-hike-to-cerro-chato
sizes:
1280:
height: 276
width: 1280
640w:
height: 138
width: 640
200x200:
height: 200
width: 200
title: Lookout
aliases:
- /gallery/2015-costa-rica-trip/99e190d-lookout.html
---
One of the breaks along the hike looked out towards La Fortuna.
<file_sep>/content/photo/2015-england-trip/a0b3f51-f4b4ccf6-6dfb-40cb-9550-307bec24ab15.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 06:29:11'
exif:
aperture: f/2.2
exposure: 1/732
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.178795
longitude: -1.82670333
next: /gallery/2015-england-trip/0aef531-fe1ac7a8-bcbb-4073-b3c6-0aaebe102eb4
ordering: 26
previous: /gallery/2015-england-trip/4d1765a-30c60656-21bb-4293-b77e-2ea9dcf2281e
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: F4B4CCF6-6DFB-40CB-9550-307BEC24AB15
aliases:
- /gallery/2015-england-trip/a0b3f51-f4b4ccf6-6dfb-40cb-9550-307bec24ab15.html
---
<file_sep>/content/photo/2015-costa-rica-trip/ec40a9e-don-juan-coffee-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 16:44:18'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.32232
longitude: -84.8349
next: /gallery/2015-costa-rica-trip/d86ce6f-don-juan-coffee-tour
ordering: 56
previous: /gallery/2015-costa-rica-trip/88a1506-don-juan-coffee-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Don Juan Coffee Tour'
aliases:
- /gallery/2015-costa-rica-trip/ec40a9e-don-juan-coffee-tour.html
---
And then we were able extract the liquid and taste it as a drink.
<file_sep>/content/galleries/_index.md
---
title: Galleries
description: To recount some adventures and places.
---
<file_sep>/content/photo/2014-london-iceland-trip/b8bd46c-feed-the-ducks.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 12:25:06'
exif:
aperture: f/2.4
exposure: 1/1063
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.14533333
longitude: -21.940005
next: /gallery/2014-london-iceland-trip/d6254b6-hallgrimskirkja
ordering: 50
previous: /gallery/2014-london-iceland-trip/bf6398b-city-hall
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Feed the Ducks'
aliases:
- /gallery/2014-london-iceland-trip/b8bd46c-feed-the-ducks.html
---
But don’t feed the seagulls. There are instructions if you need help.
<file_sep>/content/photo/2015-balloon-fiesta/8326351-img-0697.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-10 09:40:27'
exif:
aperture: f/2.2
exposure: 1/2198
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19848833
longitude: -106.59488667
next: /gallery/2015-balloon-fiesta/b115008-img-0707
ordering: 31
previous: /gallery/2015-balloon-fiesta/e6b56db-img-0647
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0697
aliases:
- /gallery/2015-balloon-fiesta/8326351-img-0697.html
---
<file_sep>/content/photo/2015-england-trip/e5ff6c8-7192f410-cbf0-40d6-8a83-0257b256dfdd.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 03:11:03'
exif:
aperture: f/2.2
exposure: 1/807
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.483525
longitude: -0.60504167
next: /gallery/2015-england-trip/c70b2ac-aa11611a-e379-4053-8457-88a2e4bc36b3
ordering: 18
previous: /gallery/2015-england-trip/986340c-41264d58-3c9c-4190-9439-7ecc06e95ace
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 7192F410-CBF0-40D6-8A83-0257B256DFDD
aliases:
- /gallery/2015-england-trip/e5ff6c8-7192f410-cbf0-40d6-8a83-0257b256dfdd.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/f89f636-img-0962.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 00:47:47'
exif:
aperture: f/2.2
exposure: 1/1276
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.57115333
longitude: 104.93
next: /gallery/2015-cambodia-thailand-trip/b5dafc7-img-0971
ordering: 4
previous: /gallery/2015-cambodia-thailand-trip/f309d4c-img-0961
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0962
aliases:
- /gallery/2015-cambodia-thailand-trip/f89f636-img-0962.html
---
<file_sep>/content/galleries/2014-london-iceland-trip/_index.md
---
slug: 2014-london-iceland-trip
title: London & Iceland Trip
date: '2014-03-04'
date_end: '2014-03-15'
highlight_photo: 'df5150c-a-classic-view'
aliases:
- /gallery/2014-london-iceland-trip/
---
Some photos from my trip to London and Iceland.
<file_sep>/content/photo/2015-costa-rica-trip/fc1a12d-bridge.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 10:46:50'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.44527167
longitude: -84.674805
next: /gallery/2015-costa-rica-trip/b0381c7-hike-to-cerro-chato
ordering: 14
previous: /gallery/2015-costa-rica-trip/904620b-hike-to-cerro-chato
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: Bridge
aliases:
- /gallery/2015-costa-rica-trip/fc1a12d-bridge.html
---
A muddy and questionably stable bridge which wobbled as we crossed it. This was only the beginning of our muddy encounters.
<file_sep>/content/photo/2015-cambodia-thailand-trip/b6df529-img-2059.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 20:50:31'
exif:
aperture: f/2.2
exposure: 1/377
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.751945
longitude: 100.49265333
next: /gallery/2015-cambodia-thailand-trip/00ae52c-img-2070
ordering: 103
previous: /gallery/2015-cambodia-thailand-trip/e31d203-img-2052
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2059
aliases:
- /gallery/2015-cambodia-thailand-trip/b6df529-img-2059.html
---
<file_sep>/content/photo/2015-balloon-fiesta/021aeeb-img-0920.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-11 15:31:07'
exif:
aperture: f/2.2
exposure: 1/1980
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.78236333
longitude: -106.27398667
next: /gallery/2015-balloon-fiesta/914279d-img-0922
ordering: 40
previous: /gallery/2015-balloon-fiesta/e42bd57-img-0916
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0920
aliases:
- /gallery/2015-balloon-fiesta/021aeeb-img-0920.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/5fdf36a-img-1159.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 18:34:40'
exif:
aperture: f/2.2
exposure: 1/260
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44076167
longitude: 103.86070333
next: /gallery/2015-cambodia-thailand-trip/abf5597-img-1162
ordering: 30
previous: /gallery/2015-cambodia-thailand-trip/baf06ff-img-1149
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1159
aliases:
- /gallery/2015-cambodia-thailand-trip/5fdf36a-img-1159.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/2206598-img-0958.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-14 23:46:47'
exif:
aperture: f/2.2
exposure: 1/50
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.5704
longitude: 104.91951167
next: /gallery/2015-cambodia-thailand-trip/3c62e0f-img-0960
ordering: 1
previous: /gallery/2015-cambodia-thailand-trip/e66908b-img-0954
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_0958
aliases:
- /gallery/2015-cambodia-thailand-trip/2206598-img-0958.html
---
<file_sep>/content/photo/2015-costa-rica-trip/698af83-hanging-bridges.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 09:11:58'
exif:
aperture: f/2.2
exposure: 1/1236
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.33856167
longitude: -84.79686167
next: /gallery/2015-costa-rica-trip/263b61d-hanging-bridges
ordering: 63
previous: /gallery/2015-costa-rica-trip/b442c36-hanging-bridges
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Hanging Bridges'
aliases:
- /gallery/2015-costa-rica-trip/698af83-hanging-bridges.html
---
It was suggested that there were more trees visible from one of the bridges, than trees that exist in New Mexico...
<file_sep>/content/photo/2015-cambodia-thailand-trip/6de27eb-img-1952.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-18 18:38:11'
exif:
aperture: f/2.2
exposure: 1/25
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.35288
longitude: 103.85186167
next: /gallery/2015-cambodia-thailand-trip/4bfb671-img-1956
ordering: 86
previous: /gallery/2015-cambodia-thailand-trip/3805378-img-1950
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1952
aliases:
- /gallery/2015-cambodia-thailand-trip/6de27eb-img-1952.html
---
<file_sep>/content/photo/2014-london-iceland-trip/b6db71d-glacier-walk.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 16:49:24'
exif:
aperture: f/2.4
exposure: 1/1004
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.53471167
longitude: -19.358355
next: /gallery/2014-london-iceland-trip/6be2794-glacier-walk
ordering: 84
previous: /gallery/2014-london-iceland-trip/a7d6a38-panorama
sizes:
1280:
height: 290
width: 1280
640w:
height: 145
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Glacier Walk'
aliases:
- /gallery/2014-london-iceland-trip/b6db71d-glacier-walk.html
---
Here our group was putting on crampons and boots to get up the glacier.
<file_sep>/content/photo/2014-london-iceland-trip/3a0cb32-skogafoss.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 19:01:15'
exif:
aperture: f/2.4
exposure: 1/40
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.530472984092
longitude: -19.51003947495
next: /gallery/2014-london-iceland-trip/b23ccc1-night-waterfall
ordering: 96
previous: /gallery/2014-london-iceland-trip/0ee679f-skogafoss
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Skógafoss
aliases:
- /gallery/2014-london-iceland-trip/3a0cb32-skogafoss.html
---
Looking back towards the river making the waterfall.
<file_sep>/content/photo/2015-england-trip/d702f2b-e9b69c74-3c6f-41d3-8f76-5d2aac504cae.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 09:10:31'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.38156167
longitude: -2.36253
next: /gallery/2015-england-trip/271af08-c8440bd3-c5d2-40fa-816a-ca2391ecb801
ordering: 39
previous: /gallery/2015-england-trip/6d56866-38a48962-13c2-419b-8273-ae7cf45c0002
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: E9B69C74-3C6F-41D3-8F76-5D2AAC504CAE
aliases:
- /gallery/2015-england-trip/d702f2b-e9b69c74-3c6f-41d3-8f76-5d2aac504cae.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/f0b8ca2-img-2352.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-21 01:18:21'
exif:
aperture: f/2.2
exposure: 1/50
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.74625333
longitude: 100.490525
next: /gallery/2015-cambodia-thailand-trip/9b4fea6-img-2358
ordering: 126
previous: /gallery/2015-cambodia-thailand-trip/e19b8cf-img-2338
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2352
aliases:
- /gallery/2015-cambodia-thailand-trip/f0b8ca2-img-2352.html
---
<file_sep>/content/photo/2014-london-iceland-trip/2028f17-buckingham-palace.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 14:57:20'
exif:
aperture: f/2.4
exposure: 1/542
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.50175
longitude: -0.14151117
next: /gallery/2014-london-iceland-trip/66e837b-hyde-park
ordering: 33
previous: /gallery/2014-london-iceland-trip/ca834b8-buckingham-palace
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Buckingham Palace'
aliases:
- /gallery/2014-london-iceland-trip/2028f17-buckingham-palace.html
---
The guards took a break from their posts to briefly march.
<file_sep>/content/photo/2015-cambodia-thailand-trip/d02a252-img-2320.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-20 23:53:42'
exif:
aperture: f/2.2
exposure: 1/1522
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.74244667
longitude: 100.48645
next: /gallery/2015-cambodia-thailand-trip/5bfa633-img-2333
ordering: 123
previous: /gallery/2015-cambodia-thailand-trip/2d2f5d5-img-2316
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2320
aliases:
- /gallery/2015-cambodia-thailand-trip/d02a252-img-2320.html
---
<file_sep>/content/photo/2014-london-iceland-trip/1f869bd-sculptures.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 16:01:56'
exif:
aperture: f/2.4
exposure: 1/20
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.519401550293
longitude: -0.12690000236
next: /gallery/2014-london-iceland-trip/87bb358-african-carvings
ordering: 39
previous: /gallery/2014-london-iceland-trip/56d4241-the-nereid-monument
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Sculptures
aliases:
- /gallery/2014-london-iceland-trip/1f869bd-sculptures.html
---
One of *many* rooms displaying recovered wall sculpture segments.
<file_sep>/content/photo/2014-barcelona-trip/07ed14a-casa-batllo.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-23 12:14:36'
exif:
aperture: f/2.2
exposure: 1/527
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.392125
longitude: 2.1653805
next: /gallery/2014-barcelona-trip/b87b004-casa-batllo
ordering: 41
previous: /gallery/2014-barcelona-trip/9a59ac6-port-de-barcelona
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Casa Batlló'
aliases:
- /gallery/2014-barcelona-trip/07ed14a-casa-batllo.html
---
<file_sep>/content/photo/2015-balloon-fiesta/8010c80-img-0465.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 18:15:13'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19512167
longitude: -106.596445
next: /gallery/2015-balloon-fiesta/3b3deb5-img-0470
ordering: 16
previous: /gallery/2015-balloon-fiesta/bc19922-img-0449
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0465
aliases:
- /gallery/2015-balloon-fiesta/8010c80-img-0465.html
---
<file_sep>/content/photo/2014-london-iceland-trip/8e50ad8-cityscape.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 13:48:48'
exif:
aperture: f/2.4
exposure: 1/1695
make: Apple
model: 'iPhone 5'
layout: gallery-photo
next: /gallery/2014-london-iceland-trip/f5a8d81-cityscape
ordering: 57
previous: /gallery/2014-london-iceland-trip/761d483-cityscape
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Cityscape
aliases:
- /gallery/2014-london-iceland-trip/8e50ad8-cityscape.html
---
A look back towards the lake and City Hall.
<file_sep>/content/photo/2015-england-trip/73b85ca-1caa4214-8ca5-4168-90a8-b731645d1503.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 03:15:03'
exif:
aperture: f/2.2
exposure: 1/501
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.48454167
longitude: -0.604845
next: /gallery/2015-england-trip/65a4a84-662d346f-778c-41ce-8754-90744c250cb3
ordering: 20
previous: /gallery/2015-england-trip/c70b2ac-aa11611a-e379-4053-8457-88a2e4bc36b3
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 1CAA4214-8CA5-4168-90A8-B731645D1503
aliases:
- /gallery/2015-england-trip/73b85ca-1caa4214-8ca5-4168-90a8-b731645d1503.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/97f665d-img-1738.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 19:01:04'
exif:
aperture: f/2.2
exposure: 1/964
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44463833
longitude: 103.88275833
next: /gallery/2015-cambodia-thailand-trip/aca3309-img-1800
ordering: 72
previous: /gallery/2015-cambodia-thailand-trip/31dca9d-img-1703
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1738
aliases:
- /gallery/2015-cambodia-thailand-trip/97f665d-img-1738.html
---
<file_sep>/content/photo/2014-london-iceland-trip/833c1b3-museum-of-skogar.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 15:13:57'
exif:
aperture: f/2.4
exposure: 1/20
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.51988667
longitude: -19.50683333
next: /gallery/2014-london-iceland-trip/e1c9e55-museum-of-skogar
ordering: 78
previous: /gallery/2014-london-iceland-trip/e32eb2b-farm
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Museum of Skógar'
aliases:
- /gallery/2014-london-iceland-trip/833c1b3-museum-of-skogar.html
---
There was a museum in Skógar with a large collection of old tools and historical items.
<file_sep>/content/photo/2014-london-iceland-trip/eddc6cd-pathway.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 13:50:32'
exif:
aperture: f/2.4
exposure: 1/1178
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.141899108887
longitude: -21.92679977417
next: /gallery/2014-london-iceland-trip/a02f087-hallgrimskirkja
ordering: 61
previous: /gallery/2014-london-iceland-trip/90e6908-colorful
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Pathway
aliases:
- /gallery/2014-london-iceland-trip/eddc6cd-pathway.html
---
My hostel was just past the end of the street leading up to this church.
<file_sep>/content/photo/2015-balloon-fiesta/5dd4971-imag2382.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-11 14:08:23'
exif:
aperture: f/2.0
exposure: 1119/1000000
make: HTC
model: HTC6500LVW
layout: gallery-photo
location:
latitude: 35.78430167
longitude: -106.280335
next: /gallery/2015-balloon-fiesta/e42bd57-img-0916
ordering: 38
previous: /gallery/2015-balloon-fiesta/670c81b-imag2366
sizes:
1280:
height: 724
width: 1280
640w:
height: 362
width: 640
200x200:
height: 200
width: 200
title: IMAG2382
aliases:
- /gallery/2015-balloon-fiesta/5dd4971-imag2382.html
---
<file_sep>/content/photo/2015-balloon-fiesta/9cd0322-img-0631.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-10 06:45:04'
exif:
aperture: f/2.2
exposure: 1/1130
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19638833
longitude: -106.59735
next: /gallery/2015-balloon-fiesta/e6b56db-img-0647
ordering: 29
previous: /gallery/2015-balloon-fiesta/4419092-img-0619
sizes:
1280:
height: 298
width: 1280
640w:
height: 149
width: 640
200x200:
height: 200
width: 200
title: IMG_0631
aliases:
- /gallery/2015-balloon-fiesta/9cd0322-img-0631.html
---
<file_sep>/content/photo/2015-balloon-fiesta/de8713a-img-0410.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 06:51:02'
exif:
aperture: f/2.2
exposure: 1/439
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19548
longitude: -106.59789167
next: /gallery/2015-balloon-fiesta/15ea128-img-0422
ordering: 11
previous: /gallery/2015-balloon-fiesta/0234c12-img-0399
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0410
aliases:
- /gallery/2015-balloon-fiesta/de8713a-img-0410.html
---
<file_sep>/content/photo/2015-costa-rica-trip/edfd7fa-playa-espadilla.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-16 16:18:33'
exif:
aperture: f/2.2
exposure: 1/1099
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.39036167
longitude: -84.14965833
next: /gallery/2015-costa-rica-trip/f279423-manuel-antonio-national-park
ordering: 85
previous: /gallery/2015-costa-rica-trip/1cb087d-first-beach
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Playa Espadilla'
aliases:
- /gallery/2015-costa-rica-trip/edfd7fa-playa-espadilla.html
---
Once we made it to <NAME> later that afternoon, we took a quick break for some beach time. Soon though, an incoming storm hurried us away.
<file_sep>/content/photo/2015-balloon-fiesta/c373a68-img-0488.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-08 11:24:03'
exif:
aperture: f/2.2
exposure: 1/2326
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.18922
longitude: -106.69171167
next: /gallery/2015-balloon-fiesta/c26bc62-img-0495
ordering: 19
previous: /gallery/2015-balloon-fiesta/6390ae2-img-0483
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0488
aliases:
- /gallery/2015-balloon-fiesta/c373a68-img-0488.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/c50ddee-img-2016.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 20:23:56'
exif:
aperture: f/2.2
exposure: 1/648
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.75150833
longitude: 100.4926
next: /gallery/2015-cambodia-thailand-trip/10fe1d2-img-2029
ordering: 96
previous: /gallery/2015-cambodia-thailand-trip/103d2e0-img-2010
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2016
aliases:
- /gallery/2015-cambodia-thailand-trip/c50ddee-img-2016.html
---
<file_sep>/content/galleries/2014-albuquerque-balloon-fiesta/_index.md
---
slug: 2014-albuquerque-balloon-fiesta
title: Albuquerque Balloon Fiesta
date: '2014-10-09'
date_end: '2014-10-13'
highlight_photo: 'f114579-img-1074'
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/
---
<file_sep>/content/photo/2014-london-iceland-trip/ef30149-trafalgar-lunch.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-10 13:57:36'
exif:
aperture: f/2.4
exposure: 1/1695
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.5078
longitude: -0.1278195
next: /gallery/2014-london-iceland-trip/a8e17f9-stegosaurus
ordering: 25
previous: /gallery/2014-london-iceland-trip/f2e51f5-the-national-gallery
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Trafalgar Lunch'
aliases:
- /gallery/2014-london-iceland-trip/ef30149-trafalgar-lunch.html
---
Took a brief break to people watch and eat lunch from Pret a Manger.
<file_sep>/content/photo/2015-costa-rica-trip/e38b136-giovannis-night-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 19:57:24'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.47144167
longitude: -84.65242833
next: /gallery/2015-costa-rica-trip/a977d06-giovannis-night-tour
ordering: 26
previous: /gallery/2015-costa-rica-trip/288f548-giovannis-night-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Giovanni''s Night Tour'
aliases:
- /gallery/2015-costa-rica-trip/e38b136-giovannis-night-tour.html
---
We saw a few different kinds of lizards hanging out on vines above streams, ready to drop and escape if there was trouble.
<file_sep>/content/photo/2015-cambodia-thailand-trip/2d3679e-img-1229.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 11:14:28'
exif:
aperture: f/2.2
exposure: 1/1412
make: Apple
model: 'iPhone 6'
layout: gallery-photo
next: /gallery/2015-cambodia-thailand-trip/411da1f-img-1526
ordering: 59
previous: /gallery/2015-cambodia-thailand-trip/a50adc7-img-1198
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1229
aliases:
- /gallery/2015-cambodia-thailand-trip/2d3679e-img-1229.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/2681241-img-1122.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-11 08:18:52'
exif:
aperture: f/2.4
exposure: 1/1004
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.198475
longitude: -106.59491667
next: /gallery/2014-albuquerque-balloon-fiesta/1b9b6f2-img-1127
ordering: 24
previous: /gallery/2014-albuquerque-balloon-fiesta/82c066d-img-1121
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1122
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/2681241-img-1122.html
---
<file_sep>/content/photo/2014-barcelona-trip/71e7a4a-estadi-olimpic-lluis-companys.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 16:59:05'
exif:
aperture: f/2.2
exposure: 1/189
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.36444667
longitude: 2.1517055
next: /gallery/2014-barcelona-trip/55ba6a5-torre-de-comunicacions-de-montjuic
ordering: 16
previous: /gallery/2014-barcelona-trip/c24ae6e-torre-de-comunicacions-de-montjuic
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Estadi Olímpic Lluís Companys'
aliases:
- /gallery/2014-barcelona-trip/71e7a4a-estadi-olimpic-lluis-companys.html
---
<file_sep>/content/photo/2014-barcelona-trip/63a2ee2-barcelona-port.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-23 14:32:05'
exif:
aperture: f/2.2
exposure: 1/1799
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.37545
longitude: 2.18360333
next: /gallery/2014-barcelona-trip/ecfb232-sagrada-familia
ordering: 58
previous: /gallery/2014-barcelona-trip/e9a1f6e-barcelona-port
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Barcelona Port'
aliases:
- /gallery/2014-barcelona-trip/63a2ee2-barcelona-port.html
---
<file_sep>/content/photo/2014-london-iceland-trip/24b9354-church.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 12:14:38'
exif:
aperture: f/2.4
exposure: 1/1391
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.147925
longitude: -21.94853
next: /gallery/2014-london-iceland-trip/bf6398b-city-hall
ordering: 48
previous: /gallery/2014-london-iceland-trip/49594d4-across-the-bay
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Church
aliases:
- /gallery/2014-london-iceland-trip/24b9354-church.html
---
I think the church thought it was a tower of a castle.
<file_sep>/content/photo/2015-cambodia-thailand-trip/24d86c2-img-1268.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 22:54:04'
exif:
aperture: f/2.2
exposure: 1/1319
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.46176333
longitude: 103.86799667
next: /gallery/2015-cambodia-thailand-trip/0ecdcf8-img-1272
ordering: 46
previous: /gallery/2015-cambodia-thailand-trip/b0a2bc2-img-1262
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1268
aliases:
- /gallery/2015-cambodia-thailand-trip/24d86c2-img-1268.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/67a9685-img-1969.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-18 19:00:17'
exif:
aperture: f/2.2
exposure: 1/33
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.35316333
longitude: 103.85199667
next: /gallery/2015-cambodia-thailand-trip/d6a4414-img-1980
ordering: 90
previous: /gallery/2015-cambodia-thailand-trip/9a3e0c9-img-1966
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1969
aliases:
- /gallery/2015-cambodia-thailand-trip/67a9685-img-1969.html
---
<file_sep>/content/photo/2015-england-trip/0250f82-dd31f942-e044-401e-b974-ad18588484d3.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 08:32:26'
exif:
aperture: f/2.2
exposure: 1/120
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.38133833
longitude: -2.35959667
next: /gallery/2015-england-trip/dccb855-c3057568-a43e-44b1-b4c5-f129d5353d85
ordering: 31
previous: /gallery/2015-england-trip/ad68e16-aa2f4220-816c-4d69-870b-7b24f42a02b1
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: DD31F942-E044-401E-B974-AD18588484D3
aliases:
- /gallery/2015-england-trip/0250f82-dd31f942-e044-401e-b974-ad18588484d3.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/2c795a3-img-1099.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-11 07:35:11'
exif:
aperture: f/2.4
exposure: 1/282
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19432833
longitude: -106.59706167
next: /gallery/2014-albuquerque-balloon-fiesta/12014b2-img-1102
ordering: 18
previous: /gallery/2014-albuquerque-balloon-fiesta/6b77a4f-img-1095
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1099
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/2c795a3-img-1099.html
---
<file_sep>/content/photo/2015-costa-rica-trip/287df54-hanging-bridges.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 10:02:08'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.33972
longitude: -84.80092
next: /gallery/2015-costa-rica-trip/88d21c0-hanging-bridges
ordering: 72
previous: /gallery/2015-costa-rica-trip/5e1987f-hanging-bridges
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Hanging Bridges'
aliases:
- /gallery/2015-costa-rica-trip/287df54-hanging-bridges.html
---
Each bridge had a plaque at its entrance to tell us about them. They listed a capacity, but it's a good thing it wasn't too busy because I don't think anyone was actually paying attention.
<file_sep>/content/photo/2015-cambodia-thailand-trip/6970dd9-img-2361.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-21 02:17:17'
exif:
aperture: f/2.2
exposure: 1/100
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.75946167
longitude: 100.49592
next: /gallery/2015-cambodia-thailand-trip/a8f5fa5-img-2371
ordering: 128
previous: /gallery/2015-cambodia-thailand-trip/9b4fea6-img-2358
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2361
aliases:
- /gallery/2015-cambodia-thailand-trip/6970dd9-img-2361.html
---
<file_sep>/content/photo/2014-london-iceland-trip/ca834b8-buckingham-palace.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 14:52:51'
exif:
aperture: f/2.4
exposure: 1/361
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.50113667
longitude: -0.14104167
next: /gallery/2014-london-iceland-trip/2028f17-buckingham-palace
ordering: 32
previous: /gallery/2014-london-iceland-trip/f9f25f0-narwhal
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Buckingham Palace'
aliases:
- /gallery/2014-london-iceland-trip/ca834b8-buckingham-palace.html
---
Back by for another look at Buckingham Palace. The Queen was there again.
<file_sep>/content/photo/2015-cambodia-thailand-trip/ba49460-img-1175.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 18:46:19'
exif:
aperture: f/2.2
exposure: 1/1799
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44161167
longitude: 103.85962833
next: /gallery/2015-cambodia-thailand-trip/f9f7cbe-img-1182
ordering: 33
previous: /gallery/2015-cambodia-thailand-trip/460fdc5-img-1171
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1175
aliases:
- /gallery/2015-cambodia-thailand-trip/ba49460-img-1175.html
---
<file_sep>/content/photo/2014-london-iceland-trip/7a5ddf9-panorama.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 14:38:08'
exif:
aperture: f/2.4
exposure: 1/1550
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.543005
longitude: -19.66236667
next: /gallery/2014-london-iceland-trip/e32eb2b-farm
ordering: 76
previous: /gallery/2014-london-iceland-trip/6a12881-panorama
sizes:
1280:
height: 287
width: 1280
640w:
height: 143
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Panorama
aliases:
- /gallery/2014-london-iceland-trip/7a5ddf9-panorama.html
---
About the same place, but looking the other direction towards the ocean.
<file_sep>/content/photo/2014-london-iceland-trip/3dae33f-saga-museum.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 17:26:35'
exif:
aperture: f/2.4
exposure: 1/218
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.12944167
longitude: -21.91857167
next: /gallery/2014-london-iceland-trip/69f14ff-hallgrimskirkja
ordering: 67
previous: /gallery/2014-london-iceland-trip/524128b-panorama
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Saga Museum'
aliases:
- /gallery/2014-london-iceland-trip/3dae33f-saga-museum.html
---
The church in the distance is where I was looking out earlier that afternoon.
<file_sep>/content/photo/2015-cambodia-thailand-trip/103d2e0-img-2010.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 20:21:11'
exif:
aperture: f/2.2
exposure: 1/1236
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.75154167
longitude: 100.49238667
next: /gallery/2015-cambodia-thailand-trip/c50ddee-img-2016
ordering: 95
previous: /gallery/2015-cambodia-thailand-trip/635e8a3-img-2008
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2010
aliases:
- /gallery/2015-cambodia-thailand-trip/103d2e0-img-2010.html
---
<file_sep>/content/photo/2015-balloon-fiesta/bc19922-img-0449.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 07:46:23'
exif:
aperture: f/2.2
exposure: 1/1319
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19596333
longitude: -106.59725833
next: /gallery/2015-balloon-fiesta/8010c80-img-0465
ordering: 15
previous: /gallery/2015-balloon-fiesta/4b23cee-img-0435
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_0449
aliases:
- /gallery/2015-balloon-fiesta/bc19922-img-0449.html
---
<file_sep>/content/photo/2015-costa-rica-trip/932f008-jeep-boat-jeep.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 10:54:12'
exif:
aperture: f/2.2
exposure: 1/1647
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.40879167
longitude: -84.89986333
next: /gallery/2015-costa-rica-trip/4e5af81-jeep-boat-jeep
ordering: 42
previous: /gallery/2015-costa-rica-trip/23e51bc-jeep-boat-jeep
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: Jeep-Boat-Jeep
aliases:
- /gallery/2015-costa-rica-trip/932f008-jeep-boat-jeep.html
---
The second van ride was extremely bumpy. Very few roads in this area were paved, so the hilly rides were much bumpier and took much longer than they otherwise would have. But at least there were still good views.
<file_sep>/content/photo/2014-london-iceland-trip/b23ccc1-night-waterfall.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 21:14:40'
exif:
aperture: f/2.4
exposure: 1/15
make: Apple
model: 'iPhone 5'
layout: gallery-photo
next: /gallery/2014-london-iceland-trip/223be54-waterfall
ordering: 97
previous: /gallery/2014-london-iceland-trip/3a0cb32-skogafoss
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Night Waterfall'
aliases:
- /gallery/2014-london-iceland-trip/b23ccc1-night-waterfall.html
---
After dinner at Anna’s, we stopped at another waterfall - it was very dark and it was lightly raining.
<file_sep>/content/photo/2015-costa-rica-trip/7bff94b-canopy-zip-line.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 16:12:30'
exif:
aperture: f/2.2
exposure: 1/791
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.34529167
longitude: -84.84487167
next: /gallery/2015-costa-rica-trip/1cb087d-first-beach
ordering: 83
previous: /gallery/2015-costa-rica-trip/15acca5-canopy-zip-line
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Canopy Zip Line'
aliases:
- /gallery/2015-costa-rica-trip/7bff94b-canopy-zip-line.html
---
A final look across the area from the lookout point.
<file_sep>/content/photo/2015-costa-rica-trip/cdb87b9-el-avion.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-18 18:54:40'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.402325
longitude: -84.1531305
next: /gallery/2015-costa-rica-trip/62f33e5-img-2464
ordering: 122
previous: /gallery/2015-costa-rica-trip/67d08eb-el-avion
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'El Avión'
aliases:
- /gallery/2015-costa-rica-trip/cdb87b9-el-avion.html
---
...and the plane at the entrance.
<file_sep>/content/photo/2015-costa-rica-trip/b0381c7-hike-to-cerro-chato.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 11:25:26'
exif:
aperture: f/2.2
exposure: 1/2326
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.44317
longitude: -84.67778833
next: /gallery/2015-costa-rica-trip/3bf02da-hike-to-cerro-chato
ordering: 15
previous: /gallery/2015-costa-rica-trip/fc1a12d-bridge
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Hike to Cerro Chato'
aliases:
- /gallery/2015-costa-rica-trip/b0381c7-hike-to-cerro-chato.html
---
Some parts of the hike seemed much more geared towards horses with steep steps and muddy areas. It was still pretty though.
<file_sep>/content/photo/2014-london-iceland-trip/ca1f5b9-river-thames.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-08 16:47:21'
exif:
aperture: f/2.4
exposure: 1/2008
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.503013450216
longitude: 0.013557650034
next: /gallery/2014-london-iceland-trip/4f82b54-fancy-building
ordering: 8
previous: /gallery/2014-london-iceland-trip/2c1b931-river-thames
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'River Thames'
aliases:
- /gallery/2014-london-iceland-trip/ca1f5b9-river-thames.html
---
A look back East towards the O2 stadium.
<file_sep>/content/photo/2015-costa-rica-trip/ae8494f-el-avion.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-18 17:47:11'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.40233667
longitude: -84.15333617
next: /gallery/2015-costa-rica-trip/67d08eb-el-avion
ordering: 120
previous: /gallery/2015-costa-rica-trip/e64375f-el-avion
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'El Avión'
aliases:
- /gallery/2015-costa-rica-trip/ae8494f-el-avion.html
---
Last photo of the beautiful sunset.
<file_sep>/content/photo/2015-costa-rica-trip/30d9cb8-giovannis-night-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 19:20:45'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.470995
longitude: -84.650345
next: /gallery/2015-costa-rica-trip/6b45122-giovannis-night-tour
ordering: 22
previous: /gallery/2015-costa-rica-trip/fb10d9a-thirsty-cow
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Giovanni''s Night Tour'
aliases:
- /gallery/2015-costa-rica-trip/30d9cb8-giovannis-night-tour.html
---
That night, we did a Night Tour hike where we were guided through a privately maintained park and saw some critters.
<file_sep>/content/photo/2015-cambodia-thailand-trip/6e79602-img-1098.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 22:59:39'
exif:
aperture: f/2.2
exposure: 1/1647
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.5783
longitude: 104.92527
next: /gallery/2015-cambodia-thailand-trip/ffde6e7-img-1117
ordering: 21
previous: /gallery/2015-cambodia-thailand-trip/8563672-img-1094
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1098
aliases:
- /gallery/2015-cambodia-thailand-trip/6e79602-img-1098.html
---
<file_sep>/content/photo/2014-barcelona-trip/df4c388-sagrada-familia.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-23 16:09:00'
exif:
aperture: f/2.2
exposure: 1/327
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.40318667
longitude: 2.17365
next: /gallery/2014-barcelona-trip/620a826-sagrada-familia
ordering: 69
previous: /gallery/2014-barcelona-trip/eba2a2b-sagrada-familia
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Sagrada Família'
aliases:
- /gallery/2014-barcelona-trip/df4c388-sagrada-familia.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/0b51e42-img-2092.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 21:21:29'
exif:
aperture: f/2.2
exposure: 1/200
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.75123
longitude: 100.49249167
next: /gallery/2015-cambodia-thailand-trip/59014a2-img-2109
ordering: 107
previous: /gallery/2015-cambodia-thailand-trip/6ce5d53-img-2081
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2092
aliases:
- /gallery/2015-cambodia-thailand-trip/0b51e42-img-2092.html
---
<file_sep>/content/post/_index.md
---
title: Posts
description: To document some thoughts and learnings.
---
<file_sep>/content/photo/2015-england-trip/84d1f65-2f92ff97-e35e-45c1-8ac4-c01b017d0636.md
---
galleries:
- 2015-england-trip
date: '2015-03-08 05:40:32'
exif:
aperture: f/2.2
exposure: 1/842
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.50868833
longitude: -0.0751805
next: /gallery/2015-england-trip/2d3df9a-184c652a-394f-40e1-b325-b3ff0ef009e3
ordering: 3
previous: /gallery/2015-england-trip/11fb097-f8f4710d-55b5-4d31-8e03-82d52b70c0d8
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 2F92FF97-E35E-45C1-8AC4-C01B017D0636
aliases:
- /gallery/2015-england-trip/84d1f65-2f92ff97-e35e-45c1-8ac4-c01b017d0636.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/2fa5b81-img-1325.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 23:38:31'
exif:
aperture: f/2.2
exposure: 1/1099
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.462195
longitude: 103.872375
next: /gallery/2015-cambodia-thailand-trip/d9133cb-img-1362
ordering: 49
previous: /gallery/2015-cambodia-thailand-trip/af60a57-img-1308
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1325
aliases:
- /gallery/2015-cambodia-thailand-trip/2fa5b81-img-1325.html
---
<file_sep>/content/photo/2015-costa-rica-trip/1665ce9-boat-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 17:07:32'
exif:
aperture: f/2.2
exposure: 1/190
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.39183833
longitude: -84.20878667
next: /gallery/2015-costa-rica-trip/ba4a018-boat-tour
ordering: 110
previous: /gallery/2015-costa-rica-trip/a0e1387-boat-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Boat Tour'
aliases:
- /gallery/2015-costa-rica-trip/1665ce9-boat-tour.html
---
Another happy dolphin. It wasn't easy timing photos of them.
<file_sep>/content/photo/2015-cambodia-thailand-trip/2e84c6b-img-1031.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 18:27:47'
exif:
aperture: f/2.2
exposure: 1/1014
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.563825
longitude: 104.93128833
next: /gallery/2015-cambodia-thailand-trip/2148845-img-1046
ordering: 13
previous: /gallery/2015-cambodia-thailand-trip/a92f6a2-img-1029
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1031
aliases:
- /gallery/2015-cambodia-thailand-trip/2e84c6b-img-1031.html
---
<file_sep>/content/photo/2015-costa-rica-trip/78b6538-red-sofa.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-11 12:20:24'
exif:
aperture: f/2.2
exposure: 1/1099
make: Apple
model: 'iPhone 6'
layout: gallery-photo
next: /gallery/2015-costa-rica-trip/319af9c-en-route-to-la-fortuna
ordering: 2
previous: /gallery/2015-costa-rica-trip/28ec865-parque-nacional
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Red Sofa'
aliases:
- /gallery/2015-costa-rica-trip/78b6538-red-sofa.html
---
We took the bus from San Jose to La Fortuna. One of the bus stops had a sofa sitting out across from the stop.
<file_sep>/content/photo/2014-london-iceland-trip/4d26938-panorama.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 18:52:06'
exif:
aperture: f/2.4
exposure: 1/120
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.528967552541
longitude: -19.51290268954
next: /gallery/2014-london-iceland-trip/0ee679f-skogafoss
ordering: 94
previous: /gallery/2014-london-iceland-trip/9fa3c9a-skogafoss
sizes:
1280:
height: 293
width: 1280
640w:
height: 146
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Panorama
aliases:
- /gallery/2014-london-iceland-trip/4d26938-panorama.html
---
A panorama of the waterfall.
<file_sep>/content/photo/2015-cambodia-thailand-trip/9ebc24f-img-1981.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 05:57:33'
exif:
aperture: f/2.2
exposure: 1/33
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.75358333
longitude: 100.53968
next: /gallery/2015-cambodia-thailand-trip/c53b1dc-img-1982
ordering: 92
previous: /gallery/2015-cambodia-thailand-trip/d6a4414-img-1980
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1981
aliases:
- /gallery/2015-cambodia-thailand-trip/9ebc24f-img-1981.html
---
<file_sep>/content/photo/2015-england-trip/04044ac-259b11e8-a284-4ef2-95e5-aae381f93cff.md
---
galleries:
- 2015-england-trip
date: '2015-03-08 05:57:26'
exif:
aperture: f/2.2
exposure: 1/1582
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.50823667
longitude: -0.07726117
next: /gallery/2015-england-trip/e564413-086f814c-6d73-4b9b-aa4b-d1fd567d9bd7
ordering: 6
previous: /gallery/2015-england-trip/bab7628-9010d32f-fe0b-4648-a498-4c68cdd114de
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 259B11E8-A284-4EF2-95E5-AAE381F93CFF
aliases:
- /gallery/2015-england-trip/04044ac-259b11e8-a284-4ef2-95e5-aae381f93cff.html
---
<file_sep>/content/photo/2015-balloon-fiesta/d77389a-img-0534.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-09 07:04:57'
exif:
aperture: f/2.2
exposure: 1/1014
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.193805
longitude: -106.59793833
next: /gallery/2015-balloon-fiesta/fa4c901-img-0549
ordering: 25
previous: /gallery/2015-balloon-fiesta/fc46ce5-img-0527
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0534
aliases:
- /gallery/2015-balloon-fiesta/d77389a-img-0534.html
---
<file_sep>/scripts/backfill-photo-aliases.go
package main
import (
"fmt"
"io/ioutil"
"path"
"path/filepath"
"strings"
yaml "gopkg.in/yaml.v2"
)
func main() {
contentPaths, err := filepath.Glob("content/photo/*/*.md")
if err != nil {
panic(err)
}
for _, contentPath := range contentPaths {
fmt.Println(contentPath)
contentBytes, err := ioutil.ReadFile(contentPath)
if err != nil {
panic(err)
}
contentParts := strings.SplitN(string(contentBytes), "---\n", 3)
var frontmatter map[string]interface{}
err = yaml.Unmarshal([]byte(contentParts[1]), &frontmatter)
if err != nil {
panic(err)
}
galleriesValue, ok := frontmatter["galleries"]
if !ok {
fmt.Println("> no galleries")
continue
}
galleries, ok := galleriesValue.([]interface{})
if !ok {
fmt.Println("> no galleries array")
continue
}
contentParts[1] = fmt.Sprintf("%saliases:\n- /gallery/%s/%s\n", contentParts[1], galleries[0].(string), strings.Replace(path.Base(contentPath), ".md", ".html", 1))
err = ioutil.WriteFile(contentPath, []byte(strings.Join(contentParts, "---\n")), 0644)
if err != nil {
panic(err)
}
}
}
<file_sep>/content/galleries/2015-cambodia-thailand-trip/_index.md
---
slug: 2015-cambodia-thailand-trip
title: Cambodia & Thailand Trip
date: '2015-11-14'
date_end: '2015-11-22'
highlight_photo: '468d46d-img-1199'
aliases:
- /gallery/2015-cambodia-thailand-trip/
---
Exploring Phnom Penh, Siem Reap, and Bangkok for a week.
with something else said
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/6b77a4f-img-1095.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 09:32:23'
exif:
aperture: f/2.4
exposure: 1/889
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.189445
longitude: -106.59749667
next: /gallery/2014-albuquerque-balloon-fiesta/2c795a3-img-1099
ordering: 17
previous: /gallery/2014-albuquerque-balloon-fiesta/e20c89c-img-1094
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1095
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/6b77a4f-img-1095.html
---
<file_sep>/content/photo/2015-costa-rica-trip/7d01cf9-don-juan-coffee-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 16:31:16'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.32269667
longitude: -84.83616667
next: /gallery/2015-costa-rica-trip/88a1506-don-juan-coffee-tour
ordering: 54
previous: /gallery/2015-costa-rica-trip/e7eb34b-don-juan-coffee-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Don Juan Coffee Tour'
aliases:
- /gallery/2015-costa-rica-trip/7d01cf9-don-juan-coffee-tour.html
---
Our guide explained how the beans are roasted, and some of the different times required for the different flavors.
<file_sep>/content/photo/2014-barcelona-trip/5b02ceb-sagrada-familia.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-23 17:00:52'
exif:
aperture: f/2.2
exposure: 1/154
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.40338833
longitude: 2.17405
next: /gallery/2014-barcelona-trip/711b33e-sagrada-familia
ordering: 84
previous: /gallery/2014-barcelona-trip/dbc6e6f-sagrada-familia
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Sagrada Família'
aliases:
- /gallery/2014-barcelona-trip/5b02ceb-sagrada-familia.html
---
<file_sep>/content/photo/2015-costa-rica-trip/f279423-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 07:16:15'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.39073833
longitude: -84.14499717
next: /gallery/2015-costa-rica-trip/917dd23-manuel-antonio-national-park
ordering: 86
previous: /gallery/2015-costa-rica-trip/edfd7fa-playa-espadilla
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: '<NAME>onio National Park'
aliases:
- /gallery/2015-costa-rica-trip/f279423-manuel-antonio-national-park.html
---
Saturday morning we walked to the park right after it opened. The park is well-known for its animal diversity, trails, and beautiful beaches.
<file_sep>/content/galleries/2014-colorado-aspens/_index.md
---
slug: 2014-colorado-aspens
title: "Colorado Aspens"
date: '2014-09-27'
highlight_photo: '2dbeedb-aspens-invading'
aliases:
- /gallery/2014-colorado-aspens/
---
<file_sep>/content/photo/2014-barcelona-trip/3f1a4bb-parc-guell.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 14:56:14'
exif:
aperture: f/2.2
exposure: 1/1199
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.41628333
longitude: 2.1528555
next: /gallery/2014-barcelona-trip/24a6783-parc-guell
ordering: 3
previous: /gallery/2014-barcelona-trip/1474689-parc-guell
sizes:
1280:
height: 415
width: 1280
640w:
height: 208
width: 640
200x200:
height: 200
width: 200
title: '<NAME>'
aliases:
- /gallery/2014-barcelona-trip/3f1a4bb-parc-guell.html
---
<file_sep>/content/photo/2015-costa-rica-trip/c7842e3-canopy-zip-line.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 14:49:57'
exif:
aperture: f/2.2
exposure: 1/1522
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.344955
longitude: -84.84433
next: /gallery/2015-costa-rica-trip/2c4b03b-canopy-zip-line
ordering: 78
previous: /gallery/2015-costa-rica-trip/de9981c-canopy-zip-line
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Canopy Zip Line'
aliases:
- /gallery/2015-costa-rica-trip/c7842e3-canopy-zip-line.html
---
A few of the lines actually went completely across the valley, making for a very long run and 360º view.
<file_sep>/content/photo/2015-cambodia-thailand-trip/f235b51-img-1252.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 20:52:56'
exif:
aperture: f/2.2
exposure: 1/2083
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44581167
longitude: 103.858825
next: /gallery/2015-cambodia-thailand-trip/b0a2bc2-img-1262
ordering: 44
previous: /gallery/2015-cambodia-thailand-trip/267b4bf-img-1243
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1252
aliases:
- /gallery/2015-cambodia-thailand-trip/f235b51-img-1252.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/b410619-img-2075.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 21:09:58'
exif:
aperture: f/2.2
exposure: 1/33
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.75113833
longitude: 100.49231667
next: /gallery/2015-cambodia-thailand-trip/6ce5d53-img-2081
ordering: 105
previous: /gallery/2015-cambodia-thailand-trip/00ae52c-img-2070
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2075
aliases:
- /gallery/2015-cambodia-thailand-trip/b410619-img-2075.html
---
<file_sep>/content/photo/2015-costa-rica-trip/47fd351-boat-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 14:07:18'
exif:
aperture: f/2.2
exposure: 1/1464
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.42549167
longitude: -84.169005
next: /gallery/2015-costa-rica-trip/f6374cd-boat-tour
ordering: 105
previous: /gallery/2015-costa-rica-trip/e56c61b-manuel-antonio-national-park
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Boat Tour'
aliases:
- /gallery/2015-costa-rica-trip/47fd351-boat-tour.html
---
On Saturday afternoon, after the park, we went on a boat tour which would take us around the coastline of <NAME>, provide snorkeling, and find some dolphins.
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/700178d-img-1048.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 07:35:36'
exif:
aperture: f/2.4
exposure: 1/120
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19454167
longitude: -106.59803833
next: /gallery/2014-albuquerque-balloon-fiesta/1953f93-img-1049
ordering: 3
previous: /gallery/2014-albuquerque-balloon-fiesta/ceb86f3-img-1039
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1048
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/700178d-img-1048.html
---
<file_sep>/content/photo/2014-london-iceland-trip/c551a16-bus-tour.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 14:21:25'
exif:
aperture: f/2.4
exposure: 1/502
make: Apple
model: 'iPhone 5'
layout: gallery-photo
next: /gallery/2014-london-iceland-trip/c8267be-sudhurland
ordering: 71
previous: /gallery/2014-london-iceland-trip/037fcaf-kaffibarinn
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Bus Tour'
aliases:
- /gallery/2014-london-iceland-trip/c551a16-bus-tour.html
---
On a bus tour, we traveled a bit North of Reyjkavik through the country.
<file_sep>/content/photo/2015-costa-rica-trip/aabb2db-don-juan-coffee-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 15:39:28'
exif:
aperture: f/2.2
exposure: 1/1883
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.32238667
longitude: -84.83499167
next: /gallery/2015-costa-rica-trip/5cdf335-don-juan-coffee-tour
ordering: 49
previous: /gallery/2015-costa-rica-trip/aa6be30-don-juan-coffee-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Don Juan Coffee Tour'
aliases:
- /gallery/2015-costa-rica-trip/aabb2db-don-juan-coffee-tour.html
---
The greenhouse where the beans are laid out to dry in the heat of the sun.
<file_sep>/content/photo/2014-london-iceland-trip/d66f55c-sudhurland.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 14:28:18'
exif:
aperture: f/2.4
exposure: 1/374
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.57055
longitude: -19.868355
next: /gallery/2014-london-iceland-trip/6a12881-panorama
ordering: 74
previous: /gallery/2014-london-iceland-trip/881baef-sudhurland
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Sudhurland
aliases:
- /gallery/2014-london-iceland-trip/d66f55c-sudhurland.html
---
The landscape of Iceland is very interesting with the cliffs, caves, and hill locations.
<file_sep>/content/photo/2015-england-trip/0b451bb-6e112ea8-32c7-434a-8b80-8458e5f034aa.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 04:07:30'
exif:
aperture: f/2.2
exposure: 1/391
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.48348333
longitude: -0.60632167
next: /gallery/2015-england-trip/4d1765a-30c60656-21bb-4293-b77e-2ea9dcf2281e
ordering: 24
previous: /gallery/2015-england-trip/9705f6a-61aa0911-1a3e-4beb-9fdc-6a280ad49ced
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 6E112EA8-32C7-434A-8B80-8458E5F034AA
aliases:
- /gallery/2015-england-trip/0b451bb-6e112ea8-32c7-434a-8b80-8458e5f034aa.html
---
<file_sep>/content/photo/2014-london-iceland-trip/6132b85-giraffe.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 11:53:50'
exif:
aperture: f/2.4
exposure: 1/30
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.495914
longitude: -0.176366
next: /gallery/2014-london-iceland-trip/c8cca33-whale
ordering: 28
previous: /gallery/2014-london-iceland-trip/59809e9-tyrannosaurus-rex
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Giraffe
aliases:
- /gallery/2014-london-iceland-trip/6132b85-giraffe.html
---
One exhibit had a whole collection of animals…
<file_sep>/content/photo/2015-cambodia-thailand-trip/9a599fd-img-1196.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 19:05:48'
exif:
aperture: f/2.2
exposure: 1/1099
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44144167
longitude: 103.85878833
next: /gallery/2015-cambodia-thailand-trip/468d46d-img-1199
ordering: 37
previous: /gallery/2015-cambodia-thailand-trip/3dbcc3b-img-1187
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1196
aliases:
- /gallery/2015-cambodia-thailand-trip/9a599fd-img-1196.html
---
<file_sep>/content/galleries/2015-costa-rica-trip/_index.md
---
slug: 2015-costa-rica-trip
title: Costa Rica Trip
date: '2015-01-09'
date_end: '2015-01-20'
highlight_photo: 'ae8494f-el-avion'
aliases:
- /gallery/2015-costa-rica-trip/
---
Myself, my sister, and a couple friends explored Costa Rica for 10 days.
<file_sep>/content/photo/2015-costa-rica-trip/be359cf-don-juan-coffee-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 15:16:57'
exif:
aperture: f/2.2
exposure: 1/273
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.32287
longitude: -84.834695
next: /gallery/2015-costa-rica-trip/ab6da0f-don-juan-coffee-tour
ordering: 45
previous: /gallery/2015-costa-rica-trip/785fc88-don-juan-coffee-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Don Juan Coffee Tour'
aliases:
- /gallery/2015-costa-rica-trip/be359cf-don-juan-coffee-tour.html
---
It's a seasonal job, but they said they're all still hand-picked into large baskets.
<file_sep>/content/photo/2015-cambodia-thailand-trip/999bece-img-1057.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 19:04:34'
exif:
aperture: f/2.2
exposure: 1/2639
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.56278
longitude: 104.93205333
next: /gallery/2015-cambodia-thailand-trip/d29a63d-img-1069
ordering: 16
previous: /gallery/2015-cambodia-thailand-trip/cb35b0a-img-1056
sizes:
1280:
height: 347
width: 1280
640w:
height: 174
width: 640
200x200:
height: 200
width: 200
title: IMG_1057
aliases:
- /gallery/2015-cambodia-thailand-trip/999bece-img-1057.html
---
<file_sep>/content/photo/2014-london-iceland-trip/77bf47b-panorama.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 17:50:20'
exif:
aperture: f/2.4
exposure: 1/1004
make: Apple
model: 'iPhone 5'
layout: gallery-photo
next: /gallery/2014-london-iceland-trip/68119f5-glacier-walk
ordering: 90
previous: /gallery/2014-london-iceland-trip/78e4415-glacier-walk
sizes:
1280:
height: 276
width: 1280
640w:
height: 138
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Panorama
aliases:
- /gallery/2014-london-iceland-trip/77bf47b-panorama.html
---
Another panorama of the glacier as we were leaving.
<file_sep>/content/photo/2014-barcelona-trip/f19bddd-walkway.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-24 13:39:46'
exif:
aperture: f/2.2
exposure: 1/384
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.38376667
longitude: 2.17142833
next: /gallery/2014-barcelona-trip/66cda3d-barcelona-port
ordering: 88
previous: /gallery/2014-barcelona-trip/de8662e-some-peppers
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: Walkway
aliases:
- /gallery/2014-barcelona-trip/f19bddd-walkway.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/f98e69a-img-1037.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 07:30:04'
exif:
aperture: f/2.4
exposure: 1/120
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19281333
longitude: -106.59905333
next: /gallery/2014-albuquerque-balloon-fiesta/ceb86f3-img-1039
ordering: 1
previous: /gallery/2014-albuquerque-balloon-fiesta/a6016aa-img-1035
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1037
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/f98e69a-img-1037.html
---
<file_sep>/content/photo/2015-costa-rica-trip/97dc064-hanging-bridges.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 08:52:21'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.35719667
longitude: -84.79606667
next: /gallery/2015-costa-rica-trip/2cdf51c-hanging-bridges
ordering: 59
previous: /gallery/2015-costa-rica-trip/0f5608b-tree-house-restaurant
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Hanging Bridges'
aliases:
- /gallery/2015-costa-rica-trip/97dc064-hanging-bridges.html
---
Thursday morning we went to a park along the forest which had hanging bridges across the rainforest canopy.
<file_sep>/content/photo/2015-costa-rica-trip/de9981c-canopy-zip-line.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 14:35:33'
exif:
aperture: f/2.2
exposure: 1/1522
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.34678
longitude: -84.84033333
next: /gallery/2015-costa-rica-trip/c7842e3-canopy-zip-line
ordering: 77
previous: /gallery/2015-costa-rica-trip/1362d41-canopy-zip-line
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Canopy Zip Line'
aliases:
- /gallery/2015-costa-rica-trip/de9981c-canopy-zip-line.html
---
But regardless, they always had beautiful views of the surrounding valley and forest.
<file_sep>/content/photo/2015-costa-rica-trip/803d85a-monteverde-chocolate-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-13 13:37:04'
exif:
aperture: f/2.2
exposure: 1/120
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.458025
longitude: -84.65208333
next: /gallery/2015-costa-rica-trip/7cd8fdf-monteverde-chocolate-tour
ordering: 35
previous: /gallery/2015-costa-rica-trip/0880939-monteverde-chocolate-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Monteverde Chocolate Tour'
aliases:
- /gallery/2015-costa-rica-trip/803d85a-monteverde-chocolate-tour.html
---
And then our guide walked us through the processes that beans go through.
<file_sep>/content/photo/2015-england-trip/0aef531-fe1ac7a8-bcbb-4073-b3c6-0aaebe102eb4.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 06:34:38'
exif:
aperture: f/2.2
exposure: 1/534
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.17834167
longitude: -1.82524667
next: /gallery/2015-england-trip/7b16292-69579f63-afd0-4663-a9dc-41c268cb5d67
ordering: 27
previous: /gallery/2015-england-trip/a0b3f51-f4b4ccf6-6dfb-40cb-9550-307bec24ab15
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: FE1AC7A8-BCBB-4073-B3C6-0AAEBE102EB4
aliases:
- /gallery/2015-england-trip/0aef531-fe1ac7a8-bcbb-4073-b3c6-0aaebe102eb4.html
---
<file_sep>/content/galleries/2015-balloon-fiesta/_index.md
---
slug: 2015-balloon-fiesta
title: Balloon Fiesta
date: '2015-10-03'
date_end: '2015-10-11'
highlight_photo: '4e5a28b-img-0355'
aliases:
- /gallery/2015-balloon-fiesta/
---
Albuquerque Balloon Fiesta
<file_sep>/content/photo/2014-barcelona-trip/334d378-sagrada-familia.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-23 16:03:06'
exif:
aperture: f/2.2
exposure: 1/120
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.40410333
longitude: 2.17491667
next: /gallery/2014-barcelona-trip/3b9ed7b-sagrada-familia
ordering: 62
previous: /gallery/2014-barcelona-trip/2e3c5fc-sagrada-familia
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Sagrada Família'
aliases:
- /gallery/2014-barcelona-trip/334d378-sagrada-familia.html
---
<file_sep>/content/photo/2015-costa-rica-trip/621981b-hanging-bridges.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 09:20:09'
exif:
aperture: f/2.2
exposure: 1/60
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.33659167
longitude: -84.79661667
next: /gallery/2015-costa-rica-trip/48f23d8-hanging-bridges
ordering: 65
previous: /gallery/2015-costa-rica-trip/263b61d-hanging-bridges
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Hanging Bridges'
aliases:
- /gallery/2015-costa-rica-trip/621981b-hanging-bridges.html
---
Walking out onto the sunny bridges from the covered forests was always a fun transition. Depending on how many others were on it, they could become very wobbly.
<file_sep>/content/photo/2015-cambodia-thailand-trip/baae0b9-img-2141.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-19 21:59:16'
exif:
aperture: f/2.2
exposure: 1/1163
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.75043333
longitude: 100.49173
next: /gallery/2015-cambodia-thailand-trip/5341bfc-img-2166
ordering: 109
previous: /gallery/2015-cambodia-thailand-trip/59014a2-img-2109
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2141
aliases:
- /gallery/2015-cambodia-thailand-trip/baae0b9-img-2141.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/2148845-img-1046.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 18:45:00'
exif:
aperture: f/2.2
exposure: 1/1199
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.56267833
longitude: 104.93156333
next: /gallery/2015-cambodia-thailand-trip/cb35b0a-img-1056
ordering: 14
previous: /gallery/2015-cambodia-thailand-trip/2e84c6b-img-1031
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1046
aliases:
- /gallery/2015-cambodia-thailand-trip/2148845-img-1046.html
---
<file_sep>/content/photo/2015-costa-rica-trip/88a1506-don-juan-coffee-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 16:41:42'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.32283833
longitude: -84.82643833
next: /gallery/2015-costa-rica-trip/ec40a9e-don-juan-coffee-tour
ordering: 55
previous: /gallery/2015-costa-rica-trip/7d01cf9-don-juan-coffee-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Don Juan Coffee Tour'
aliases:
- /gallery/2015-costa-rica-trip/88a1506-don-juan-coffee-tour.html
---
In addition to coffee and cocoa, we also learned about sugar cane. Here were able to taste it in it's raw stick form.
<file_sep>/content/photo/2015-costa-rica-trip/28ec865-parque-nacional.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-10 10:16:04'
exif:
aperture: f/2.2
exposure: 1/302
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.93482833
longitude: -84.07070833
next: /gallery/2015-costa-rica-trip/78b6538-red-sofa
ordering: 1
previous: /gallery/2015-costa-rica-trip/3058bbd-monument-at-parque-nacional
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Parque Nacional'
aliases:
- /gallery/2015-costa-rica-trip/28ec865-parque-nacional.html
---
Apparently Florida is significant here.
<file_sep>/content/photo/2014-london-iceland-trip/7cb9f32-museum-of-skogar.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 15:23:46'
exif:
aperture: f/2.4
exposure: 1/15
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.52184667
longitude: -19.52075
next: /gallery/2014-london-iceland-trip/04cac52-museum-of-skogar
ordering: 81
previous: /gallery/2014-london-iceland-trip/fc55b8c-museum-of-skogar
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Museum of Skógar'
aliases:
- /gallery/2014-london-iceland-trip/7cb9f32-museum-of-skogar.html
---
And old looms, too.
<file_sep>/content/photo/2015-england-trip/ee3f59d-475fbb88-fe94-40ea-a82a-9d964340dc9d.md
---
galleries:
- 2015-england-trip
date: '2015-03-08 06:52:18'
exif:
aperture: f/2.2
exposure: 1/20
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.50775833
longitude: -0.0787195
next: /gallery/2015-england-trip/3f5cb97-ad05b78c-0cf1-449a-a827-48b199cefce9
ordering: 10
previous: /gallery/2015-england-trip/20a13d4-6cad5405-2223-45c7-aa02-f5a7220579a8
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 475FBB88-FE94-40EA-A82A-9D964340DC9D
aliases:
- /gallery/2015-england-trip/ee3f59d-475fbb88-fe94-40ea-a82a-9d964340dc9d.html
---
<file_sep>/content/photo/2015-costa-rica-trip/4aa865c-giovannis-night-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 21:10:20'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.470475
longitude: -84.650505
next: /gallery/2015-costa-rica-trip/c732c52-monteverde-chocolate-tour
ordering: 32
previous: /gallery/2015-costa-rica-trip/238588a-giovannis-night-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Giovanni''s Night Tour'
aliases:
- /gallery/2015-costa-rica-trip/4aa865c-giovannis-night-tour.html
---
The red-eyed tree frog posed in front of a leaf for us.
<file_sep>/content/photo/2015-costa-rica-trip/5f71bc8-jeep-boat-jeep.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 08:52:49'
exif:
aperture: f/2.2
exposure: 1/942
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.47801333
longitude: -84.762955
next: /gallery/2015-costa-rica-trip/6a78f2e-jeep-boat-jeep
ordering: 39
previous: /gallery/2015-costa-rica-trip/c8f8633-monteverde-chocolate-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: Jeep-Boat-Jeep
aliases:
- /gallery/2015-costa-rica-trip/5f71bc8-jeep-boat-jeep.html
---
After the tiny bus seats and broken down bus to La Fortuna, we decided to take a different route to Monteverde. There's a large lake between the cities that we crossed by boat, and vans took us the rest of the way on either side.
<file_sep>/content/photo/2015-cambodia-thailand-trip/3805378-img-1950.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-18 18:34:10'
exif:
aperture: f/2.2
exposure: 1/33
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.35284167
longitude: 103.8518
next: /gallery/2015-cambodia-thailand-trip/6de27eb-img-1952
ordering: 85
previous: /gallery/2015-cambodia-thailand-trip/7fa2005-img-1948
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1950
aliases:
- /gallery/2015-cambodia-thailand-trip/3805378-img-1950.html
---
<file_sep>/content/photo/2015-england-trip/11fb097-f8f4710d-55b5-4d31-8e03-82d52b70c0d8.md
---
galleries:
- 2015-england-trip
date: '2015-03-08 05:14:21'
exif:
aperture: f/2.2
exposure: 1/1980
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.50845833
longitude: -0.07676667
next: /gallery/2015-england-trip/84d1f65-2f92ff97-e35e-45c1-8ac4-c01b017d0636
ordering: 2
previous: /gallery/2015-england-trip/642bebc-52866970-d255-4df1-a459-c1232d53d51b
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: F8F4710D-55B5-4D31-8E03-82D52B70C0D8
aliases:
- /gallery/2015-england-trip/11fb097-f8f4710d-55b5-4d31-8e03-82d52b70c0d8.html
---
<file_sep>/content/photo/2015-england-trip/af28ed2-838aee87-dd8c-49bd-9780-ed48fc47ac1c.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 08:42:19'
exif:
aperture: f/2.2
exposure: 1/120
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.38083667
longitude: -2.35949167
next: /gallery/2015-england-trip/fac9303-a5ee73bd-dff0-4ba1-9e73-a9acf32de02a
ordering: 34
previous: /gallery/2015-england-trip/bb01fc5-3df722fc-172d-4e42-acb5-a5201452f47f
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 838AEE87-DD8C-49BD-9780-ED48FC47AC1C
aliases:
- /gallery/2015-england-trip/af28ed2-838aee87-dd8c-49bd-9780-ed48fc47ac1c.html
---
<file_sep>/content/photo/2015-costa-rica-trip/904620b-hike-to-cerro-chato.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 10:39:41'
exif:
aperture: f/2.2
exposure: 1/898
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.44572167
longitude: -84.67426333
next: /gallery/2015-costa-rica-trip/fc1a12d-bridge
ordering: 13
previous: /gallery/2015-costa-rica-trip/99e190d-lookout
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Hike to Cerro Chato'
aliases:
- /gallery/2015-costa-rica-trip/904620b-hike-to-cerro-chato.html
---
Fortunately, it was a great day for a hike. There were quite a few rainstorms throughout our visit - most of them in the evenings.
<file_sep>/content/photo/2014-london-iceland-trip/70668ad-panorama.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 11:36:29'
exif:
aperture: f/2.4
exposure: 1/1130
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.14971117
longitude: -21.93162833
next: /gallery/2014-london-iceland-trip/49594d4-across-the-bay
ordering: 46
previous: /gallery/2014-london-iceland-trip/238d28c-reyjkavik-docks
sizes:
1280:
height: 389
width: 1280
640w:
height: 195
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Panorama
aliases:
- /gallery/2014-london-iceland-trip/70668ad-panorama.html
---
A panorama looking out into the bay. It was very windy that morning.
<file_sep>/content/photo/2015-cambodia-thailand-trip/404cac7-img-1900.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 22:24:55'
exif:
aperture: f/2.2
exposure: 1/1276
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.42992833
longitude: 103.89800333
next: /gallery/2015-cambodia-thailand-trip/675e7f0-img-1918
ordering: 78
previous: /gallery/2015-cambodia-thailand-trip/9b2edec-img-1877
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1900
aliases:
- /gallery/2015-cambodia-thailand-trip/404cac7-img-1900.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/e66908b-img-0954.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-14 21:34:15'
exif:
aperture: f/2.2
exposure: 1/120
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.56310833
longitude: 104.86049667
next: /gallery/2015-cambodia-thailand-trip/2206598-img-0958
ordering: 0
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0954
aliases:
- /gallery/2015-cambodia-thailand-trip/e66908b-img-0954.html
---
<file_sep>/content/photo/2014-london-iceland-trip/bf6398b-city-hall.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 12:24:04'
exif:
aperture: f/2.4
exposure: 1/1506
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.14543883
longitude: -21.94050333
next: /gallery/2014-london-iceland-trip/b8bd46c-feed-the-ducks
ordering: 49
previous: /gallery/2014-london-iceland-trip/24b9354-church
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'City Hall'
aliases:
- /gallery/2014-london-iceland-trip/bf6398b-city-hall.html
---
City Hall next to (in?) the pond.
<file_sep>/content/photo/2015-costa-rica-trip/7d3c2d9-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 11:39:41'
exif:
aperture: f/2.2
exposure: 1/4405
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.37954167
longitude: -84.146325
next: /gallery/2015-costa-rica-trip/e56c61b-manuel-antonio-national-park
ordering: 103
previous: /gallery/2015-costa-rica-trip/b9cdf82-manuel-antonio-national-park
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Manuel Antonio National Park'
aliases:
- /gallery/2015-costa-rica-trip/7d3c2d9-manuel-antonio-national-park.html
---
Another view from the same location.
<file_sep>/content/photo/2015-costa-rica-trip/e7eb34b-don-juan-coffee-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 16:29:40'
exif:
aperture: f/2.2
exposure: 1/24
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.322145
longitude: -84.835005
next: /gallery/2015-costa-rica-trip/7d01cf9-don-juan-coffee-tour
ordering: 53
previous: /gallery/2015-costa-rica-trip/507297f-don-juan-coffee-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Don Juan Coffee Tour'
aliases:
- /gallery/2015-costa-rica-trip/e7eb34b-don-juan-coffee-tour.html
---
The big roaster. It was still warm from them doing a batch right before our group arrived.
<file_sep>/content/photo/2014-london-iceland-trip/c8cca33-whale.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 11:54:12'
exif:
aperture: f/2.4
exposure: 1/20
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.495914
longitude: -0.176366
next: /gallery/2014-london-iceland-trip/43e714a-missouri-monster
ordering: 29
previous: /gallery/2014-london-iceland-trip/6132b85-giraffe
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Whale
aliases:
- /gallery/2014-london-iceland-trip/c8cca33-whale.html
---
And some of them were bigger than others
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/9691dba-img-1051.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 07:37:40'
exif:
aperture: f/2.4
exposure: 1/127
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19539167
longitude: -106.59832
next: /gallery/2014-albuquerque-balloon-fiesta/8230d10-img-1053
ordering: 5
previous: /gallery/2014-albuquerque-balloon-fiesta/1953f93-img-1049
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1051
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/9691dba-img-1051.html
---
<file_sep>/content/photo/2015-balloon-fiesta/4e5a28b-img-0355.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 06:29:37'
exif:
aperture: f/2.2
exposure: 1/120
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19336333
longitude: -106.597755
next: /gallery/2015-balloon-fiesta/39f7b01-img-0359
ordering: 4
previous: /gallery/2015-balloon-fiesta/4425ab5-img-0344
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0355
aliases:
- /gallery/2015-balloon-fiesta/4e5a28b-img-0355.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/5cd399d-img-1055.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 07:40:51'
exif:
aperture: f/2.4
exposure: 1/60
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19606667
longitude: -106.59796167
next: /gallery/2014-albuquerque-balloon-fiesta/73caf88-img-1058
ordering: 8
previous: /gallery/2014-albuquerque-balloon-fiesta/12895b3-img-1054
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1055
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/5cd399d-img-1055.html
---
<file_sep>/content/photo/2015-costa-rica-trip/b8030bb-hike-to-cerro-chato.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 12:51:06'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.44185
longitude: -84.687325
next: /gallery/2015-costa-rica-trip/c312ad5-cerro-chato
ordering: 17
previous: /gallery/2015-costa-rica-trip/3bf02da-hike-to-cerro-chato
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Hike to Cerro Chato'
aliases:
- /gallery/2015-costa-rica-trip/b8030bb-hike-to-cerro-chato.html
---
Once we reached the top, the final section down to the crater was essentially a steep mud slide with the occasional step which hasn't been washed out.
<file_sep>/content/photo/2014-london-iceland-trip/df5150c-a-classic-view.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-06 16:44:12'
exif:
aperture: f/2.4
exposure: 1/354
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.50038
longitude: -0.12786667
next: /gallery/2014-london-iceland-trip/7cf02b5-night
ordering: 0
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'A Classic View'
aliases:
- /gallery/2014-london-iceland-trip/df5150c-a-classic-view.html
---
QCon was held at The Queen Elizabeth II Conference Centre and this was the view out one of the common areas.
<file_sep>/content/photo/2014-london-iceland-trip/489fc1a-skolavor-ustigur.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 09:36:27'
exif:
aperture: f/2.4
exposure: 1/274
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.146447976825
longitude: -21.933189686142
next: /gallery/2014-london-iceland-trip/037fcaf-kaffibarinn
ordering: 69
previous: /gallery/2014-london-iceland-trip/69f14ff-hallgrimskirkja
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Skólavörðustígur
aliases:
- /gallery/2014-london-iceland-trip/489fc1a-skolavor-ustigur.html
---
A look back up the roadway to the church.
<file_sep>/content/photo/2015-costa-rica-trip/b442c36-hanging-bridges.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 09:01:35'
exif:
aperture: f/2.2
exposure: 1/359
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.34007
longitude: -84.79776667
next: /gallery/2015-costa-rica-trip/698af83-hanging-bridges
ordering: 62
previous: /gallery/2015-costa-rica-trip/52fbc4f-hanging-bridges
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Hanging Bridges'
aliases:
- /gallery/2015-costa-rica-trip/b442c36-hanging-bridges.html
---
Being high up on the bridges made it very easy to see the canopy. It's still green.
<file_sep>/content/photo/2015-england-trip/4d1765a-30c60656-21bb-4293-b77e-2ea9dcf2281e.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 06:27:17'
exif:
aperture: f/2.2
exposure: 1/879
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.17924167
longitude: -1.82635833
next: /gallery/2015-england-trip/a0b3f51-f4b4ccf6-6dfb-40cb-9550-307bec24ab15
ordering: 25
previous: /gallery/2015-england-trip/0b451bb-6e112ea8-32c7-434a-8b80-8458e5f034aa
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 30C60656-21BB-4293-B77E-2EA9DCF2281E
aliases:
- /gallery/2015-england-trip/4d1765a-30c60656-21bb-4293-b77e-2ea9dcf2281e.html
---
<file_sep>/content/photo/2014-london-iceland-trip/493e33e-gherkin.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-10 10:40:30'
exif:
aperture: f/2.4
exposure: 1/1153
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.514345
longitude: -0.08133617
next: /gallery/2014-london-iceland-trip/9b3e52f-st-pauls-cathedral
ordering: 17
previous: /gallery/2014-london-iceland-trip/aa978b7-platform-9-3-4
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Gherkin
aliases:
- /gallery/2014-london-iceland-trip/493e33e-gherkin.html
---
Hey, look, it’s the strange bullet I’ve seen in a lot of pictures.
<file_sep>/content/photo/2014-london-iceland-trip/1e88721-saga-museum.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 17:24:42'
exif:
aperture: f/2.4
exposure: 1/371
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.12920283
longitude: -21.91857
next: /gallery/2014-london-iceland-trip/524128b-panorama
ordering: 65
previous: /gallery/2014-london-iceland-trip/340d0ac-cured-shark
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Saga Museum'
aliases:
- /gallery/2014-london-iceland-trip/1e88721-saga-museum.html
---
There was a patio on top of these six large water tanks just outside downtown.
<file_sep>/content/galleries/2014-barcelona-trip/_index.md
---
slug: 2014-barcelona-trip
title: Barcelona Trip
date: '2014-11-16'
date_end: '2014-11-25'
highlight_photo: '106c907-museu-nacional-dart-de-catalunya'
aliases:
- /gallery/2014-barcelona-trip/
---
Some photos from my trip to Barcelona.
<file_sep>/content/photo/2015-costa-rica-trip/327d1bb-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 09:02:59'
exif:
aperture: f/2.2
exposure: 1/1883
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.38446167
longitude: -84.13861117
next: /gallery/2015-costa-rica-trip/f46cf80-manuel-antonio-national-park
ordering: 97
previous: /gallery/2015-costa-rica-trip/59c3d74-manuel-antonio-national-park
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Manuel Antonio National Park'
aliases:
- /gallery/2015-costa-rica-trip/327d1bb-manuel-antonio-national-park.html
---
A view from one of the viewpoints at the far end of the park.
<file_sep>/content/photo/2015-cambodia-thailand-trip/bf24d58-img-1125.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 23:18:53'
exif:
aperture: f/2.2
exposure: 1/608
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.57605333
longitude: 104.92295
next: /gallery/2015-cambodia-thailand-trip/7295d88-img-1130
ordering: 23
previous: /gallery/2015-cambodia-thailand-trip/ffde6e7-img-1117
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1125
aliases:
- /gallery/2015-cambodia-thailand-trip/bf24d58-img-1125.html
---
<file_sep>/content/photo/2014-barcelona-trip/55ba6a5-torre-de-comunicacions-de-montjuic.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 17:00:35'
exif:
aperture: f/2.2
exposure: 1/247
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.36425833
longitude: 2.1507945
next: /gallery/2014-barcelona-trip/31bbfef-olympic-park
ordering: 17
previous: /gallery/2014-barcelona-trip/71e7a4a-estadi-olimpic-lluis-companys
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Torre de Comunicacions de Montjuïc'
aliases:
- /gallery/2014-barcelona-trip/55ba6a5-torre-de-comunicacions-de-montjuic.html
---
<file_sep>/content/photo/2015-costa-rica-trip/d557dab-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 08:33:27'
exif:
aperture: f/2.2
exposure: 1/1980
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.38027167
longitude: -84.13666667
next: /gallery/2015-costa-rica-trip/adac11d-manuel-antonio-national-park
ordering: 94
previous: /gallery/2015-costa-rica-trip/8114c5b-manuel-antonio-national-park
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Manuel Antonio National Park'
aliases:
- /gallery/2015-costa-rica-trip/d557dab-manuel-antonio-national-park.html
---
The map the park provided was fairly useless... trails not matching up and even the physical land outlines not making sense. Somehow though, we ended up here at the bottom of many flights of stairs looking out over this lagoon.
<file_sep>/content/photo/2015-cambodia-thailand-trip/5c50d93-img-2380.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-21 20:10:38'
exif:
aperture: f/2.2
exposure: 1/33
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.69191167
longitude: 100.75005333
next: /gallery/2015-cambodia-thailand-trip/2927987-img-2383
ordering: 130
previous: /gallery/2015-cambodia-thailand-trip/a8f5fa5-img-2371
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2380
aliases:
- /gallery/2015-cambodia-thailand-trip/5c50d93-img-2380.html
---
<file_sep>/content/photo/2015-costa-rica-trip/5d967d2-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 11:22:32'
exif:
aperture: f/2.2
exposure: 1/2198
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.38514667
longitude: -84.14583617
next: /gallery/2015-costa-rica-trip/b9cdf82-manuel-antonio-national-park
ordering: 101
previous: /gallery/2015-costa-rica-trip/169e642-manuel-antonio-national-park
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Manuel Antonio National Park'
aliases:
- /gallery/2015-costa-rica-trip/5d967d2-manuel-antonio-national-park.html
---
Another view from the park's viewpoints.
<file_sep>/content/photo/2015-costa-rica-trip/95df46a-en-route-to-la-fortuna.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-11 14:01:24'
exif:
aperture: f/2.2
exposure: 1/2639
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.24826333
longitude: -84.42994667
next: /gallery/2015-costa-rica-trip/1f2b63b-ciudad-quesada
ordering: 6
previous: /gallery/2015-costa-rica-trip/ee30c9f-en-route-to-la-fortuna
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'En route to La Fortuna'
aliases:
- /gallery/2015-costa-rica-trip/95df46a-en-route-to-la-fortuna.html
---
Throughout the trip we saw quite a few cows appreciating the very green pastures everywhere.
<file_sep>/content/photo/2014-colorado-aspens/3c21081-tall-aspens.md
---
galleries:
- 2014-colorado-aspens
date: '2014-09-27 11:54:51'
exif:
aperture: f/2.4
exposure: 1/237
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 39.61163667
longitude: -105.95157
next: /gallery/2014-colorado-aspens/0b8c502-surrounded-by-aspens
ordering: 2
previous: /gallery/2014-colorado-aspens/6e859c1-aspens-are-turning
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Tall Aspens'
aliases:
- /gallery/2014-colorado-aspens/3c21081-tall-aspens.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/b53c895-img-1140.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 18:20:48'
exif:
aperture: f/2.2
exposure: 1/1464
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.42703667
longitude: 103.85952
next: /gallery/2015-cambodia-thailand-trip/baf06ff-img-1149
ordering: 28
previous: /gallery/2015-cambodia-thailand-trip/7156473-img-1132
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1140
aliases:
- /gallery/2015-cambodia-thailand-trip/b53c895-img-1140.html
---
<file_sep>/content/photo/2015-england-trip/c70b2ac-aa11611a-e379-4053-8457-88a2e4bc36b3.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 03:13:03'
exif:
aperture: f/2.2
exposure: 1/565
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.48373833
longitude: -0.60553
next: /gallery/2015-england-trip/73b85ca-1caa4214-8ca5-4168-90a8-b731645d1503
ordering: 19
previous: /gallery/2015-england-trip/e5ff6c8-7192f410-cbf0-40d6-8a83-0257b256dfdd
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: AA11611A-E379-4053-8457-88A2E4BC36B3
aliases:
- /gallery/2015-england-trip/c70b2ac-aa11611a-e379-4053-8457-88a2e4bc36b3.html
---
<file_sep>/content/photo/2014-barcelona-trip/a509b76-parc-guell-entry.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 15:23:37'
exif:
aperture: f/2.2
exposure: 1/628
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.413555
longitude: 2.15313333
next: /gallery/2014-barcelona-trip/43412b6-parc-guell-building
ordering: 7
previous: /gallery/2014-barcelona-trip/38b9ecd-parc-guell
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Parc Güell Entry'
aliases:
- /gallery/2014-barcelona-trip/a509b76-parc-guell-entry.html
---
<file_sep>/content/photo/2014-barcelona-trip/38b9ecd-parc-guell.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 15:20:54'
exif:
aperture: f/2.2
exposure: 1/136
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.41300833
longitude: 2.1523305
next: /gallery/2014-barcelona-trip/a509b76-parc-guell-entry
ordering: 6
previous: /gallery/2014-barcelona-trip/71bf8a4-parc-guell
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: '<NAME>'
aliases:
- /gallery/2014-barcelona-trip/38b9ecd-parc-guell.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/cbb80b5-img-1023.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 18:20:32'
exif:
aperture: f/2.2
exposure: 1/2475
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.56391167
longitude: 104.931175
next: /gallery/2015-cambodia-thailand-trip/a92f6a2-img-1029
ordering: 11
previous: /gallery/2015-cambodia-thailand-trip/22deb2a-img-1010
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1023
aliases:
- /gallery/2015-cambodia-thailand-trip/cbb80b5-img-1023.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/0e588f6-img-1110.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-11 07:59:15'
exif:
aperture: f/2.4
exposure: 1/553
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.195625
longitude: -106.596955
next: /gallery/2014-albuquerque-balloon-fiesta/82c066d-img-1121
ordering: 22
previous: /gallery/2014-albuquerque-balloon-fiesta/a42dbc3-img-1106
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1110
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/0e588f6-img-1110.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/9f0162c-img-1436.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 01:46:05'
exif:
aperture: f/2.2
exposure: 1/879
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.437745
longitude: 103.92146333
next: /gallery/2015-cambodia-thailand-trip/d43684e-img-1440
ordering: 53
previous: /gallery/2015-cambodia-thailand-trip/4d68b2e-img-1416
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1436
aliases:
- /gallery/2015-cambodia-thailand-trip/9f0162c-img-1436.html
---
<file_sep>/content/photo/2014-colorado-aspens/0b8c502-surrounded-by-aspens.md
---
galleries:
- 2014-colorado-aspens
date: '2014-09-27 12:15:17'
exif:
aperture: f/2.4
exposure: 1/1106
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 39.608875
longitude: -105.94609667
next: /gallery/2014-colorado-aspens/9e9e818-valley-of-aspens
ordering: 3
previous: /gallery/2014-colorado-aspens/3c21081-tall-aspens
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Surrounded by Aspens'
aliases:
- /gallery/2014-colorado-aspens/0b8c502-surrounded-by-aspens.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/9b2edec-img-1877.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 22:14:29'
exif:
aperture: f/2.2
exposure: 1/920
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.43002833
longitude: 103.89913
next: /gallery/2015-cambodia-thailand-trip/404cac7-img-1900
ordering: 77
previous: /gallery/2015-cambodia-thailand-trip/3876052-img-1852
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1877
aliases:
- /gallery/2015-cambodia-thailand-trip/9b2edec-img-1877.html
---
<file_sep>/content/photo/2015-balloon-fiesta/fa4c901-img-0549.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-09 13:06:02'
exif:
aperture: f/2.2
exposure: 1/7937
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19175833
longitude: -106.47875333
next: /gallery/2015-balloon-fiesta/ae76c84-img-0598
ordering: 26
previous: /gallery/2015-balloon-fiesta/d77389a-img-0534
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0549
aliases:
- /gallery/2015-balloon-fiesta/fa4c901-img-0549.html
---
<file_sep>/content/photo/2014-barcelona-trip/6dffda5-estadi-olimpic-lluis-companys.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 17:15:04'
exif:
aperture: f/2.2
exposure: 1/120
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.36559667
longitude: 2.15476117
next: /gallery/2014-barcelona-trip/26a5044-estadi-olimpic-lluis-companys
ordering: 19
previous: /gallery/2014-barcelona-trip/31bbfef-olympic-park
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: '<NAME> Lluís Companys'
aliases:
- /gallery/2014-barcelona-trip/6dffda5-estadi-olimpic-lluis-companys.html
---
<file_sep>/content/photo/2014-barcelona-trip/4af8a11-font-magica-de-montjuic.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 19:45:04'
exif:
aperture: f/2.2
exposure: 1/24
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.37133333
longitude: 2.15130283
next: /gallery/2014-barcelona-trip/606fd97-christmas-lights
ordering: 31
previous: /gallery/2014-barcelona-trip/a061586-font-magica-de-montjuic
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Font màgica de Montjuïc'
aliases:
- /gallery/2014-barcelona-trip/4af8a11-font-magica-de-montjuic.html
---
<file_sep>/content/photo/2015-balloon-fiesta/b115008-img-0707.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-10 16:29:08'
exif:
aperture: f/2.2
exposure: 1/1799
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.1655195
longitude: -106.60548333
next: /gallery/2015-balloon-fiesta/e94146c-img-0741
ordering: 32
previous: /gallery/2015-balloon-fiesta/8326351-img-0697
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0707
aliases:
- /gallery/2015-balloon-fiesta/b115008-img-0707.html
---
<file_sep>/content/photo/2014-london-iceland-trip/f9b153c-artifacts.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 15:52:19'
exif:
aperture: f/2.4
exposure: 1/20
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.519401550293
longitude: -0.12690000236
next: /gallery/2014-london-iceland-trip/56d4241-the-nereid-monument
ordering: 37
previous: /gallery/2014-london-iceland-trip/632b686-rosetta-stone
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Artifacts
aliases:
- /gallery/2014-london-iceland-trip/f9b153c-artifacts.html
---
Old vases which looked exactly like a photo from a sixth grade textbook. Pretty sure they’re fairly common though.
<file_sep>/content/photo/2015-costa-rica-trip/15acca5-canopy-zip-line.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 16:10:55'
exif:
aperture: f/2.2
exposure: 1/218
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.3453
longitude: -84.84487167
next: /gallery/2015-costa-rica-trip/7bff94b-canopy-zip-line
ordering: 82
previous: /gallery/2015-costa-rica-trip/df11754-canopy-zip-line
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Canopy Zip Line'
aliases:
- /gallery/2015-costa-rica-trip/15acca5-canopy-zip-line.html
---
In addition to zip lines, they also had bungee jumping which they ran off these cables and down towards the valley. Unfortunately nobody was doing it while we were there to see.
<file_sep>/content/photo/2015-cambodia-thailand-trip/7295d88-img-1130.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 23:36:15'
exif:
aperture: f/2.2
exposure: 1/430
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.57545
longitude: 104.92311167
next: /gallery/2015-cambodia-thailand-trip/2423cce-img-1107
ordering: 24
previous: /gallery/2015-cambodia-thailand-trip/bf24d58-img-1125
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1130
aliases:
- /gallery/2015-cambodia-thailand-trip/7295d88-img-1130.html
---
<file_sep>/content/photo/2015-balloon-fiesta/731c67c-img-0378.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 06:35:40'
exif:
aperture: f/2.2
exposure: 1/824
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.194305
longitude: -106.59848
next: /gallery/2015-balloon-fiesta/41183bb-img-0389
ordering: 6
previous: /gallery/2015-balloon-fiesta/39f7b01-img-0359
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0378
aliases:
- /gallery/2015-balloon-fiesta/731c67c-img-0378.html
---
<file_sep>/content/photo/2015-costa-rica-trip/e64375f-el-avion.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-18 17:43:21'
exif:
aperture: f/2.2
exposure: 1/60
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.40215833
longitude: -84.1534805
next: /gallery/2015-costa-rica-trip/ae8494f-el-avion
ordering: 119
previous: /gallery/2015-costa-rica-trip/5018806-el-avion
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'El Avión'
aliases:
- /gallery/2015-costa-rica-trip/e64375f-el-avion.html
---
Thankfully the great weather that evening made for some very pretty pictures and a very enjoyable dinner.
<file_sep>/content/photo/2015-cambodia-thailand-trip/37977f2-img-1943.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 23:25:57'
exif:
aperture: f/2.2
exposure: 1/1647
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.41985333
longitude: 103.89958
next: /gallery/2015-cambodia-thailand-trip/7fa2005-img-1948
ordering: 83
previous: /gallery/2015-cambodia-thailand-trip/88f556a-img-1930
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1943
aliases:
- /gallery/2015-cambodia-thailand-trip/37977f2-img-1943.html
---
<file_sep>/content/photo/2015-costa-rica-trip/d7c274a-canopy-zip-line.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 14:03:46'
exif:
aperture: f/2.2
exposure: 1/2198
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.34482833
longitude: -84.84491667
next: /gallery/2015-costa-rica-trip/0817658-canopy-zip-line
ordering: 74
previous: /gallery/2015-costa-rica-trip/88d21c0-hanging-bridges
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Canopy Zip Line'
aliases:
- /gallery/2015-costa-rica-trip/d7c274a-canopy-zip-line.html
---
While waiting to get started on a zip lining adventure, a large parrot flew by to wish us a good time.
<file_sep>/content/photo/2015-balloon-fiesta/4419092-img-0619.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-10 06:41:27'
exif:
aperture: f/2.2
exposure: 1/760
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.196245
longitude: -106.59739667
next: /gallery/2015-balloon-fiesta/9cd0322-img-0631
ordering: 28
previous: /gallery/2015-balloon-fiesta/ae76c84-img-0598
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0619
aliases:
- /gallery/2015-balloon-fiesta/4419092-img-0619.html
---
<file_sep>/content/photo/2015-costa-rica-trip/288f548-giovannis-night-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 19:46:51'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.47199167
longitude: -84.65156667
next: /gallery/2015-costa-rica-trip/e38b136-giovannis-night-tour
ordering: 25
previous: /gallery/2015-costa-rica-trip/745372b-giovannis-night-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Giovanni''s Night Tour'
aliases:
- /gallery/2015-costa-rica-trip/288f548-giovannis-night-tour.html
---
Saw several different kinds of frogs on the tour, although I quickly forgot their official names.
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/3c75e84-img-1059.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 07:42:38'
exif:
aperture: f/2.4
exposure: 1/141
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19605
longitude: -106.597655
next: /gallery/2014-albuquerque-balloon-fiesta/700b097-img-1071
ordering: 10
previous: /gallery/2014-albuquerque-balloon-fiesta/73caf88-img-1058
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1059
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/3c75e84-img-1059.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/a408209-img-1209.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 19:51:26'
exif:
aperture: f/2.2
exposure: 1/1464
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44342833
longitude: 103.85881167
next: /gallery/2015-cambodia-thailand-trip/f964113-img-1220
ordering: 40
previous: /gallery/2015-cambodia-thailand-trip/4ad3c57-img-1204
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1209
aliases:
- /gallery/2015-cambodia-thailand-trip/a408209-img-1209.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/84c4728-img-1820.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 20:12:03'
exif:
aperture: f/2.2
exposure: 1/1014
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.43491167
longitude: 103.8899
next: /gallery/2015-cambodia-thailand-trip/3876052-img-1852
ordering: 75
previous: /gallery/2015-cambodia-thailand-trip/52209eb-img-1815
sizes:
1280:
height: 1280
width: 677
640w:
height: 1210
width: 640
200x200:
height: 200
width: 200
title: IMG_1820
aliases:
- /gallery/2015-cambodia-thailand-trip/84c4728-img-1820.html
---
<file_sep>/content/photo/2015-balloon-fiesta/254747e-imag2195.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 06:25:08'
exif:
aperture: f/2.0
exposure: 1770/1000000
make: HTC
model: HTC6500LVW
layout: gallery-photo
location:
latitude: 35.19360667
longitude: -106.59726
next: /gallery/2015-balloon-fiesta/4425ab5-img-0344
ordering: 2
previous: /gallery/2015-balloon-fiesta/a320270-imag2180
sizes:
1280:
height: 724
width: 1280
640w:
height: 362
width: 640
200x200:
height: 200
width: 200
title: IMAG2195
aliases:
- /gallery/2015-balloon-fiesta/254747e-imag2195.html
---
<file_sep>/content/photo/2014-london-iceland-trip/34da741-cityscape.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 13:48:25'
exif:
aperture: f/2.4
exposure: 1/1232
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.141899108887
longitude: -21.92679977417
next: /gallery/2014-london-iceland-trip/761d483-cityscape
ordering: 55
previous: /gallery/2014-london-iceland-trip/a6011b3-organist
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Cityscape
aliases:
- /gallery/2014-london-iceland-trip/34da741-cityscape.html
---
They had a small elevator to get to the top of the church where you could look out over the whole city.
<file_sep>/content/photo/2015-cambodia-thailand-trip/d6a4414-img-1980.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-18 22:23:48'
exif:
aperture: f/2.2
exposure: 1/1721
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.36013667
longitude: 103.87645833
next: /gallery/2015-cambodia-thailand-trip/9ebc24f-img-1981
ordering: 91
previous: /gallery/2015-cambodia-thailand-trip/67a9685-img-1969
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1980
aliases:
- /gallery/2015-cambodia-thailand-trip/d6a4414-img-1980.html
---
<file_sep>/content/photo/2015-costa-rica-trip/1654b98-hanging-bridges.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 09:42:09'
exif:
aperture: f/2.2
exposure: 1/120
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.3368
longitude: -84.80032167
next: /gallery/2015-costa-rica-trip/5e1987f-hanging-bridges
ordering: 70
previous: /gallery/2015-costa-rica-trip/efa7952-hanging-bridges
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Hanging Bridges'
aliases:
- /gallery/2015-costa-rica-trip/1654b98-hanging-bridges.html
---
Looking down from the bridges could be a bit daunting. Their heights ranged from 36ft to 180ft.
<file_sep>/content/photo/2015-costa-rica-trip/a7a2bac-don-juan-coffee-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 15:47:48'
exif:
aperture: f/2.2
exposure: 1/60
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.32235333
longitude: -84.83503
next: /gallery/2015-costa-rica-trip/507297f-don-juan-coffee-tour
ordering: 51
previous: /gallery/2015-costa-rica-trip/5cdf335-don-juan-coffee-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Don Juan Coffee Tour'
aliases:
- /gallery/2015-costa-rica-trip/a7a2bac-don-juan-coffee-tour.html
---
This machine would help sort the beans by their weights. Since smaller sizes will roast more quickly, they should be roasted separately to avoid batches tasting burnt.
<file_sep>/content/photo/2015-england-trip/9705f6a-61aa0911-1a3e-4beb-9fdc-6a280ad49ced.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 03:56:51'
exif:
aperture: f/2.2
exposure: 1/233
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.48346333
longitude: -0.60686333
next: /gallery/2015-england-trip/0b451bb-6e112ea8-32c7-434a-8b80-8458e5f034aa
ordering: 23
previous: /gallery/2015-england-trip/c562b5a-55767f0e-9154-4e92-99d3-4db88d659d0e
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 61AA0911-1A3E-4BEB-9FDC-6A280AD49CED
aliases:
- /gallery/2015-england-trip/9705f6a-61aa0911-1a3e-4beb-9fdc-6a280ad49ced.html
---
<file_sep>/content/photo/2014-barcelona-trip/9a59ac6-port-de-barcelona.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-22 21:53:24'
exif:
aperture: f/2.2
exposure: 1/17
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.37564667
longitude: 2.17856667
next: /gallery/2014-barcelona-trip/07ed14a-casa-batllo
ordering: 40
previous: /gallery/2014-barcelona-trip/baf4bfd-mirador-de-colom
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Port de Barcelona'
aliases:
- /gallery/2014-barcelona-trip/9a59ac6-port-de-barcelona.html
---
<file_sep>/content/photo/2014-london-iceland-trip/d6254b6-hallgrimskirkja.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 12:55:55'
exif:
aperture: f/2.4
exposure: 1/1178
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.1423195
longitude: -21.92818667
next: /gallery/2014-london-iceland-trip/b88e820-hallgrimskirkja
ordering: 51
previous: /gallery/2014-london-iceland-trip/b8bd46c-feed-the-ducks
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Hallgrímskirkja
aliases:
- /gallery/2014-london-iceland-trip/d6254b6-hallgrimskirkja.html
---
A massive building at the top of a hill which overlooks the city.
<file_sep>/content/photo/2015-costa-rica-trip/23e51bc-jeep-boat-jeep.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 09:29:51'
exif:
aperture: f/2.2
exposure: 1/3300
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.46492167
longitude: -84.772255
next: /gallery/2015-costa-rica-trip/932f008-jeep-boat-jeep
ordering: 41
previous: /gallery/2015-costa-rica-trip/6a78f2e-jeep-boat-jeep
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: Jeep-Boat-Jeep
aliases:
- /gallery/2015-costa-rica-trip/23e51bc-jeep-boat-jeep.html
---
But eventually it cleared up and were able to see the pretty colors around.
<file_sep>/content/photo/2015-costa-rica-trip/785fc88-don-juan-coffee-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 15:16:40'
exif:
aperture: f/2.2
exposure: 1/1647
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.3228
longitude: -84.83473333
next: /gallery/2015-costa-rica-trip/be359cf-don-juan-coffee-tour
ordering: 44
previous: /gallery/2015-costa-rica-trip/4e5af81-jeep-boat-jeep
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Don Juan Coffee Tour'
aliases:
- /gallery/2015-costa-rica-trip/785fc88-don-juan-coffee-tour.html
---
On Wednesday we took a tour of a coffee plantation. We were able to see some of the young beans on the trees.
<file_sep>/run
#!/bin/bash
exec hugo serve \
--baseURL=http://penguin.termina.linux.test:1313 \
--buildFuture \
--disableFastRender
<file_sep>/content/photo/2014-barcelona-trip/d54aeba-museu-nacional-dart-de-catalunya.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-22 20:20:10'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.36887167
longitude: 2.153175
next: /gallery/2014-barcelona-trip/9d3b72c-casa-de-la-ciutat
ordering: 35
previous: /gallery/2014-barcelona-trip/9563242-museu-nacional-dart-de-catalunya
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Museu Nacional d''Art de Catalunya'
aliases:
- /gallery/2014-barcelona-trip/d54aeba-museu-nacional-dart-de-catalunya.html
---
<file_sep>/content/photo/2015-costa-rica-trip/59c3d74-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 09:01:46'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.38444667
longitude: -84.13856383
next: /gallery/2015-costa-rica-trip/327d1bb-manuel-antonio-national-park
ordering: 96
previous: /gallery/2015-costa-rica-trip/adac11d-manuel-antonio-national-park
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: '<NAME>onio National Park'
aliases:
- /gallery/2015-costa-rica-trip/59c3d74-manuel-antonio-national-park.html
---
He walked along the railings for a while, hopping back and forth trying to figure out if I was good or bad.
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/a42dbc3-img-1106.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-11 07:49:26'
exif:
aperture: f/2.4
exposure: 1/471
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19496667
longitude: -106.59674667
next: /gallery/2014-albuquerque-balloon-fiesta/0e588f6-img-1110
ordering: 21
previous: /gallery/2014-albuquerque-balloon-fiesta/924c0ae-img-1103
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1106
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/a42dbc3-img-1106.html
---
<file_sep>/content/photo/2014-london-iceland-trip/033bb54-royal-observatory.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-08 15:38:50'
exif:
aperture: f/2.4
exposure: 1/3195
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.478298187256
longitude: -0.001099999994
next: /gallery/2014-london-iceland-trip/c217f20-greenwich-park
ordering: 4
previous: /gallery/2014-london-iceland-trip/fbe9b12-hyde-park
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Royal Observatory'
aliases:
- /gallery/2014-london-iceland-trip/033bb54-royal-observatory.html
---
Another stop on the transportation tour was the Royal Observatory with the line separating East from West.
<file_sep>/content/photo/2014-london-iceland-trip/1c7cea9-st-pauls-cathedral.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-10 12:38:10'
exif:
aperture: f/2.4
exposure: 1/1323
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.513973
longitude: -0.098416
next: /gallery/2014-london-iceland-trip/3bb5ad8-trafalgar-square
ordering: 22
previous: /gallery/2014-london-iceland-trip/d6abeff-st-pauls-cathedral
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'St. Paul''s Cathedral'
aliases:
- /gallery/2014-london-iceland-trip/1c7cea9-st-pauls-cathedral.html
---
Yet another view, but this time looking back towards the London Eye.
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/1b9b6f2-img-1127.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-11 08:35:22'
exif:
aperture: f/2.4
exposure: 1/1130
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19814667
longitude: -106.59590333
next: /gallery/2014-albuquerque-balloon-fiesta/c60d938-img-1145
ordering: 25
previous: /gallery/2014-albuquerque-balloon-fiesta/2681241-img-1122
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1127
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/1b9b6f2-img-1127.html
---
<file_sep>/content/photo/2014-barcelona-trip/231151b-casa-batllo.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-23 12:48:50'
exif:
aperture: f/2.2
exposure: 1/380
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.391175
longitude: 2.16322783
next: /gallery/2014-barcelona-trip/50acdde-casa-batllo
ordering: 46
previous: /gallery/2014-barcelona-trip/dcea5d9-casa-batllo
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Casa Batlló'
aliases:
- /gallery/2014-barcelona-trip/231151b-casa-batllo.html
---
<file_sep>/content/photo/2015-costa-rica-trip/bc39503-el-avion.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-18 17:15:08'
exif:
aperture: f/2.2
exposure: 1/1412
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.40217833
longitude: -84.1534195
next: /gallery/2015-costa-rica-trip/5ea206c-el-avion
ordering: 113
previous: /gallery/2015-costa-rica-trip/19fb74d-boat-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'El Avión'
aliases:
- /gallery/2015-costa-rica-trip/bc39503-el-avion.html
---
Sunday night after spending a relaxing day with the beach we went to a restaurant themed around an old airplane. We went a bit early to catch the sunset. This was the view from our table.
<file_sep>/content/photo/2015-costa-rica-trip/020bc58-giovannis-night-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 20:49:19'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.4711
longitude: -84.65058
next: /gallery/2015-costa-rica-trip/fcef47e-giovannis-night-tour
ordering: 29
previous: /gallery/2015-costa-rica-trip/52e4f19-giovannis-night-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Giovanni''s Night Tour'
aliases:
- /gallery/2015-costa-rica-trip/020bc58-giovannis-night-tour.html
---
There was a large termites nest here. Giovanni demonstrated how to set your finger on the nest and attract some of them to it... and then snack on them. I passed on that opportunity though.
<file_sep>/content/photo/2014-colorado-aspens/79c5a71-through-the-aspens.md
---
galleries:
- 2014-colorado-aspens
date: '2014-09-27 12:21:05'
exif:
aperture: f/2.4
exposure: 1/2584
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 39.610845
longitude: -105.95208667
next: /gallery/2014-colorado-aspens/2dbeedb-aspens-invading
ordering: 5
previous: /gallery/2014-colorado-aspens/9e9e818-valley-of-aspens
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Through the Aspens'
aliases:
- /gallery/2014-colorado-aspens/79c5a71-through-the-aspens.html
---
<file_sep>/content/photo/2015-balloon-fiesta/89dbad4-img-0392.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 06:39:47'
exif:
aperture: f/2.2
exposure: 1/3968
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19433333
longitude: -106.59866333
next: /gallery/2015-balloon-fiesta/c7a6b71-imag2233
ordering: 8
previous: /gallery/2015-balloon-fiesta/41183bb-img-0389
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0392
aliases:
- /gallery/2015-balloon-fiesta/89dbad4-img-0392.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/cb35b0a-img-1056.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 18:50:01'
exif:
aperture: f/2.2
exposure: 1/1721
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.56295
longitude: 104.932145
next: /gallery/2015-cambodia-thailand-trip/999bece-img-1057
ordering: 15
previous: /gallery/2015-cambodia-thailand-trip/2148845-img-1046
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1056
aliases:
- /gallery/2015-cambodia-thailand-trip/cb35b0a-img-1056.html
---
<file_sep>/content/photo/2015-costa-rica-trip/745372b-giovannis-night-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 19:40:22'
exif:
aperture: f/2.2
exposure: 1/20
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.47218
longitude: -84.65117
next: /gallery/2015-costa-rica-trip/288f548-giovannis-night-tour
ordering: 24
previous: /gallery/2015-costa-rica-trip/6b45122-giovannis-night-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Giovanni''s Night Tour'
aliases:
- /gallery/2015-costa-rica-trip/745372b-giovannis-night-tour.html
---
This flower looks like fireworks.
<file_sep>/content/photo/2014-london-iceland-trip/a7208f4-cityscape.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 13:49:23'
exif:
aperture: f/2.4
exposure: 1/2463
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.141899108887
longitude: -21.92679977417
next: /gallery/2014-london-iceland-trip/90e6908-colorful
ordering: 59
previous: /gallery/2014-london-iceland-trip/f5a8d81-cityscape
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Cityscape
aliases:
- /gallery/2014-london-iceland-trip/a7208f4-cityscape.html
---
While at the top, there was a nice break in the clouds, but more weather was definitely coming.
<file_sep>/content/photo/2015-costa-rica-trip/e3b74ac-hike-to-cerro-chato.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 10:15:47'
exif:
aperture: f/2.2
exposure: 1/2198
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.4465
longitude: -84.66960833
next: /gallery/2015-costa-rica-trip/a3b1d00-hike-to-cerro-chato
ordering: 10
previous: /gallery/2015-costa-rica-trip/9606542-horse-parade
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Hike to Cerro Chato'
aliases:
- /gallery/2015-costa-rica-trip/e3b74ac-hike-to-cerro-chato.html
---
Monday we planned a hike up to Cerro Chato. A small crater lake next to the Arenal Volcano.
<file_sep>/content/photo/2015-cambodia-thailand-trip/4050aa0-img-1408.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 01:31:02'
exif:
aperture: f/2.2
exposure: 1/1199
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44618
longitude: 103.9197
next: /gallery/2015-cambodia-thailand-trip/4d68b2e-img-1416
ordering: 51
previous: /gallery/2015-cambodia-thailand-trip/d9133cb-img-1362
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1408
aliases:
- /gallery/2015-cambodia-thailand-trip/4050aa0-img-1408.html
---
<file_sep>/content/photo/2015-england-trip/642bebc-52866970-d255-4df1-a459-c1232d53d51b.md
---
galleries:
- 2015-england-trip
date: '2015-03-07 04:32:24'
exif:
aperture: f/2.2
exposure: 1/2475
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.50587
longitude: -0.0748805
next: /gallery/2015-england-trip/11fb097-f8f4710d-55b5-4d31-8e03-82d52b70c0d8
ordering: 1
previous: /gallery/2015-england-trip/7b5c044-6d174d24-b03f-4d4d-8e70-019ab0b1cb16
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 52866970-D255-4DF1-A459-C1232D53D51B
aliases:
- /gallery/2015-england-trip/642bebc-52866970-d255-4df1-a459-c1232d53d51b.html
---
<file_sep>/content/photo/2015-costa-rica-trip/4a08af3-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 08:05:33'
exif:
aperture: f/2.2
exposure: 1/124
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.37966167
longitude: -84.1396945
next: /gallery/2015-costa-rica-trip/6a344be-manuel-antonio-national-park
ordering: 91
previous: /gallery/2015-costa-rica-trip/04b40de-manuel-antonio-national-park
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Manuel Antonio National Park'
aliases:
- /gallery/2015-costa-rica-trip/4a08af3-manuel-antonio-national-park.html
---
Another crab trying to be king of the rock.
<file_sep>/content/photo/2015-cambodia-thailand-trip/ff63707-img-2314.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-20 21:04:55'
exif:
aperture: f/2.2
exposure: 1/100
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.79940333
longitude: 100.54976667
next: /gallery/2015-cambodia-thailand-trip/2d2f5d5-img-2316
ordering: 121
previous: /gallery/2015-cambodia-thailand-trip/1c60947-img-2306
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2314
aliases:
- /gallery/2015-cambodia-thailand-trip/ff63707-img-2314.html
---
<file_sep>/content/photo/2014-london-iceland-trip/570329a-loft-hostel.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-12 18:03:54'
exif:
aperture: f/2.4
exposure: 1/40
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.146797936501
longitude: -21.93404783668
next: /gallery/2014-london-iceland-trip/238d28c-reyjkavik-docks
ordering: 44
previous: /gallery/2014-london-iceland-trip/2f35742-loop
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Loft Hostel'
aliases:
- /gallery/2014-london-iceland-trip/570329a-loft-hostel.html
---
A view of Reyjkavik from the patio of where I stayed.
<file_sep>/content/photo/2015-cambodia-thailand-trip/267b4bf-img-1243.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 20:31:55'
exif:
aperture: f/2.2
exposure: 1/50
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44445833
longitude: 103.85518667
next: /gallery/2015-cambodia-thailand-trip/f235b51-img-1252
ordering: 43
previous: /gallery/2015-cambodia-thailand-trip/4683f98-img-1234
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_1243
aliases:
- /gallery/2015-cambodia-thailand-trip/267b4bf-img-1243.html
---
<file_sep>/content/galleries/2015-england-trip/_index.md
---
slug: 2015-england-trip
title: England Trip
date: '2015-03-01'
date_end: '2015-03-09'
highlight_photo: '7b5c044-6d174d24-b03f-4d4d-8e70-019ab0b1cb16'
aliases:
- /gallery/2015-england-trip/
---
Exploring London, Windsor Castle, Stonehenge, and Bath.
<file_sep>/content/photo/2015-balloon-fiesta/a320270-imag2180.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 06:13:01'
exif:
aperture: f/2.0
exposure: 2552/1000000
make: HTC
model: HTC6500LVW
layout: gallery-photo
location:
latitude: 35.19445333
longitude: -106.59636
next: /gallery/2015-balloon-fiesta/254747e-imag2195
ordering: 1
previous: /gallery/2015-balloon-fiesta/958ec45-img-0336
sizes:
1280:
height: 724
width: 1280
640w:
height: 362
width: 640
200x200:
height: 200
width: 200
title: IMAG2180
aliases:
- /gallery/2015-balloon-fiesta/a320270-imag2180.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/a0e0593-img-1924.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 22:50:58'
exif:
aperture: f/2.2
exposure: 1/1980
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.42921667
longitude: 103.90346333
next: /gallery/2015-cambodia-thailand-trip/5f1972f-img-1927
ordering: 80
previous: /gallery/2015-cambodia-thailand-trip/675e7f0-img-1918
sizes:
1280:
height: 396
width: 1280
640w:
height: 198
width: 640
200x200:
height: 200
width: 200
title: IMG_1924
aliases:
- /gallery/2015-cambodia-thailand-trip/a0e0593-img-1924.html
---
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/73caf88-img-1058.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 07:42:33'
exif:
aperture: f/2.4
exposure: 1/152
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19605
longitude: -106.597655
next: /gallery/2014-albuquerque-balloon-fiesta/3c75e84-img-1059
ordering: 9
previous: /gallery/2014-albuquerque-balloon-fiesta/5cd399d-img-1055
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1058
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/73caf88-img-1058.html
---
<file_sep>/content/photo/2015-costa-rica-trip/efa7952-hanging-bridges.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 09:38:04'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.336505
longitude: -84.8004
next: /gallery/2015-costa-rica-trip/1654b98-hanging-bridges
ordering: 69
previous: /gallery/2015-costa-rica-trip/128cc05-hanging-bridges
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Hanging Bridges'
aliases:
- /gallery/2015-costa-rica-trip/efa7952-hanging-bridges.html
---
We went fairly early in the morning hoping to see some wildlife, but aside from the hummingbirds and this crossing the path, we didn't see much activity.
<file_sep>/content/photo/2015-cambodia-thailand-trip/a8f5fa5-img-2371.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-21 19:16:24'
exif:
aperture: f/2.2
exposure: 1/17
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.70845
longitude: 100.75435
next: /gallery/2015-cambodia-thailand-trip/5c50d93-img-2380
ordering: 129
previous: /gallery/2015-cambodia-thailand-trip/6970dd9-img-2361
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2371
aliases:
- /gallery/2015-cambodia-thailand-trip/a8f5fa5-img-2371.html
---
<file_sep>/content/photo/2015-costa-rica-trip/4e5af81-jeep-boat-jeep.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 11:09:38'
exif:
aperture: f/2.2
exposure: 1/1068
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.381675
longitude: -84.90256333
next: /gallery/2015-costa-rica-trip/785fc88-don-juan-coffee-tour
ordering: 43
previous: /gallery/2015-costa-rica-trip/932f008-jeep-boat-jeep
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: Jeep-Boat-Jeep
aliases:
- /gallery/2015-costa-rica-trip/4e5af81-jeep-boat-jeep.html
---
The vans made a brief stop at a shop for snacks and to break up the bumpy, hour long ride.
<file_sep>/content/photo/2014-london-iceland-trip/0c6bcfa-its-a-peacock.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-09 17:47:05'
exif:
aperture: f/2.4
exposure: 1/20
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.796502764532
longitude: -0.634219271083
next: /gallery/2014-london-iceland-trip/293e193-its-an-albino-peacock
ordering: 14
previous: /gallery/2014-london-iceland-trip/49522b3-bletchley-codebreaking
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'It''s a Peacock'
aliases:
- /gallery/2014-london-iceland-trip/0c6bcfa-its-a-peacock.html
---
Stopped by <NAME> for drinks, and they had peacocks on the property.
<file_sep>/content/photo/2015-costa-rica-trip/2cb76f3-hike-from-cerro-chato.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 14:18:05'
exif:
aperture: f/2.2
exposure: 1/682
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.44338833
longitude: -84.67671167
next: /gallery/2015-costa-rica-trip/fb10d9a-thirsty-cow
ordering: 20
previous: /gallery/2015-costa-rica-trip/bccbec3-hike-from-cerro-chato
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Hike from Cerro Chato'
aliases:
- /gallery/2015-costa-rica-trip/2cb76f3-hike-from-cerro-chato.html
---
There were cow pastures along this hike, too.
<file_sep>/content/photo/2015-costa-rica-trip/6b45122-giovannis-night-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 19:28:39'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.47176667
longitude: -84.64981167
next: /gallery/2015-costa-rica-trip/745372b-giovannis-night-tour
ordering: 23
previous: /gallery/2015-costa-rica-trip/30d9cb8-giovannis-night-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Giovanni''s Night Tour'
aliases:
- /gallery/2015-costa-rica-trip/6b45122-giovannis-night-tour.html
---
Add a description…Some sleeping birds in the trees who apparently didn't mind bright lights waking them up from their sleep.
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/924c0ae-img-1103.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-11 07:44:31'
exif:
aperture: f/2.4
exposure: 1/341
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.195255
longitude: -106.59671667
next: /gallery/2014-albuquerque-balloon-fiesta/a42dbc3-img-1106
ordering: 20
previous: /gallery/2014-albuquerque-balloon-fiesta/12014b2-img-1102
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1103
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/924c0ae-img-1103.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/7954a7d-img-1647.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-17 16:50:49'
exif:
aperture: f/2.2
exposure: 1/1364
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.41127167
longitude: 103.868155
next: /gallery/2015-cambodia-thailand-trip/7d5c98a-img-1674
ordering: 69
previous: /gallery/2015-cambodia-thailand-trip/347d0f9-img-1646
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1647
aliases:
- /gallery/2015-cambodia-thailand-trip/7954a7d-img-1647.html
---
<file_sep>/content/photo/2014-london-iceland-trip/82328eb-bletchley-codebreaking.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-09 14:57:29'
exif:
aperture: f/2.4
exposure: 1/20
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.998249098373
longitude: -0.744062420344
next: /gallery/2014-london-iceland-trip/49522b3-bletchley-codebreaking
ordering: 12
previous: /gallery/2014-london-iceland-trip/120fd55-countryside
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Bletchley Codebreaking'
aliases:
- /gallery/2014-london-iceland-trip/82328eb-bletchley-codebreaking.html
---
Took a tour of the museum - this was responsible for much of the codebreaking during World War II.
<file_sep>/content/photo/2014-london-iceland-trip/385ec5f-british-museum.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 16:55:06'
exif:
aperture: f/2.4
exposure: 1/298
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.519401550293
longitude: -0.12690000236
next: /gallery/2014-london-iceland-trip/2f35742-loop
ordering: 42
previous: /gallery/2014-london-iceland-trip/37da195-african-carvings
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'British Museum'
aliases:
- /gallery/2014-london-iceland-trip/385ec5f-british-museum.html
---
A look back on my way out…
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/f114579-img-1074.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 07:50:17'
exif:
aperture: f/2.4
exposure: 1/420
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19653
longitude: -106.59666333
next: /gallery/2014-albuquerque-balloon-fiesta/cf568c1-img-1084
ordering: 12
previous: /gallery/2014-albuquerque-balloon-fiesta/700b097-img-1071
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1074
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/f114579-img-1074.html
---
<file_sep>/content/photo/2014-london-iceland-trip/49594d4-across-the-bay.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 11:41:34'
exif:
aperture: f/2.4
exposure: 1/1595
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.14911667
longitude: -21.92892
next: /gallery/2014-london-iceland-trip/24b9354-church
ordering: 47
previous: /gallery/2014-london-iceland-trip/70668ad-panorama
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Across the Bay'
aliases:
- /gallery/2014-london-iceland-trip/49594d4-across-the-bay.html
---
Snowy weather came through several times, very quickly.
<file_sep>/content/photo/2015-balloon-fiesta/fc46ce5-img-0527.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-09 06:50:19'
exif:
aperture: f/2.2
exposure: 1/581
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19389667
longitude: -106.59716167
next: /gallery/2015-balloon-fiesta/d77389a-img-0534
ordering: 24
previous: /gallery/2015-balloon-fiesta/0a0247c-img-0522
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0527
aliases:
- /gallery/2015-balloon-fiesta/fc46ce5-img-0527.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/4683f98-img-1234.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-16 20:21:17'
exif:
aperture: f/2.2
exposure: 1/573
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.44407
longitude: 103.85608667
next: /gallery/2015-cambodia-thailand-trip/267b4bf-img-1243
ordering: 42
previous: /gallery/2015-cambodia-thailand-trip/f964113-img-1220
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1234
aliases:
- /gallery/2015-cambodia-thailand-trip/4683f98-img-1234.html
---
<file_sep>/content/photo/2015-costa-rica-trip/ee30c9f-en-route-to-la-fortuna.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-11 13:58:39'
exif:
aperture: f/2.2
exposure: 1/2326
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.23802833
longitude: -84.427095
next: /gallery/2015-costa-rica-trip/95df46a-en-route-to-la-fortuna
ordering: 5
previous: /gallery/2015-costa-rica-trip/7bc5479-en-route-to-la-fortuna
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'En route to La Fortuna'
aliases:
- /gallery/2015-costa-rica-trip/ee30c9f-en-route-to-la-fortuna.html
---
It was about a six hour trip (mostly on the bus) from San José. Plenty of pretty views as we wound through the hills.
<file_sep>/content/photo/2014-london-iceland-trip/a8e17f9-stegosaurus.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 11:21:47'
exif:
aperture: f/2.4
exposure: 1/15
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.495914
longitude: -0.176366
next: /gallery/2014-london-iceland-trip/59809e9-tyrannosaurus-rex
ordering: 26
previous: /gallery/2014-london-iceland-trip/ef30149-trafalgar-lunch
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Stegosaurus
aliases:
- /gallery/2014-london-iceland-trip/a8e17f9-stegosaurus.html
---
Back at the Natural History museum, they had a large exhibit on the dinosaurs.
<file_sep>/content/photo/2015-cambodia-thailand-trip/22deb2a-img-1010.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 18:17:29'
exif:
aperture: f/2.2
exposure: 1/2198
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.56404667
longitude: 104.931555
next: /gallery/2015-cambodia-thailand-trip/cbb80b5-img-1023
ordering: 10
previous: /gallery/2015-cambodia-thailand-trip/787e563-img-1005
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1010
aliases:
- /gallery/2015-cambodia-thailand-trip/22deb2a-img-1010.html
---
<file_sep>/content/photo/2014-barcelona-trip/24a6783-parc-guell.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 14:56:53'
exif:
aperture: f/2.2
exposure: 1/1014
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.41623667
longitude: 2.15294717
next: /gallery/2014-barcelona-trip/71bf8a4-parc-guell
ordering: 4
previous: /gallery/2014-barcelona-trip/3f1a4bb-parc-guell
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: '<NAME>'
aliases:
- /gallery/2014-barcelona-trip/24a6783-parc-guell.html
---
<file_sep>/content/photo/2014-london-iceland-trip/c828133-panorama.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-15 11:53:49'
exif:
aperture: f/2.4
exposure: 1/861
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 64.14672783
longitude: -21.9341
ordering: 99
previous: /gallery/2014-london-iceland-trip/223be54-waterfall
sizes:
1280:
height: 297
width: 1280
640w:
height: 149
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Panorama
aliases:
- /gallery/2014-london-iceland-trip/c828133-panorama.html
---
A panorama from the hostel looking across downton Reyjkavik.
<file_sep>/content/photo/2015-costa-rica-trip/a0e1387-boat-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 17:06:44'
exif:
aperture: f/2.2
exposure: 1/129
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.38989167
longitude: -84.20978667
next: /gallery/2015-costa-rica-trip/1665ce9-boat-tour
ordering: 109
previous: /gallery/2015-costa-rica-trip/41990a7-boat-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Boat Tour'
aliases:
- /gallery/2015-costa-rica-trip/a0e1387-boat-tour.html
---
After we passed the dolphins, they started being a bit more playful and jumping out of the water.
<file_sep>/content/photo/2014-london-iceland-trip/b6360f4-glacier-walk.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 17:25:15'
exif:
aperture: f/2.4
exposure: 1/553
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.53497167
longitude: -19.34731333
next: /gallery/2014-london-iceland-trip/78e4415-glacier-walk
ordering: 88
previous: /gallery/2014-london-iceland-trip/5303bd3-panorama
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Glacier Walk'
aliases:
- /gallery/2014-london-iceland-trip/b6360f4-glacier-walk.html
---
A look back towards where we originally started.
<file_sep>/content/photo/2015-costa-rica-trip/5ea206c-el-avion.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-18 17:18:02'
exif:
aperture: f/2.2
exposure: 1/60
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.402325
longitude: -84.15323617
next: /gallery/2015-costa-rica-trip/02aeb31-el-avion
ordering: 114
previous: /gallery/2015-costa-rica-trip/bc39503-el-avion
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'El Avión'
aliases:
- /gallery/2015-costa-rica-trip/5ea206c-el-avion.html
---
The story is there were two covert airplanes being used for transporting by the United States. One of them was shot down and this one was abandoned at the airport before being bought and moved/transformed into a restaurant.
<file_sep>/content/photo/2015-england-trip/7b16292-69579f63-afd0-4663-a9dc-41c268cb5d67.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 06:37:14'
exif:
aperture: f/2.2
exposure: 1/682
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.179255
longitude: -1.82541333
next: /gallery/2015-england-trip/9ef2927-bb8d439b-c58d-4cf4-ac0c-805f643a1ae0
ordering: 28
previous: /gallery/2015-england-trip/0aef531-fe1ac7a8-bcbb-4073-b3c6-0aaebe102eb4
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 69579F63-AFD0-4663-A9DC-41C268CB5D67
aliases:
- /gallery/2015-england-trip/7b16292-69579f63-afd0-4663-a9dc-41c268cb5d67.html
---
<file_sep>/content/photo/2014-barcelona-trip/26a5044-estadi-olimpic-lluis-companys.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 17:22:01'
exif:
aperture: f/2.2
exposure: 1/60
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.36607
longitude: 2.15583883
next: /gallery/2014-barcelona-trip/2810fe3-estadi-olimpic-lluis-companys
ordering: 20
previous: /gallery/2014-barcelona-trip/6dffda5-estadi-olimpic-lluis-companys
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: '<NAME> Lluís Companys'
aliases:
- /gallery/2014-barcelona-trip/26a5044-estadi-olimpic-lluis-companys.html
---
<file_sep>/content/photo/2014-london-iceland-trip/761d483-cityscape.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 13:48:31'
exif:
aperture: f/2.4
exposure: 1/1808
make: Apple
model: 'iPhone 5'
layout: gallery-photo
next: /gallery/2014-london-iceland-trip/8e50ad8-cityscape
ordering: 56
previous: /gallery/2014-london-iceland-trip/34da741-cityscape
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Cityscape
aliases:
- /gallery/2014-london-iceland-trip/761d483-cityscape.html
---
The unique house and roof colors were fun to see throughout the city.
<file_sep>/content/photo/2015-balloon-fiesta/e68c31f-img-0426.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-03 07:02:08'
exif:
aperture: f/2.2
exposure: 1/791
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19668833
longitude: -106.59655
next: /gallery/2015-balloon-fiesta/4b23cee-img-0435
ordering: 13
previous: /gallery/2015-balloon-fiesta/15ea128-img-0422
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0426
aliases:
- /gallery/2015-balloon-fiesta/e68c31f-img-0426.html
---
<file_sep>/content/photo/2014-london-iceland-trip/66e837b-hyde-park.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-11 14:59:27'
exif:
aperture: f/2.4
exposure: 1/274
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 51.50276167
longitude: -0.14200283
next: /gallery/2014-london-iceland-trip/b0d46ee-british-museum
ordering: 34
previous: /gallery/2014-london-iceland-trip/2028f17-buckingham-palace
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Hyde Park'
aliases:
- /gallery/2014-london-iceland-trip/66e837b-hyde-park.html
---
Hyde Park, this time walking instead of biking. Seemed like the England version of Central Park.
<file_sep>/content/photo/2015-costa-rica-trip/8114c5b-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 08:29:12'
exif:
aperture: f/2.2
exposure: 1/1883
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.37993
longitude: -84.1368555
next: /gallery/2015-costa-rica-trip/d557dab-manuel-antonio-national-park
ordering: 93
previous: /gallery/2015-costa-rica-trip/6a344be-manuel-antonio-national-park
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Manuel Antonio National Park'
aliases:
- /gallery/2015-costa-rica-trip/8114c5b-manuel-antonio-national-park.html
---
Some of the trails wound around the outskirts where we would catch occasional glimpses of the ocean.
<file_sep>/content/photo/2015-cambodia-thailand-trip/7fa2005-img-1948.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-18 04:25:53'
exif:
aperture: f/2.2
exposure: 1/33
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.35547833
longitude: 103.85303667
next: /gallery/2015-cambodia-thailand-trip/3805378-img-1950
ordering: 84
previous: /gallery/2015-cambodia-thailand-trip/37977f2-img-1943
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1948
aliases:
- /gallery/2015-cambodia-thailand-trip/7fa2005-img-1948.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/3c62e0f-img-0960.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-15 00:37:10'
exif:
aperture: f/2.2
exposure: 1/226
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 11.571405
longitude: 104.926645
next: /gallery/2015-cambodia-thailand-trip/f309d4c-img-0961
ordering: 2
previous: /gallery/2015-cambodia-thailand-trip/2206598-img-0958
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0960
aliases:
- /gallery/2015-cambodia-thailand-trip/3c62e0f-img-0960.html
---
<file_sep>/content/photo/2015-costa-rica-trip/a3b1d00-hike-to-cerro-chato.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 10:31:49'
exif:
aperture: f/2.2
exposure: 1/204
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.44659167
longitude: -84.67296667
next: /gallery/2015-costa-rica-trip/99e190d-lookout
ordering: 11
previous: /gallery/2015-costa-rica-trip/e3b74ac-hike-to-cerro-chato
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Hike to Cerro Chato'
aliases:
- /gallery/2015-costa-rica-trip/a3b1d00-hike-to-cerro-chato.html
---
The hike started out relatively easy and on well-marked trails.
<file_sep>/content/photo/2014-barcelona-trip/9563242-museu-nacional-dart-de-catalunya.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-22 20:14:31'
exif:
aperture: f/2.2
exposure: 1/17
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.37010333
longitude: 2.1524305
next: /gallery/2014-barcelona-trip/d54aeba-museu-nacional-dart-de-catalunya
ordering: 34
previous: /gallery/2014-barcelona-trip/cfa4e7e-our-team-workplace
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Museu Nacional d''Art de Catalunya'
aliases:
- /gallery/2014-barcelona-trip/9563242-museu-nacional-dart-de-catalunya.html
---
<file_sep>/content/photo/2015-cambodia-thailand-trip/062b0a1-img-2234.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-20 00:47:57'
exif:
aperture: f/2.2
exposure: 1/116
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.74603333
longitude: 100.49268333
next: /gallery/2015-cambodia-thailand-trip/0119242-img-2251
ordering: 115
previous: /gallery/2015-cambodia-thailand-trip/8b6fd8e-img-2223
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_2234
aliases:
- /gallery/2015-cambodia-thailand-trip/062b0a1-img-2234.html
---
<file_sep>/content/photo/2015-costa-rica-trip/7bc5479-en-route-to-la-fortuna.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-11 13:46:30'
exif:
aperture: f/2.2
exposure: 1/1464
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.21156667
longitude: -84.40248833
next: /gallery/2015-costa-rica-trip/ee30c9f-en-route-to-la-fortuna
ordering: 4
previous: /gallery/2015-costa-rica-trip/319af9c-en-route-to-la-fortuna
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'En route to La Fortuna'
aliases:
- /gallery/2015-costa-rica-trip/7bc5479-en-route-to-la-fortuna.html
---
Everything was very green. The rainy season ended a few weeks before we were there.
<file_sep>/content/photo/2015-cambodia-thailand-trip/5bfa633-img-2333.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-21 00:06:18'
exif:
aperture: f/2.2
exposure: 1/3968
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.74362
longitude: 100.48867
next: /gallery/2015-cambodia-thailand-trip/e19b8cf-img-2338
ordering: 124
previous: /gallery/2015-cambodia-thailand-trip/d02a252-img-2320
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2333
aliases:
- /gallery/2015-cambodia-thailand-trip/5bfa633-img-2333.html
---
<file_sep>/content/photo/2015-costa-rica-trip/7c61a51-don-juan-coffee-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 15:38:31'
exif:
aperture: f/2.2
exposure: 1/40
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.32338
longitude: -84.83493833
next: /gallery/2015-costa-rica-trip/aa6be30-don-juan-coffee-tour
ordering: 47
previous: /gallery/2015-costa-rica-trip/ab6da0f-don-juan-coffee-tour
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Don Juan Coffee Tour'
aliases:
- /gallery/2015-costa-rica-trip/7c61a51-don-juan-coffee-tour.html
---
This machine helped them separate the pieces of the coffee bean, once harvested.
<file_sep>/content/photo/2015-costa-rica-trip/ce6a440-horse-parade.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-11 16:25:02'
exif:
aperture: f/2.2
exposure: 1/1319
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.419025
longitude: -84.51965333
next: /gallery/2015-costa-rica-trip/9606542-horse-parade
ordering: 8
previous: /gallery/2015-costa-rica-trip/1f2b63b-ciudad-quesada
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Horse Parade'
aliases:
- /gallery/2015-costa-rica-trip/ce6a440-horse-parade.html
---
Halfway between Ciudad Quesada and La Fortuna the bus broke down going over a bump. We all had to get off while we waited for another one. Soon after, a parade of several dozen horses started trotting down the street towards us.
<file_sep>/content/photo/2015-costa-rica-trip/adac11d-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 09:01:35'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.38444667
longitude: -84.13856383
next: /gallery/2015-costa-rica-trip/59c3d74-manuel-antonio-national-park
ordering: 95
previous: /gallery/2015-costa-rica-trip/d557dab-manuel-antonio-national-park
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: '<NAME> National Park'
aliases:
- /gallery/2015-costa-rica-trip/adac11d-manuel-antonio-national-park.html
---
One of the more friendly animals of the park are the monkeys. This guy was feeling very photogenic when I was walking by.
<file_sep>/content/photo/2015-cambodia-thailand-trip/8b6fd8e-img-2223.md
---
galleries:
- 2015-cambodia-thailand-trip
date: '2015-11-20 00:36:30'
exif:
aperture: f/2.2
exposure: 1/807
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 13.74629667
longitude: 100.49223333
next: /gallery/2015-cambodia-thailand-trip/062b0a1-img-2234
ordering: 114
previous: /gallery/2015-cambodia-thailand-trip/e61d2c7-img-2196
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_2223
aliases:
- /gallery/2015-cambodia-thailand-trip/8b6fd8e-img-2223.html
---
<file_sep>/content/photo/2014-london-iceland-trip/c8267be-sudhurland.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 14:24:08'
exif:
aperture: f/2.4
exposure: 1/343
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 63.602055
longitude: -19.98391333
next: /gallery/2014-london-iceland-trip/881baef-sudhurland
ordering: 72
previous: /gallery/2014-london-iceland-trip/c551a16-bus-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Sudhurland
aliases:
- /gallery/2014-london-iceland-trip/c8267be-sudhurland.html
---
There were many waterfalls along the way.
<file_sep>/content/photo/2015-balloon-fiesta/711f1d1-img-0499.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-08 11:44:35'
exif:
aperture: f/2.2
exposure: 1/1980
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.18734667
longitude: -106.69151333
next: /gallery/2015-balloon-fiesta/9ee1c77-img-0503
ordering: 21
previous: /gallery/2015-balloon-fiesta/c26bc62-img-0495
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: IMG_0499
aliases:
- /gallery/2015-balloon-fiesta/711f1d1-img-0499.html
---
<file_sep>/content/photo/2014-barcelona-trip/31bbfef-olympic-park.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 17:04:41'
exif:
aperture: f/2.2
exposure: 1/304
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.36472167
longitude: 2.14998617
next: /gallery/2014-barcelona-trip/6dffda5-estadi-olimpic-lluis-companys
ordering: 18
previous: /gallery/2014-barcelona-trip/55ba6a5-torre-de-comunicacions-de-montjuic
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Olympic Park'
aliases:
- /gallery/2014-barcelona-trip/31bbfef-olympic-park.html
---
<file_sep>/content/photo/2014-london-iceland-trip/a02f087-hallgrimskirkja.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 14:07:07'
exif:
aperture: f/2.4
exposure: 1/3195
make: Apple
model: 'iPhone 5'
layout: gallery-photo
next: /gallery/2014-london-iceland-trip/bd9f003-weather
ordering: 62
previous: /gallery/2014-london-iceland-trip/eddc6cd-pathway
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Hallgrímskirkja
aliases:
- /gallery/2014-london-iceland-trip/a02f087-hallgrimskirkja.html
---
The church had a very distinctive look.
<file_sep>/content/photo/2014-barcelona-trip/43412b6-parc-guell-building.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 15:24:15'
exif:
aperture: f/2.2
exposure: 1/514
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.41353333
longitude: 2.15313617
next: /gallery/2014-barcelona-trip/bb97e7b-up-the-hill
ordering: 8
previous: /gallery/2014-barcelona-trip/a509b76-parc-guell-entry
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Parc Güell Building'
aliases:
- /gallery/2014-barcelona-trip/43412b6-parc-guell-building.html
---
<file_sep>/content/photo/2014-barcelona-trip/bb97e7b-up-the-hill.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 15:30:04'
exif:
aperture: f/2.2
exposure: 1/158
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.41262833
longitude: 2.15459167
next: /gallery/2014-barcelona-trip/fccc428-font-magica-de-montjuic
ordering: 9
previous: /gallery/2014-barcelona-trip/43412b6-parc-guell-building
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Up the Hill'
aliases:
- /gallery/2014-barcelona-trip/bb97e7b-up-the-hill.html
---
<file_sep>/content/photo/2015-england-trip/9ef2927-bb8d439b-c58d-4cf4-ac0c-805f643a1ae0.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 06:41:03'
exif:
aperture: f/2.2
exposure: 1/670
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.1792
longitude: -1.8264
next: /gallery/2015-england-trip/ad68e16-aa2f4220-816c-4d69-870b-7b24f42a02b1
ordering: 29
previous: /gallery/2015-england-trip/7b16292-69579f63-afd0-4663-a9dc-41c268cb5d67
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: BB8D439B-C58D-4CF4-AC0C-805F643A1AE0
aliases:
- /gallery/2015-england-trip/9ef2927-bb8d439b-c58d-4cf4-ac0c-805f643a1ae0.html
---
<file_sep>/content/page/about.md
---
slug: about
title: About Me
description: To intrigue those with technical challenges.
print_blurb: "résumé"
aliases:
- about.html
---
I am a _software engineer_ who enjoys pushing the limits of _web technology_ and applying them to _business processes_. Ideally, my job provides me with technical challenges that need _well-designed_ solutions. I have a solid understanding of industry best practices, but I am more interested in _continuously learning_ about why they exist and how they can be further _applied and improved_.
## Skill Set
I am especially familiar with 'cloud' concepts, e-commerce, server administration, and web applications. When working on a project, my preferred technologies are Linux, PHP (with symfony2, lately) and JavaScript (node.js, especially). Recently I have been able to gain experience and understanding in the following areas:
* languages:
[applescript](https://developer.apple.com/library/mac/#documentation/applescript/conceptual/applescriptx/AppleScriptX.html),
[css](http://en.wikipedia.org/wiki/Cascading_Style_Sheets),
[go](https://golang.org/),
[html](http://en.wikipedia.org/wiki/HTML),
[javascript](http://en.wikipedia.org/wiki/JavaScript),
[less](http://lesscss.org/),
[node.js](http://nodejs.org/),
[php](http://php.net/),
[ruby](https://www.ruby-lang.org/en/),
[sql](http://en.wikipedia.org/wiki/SQL),
[xslt](http://en.wikipedia.org/wiki/XSLT)
* libraries:
[composer](http://getcomposer.org/),
[doctrine](http://www.doctrine-project.org/),
[highcharts](http://www.highcharts.com/),
[mootools](http://mootools.net/),
[phpunit](https://github.com/sebastianbergmann/phpunit/),
[require.js](http://requirejs.org/),
[swiftmailer](http://swiftmailer.org/),
[symfony2](http://symfony.com/),
[twig](http://twig.sensiolabs.org/)
* software:
[bosh](https://github.com/cloudfoundry/bosh),
[docker](http://docker.io/),
[elasticsearch](http://www.elasticsearch.org/),
[git](http://git-scm.com/),
[jenkins](http://jenkins-ci.org/),
[kibana](http://www.elasticsearch.org/overview/kibana/),
[logstash](https://www.elastic.co/products/logstash),
[memcached](http://memcached.org/),
[mysql](http://www.mysql.com/),
[nginx](http://nginx.org/),
[openvpn](http://openvpn.net/),
[puppet](https://puppetlabs.com/),
[vagrant](http://www.vagrantup.com/)
* systems:
[linux](http://www.linux.org/),
[osx](http://www.apple.com/osx/),
[ubuntu](http://www.ubuntu.com/)
* services:
[aws](http://aws.amazon.com/),
[github](https://github.com/),
[paypal](https://www.paypal.com/)
## Experience
**Software Engineer** --- December '15 -- present
Pivotal Software, Inc ([website](http://pivotal.io/)) --- San Francisco, California
**Software Developer** --- August '13 -- August '15
City Index Ltd, Labs Team ([website](http://www.cityindex.co.uk/)) --- London, England
* Implemented and managed scalable logstash + elasticsearch + kibana stacks on AWS
* Researched and tested elasticsearch scaling for project needs
* Creating and managing BOSH releases for logsearch
* Creating logsearch-shipper, designed for log forwarding and monitoring of any other BOSH deployments
* Designing and supporting VPC environments on AWS
* Defining and implementing logging and monitoring practices for deployments
* Worked remotely
* Technologies: aws, bosh, elasticsearch, git, kibana, logstash, linux, nginx, node.js, openvpn, ruby, ubuntu, vagrant
**Software Systems Engineer** --- June '06 -- present
The Loopy Ewe ([website](https://theloopyewe.com/)) --- Fort Collins, Colorado
* Developed and currently maintain in-house e-commerce frontend and backoffice tools using primarily PHP and MySQL
* Migrated the backend website and services to the open-source symfony2 framework
* Integrated business tools with APIs including PayPal and Endicia
* Advising on strategic goals for the business and assisting in implementation
* Migrating from traditional servers to a multi-region cloud environment on AWS
* Migrating from Puppet-managed servers to a BOSH-managed environment
* Currently maintain production server environments and services
* Technologies: applescript, aws, composer, css, elasticsearch, git, html, javascript, linux, mootools, mysql, nginx, osx, paypal, php, puppet, require.js, rpm, sql, swiftmailer, symfony2, twig, twilio, vagrant
**Software Developer** --- July '09 -- October '12; Summer '08, intern
Sentry Data Systems ([website](http://www.sentryds.com/)) --- Deerfield Beach, Florida
* Guided the adoption of and migration to the open-source symfony2 framework from an internal framework for main customer SaaS web application
* Implemented development tools and standards including opengrok, composer, and PSR conventions
* Advised and taught on software design, industry practices, and development workflows
* Created automated systems for detecting data quality issues in client data feeds, significantly reducing manual work
* Created custom issue tracking system to support existing Oracle-based applications, email ticketing, workflows, and time estimations
* Worked locally for 18 months and remotely for 22 months
* Technologies: composer, git, html, javascript, jenkins, linux, mootools, opengrok, oracle-database, php, phpunit, sql, subversion, symfony2, twig
**Student System Administrator** --- Spring '06 -- Fall '08
CSE Department, Taylor University ([website](http://www.taylor.edu/)) --- Upland, Indiana
* Created web-based applications to aid in department processes for faculty and students
* Maintained and provided support for the Computer Science department lab computers and servers (Linux, Windows)
* Acted as contributing editor and webmaster for the department's public website
* Technologies: html, linux, mysql, php, sql, windows
**Network Administrator** --- Spring '03 -- Summer '07
The Covenant Presbyterian Church ([website](http://www.cpcstl.org/)) --- St. Louis, Missouri
* Created, maintained, and hosted their website CMS during employment and until 2010
* Provided technical support (on-site, phone, and email) to ministry staff
* Managed Microsoft Windows and Exchange servers, internal ministry applications, and other productivity software
* Technologies: css, exchange, html, linux, mysql, php, sql, windows, windows-server
## Open-Source Contributions
* [logstash/logstash](https://github.com/logstash/logstash/commits?author=dpb587) -- small enhancements
* [elasticsearch/kibana](https://github.com/elasticsearch/kibana/commits?author=dpb587) -- small bug fixes
* [composer/composer](https://github.com/composer/composer/commits?author=dpb587) -- small enhancements, bug fixes
* [symfony/symfony](https://github.com/symfony/symfony/commits?author=dpb587) -- small enhancements, bug fixes
* [doctrine/dbal](https://github.com/doctrine/dbal/commits?author=dpb587) -- oracle bug fixes
## Education
* [Taylor University](http://www.taylor.edu/) --- Bachelor of Science (2005 -- 2009), Computer Science, Systems (Business Information Systems)
* [Westminster Christian Academy](http://www.wcastl.org/) --- high school (2001 -- 2005)
<file_sep>/content/photo/2015-balloon-fiesta/0a0247c-img-0522.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-09 06:35:42'
exif:
aperture: f/2.2
exposure: 1/356
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.19396167
longitude: -106.59698667
next: /gallery/2015-balloon-fiesta/fc46ce5-img-0527
ordering: 23
previous: /gallery/2015-balloon-fiesta/9ee1c77-img-0503
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0522
aliases:
- /gallery/2015-balloon-fiesta/0a0247c-img-0522.html
---
<file_sep>/content/photo/2014-barcelona-trip/c24ae6e-torre-de-comunicacions-de-montjuic.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-21 16:58:28'
exif:
aperture: f/2.2
exposure: 1/807
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.36456333
longitude: 2.15171117
next: /gallery/2014-barcelona-trip/71e7a4a-estadi-olimpic-lluis-companys
ordering: 15
previous: /gallery/2014-barcelona-trip/80e027b-torre-de-comunicacions-de-montjuic
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Torre de Comunicacions de Montjuïc'
aliases:
- /gallery/2014-barcelona-trip/c24ae6e-torre-de-comunicacions-de-montjuic.html
---
<file_sep>/content/photo/2015-costa-rica-trip/7cd8fdf-monteverde-chocolate-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-13 13:45:33'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.46543833
longitude: -84.66343
next: /gallery/2015-costa-rica-trip/0a29380-monteverde-chocolate-tour
ordering: 36
previous: /gallery/2015-costa-rica-trip/803d85a-monteverde-chocolate-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Monteverde Chocolate Tour'
aliases:
- /gallery/2015-costa-rica-trip/7cd8fdf-monteverde-chocolate-tour.html
---
One of the first steps is fermenting the beans which kills off the germination in the bean. We opened one of the fruits and were able to taste the outer coating of the bean which had a sweet flavor.
<file_sep>/content/photo/2015-costa-rica-trip/ab6da0f-don-juan-coffee-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-14 15:28:09'
exif:
aperture: f/2.2
exposure: 1/581
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.32338
longitude: -84.83493833
next: /gallery/2015-costa-rica-trip/7c61a51-don-juan-coffee-tour
ordering: 46
previous: /gallery/2015-costa-rica-trip/be359cf-don-juan-coffee-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Don Juan Coffee Tour'
aliases:
- /gallery/2015-costa-rica-trip/ab6da0f-don-juan-coffee-tour.html
---
Some baby coffee tree sprouts.
<file_sep>/content/photo/2015-costa-rica-trip/19fb74d-boat-tour.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 17:30:18'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.42608667
longitude: -84.17048667
next: /gallery/2015-costa-rica-trip/bc39503-el-avion
ordering: 112
previous: /gallery/2015-costa-rica-trip/ba4a018-boat-tour
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Boat Tour'
aliases:
- /gallery/2015-costa-rica-trip/19fb74d-boat-tour.html
---
...and arriving back to the marina.
<file_sep>/content/photo/2015-costa-rica-trip/917dd23-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 07:58:40'
exif:
aperture: f/2.2
exposure: 1/1980
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.380125
longitude: -84.13964717
next: /gallery/2015-costa-rica-trip/e6652a0-manuel-antonio-national-park
ordering: 87
previous: /gallery/2015-costa-rica-trip/f279423-manuel-antonio-national-park
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: '<NAME>onio National Park'
aliases:
- /gallery/2015-costa-rica-trip/917dd23-manuel-antonio-national-park.html
---
The park has three beaches. We came across this small, secluded one first.
<file_sep>/content/photo/2014-albuquerque-balloon-fiesta/e20c89c-img-1094.md
---
galleries:
- 2014-albuquerque-balloon-fiesta
date: '2014-10-10 09:28:03'
exif:
aperture: f/2.4
exposure: 1/2169
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 35.19006333
longitude: -106.59783833
next: /gallery/2014-albuquerque-balloon-fiesta/6b77a4f-img-1095
ordering: 16
previous: /gallery/2014-albuquerque-balloon-fiesta/e93dd19-img-1091
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_1094
aliases:
- /gallery/2014-albuquerque-balloon-fiesta/e20c89c-img-1094.html
---
<file_sep>/content/photo/2015-costa-rica-trip/fb10d9a-thirsty-cow.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-12 14:28:35'
exif:
aperture: f/2.2
exposure: 1/194
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.44417
longitude: -84.67508667
next: /gallery/2015-costa-rica-trip/30d9cb8-giovannis-night-tour
ordering: 21
previous: /gallery/2015-costa-rica-trip/2cb76f3-hike-from-cerro-chato
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Thirsty Cow'
aliases:
- /gallery/2015-costa-rica-trip/fb10d9a-thirsty-cow.html
---
Including this one who came over to take a drink while we were walking by.
<file_sep>/content/photo/2015-england-trip/6656c15-8c6a8abc-f5e5-4524-afcc-d3f7bba46a46.md
---
galleries:
- 2015-england-trip
date: '2015-03-08 07:59:30'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.50764667
longitude: -0.07917783
next: /gallery/2015-england-trip/41a98dc-7d7137a6-38d4-42c8-9971-97507f697a7b
ordering: 14
previous: /gallery/2015-england-trip/9606663-9befa48b-c37e-4cf6-b729-41e6d96cd3d6
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 8C6A8ABC-F5E5-4524-AFCC-D3F7BBA46A46
aliases:
- /gallery/2015-england-trip/6656c15-8c6a8abc-f5e5-4524-afcc-d3f7bba46a46.html
---
<file_sep>/content/photo/2015-costa-rica-trip/388aa87-canopy-zip-line.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-15 15:45:06'
exif:
aperture: f/2.2
exposure: 1/128
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 10.34984667
longitude: -84.84081333
next: /gallery/2015-costa-rica-trip/df11754-canopy-zip-line
ordering: 80
previous: /gallery/2015-costa-rica-trip/2c4b03b-canopy-zip-line
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Canopy Zip Line'
aliases:
- /gallery/2015-costa-rica-trip/388aa87-canopy-zip-line.html
---
One of the final zip line styles was the "superman".
<file_sep>/content/photo/2015-england-trip/271af08-c8440bd3-c5d2-40fa-816a-ca2391ecb801.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 09:58:04'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.36581167
longitude: -2.38178
ordering: 40
previous: /gallery/2015-england-trip/d702f2b-e9b69c74-3c6f-41d3-8f76-5d2aac504cae
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: C8440BD3-C5D2-40FA-816A-CA2391ECB801
aliases:
- /gallery/2015-england-trip/271af08-c8440bd3-c5d2-40fa-816a-ca2391ecb801.html
---
<file_sep>/content/photo/2015-england-trip/dccb855-c3057568-a43e-44b1-b4c5-f129d5353d85.md
---
galleries:
- 2015-england-trip
date: '2015-03-09 08:40:09'
exif:
aperture: f/2.2
exposure: 1/60
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 51.38090833
longitude: -2.35918333
next: /gallery/2015-england-trip/bb01fc5-3df722fc-172d-4e42-acb5-a5201452f47f
ordering: 32
previous: /gallery/2015-england-trip/0250f82-dd31f942-e044-401e-b974-ad18588484d3
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: C3057568-A43E-44B1-B4C5-F129D5353D85
aliases:
- /gallery/2015-england-trip/dccb855-c3057568-a43e-44b1-b4c5-f129d5353d85.html
---
<file_sep>/content/photo/2014-london-iceland-trip/68119f5-glacier-walk.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-14 18:03:16'
exif:
aperture: f/2.4
exposure: 1/241
make: Apple
model: 'iPhone 5'
layout: gallery-photo
next: /gallery/2014-london-iceland-trip/c4ff904-glacier-walk
ordering: 91
previous: /gallery/2014-london-iceland-trip/77bf47b-panorama
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: 'Glacier Walk'
aliases:
- /gallery/2014-london-iceland-trip/68119f5-glacier-walk.html
---
More glacier pictures…
<file_sep>/content/photo/2015-costa-rica-trip/319af9c-en-route-to-la-fortuna.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-11 13:26:17'
exif:
aperture: f/2.2
exposure: 1/2326
make: Apple
model: 'iPhone 6'
layout: gallery-photo
next: /gallery/2015-costa-rica-trip/7bc5479-en-route-to-la-fortuna
ordering: 3
previous: /gallery/2015-costa-rica-trip/78b6538-red-sofa
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'En route to La Fortuna'
aliases:
- /gallery/2015-costa-rica-trip/319af9c-en-route-to-la-fortuna.html
---
It was nice being able to see the countryside along the bus route.
<file_sep>/content/photo/2015-balloon-fiesta/670c81b-imag2366.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-11 13:34:52'
exif:
aperture: f/2.0
exposure: 390/1000000
make: HTC
model: HTC6500LVW
layout: gallery-photo
location:
latitude: 35.78374167
longitude: -106.272545
next: /gallery/2015-balloon-fiesta/5dd4971-imag2382
ordering: 37
previous: /gallery/2015-balloon-fiesta/0373f93-img-0898
sizes:
1280:
height: 724
width: 1280
640w:
height: 362
width: 640
200x200:
height: 200
width: 200
title: IMAG2366
aliases:
- /gallery/2015-balloon-fiesta/670c81b-imag2366.html
---
<file_sep>/content/photo/2014-barcelona-trip/baf4bfd-mirador-de-colom.md
---
galleries:
- 2014-barcelona-trip
date: '2014-11-22 21:37:57'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 41.376545
longitude: 2.17872167
next: /gallery/2014-barcelona-trip/9a59ac6-port-de-barcelona
ordering: 39
previous: /gallery/2014-barcelona-trip/ffd7d37-christmasy-walkways
sizes:
1280:
height: 1280
width: 960
640w:
height: 853
width: 640
200x200:
height: 200
width: 200
title: 'Mirador de Colom'
aliases:
- /gallery/2014-barcelona-trip/baf4bfd-mirador-de-colom.html
---
<file_sep>/content/photo/2015-balloon-fiesta/e94146c-img-0741.md
---
galleries:
- 2015-balloon-fiesta
date: '2015-10-10 18:07:32'
exif:
aperture: f/2.2
exposure: 1/15
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 35.196225
longitude: -106.59674667
next: /gallery/2015-balloon-fiesta/4c7a9b0-img-0820
ordering: 33
previous: /gallery/2015-balloon-fiesta/b115008-img-0707
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: IMG_0741
aliases:
- /gallery/2015-balloon-fiesta/e94146c-img-0741.html
---
<file_sep>/content/photo/2014-colorado-aspens/2dbeedb-aspens-invading.md
---
galleries:
- 2014-colorado-aspens
date: '2014-09-27 12:23:19'
exif:
aperture: f/2.4
exposure: 1/2584
make: Apple
model: 'iPhone 5'
layout: gallery-photo
location:
latitude: 39.61043833
longitude: -105.95197167
ordering: 6
previous: /gallery/2014-colorado-aspens/79c5a71-through-the-aspens
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Aspens Invading'
aliases:
- /gallery/2014-colorado-aspens/2dbeedb-aspens-invading.html
---
<file_sep>/content/photo/2015-costa-rica-trip/169e642-manuel-antonio-national-park.md
---
galleries:
- 2015-costa-rica-trip
date: '2015-01-17 09:54:38'
exif:
aperture: f/2.2
exposure: 1/30
make: Apple
model: 'iPhone 6'
layout: gallery-photo
location:
latitude: 9.38128833
longitude: -84.14591117
next: /gallery/2015-costa-rica-trip/5d967d2-manuel-antonio-national-park
ordering: 100
previous: /gallery/2015-costa-rica-trip/b89996d-manuel-antonio-national-park
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
title: 'Manuel Antonio National Park'
aliases:
- /gallery/2015-costa-rica-trip/169e642-manuel-antonio-national-park.html
---
This monkey enjoyed people watching, hanging out over the trail just within reach of everybody passing by.
<file_sep>/content/photo/2014-london-iceland-trip/f5a8d81-cityscape.md
---
galleries:
- 2014-london-iceland-trip
date: '2014-03-13 13:48:59'
exif:
aperture: f/2.4
exposure: 1/2463
make: Apple
model: 'iPhone 5'
layout: gallery-photo
next: /gallery/2014-london-iceland-trip/a7208f4-cityscape
ordering: 58
previous: /gallery/2014-london-iceland-trip/8e50ad8-cityscape
sizes:
1280:
height: 960
width: 1280
640w:
height: 480
width: 640
200x200:
height: 200
width: 200
96x96:
height: 96
width: 96
title: Cityscape
aliases:
- /gallery/2014-london-iceland-trip/f5a8d81-cityscape.html
---
Another angle of the city.
| 706ab23bec7ce7695980c5529b4f09c235e8a013 | [
"HTML",
"Markdown",
"TOML",
"Go",
"Shell"
] | 385 | Markdown | s4heid/dpb587.me | 0ac045f4a3ca04f72b4f542bbc655661c697ad1d | 59a8494c48a0b3faff89d751705682497beadcb0 |
refs/heads/master | <repo_name>A-Bee-4/leetcode<file_sep>/src/LongestRepeatingChars/Solution.java
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int maxLen = 0;
int currentLen = 0;
int start = 0;
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(map.containsKey(c)) {
int index = map.get(c);
if(index < start) {
currentLen++;
} else {
if(currentLen > maxLen)
maxLen = currentLen;
start = index + 1;
currentLen = i - start + 1;
}
} else {
currentLen++;
}
map.put(c, i);
}
return currentLen > maxLen ? currentLen : maxLen;
}
}
<file_sep>/src/VersionNumbers/Solution.java
public class Solution {
public int compareVersion(String version1, String version2) {
String[] parts1 = version1.split("\\.");
String[] parts2 = version2.split("\\.");
int i = 0;
while(i < parts1.length && i < parts2.length) {
int val1 = Integer.parseInt(parts1[i]);
int val2 = Integer.parseInt(parts2[i]);
if(val1 > val2)
return 1;
if(val1 < val2)
return -1;
i++;
}
if(i < parts1.length && Integer.parseInt(parts1[i]) > 0 &&
i >= parts2.length)
return 1;
if(i >= parts1.length && i < parts2.length &&
Integer.parseInt(parts2[i]) > 0)
return -1;
return 0;
}
}
<file_sep>/src/ReverseInteger/Solution.java
public class Solution {
public int reverse(int x) {
boolean isNeg = x < 0;
x = Math.abs(x);
long reverse = 0;
while(x > 0) {
int d = x % 10;
reverse = reverse * 10 + d;
x /= 10;
}
if(reverse > Integer.MAX_VALUE)
return 0;
reverse = isNeg ? -reverse : reverse;
return (int) reverse;
}
}
<file_sep>/src/Permutations2/Solution.java
public class Solution {
public List<List<Integer>> permuteUnique(int[] num) {
LinkedList<List<Integer>> permutations =
new LinkedList<List<Integer>>();
if(num.length == 0) {
permutations.add(new LinkedList<Integer>());
return permutations;
}
if(num.length == 1) {
LinkedList<Integer> permutation = new LinkedList<Integer>();
permutation.add(num[0]);
permutations.add(permutation);
return permutations;
}
HashSet<Integer> set = new HashSet<Integer>();
List<List<Integer>> partials;
int[] shorter;
for(int i = 0; i < num.length; i++) {
if(!set.contains(num[i])) {
shorter = remove(num, i);
partials = permuteUnique(shorter);
for(List<Integer> partial : partials) {
partial.add(0, num[i]);
permutations.add(partial);
}
set.add(num[i]);
}
}
return permutations;
}
private int[] remove(int[] arr, int i) {
int[] result = new int[arr.length - 1];
for(int j = 0; j < i; j++)
result[j] = arr[j];
for(int j = i; j < result.length; j++)
result[j] = arr[j + 1];
return result;
}
}
<file_sep>/src/PartitionList/Solution.java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode smallerHead = null;
ListNode smallerTail = null;
ListNode greaterHead = null;
ListNode greaterTail = null;
ListNode next;
while(head != null) {
next = head.next;
if(head.val < x) {
if(smallerHead == null) {
smallerHead = head;
smallerTail = head;
} else {
smallerTail.next = head;
smallerTail = head;
}
smallerTail.next = null;
} else {
if(greaterHead == null) {
greaterHead = head;
greaterTail = head;
} else {
greaterTail.next = head;
greaterTail = head;
}
greaterTail.next = null;
}
head = next;
}
if(smallerHead == null)
return greaterHead;
smallerTail.next = greaterHead;
return smallerHead;
}
}
<file_sep>/src/ReverseLinkedList2/Solution.java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode n1 = null;
ListNode n2 = null;
ListNode current;
ListNode next;
for(int i = n - m + 2; i > 0; i--) {
if(n2 == null)
n2 = head;
else
n2 = n2.next;
}
for(int i = m - 1; i > 0; i--) {
if(n1 == null)
n1 = head;
else
n1 = n1.next;
n2 = n2.next;
}
if(n1 == null)
current = head;
else
current = n1.next;
for(int i = n - m + 1; i > 0; i--) {
next = current.next;
current.next = n2;
n2 = current;
current = next;
}
if(n1 == null)
head = n2;
else
n1.next = n2;
return head;
}
}
<file_sep>/src/LongestPalindromicSubstring/Solution.java
public class Solution {
public String longestPalindrome(String s) {
if(s == null)
return null;
if(s.length() <= 1)
return s;
int len = s.length();
boolean[][] isPalindrome = new boolean[len][len];
String longest = s.substring(0, 1);
int maxLen = 1;
for(int i = 0; i < len; i++)
isPalindrome[i][i] = true;
for(int i = 0; i <= len - 2; i++) {
if(s.charAt(i) == s.charAt(i + 1)) {
isPalindrome[i][i+1] = true;
longest = s.substring(i, i + 2);
}
}
for(int d = 2; d < len; d++) {
for(int i = 0; i < len - d; i++) {
int j = d + i;
if(s.charAt(i) == s.charAt(j)) {
isPalindrome[i][j] = isPalindrome[i + 1][j - 1];
if(j - i + 1 > maxLen && isPalindrome[i][j]) {
maxLen = j - i + 1;
longest = s.substring(i, j + 1);
}
} else {
isPalindrome[i][j] = false;
}
}
}
return longest;
}
}
<file_sep>/src/ValidSudoku/Solution.java
public class Solution {
public boolean isValidSudoku(char[][] board) {
HashSet<Integer> set = new HashSet<Integer>();
int num;
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
num = board[i][j] - '0';
if(set.contains(num))
return false;
if(board[i][j] != '.')
set.add(num);
}
set.clear();
}
for(int j = 0; j < 9; j++) {
for(int i = 0; i < 9; i++) {
num = board[i][j] - '0';
if(set.contains(num))
return false;
if(board[i][j] != '.')
set.add(num);
}
set.clear();
}
for(int i = 0; i <= 6; i += 3) {
for(int j = 0; j <= 6; j += 3) {
if(!validBox(i, j, board))
return false;
}
}
return true;
}
private boolean validBox(int i, int j, char[][] board) {
HashSet<Integer> set = new HashSet<Integer>();
int num;
for(int m = 0; m < 3; m++) {
for(int n = 0; n < 3; n++) {
num = board[i + m][j + n] - '0';
if(set.contains(num))
return false;
if(board[i + m][j + n] != '.')
set.add(num);
}
}
return true;
}
}
<file_sep>/src/SymmetricTree/Solution.java
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
if(root.left == null && root.right == null)
return true;
if(root.left == null || root.right == null)
return false;
TreeNode tmp = root.left.right;
root.left.right = root.right.right;
root.right.right = tmp;
return root.left.val == root.right.val &&
isSymmetric(root.left) && isSymmetric(root.right);
}
public boolean isSymmetricIterative(TreeNode root) {
ArrayList<TreeNode> level = new ArrayList<TreeNode>();
ArrayList<TreeNode> nextLevel = new ArrayList<TreeNode>();
ArrayList<TreeNode> tmp;
int i;
int j;
if(root != null)
level.add(root);
while(level.size() != 0) {
i = 0;
j = level.size() - 1;
while(i < j) {
if((level.get(i) == null && level.get(j) != null) ||
(level.get(i) != null && level.get(j) == null) ||
(level.get(i) != null && level.get(j) != null &&
level.get(i).val != level.get(j).val))
return false;
i++;
j--;
}
for(TreeNode node : level) {
if(node != null) {
nextLevel.add(node.left);
nextLevel.add(node.right);
}
}
level.clear();
tmp = level;
level = nextLevel;
nextLevel = tmp;
}
return true;
}
}
<file_sep>/src/MajorityElement/Solution.java
import java.util.HashMap;
public class Solution {
public int majorityElement(int[] num) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int len = num.length;
for(int n : num) {
if(map.containsKey(n))
map.put(n, map.get(n) + 1);
else
map.put(n, 1);
if(map.get(n) > len / 2)
return n;
}
return -1;
}
}
<file_sep>/src/MinStack/MinStack.java
class MinStack {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> mins = new Stack<Integer>();
public void push(int x) {
stack.push(x);
if(mins.isEmpty() || x <= mins.peek())
mins.push(x);
}
public void pop() {
if(stack.pop().equals(mins.peek()))
mins.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return mins.peek();
}
}
<file_sep>/src/RemoveDuplicatesList2/Solution.java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode node = null;
ListNode tail = null;
ListNode tmp;
int count;
while(head != null) {
tmp = head;
count = 1;
head = head.next;
while(head != null && head.val == tmp.val) {
head = head.next;
count++;
}
if(count == 1) {
if(node == null) {
node = tmp;
tail = tmp;
} else {
tail.next = tmp;
tail = tmp;
}
tail.next = null;
}
}
return node;
}
}
<file_sep>/src/Combinations/Solution.java
public class Solution {
public List<List<Integer>> combine(int n, int k) {
LinkedList<List<Integer>> combinations =
new LinkedList<List<Integer>>();
LinkedList<Integer> currentCombination = new LinkedList<Integer>();
combineHelper(1, n, k, combinations, currentCombination);
return combinations;
}
private void combineHelper(int m, int n, int k,
LinkedList<List<Integer>> combinations,
LinkedList<Integer> currentCombination) {
if(k == 0) {
LinkedList<Integer> combination =
new LinkedList<Integer>(currentCombination);
combinations.add(combination);
return;
}
if(m > n)
return;
combineHelper(m + 1, n, k, combinations, currentCombination);
currentCombination.add(m);
combineHelper(m + 1, n, k - 1, combinations, currentCombination);
currentCombination.removeLast();
}
}
<file_sep>/src/ReorderList/Solution.java
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null)
return;
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode p2 = slow.next;
slow.next = null;
ListNode p1 = head;
p2 = reverse(p2);
ListNode next1;
ListNode next2;
while(p2 != null) {
next1 = p1.next;
next2 = p2.next;
p1.next = p2;
p2.next = next1;
p1 = next1;
p2 = next2;
}
}
private ListNode reverse(ListNode head) {
ListNode node = null;
ListNode next;
while(head != null) {
next = head.next;
head.next = node;
node = head;
head = next;
}
return node;
}
}
<file_sep>/src/BinaryTreeLevelOrderTraversalII/Solution.java
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
LinkedList<List<Integer>> traversal = new LinkedList<List<Integer>>();
Queue<TreeNode> level = new LinkedList<TreeNode>();
Queue<TreeNode> nextLevel = new LinkedList<TreeNode>();
Queue<TreeNode> temp;
if(root != null)
level.add(root);
while(!level.isEmpty()) {
LinkedList<Integer> list = new LinkedList<Integer>();
traversal.add(0, list);
while(!level.isEmpty()) {
TreeNode node = level.remove();
list.add(node.val);
if(node.left != null)
nextLevel.add(node.left);
if(node.right != null)
nextLevel.add(node.right);
}
temp = level;
level = nextLevel;
nextLevel = temp;
}
return traversal;
}
}
<file_sep>/src/Subsets/Solution.java
public class Solution {
public List<List<Integer>> subsets(int[] S) {
Arrays.sort(S);
LinkedList<List<Integer>> subsets = new LinkedList<List<Integer>>();
LinkedList<Integer> currentSubset = new LinkedList<Integer>();
subsetsHelper(0, S, subsets, currentSubset);
return subsets;
}
public void subsetsHelper(int i, int[] S,
LinkedList<List<Integer>> subsets,
LinkedList<Integer> currentSubset) {
if(i >= S.length) {
LinkedList<Integer> subset =
new LinkedList<Integer>(currentSubset);
subsets.add(subset);
return;
}
currentSubset.add(S[i]);
subsetsHelper(i + 1, S, subsets, currentSubset);
currentSubset.removeLast();
subsetsHelper(i + 1, S, subsets, currentSubset);
}
}
<file_sep>/src/Permutations/Solution.java
public class Solution {
public List<List<Integer>> permute(int[] num) {
LinkedList<List<Integer>> permutations =
new LinkedList<List<Integer>>();
if(num.length == 0) {
permutations.add(new LinkedList<Integer>());
return permutations;
}
if(num.length == 1) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(num[0]);
permutations.add(list);
return permutations;
}
List<List<Integer>> partials;
int[] shorter;
for(int i = 0; i < num.length; i++) {
shorter = remove(num, i);
partials = permute(shorter);
for(List<Integer> permutation : partials) {
permutation.add(0, num[i]);
permutations.add(permutation);
}
}
return permutations;
}
private int[] remove(int[] arr, int i) {
int[] result = new int[arr.length - 1];
for(int j = 0; j < i; j++)
result[j] = arr[j];
for(int j = i; j < result.length; j++)
result[j] = arr[j + 1];
return result;
}
}
<file_sep>/README.md
LeetCode
========
Solutions to [LeetCode](https://oj.leetcode.com/) coding challenges.
| # | Title | Java | Python | Difficulty |
|-----|-------|------|--------|------------|
| 1 |[Two Sum](https://oj.leetcode.com/problems/two-sum/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/TwoSum/Solution.java)| |Medium|
| 2 |[Add Two Numbers](https://oj.leetcode.com/problems/add-two-numbers/) |[Java](https://github.com/mirandaio/leetcode/blob/master/src/AddTwoNumbers/Solution.java)| |Medium|
| 3 |[Longest Substring Without Repeating Characters](https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/LongestRepeatingChars/Solution.java)| |Medium|
| 4 |[Median of Two Sorted Arrays](https://oj.leetcode.com/problems/median-of-two-sorted-arrays/)|| |Hard|
| 5 |[Longest Palindromic Substring](https://oj.leetcode.com/problems/longest-palindromic-substring/)|[Java](https://github.com/mirandaio/leetcode/tree/master/src/LongestPalindromicSubstring)| | Medium |
| 7 |[Reverse Integer](https://oj.leetcode.com/problems/reverse-integer/)|[Java](https://github.com/mirandaio/leetcode/tree/master/src/ReverseInteger)|||Easy|
| 8 |[String to Integer (atoi)](https://oj.leetcode.com/problems/string-to-integer-atoi/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/Atoi/Solution.java)| |Easy|
| 9 |[Palindrome Number](https://oj.leetcode.com/problems/palindrome-number/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/PalindromeNumber/Solution.java)
| 12 |[Integer to Roman](https://oj.leetcode.com/problems/integer-to-roman/)| | | Medium |
| 13 |[Roman to Integer](https://oj.leetcode.com/problems/roman-to-integer/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/RomanToInteger/Solution.java)| | Easy |
| 14 |[Longest Common Prefix](https://oj.leetcode.com/problems/longest-common-prefix/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/LongestCommonPrefix/Solution.java)||Easy|
| 19 |[Remove Nth Node From End of List](https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/RemoveNth/Solution.java)||Easy|
| 20 |[Valid Parentheses](https://oj.leetcode.com/problems/valid-parentheses/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ValidParentheses/Solution.java)||Easy|
| 21 |[Merge Two Sorted Lists](https://oj.leetcode.com/problems/merge-two-sorted-lists/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/MergeLists/Solution.java)||Easy|
| 22 |[Generate Parentheses](https://oj.leetcode.com/problems/generate-parentheses/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/GenerateParentheses/Solution.java)||Medium|
| 24 |[Swap Nodes in Pairs](https://oj.leetcode.com/problems/swap-nodes-in-pairs/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/SwapNodesInPairs/Solution.java)||Medium|
| 26 |[Remove Duplicates from Sorted Array](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/RemoveDuplicatesArray/Solution.java)||Easy|
| 27 |[Remove Element](https://oj.leetcode.com/problems/remove-element/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/RemoveElement/Solution.java)||Easy|
| 28 |[Implement strStr()](https://oj.leetcode.com/problems/implement-strstr/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ImplementstrStr/Solution.java)||Easy|
| 36 |[Valid Sudoku](https://oj.leetcode.com/problems/valid-sudoku/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ValidSudoku/Solution.java)||Easy|
| 46 |[Permutations](https://oj.leetcode.com/problems/permutations/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/Permutations/Solution.java)||Medium|
| 47 |[Permutations 2](https://oj.leetcode.com/problems/permutations-ii/)|[Java](https://github.com/mirandaio/leetcode/tree/master/src/Permutations2)||Hard|
| 51 |[N-Queens](https://oj.leetcode.com/problems/n-queens/)|[Java](https://github.com/mirandaio/leetcode/tree/master/src/NQueens)||Hard|
| 52 |[N-Queens 2](https://oj.leetcode.com/problems/n-queens-ii/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/NQueens2/Solution.java)||Hard|
| 58 |[Length of Last Word](https://oj.leetcode.com/problems/length-of-last-word/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/LastWord/Solution.java)||Easy|
| 61 |[Rotate List](https://oj.leetcode.com/problems/rotate-list/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/RotateList/Solution.java)||Medium|
| 66 |[Plus One](https://oj.leetcode.com/problems/plus-one/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/PlusOne/Solution.java)||Easy|
| 67 |[Add Binary](https://oj.leetcode.com/problems/add-binary/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/AddBinary/Solution.java)||Easy|
| 70 |[Climbing Stairs](https://oj.leetcode.com/problems/climbing-stairs/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ClimbingStairs/Solution.java)||Easy|
| 73 |[Set Matrix Zeroes](https://oj.leetcode.com/problems/set-matrix-zeroes/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/SetMatrixZeroes/Solution.java)||Medium|
| 77 |[Combinations](https://oj.leetcode.com/problems/combinations/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/Combinations/Solution.java)||Medium|
| 78 |[Subsets](https://oj.leetcode.com/problems/subsets/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/Subsets/Solution.java)||Medium|
| 82 |[Remove Duplicates from Sorted List 2](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/RemoveDuplicatesList2/Solution.java)||Medium|
| 83 |[Remove Duplicates from Sorted List](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/RemoveDuplicatesList/Solution.java)||Easy|
| 86 |[Partition List](https://oj.leetcode.com/problems/partition-list/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/PartitionList/Solution.java)||Medium|
| 88 |[Merge Sorted Array](https://oj.leetcode.com/problems/merge-sorted-array/)|[Java](https://github.com/mirandaio/leetcode/tree/master/src/MergeSortedArray)||Easy|
| 92 |[Reverse Linked List 2](https://oj.leetcode.com/problems/reverse-linked-list-ii/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ReverseLinkedList2/Solution.java)||Medium|
| 94 |[Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/BinaryTreeInorder/Solution.java)|[Python](https://github.com/mirandaio/leetcode/blob/master/src/BinaryTreeInorder/inorder.py)|Medium|
| 98 |[Validate Binary Search Tree](https://oj.leetcode.com/problems/validate-binary-search-tree/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ValidateBST/Solution.java)||Medium|
| 100 |[Same Tree](https://oj.leetcode.com/problems/same-tree/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/SameTree/Solution.java)||Easy|
| 101 |[Symmetric Tree](https://oj.leetcode.com/problems/symmetric-tree/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/SymmetricTree/Solution.java)||Easy|
| 102 |[Binary Tree Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-level-order-traversal/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/BinaryTreeLevelOrderTraversal/Solution.java)||Easy|
| 104 |[Maximum Depth of Binary Tree](https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/MaximumDepthBinaryTree/Solution.java)||Easy|
| 105 |[Construct Binary Tree from Preorder and Inorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ConstructPreorderInorder/Solution.java)||Medium|
| 106 |[Construct Binary Tree from Inorder and Postorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ConstructInorderPostorder/Solution.java)||Medium|
| 107 |[Binary Tree Level Order Traversal 2](https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/BinaryTreeLevelOrderTraversalII/Solution.java)||Easy|
| 110 |[Balanced Binary Tree](https://oj.leetcode.com/problems/balanced-binary-tree/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/BalancedBinaryTree/Solution.java)||Easy|
| 111 |[Minimum Depth of Binary Tree](https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/MinimumDepthBinaryTree/Solution.java)||Easy|
| 112 |[Path Sum](https://oj.leetcode.com/problems/path-sum/)|[Java](https://github.com/mirandaio/leetcode/tree/master/src/PathSum)||Easy|
| 114 |[Flatten Binary Tree to Linked List](https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/FlattenBinaryTree/Solution.java)||Medium|
| 118 |[Pascal's Triangle](https://oj.leetcode.com/problems/pascals-triangle/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/PascalsTriangle/Solution.java)||Easy|
| 119 |[Pascal's Triangle 2](https://oj.leetcode.com/problems/pascals-triangle-ii/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/PascalsTriangleII/Solution.java)||Easy|
| 125 |[Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/)|[Java](https://github.com/mirandaio/leetcode/tree/master/src/ValidPalindrome)||Easy|
| 133 |[Clone Graph](https://oj.leetcode.com/problems/clone-graph/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/CloneGraph/Solution.java)||Medium|
| 138 |[Copy List with Random Pointer](https://oj.leetcode.com/problems/copy-list-with-random-pointer/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/CopyListRandomPointer/Solution.java)| |Hard|
| 141 |[Linked List Cycle](https://oj.leetcode.com/problems/linked-list-cycle/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/LinkedListCycle/Solution.java)| |Medium|
| 142 |[Linked List Cycle 2](https://oj.leetcode.com/problems/linked-list-cycle-ii/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/LinkedListCycle2/Solution.java)| |Medium|
| 143 |[Reorder List](https://oj.leetcode.com/problems/reorder-list/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ReorderList/Solution.java)||Medium|
| 144 |[Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/BinaryTreePreorder/Solution.java)||Medium|
| 145 |[Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/BinaryTreePostorder/Solution.java)||Hard|
| 147 |[Insertion Sort List](https://oj.leetcode.com/problems/insertion-sort-list/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/InsertionSortList/Solution.java)||Medium|
| 148 |[Sort List](https://oj.leetcode.com/problems/sort-list/)|[Java](https://github.com/mirandaio/leetcode/tree/master/src/SortList)||Medium|
| 150 |[Evaluate Reverse Polish Notation](https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/)|[Java](https://github.com/mirandaio/leetcode/tree/master/src/EvaluateRPN)||Medium|
| 151 |[Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ReverseWordsString/Solution.java)||Medium|
| 155 |[Min Stack](https://oj.leetcode.com/problems/min-stack/)|[Java](https://github.com/mirandaio/leetcode/tree/master/src/MinStack)||Medium|
| 160 |[Intersection of Two Linked Lists](https://oj.leetcode.com/problems/intersection-of-two-linked-lists/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/IntersectionLinkedLists/Main.java)||Easy|
| 165 |[Compare Version Numbers](https://oj.leetcode.com/problems/compare-version-numbers/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/VersionNumbers/Solution.java)||Easy|
| 168 |[Excel Sheet Column Title](https://oj.leetcode.com/problems/excel-sheet-column-title/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ExcelColumn/Solution.java) | |Easy|
| 169 |[Majority Element](https://oj.leetcode.com/problems/majority-element/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/MajorityElement/Solution.java)||Easy|
| 171 |[Excel Sheet Column Number](https://oj.leetcode.com/problems/excel-sheet-column-number/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/ExcelColumnNumber/Solution.java)| |Easy|
| 172 |[Factorial Trailing Zeroes](https://oj.leetcode.com/problems/factorial-trailing-zeroes/)|[Java](https://github.com/mirandaio/leetcode/blob/master/src/FactorialTrailingZeroes/Solution.java)||Easy|
<file_sep>/src/PalindromeNumber/Solution.java
public class Solution {
public boolean isPalindrome(int x) {
if(x < 0)
return false;
int div = (int) Math.pow(10, (int) Math.log10(x));
int left;
int right;
while(x > 0) {
left = x / div;
right = x % 10;
if(left != right)
return false;
x = x % div;
x = x / 10;
div /= 100;
}
return true;
}
}
| 50981abc34cf10c142e3f1d6058cb94908b4af9c | [
"Markdown",
"Java"
] | 19 | Java | A-Bee-4/leetcode | 408dd98fb55411c12c3f05e5bb6713574898cd9d | 5053d388f956e90903492c0abf34232544b2da86 |
refs/heads/master | <file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Лаба_про_граф.Graphs;
namespace Лаба_про_граф
{
class Graph
{
public const string isolated = "ISOLATED";
public const string rootTag = "ROOT";
public const string finalTag = "FINAL";
public const string defaultTag = "DEFAULT";
public delegate void nodeCallback(Node n);
public delegate void nodeToLinkCallback(Node n, Node link);
public List<Node> nodes
{
get;
}
public List<Node> tempNodes;
public Node root
{
get;
}
public Graph(String rootData)
{
nodes = new List<Node>();
root = new Node(rootData);
nodes.Add(root);
}
public Graph(Node root)
{
nodes = new List<Node>();
this.root = root;
nodes.Add(root);
}
public void addNode(Node to, Node added, String linkData)
{
to.links.Add(new KeyValuePair<string, Node>(linkData,added));
nodes.Add(added);
}
public void addNode(Node node)
{
nodes.Add(node);
}
private Node finded;
public Node depthSearh(String data)
{
subSearh(root, data);
return finded;
}
private void subSearh(Node currNode, String data)
{
currNode.isChecked = true;
if (currNode.data == data)
{
finded = currNode;
}
foreach (var n in currNode.links)
{
if (!n.Value.isChecked)
{
subSearh(n.Value, data);
}
}
currNode.isChecked = false;
}
public void forAllExceptIsolated(nodeCallback nodeCallback)
{
forAllSub(nodeCallback, root);
}
public void forAll(nodeCallback callback)
{
tempNodes = new List<Node>();
forAllSub(callback, root);
forIsoalted(callback);
tempNodes.Clear();
}
private void forAllSub(nodeCallback callback, Node currNode)
{
currNode.isChecked = true;
tempNodes.Add(currNode);
callback(currNode);
foreach (var n in currNode.links)
{
if (!n.Value.isChecked)
{
forAllSub(callback, n.Value);
}
}
currNode.isChecked = false;
}
public void forAll(nodeCallback nodeCallback, nodeToLinkCallback linkCallback)
{
tempNodes = new List<Node>();
forAllSub(nodeCallback, linkCallback, root);
forIsoalted(nodeCallback, linkCallback);
tempNodes.Clear();
}
private void forAllSub(nodeCallback nodeCallback, nodeToLinkCallback linkCallback, Node currNode)
{
currNode.isChecked = true;
tempNodes.Add(currNode);
nodeCallback(currNode);
foreach (var n in currNode.links)
{
linkCallback(currNode, n.Value);
if (!n.Value.isChecked)
{
forAllSub(nodeCallback, linkCallback, n.Value);
}
}
currNode.isChecked = false;
}
private void forIsoalted(nodeCallback nodeCallback)
{
foreach (Node n in nodes)
{
if (!tempNodes.Contains(n))
{
forAllSub(nodeCallback, n);
}
}
}
private void forIsoalted(nodeCallback nodeCallback, nodeToLinkCallback linkCallback)
{
foreach (Node n in nodes)
{
if (!tempNodes.Contains(n))
{
forAllSub(nodeCallback, linkCallback, n);
}
}
}
public void link(Node from, Node to, String linkData)
{
if (from.links.Select(e => e.Value).Contains(to))
{
var link = from.links.Find(e => e.Value == to);
if (link.Key != linkData)
{
linkData = link.Key + linkData;
}
}
from.links.Add(new KeyValuePair<string, Node>(linkData,to));
forAllSub(e => { if (e.tag == Graph.isolated)
e.tag = Graph.defaultTag;},
to);
}
public void markIsolated()
{
tempNodes = new List<Node>();
forAllSub(e => { }, root);
foreach (Node n in nodes)
{
if (!tempNodes.Contains(n))
{
n.tag = isolated;
}
}
}
public void deleteByData(String data)
{
Node finded = depthSearh(data);
if (finded!=null)
delete(finded);
}
public void deleteFirstByTag(String tag)
{
Node finded = null;
forAll(e => { if (e.tag == tag) finded = e; });
if (finded!=null)
delete(finded);
}
public void deleteAllByTag(String tag)
{
List<Node> finded = new List<Node>();
forAll(e => { if (e.tag == tag) finded.Add(e); });
foreach (Node n in finded)
{
delete(n);
}
}
public void delete(Node node)
{
foreach (Node n in nodes)
{
n.links.RemoveAll(e => { return e.Value == node; });
}
nodes.Remove(node);
}
public void optimize()
{
List<Node> allStates = new List<Node>();
List<Node> endStates = new List<Node>();
foreach (Node n in nodes)
{
if (n.tag == Graph.finalTag)
{
endStates.Add(n);
}
else allStates.Add(n);
}
bool isChanged = true;
while(isChanged)
{
isChanged = false;
//Для каждого конечного состояния
//Собрать все узлы, ведущие в конечное сотояние
//Сгрупировать узлы по символам
//Создать из них конечные состояния
foreach (var finalState in endStates)
{
var temp = nodes.Where(
e =>
{
return e.links.Select(
u => u.Value).Contains(finalState);
});
var grouped = temp.GroupBy(
e => e.links.Find(
u => { return u.Value == finalState; }).Key);
}
}
//nodes.All(e => {if (e.tag == Graph.finalTag) endStates.Add(e) })
}
private Node uniteToFinalState(List<Node> nodes)
{
string resData = "";
nodes.ForEach(node => resData += (node.data + " "));
Node res = new Node(resData);
//nodes.ForEach(node =>
//{if (res.links.Contains(node)) })
return null;
}
}
}
<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;
using Лаба_про_граф.Graphs;
namespace Лаба_про_граф
{
public partial class Form1 : Form
{
int size = 30;
private Graph graph;
Node choosed;
bool isClicked = false;
bool isLinking = false;
bool isMovedOnNode = false;
int mouseX = 0;
int mouseY = 0;
int childNumber = 0;
int step = 0;
Node finded = new Node("");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
nameBox.Enabled = false;
timer1.Interval = 1;
timer1.Enabled = true;
stepButton.Visible = false;
}
private void initGraph()
{
Node root = new Node("root", Width / 2, Height / 2);
root.tag = Graph.rootTag;
root.size = 45;
graph = new Graph(root);
}
private void button1_Click(object sender, EventArgs e)
{
nameBox.Text = "child" + childNumber;
try
{
if (!nameBox.Enabled)
{
initGraph();
nameBox.Enabled = true;
return;
}
Node toAdd = new Node(nameBox.Text, this.Width / 2 - 30, this.Height / 2 - 30);
toAdd.size = 40;
if (isFinalState.Checked) toAdd.tag = Graph.finalTag;
graph.addNode(toAdd);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
childNumber++;
}
private void drawGraph(Graph graph, Graphics G)
{
subDraw(graph.root, G);
}
private void subDraw(Node root, Graphics G)
{
graph.forAll(e => {
drawNode(e, G);
}, (y,u)=> {
KeyValuePair<float, float> pos = getCrossing(u, y.centerX, y.centerY);
G.FillEllipse(Brushes.Blue, pos.Key - 3, pos.Value - 3, 6, 6);
G.DrawLine(Pens.Blue, y.centerX, y.centerY, pos.Key, pos.Value);
});
}
private KeyValuePair<float,float> getCrossing(Node node, int x, int y)
{
float absX = Math.Abs(node.centerX - x);
float absY = Math.Abs(node.centerY - y);
float hypotenuse = (float)Math.Sqrt(absX * absX + absY * absY);
float sin = absY / hypotenuse;
float cos = absX / hypotenuse;
float newY = node.size/2 * sin;
float newX = node.size/2 * cos;
if (node.centerX < x)
{
newX = node.centerX + newX;
}
else
{
newX = node.centerX - newX;
}
if (node.centerY < y)
{
newY = node.centerY + newY;
}
else
{
newY = node.centerY - newY;
}
return new KeyValuePair<float, float>(newX, newY);
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Middle)
{
if (!isLinking)
{
choosed = getNode(e.Location.X, e.Location.Y);
if (choosed!=null)
{
isLinking = true;
}
}
else
{
Node h = getNode(e.Location.X, e.Location.Y);
if (h!=null)
{
Me
graph.link(choosed, h, "new link");
isLinking = false;
//G.Clear(DefaultBackColor);
//drawGraph(graph);
}
}
}
else if (e.Button == MouseButtons.Left)
{
if (!isClicked)
{
choosed = getNode(e.X, e.Y);
if (choosed!=null)
{
isClicked = !isClicked;
}
}
else
isClicked = false;
isLinking = false;
}
else if (e.Button == MouseButtons.Right)
{
nodeContext.Show(mouseX, mouseY);
//choosed = getNode(e.Location.X, e.Location.Y);
//choosed.links.Clear();
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
mouseX = e.X;
mouseY = e.Y;
if (isLinking)
{
return;
}
if (isClicked)
{
choosed.X = e.X - choosed.size / 2;
choosed.Y = e.Y - choosed.size / 2;
}
else if (graph!=null)
{
Node ifFinded = getNode(e.X, e.Y);
}
}
private Node getNode(int x, int y)
{
if (graph == null)
{
return null;
}
foreach (Node n in graph.nodes)
{
if (Math.Sqrt(Math.Pow(x - n.centerX, 2) + Math.Pow(y - n.centerY, 2)) <= n.size)
{
return n;
}
}
return null;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (graph!=null)
drawGraph(graph,e.Graphics);
if (isLinking)
{
e.Graphics.DrawLine(Pens.Black, choosed.centerX, choosed.centerY, mouseX, mouseY);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
Invalidate();
}
private void button2_Click(object sender, EventArgs e)
{
step = 0;
stepButton.Visible = true;
}
private void button3_Click(object sender, EventArgs e)
{
switch (step)
{
case 0: graph.markIsolated(); step++; stepButton.Text = "Шаг 2"; statusStrip.Text = "Изолированные вершины помечены"; break;
case 1: graph.deleteAllByTag(Graph.isolated); step++; stepButton.Text = "Шаг 3"; statusStrip.Text = "Изолированные вершины удалены"; break;
case 2: graph.optimize(); step = 0; stepButton.Text = "Шаг 1"; statusStrip.Text = "Оптимизация выполнена"; break;
}
}
private void drawNode(Node e, Graphics G)
{
if (e.tag == Graph.rootTag)
{
G.DrawEllipse(Pens.Green, e.X, e.Y, e.size, e.size);
G.FillEllipse(Brushes.ForestGreen, e.X, e.Y, e.size, e.size);
G.DrawString(e.data, DefaultFont, Brushes.Black, e.centerX, e.centerY);
}
else if (e.tag == Graph.isolated)
{
G.DrawEllipse(Pens.Yellow, e.X, e.Y, e.size, e.size);
G.FillEllipse(Brushes.YellowGreen, e.X, e.Y, e.size, e.size);
G.DrawString(e.data, DefaultFont, Brushes.Black, e.centerX, e.centerY);
}
else if (e.tag == Graph.finalTag)
{
G.DrawEllipse(Pens.Red, e.X, e.Y, e.size, e.size);
G.DrawEllipse(Pens.Red, e.X-3, e.Y-3, e.size + 6, e.size + 6);
G.DrawString(e.data, DefaultFont, Brushes.Black, e.centerX, e.centerY);
}
else
{
G.DrawEllipse(Pens.Red, e.X, e.Y, e.size, e.size);
G.DrawString(e.data, DefaultFont, Brushes.Black, e.centerX, e.centerY);
}
}
private void isFinalState_CheckedChanged(object sender, EventArgs e)
{
}
private void nodeContext_Opening(object sender, CancelEventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Лаба_про_граф.Graphs
{
class Node
{
public List<KeyValuePair<String, Node>> links
{
get;
}
public String data
{
get;
}
public String tag
{
get;
set;
}
public int X
{
get;
set;
}
public int Y
{
get;
set;
}
public int size
{
get;
set;
}
public int centerX
{
get
{
return X + size / 2;
}
}
public int centerY
{
get
{
return Y + size / 2;
}
}
public bool isChecked
{
get;
set;
}
public Node(String data)
{
isChecked = false;
links = new List<KeyValuePair<string, Node>>();
this.data = data;
X = 50;
Y = 50;
this.size = 20;
}
public Node(String data, int x, int y) : this(data)
{
this.X = x;
this.Y = y;
}
}
}
| 7a7086f75e2899d2c63c31859d3ccbe8e22c0dd7 | [
"C#"
] | 3 | C# | GithubSupport6/Automats.Graph | 72e7a832f4a51cf197cac7cca40311d22950c554 | 84d8db5df94fc3f853202d1b1b3d312f74327961 |
refs/heads/master | <file_sep>$("#portfolios > li").click(function () {
let num = $(this).index() + 1;
console.log(num);
if (num == 1) {
$(".detail_portfolio").addClass("on");
$("body").css("overflow", "hidden");
}
})
$("#closeBtn").click(function (e) {
e.preventDefault();
$(".detail_portfolio").removeClass("on");
$("body").css("overflow", "hidden scroll");
}) | 6b112d7f524f6038f6db11d0fdd0b7d956626fa1 | [
"JavaScript"
] | 1 | JavaScript | ChoYoungHo-web/portfolio | 0471167e19a0361cf85cd6157674f7c22333258d | 5c57e72141f695f00fe7aa681bc3b4bc5b335cba |
refs/heads/main | <file_sep>package com.adn.mutante;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AdnMutanteApplication {
public static void main(String[] args) {
SpringApplication.run(AdnMutanteApplication.class, args);
}
}
<file_sep>package com.adn.mutante.repository.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.adn.mutante.entity.Dna;
import com.adn.mutante.persistence.crud.MutanteCrudRepository;
import com.adn.mutante.repository.MutanteRepository;
@Repository
public class MutanteRepositoryImpl implements MutanteRepository {
@Autowired
private MutanteCrudRepository mutanteCrudRepository;
@Override
public List<Dna> getAll() {
return (List<Dna>) mutanteCrudRepository.listarAdnMutanteID();
}
@Override
public Dna save(Dna mutante) {
return mutanteCrudRepository.save(mutante);
}
}
<file_sep>package com.adn.mutante.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.adn.mutante.entity.Dna;
import com.adn.mutante.entity.ValidacionesADN;
import com.adn.mutante.repository.MutanteRepository;
@Service
public class MutanteService {
@Autowired
private MutanteRepository mutanteRepository;
public static boolean isMutant(String[] dnaAux) {
boolean snMutante = false;
int posLetraCadenaAux;
int posCadenaAux;
String cadena;
int cont = 0;
ValidacionADN validar = new ValidacionADN();
for(int posCadena = 0; posCadena<dnaAux.length; posCadena++){ // Ciclo que permite recorrer todo el arreglo
dnaAux[posCadena] = dnaAux[posCadena] + "*";
cadena = dnaAux[posCadena];
for (int posLetraCadena = 0; posLetraCadena<(cadena.length()-1); posLetraCadena++) { //Ciclo que permite recorre toda la cadena de caracteres
boolean posibleMutante = false;
char letra = cadena.charAt(posLetraCadena);
if (letra == cadena.charAt(posLetraCadena + 1)) {
posibleMutante = validar.validarCadenaADNMutante(posCadena, posLetraCadena, posCadena, (posLetraCadena + 1), letra, cadena, dnaAux);
if (posibleMutante) {
cont++;
}
}
if (posibleMutante==false) {
if (posCadena != cadena.length()) {
posLetraCadenaAux = posLetraCadena;
posCadenaAux = posCadena;
posCadenaAux++; //Aumenta para tomar la siguiente fila
posLetraCadenaAux--; //Disminuye para tomar la letra anterior
for (int i = 0; i<=2; i++) {
if(posLetraCadenaAux != -1 && posLetraCadenaAux < (cadena.length()-1) && posCadenaAux < dnaAux.length ) {
if (letra == dnaAux[posCadenaAux].charAt(posLetraCadenaAux)) {
posibleMutante = validar.validarCadenaADNMutante(posCadena, posLetraCadena, posCadenaAux, posLetraCadenaAux, letra, cadena, dnaAux);
if (posibleMutante) {
cont++;
}
}
}
posLetraCadenaAux++;
}
}
}
}
}
if (cont > 0) {
snMutante = true;
}
return snMutante;
}
public List<Dna> getAll() {
return mutanteRepository.getAll();
}
public Dna save(Dna dna) {
return mutanteRepository.save(dna);
}
public ValidacionesADN validacion() {
List<Dna> mutante = mutanteRepository.getAll();
int contMutantes = 0;
int contNOMutantes = 0;
ValidacionesADN validacionesADN = new ValidacionesADN();
for (Dna dna : mutante) {
String[] Auxdna = new String[dna.getDna().length];
System.arraycopy(dna.getDna(), 0, Auxdna, 0, dna.getDna().length);
if (isMutant(Auxdna)) {
contMutantes++;
}else {
contNOMutantes++;
}
}
validacionesADN.setCount_mutant_dna(contMutantes);
validacionesADN.setCount_human_dna(contNOMutantes);
return validacionesADN;
}
}
<file_sep>API REST para detectar secuencias de ADN
## Objetivo
Evaluar conocimientos en desarrollo API/Rest a través de la elaboración el proyecto para identificar el adn mutante para Magneto
## Introducción
Magneto quiere reclutar la mayor cantidad de mutantes para poder luchar contra los X-Men. En donde se recibe como parámetro un array de Strings que representan cada fila de una tablade (NxN) con la secuencia del ADN. Las letras de los Strings solo pueden ser: (A,T,C,G), las cuales representa cada base nitrogenada del ADN.
## Status del Proyecto
Nivel 3 completo:
* API REST con el objetivo de detectar ADN mutante desplegado en Heroku.
* Agregado de estadísticas y persistencia en Base de Datos postgreSQL.
* Test Coverage: 83%
## Instrucciones para su prueba
El servicio se encuentra desplegado en [https://adnmutantes.herokuapp.com/](https://adnmutantes.herokuapp.com/)
El servicio actualmente cuenta con los siguientes métodos:
* Método POST para detectar si un ADN dado es mutante:<br><br>
La URL del método es [https://adnmutantes.herokuapp.com/adn-mutante/api/mutant](https://adnmutantes.herokuapp.com/adn-mutante/api/mutant)<br><br>
Se puede detectar si un humano es mutante enviando la secuencia de ADN mediante un HTTP POST con un Json el cual tenga el siguiente formato:<br><br>
POST → /mutant/<br />
{<br />
"dna":["ATGCGA","CAGTGC","TTATGT","AGAAGG","CCCCTA","TCACTG"]<br />
}<br><br>
En caso de verificar que el ADN enviado es mutante, el método devuelve como respuesta un HTTP 200-OK, en caso contrario un
403-Forbidden <br><br>
* Método GET para obtener las estadísticas de las verificaciones de ADN para Magneto<br><br>
La URL del método es [https://adnmutantes.herokuapp.com/adn-mutante/api/stats](https://adnmutantes.herokuapp.com/adn-mutante/api/stats)<br><br>
## Descarga del código fuente
Este proyecto utiliza Apache Maven embebido. Antes de empezar, asegurese de descargarlo e instalarlo. Luego, Maven descargará automáticamente las librerias requeridas por el proyecto
#### Repositorio
El código se encuentra alojado en GitHub. Para descargarlo necesita un cliente git, que puede encontrarlo en https://git-scm.com/downloads
* Cree una carpeta en donde se incluirá el código fuente<br>
* Abra su consola y posicionese en la carpeta previamente creada<br>
* Ejecute el comando<br>
git clone https://github.com/cesarlatorre2021/mutante.git
Luego de que termine la descarga, usted tendrá clonado el branch master en la carpeta previamente creada.
## Environment
* Open jdk version 11
* IDE: Eclipse IDE
* PostgreSQL
<file_sep>package com.adn.mutante.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "mutante")
public class Dna {
@Id
@Column (name = "dna")
private String[] dna;
public String[] getDna() {
return dna;
}
public void setDna(String[] dna) {
this.dna = dna;
}
}
<file_sep>package com.adn.mutante.persistence.crud;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.adn.mutante.entity.Dna;
public interface MutanteCrudRepository extends CrudRepository <Dna, Integer>{
@Query(value = "SELECT * "
+ " FROM MUTANTE", nativeQuery = true)
List<Dna> listarAdnMutanteID();
}
<file_sep>server.port=9090
server.servlet.context-path=/adn-mutante/api
spring.datasource.url=jdbc:postgresql://localhost/adn-mutante
spring.datasource.username=postgres
spring.datasource.password=<PASSWORD> | 493b600a45e5711b54350d73939199d5dd7a6e63 | [
"Markdown",
"Java",
"INI"
] | 7 | Java | cesarlatorre2021/mutante | 2f714b0a1279af7a3f438b7a9b9443811adaaf61 | c126e17ac94db89baaaa71d2481d1cc4329ea9ef |
refs/heads/master | <file_sep>package br.com.serpente;
import java.awt.Color;
public interface Constantes {
public static final byte TOTAL_FASES = 2;
public static final byte TOTAL_POR_FASE = 5;
public static final byte LADO_QUADRADO = 10;
public static final Color COR_CABECA = Color.BLUE;
public static final Color COR_CORPO = Color.BLACK;
public static final short INTERVALO_MOVIMENTO = 200;
public static final short INTERVALO_DECREMENTO = 50;
public static final int COMPRIMENTO_SERPENTE = TOTAL_FASES * TOTAL_POR_FASE;
public static final short LARGURA_JANELA = 500;
public static final short ALTURA_JANELA = 400;
} | f008260e6287ca00e6789cb055c9d2ad7b3f0d83 | [
"Java"
] | 1 | Java | gilluan/serpente | 8d3ff23e358f624c0c609d8dd8cefb95894169fc | 71875ae29bc7aa6b3ce5120384ad36db97479c10 |
refs/heads/main | <repo_name>NateTheDev1/rateyours-server<file_sep>/src/db/models/Categories.ts
import BaseModel from './BaseModel';
class Category extends BaseModel {
id!: number;
title!: string;
caption!: string;
iconKey?: string;
approved!: boolean;
banner?: string;
static get tableName() {
return 'categories';
}
}
export default Category;
<file_sep>/src/resolvers/index.ts
import { entityMutationResolvers } from './mutation/entity';
import { searchMutationResolvers } from './mutation/search';
import { userMutationResolvers } from './mutation/user';
import { entityResolvers } from './query/entity';
import { reviewQueryResolvers } from './query/review';
import { reviewResolvers } from './query/review/Review';
import { CategoryResolvers, searchQueryResolvers } from './query/search';
import { userQueryResolvers } from './query/user';
export const resolvers: Resolvers.Resolvers = {
Query: {
...userQueryResolvers,
...searchQueryResolvers,
...entityResolvers,
...reviewQueryResolvers
},
Mutation: {
...userMutationResolvers,
...searchMutationResolvers,
...entityMutationResolvers
},
Review: {
...reviewResolvers
},
Category: {
...CategoryResolvers
}
};
<file_sep>/src/resolvers/mutation/user/deleteSearchHistory.ts
import SearchHistory from '../../../db/models/SearchHistory';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
export const deleteSearchHistory: Resolvers.MutationResolvers['deleteSearchHistory'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Mutation: deleteSearchHistory');
verifyAuthentication(context, true);
await SearchHistory.query().delete().where({ user: args.id });
return true;
};
<file_sep>/src/resolvers/query/review/index.ts
import { hasReviewed } from './hasReviewed';
import { searchReviews } from './searchReviews';
export const reviewQueryResolvers = {
searchReviews,
hasReviewed
};
<file_sep>/src/resolvers/query/search/getPopularSearches.ts
import Category from '../../../db/models/Categories';
import PopularSearches from '../../../db/models/PopularSearches';
export const getPopularSearches: Resolvers.QueryResolvers['getPopularSearches'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Query: getPopularSearches');
const popularSearches = await PopularSearches.query()
.orderBy('searches', 'DESC')
.limit(5);
return popularSearches;
};
<file_sep>/src/db/models/Entity.ts
import BaseModel from './BaseModel';
class Entity extends BaseModel {
id!: number;
name!: string;
type!: string;
ownedBy?: number;
// Json object including type specific data like location, teacher name etc.
specialContent?: string;
views?: number = 0;
static get tableName() {
return 'entities';
}
}
export default Entity;
<file_sep>/src/resolvers/mutation/entity/addReview.ts
import Reviews from '../../../db/models/Reviews';
//@ts-ignore
export const addReview: Resolvers.MutationResolvers['addReview'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Mutation: addReview' + ' ' + args.review.type);
const {
type,
title,
createdBy,
body,
tags,
rating,
specialContent,
entity
} = args.review;
if (args.hasReviewed) {
await Reviews.query().delete().where({ createdBy, entity });
}
let review = await Reviews.query().insertAndFetch({
type,
title,
createdBy,
createdAt: new Date().toString(),
body,
tags,
rating,
specialContent,
entity
});
return { ...review };
};
<file_sep>/src/resolvers/mutation/user/index.ts
import { createUser } from './createUser';
import { deleteSearchHistory } from './deleteSearchHistory';
import { login } from './login';
import { resetPassword } from './resetPassword';
import { sendPasswordReset } from './sendPasswordReset';
import { updateUserDetails } from './updateUserDetails';
export const userMutationResolvers = {
createUser,
login,
sendPasswordReset,
resetPassword,
updateUserDetails,
deleteSearchHistory
};
<file_sep>/src/resolvers/mutation/entity/index.ts
import { addReview } from './addReview';
import { requestOwnership } from './requestOwnership';
import { updateEntityViews } from './updateEntityViews';
export const entityMutationResolvers = {
addReview,
updateEntityViews,
requestOwnership
};
<file_sep>/src/resolvers/query/user/hasRequestedProfilePriority.ts
import ProfilePriorityRequests from '../../../db/models/ProfilePriorityRequests';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
export const hasRequestedProfilePriority: Resolvers.QueryResolvers['hasRequestedProfilePriority'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info(
'Query: hasRequestedProfilePriority',
args.entityId
);
verifyAuthentication(context);
const request = await ProfilePriorityRequests.query()
.where({
requestedBy: context.session?.userId,
entityId: args.entityId
})
.first();
if (!request) {
return false;
} else {
return true;
}
};
<file_sep>/src/db/db-config.ts
import dotenv from 'dotenv';
dotenv.config();
const pg = require('pg');
pg.defaults.ssl = true;
const config = {
development: {
client: 'pg',
connection: process.env.DB_URL,
ssl: { rejectUnauthorized: false }
}
};
export default config;
<file_sep>/src/resolvers/query/user/getUserActivity.ts
import { ApolloError } from 'apollo-server-express';
import Reviews from '../../../db/models/Reviews';
import User from '../../../db/models/User';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
//@ts-ignore
export const getUserActivity: Resolvers.QueryResolvers['getUserActivity'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Query: getUserActivity', args.id);
verifyAuthentication(context);
const user = await User.query().findById(args.id);
if (!user) {
throw new ApolloError('User does not exist', '400');
}
const revs = await Reviews.query().where({ createdBy: args.id });
return { reviews: revs };
};
<file_sep>/src/resolvers/query/search/getCategory.ts
import Category from '../../../db/models/Categories';
//@ts-ignore
export const getCategory: Resolvers.QueryResolvers['getCategory'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Query: getCategory');
const category = await Category.query()
.findById(args.id)
.where({ approved: true })
.first();
return category;
};
<file_sep>/src/resolvers/query/review/Review.ts
import { ReviewVotes } from '../../../db/models/ReviewVotes';
import User from '../../../db/models/User';
export const reviewResolvers: Resolvers.ReviewResolvers = {
createdByUser: async (parent, args, context: Services.ServerContext) => {
context.logger.info('createdByUser');
const user = await User.query().findById(parent.createdBy);
return user;
},
upvotes: async (parent, args, context: Services.ServerContext) => {
context.logger.info('upvotes');
const upvotes = await ReviewVotes.query().where({
reviewId: parent.id,
voteType: 'UPVOTE'
});
return upvotes.length;
},
downvotes: async (parent, args, context: Services.ServerContext) => {
context.logger.info('downvotes');
const downvotes = await ReviewVotes.query().where({
reviewId: parent.id,
voteType: 'DOWNVOTE'
});
return downvotes.length;
}
};
<file_sep>/src/utils/verifyAuthentication.ts
import { AuthenticationError } from 'apollo-server-express';
export const verifyAuthentication = (
context: Services.ServerContext,
reverse: boolean = false
) => {
// if (!context.authenticated && !reverse) {
// throw new AuthenticationError('Unauthorized');
// }
// if (context.authenticated && reverse) {
// throw new AuthenticationError('Unauthorized. Already logged in.');
// }
};
<file_sep>/scripts/import-actors.ts
import jsonData from './actors.json';
import Entity from '../src/db/models/Entity';
type PropertyJSONType = {
name: string;
};
const main = async () => {
const json: PropertyJSONType[] = JSON.parse(
JSON.stringify(jsonData as any)
);
for (let i = 0; i < json.length; i++) {
await Entity.query().insert({
name: json[i].name,
type: 'People',
specialContent: {
field: 'actor'
}
});
console.log(`${i}/${json.length}`);
}
};
main();
<file_sep>/src/db/models/SearchHistory.ts
import BaseModel from './BaseModel';
class SearchHistory extends BaseModel {
id!: number;
query!: string;
user!: number;
static get tableName() {
return 'user_search_history';
}
}
export default SearchHistory;
<file_sep>/src/utils/logger.ts
import debugsx from 'debug-sx';
import dotenv from 'dotenv';
dotenv.config();
process.env['DEBUG'] = '*::INFO, *::WARN, *::ERR';
export const logger: debugsx.IDefaultLogger & {
err?: any;
} = debugsx.createDefaultLogger('main');
logger.err = debugsx('::ERR');
const h: debugsx.IHandler = debugsx.createConsoleHandler('stdout', '*');
debugsx.addHandler(h);
<file_sep>/src/services/PopularSearchService.ts
import PopularSearches from '../db/models/PopularSearches';
export class PopularSearchService {
query: string;
constructor(query: string) {
this.query = query;
}
async exists() {
const exists = await PopularSearches.query()
.where({
query: this.query
})
.first();
if (exists) {
return true;
} else {
return false;
}
}
async insert() {
await PopularSearches.query().insert({
query: this.query,
searches: 1
});
}
async update() {
const exists = await PopularSearches.query()
.where({ query: this.query })
.first();
await PopularSearches.query()
.patch({
query: this.query,
searches: exists.searches + 1
})
.where({ query: this.query });
}
}
<file_sep>/src/resolvers/query/review/hasReviewed.ts
import Reviews from '../../../db/models/Reviews';
export const hasReviewed: Resolvers.QueryResolvers['hasReviewed'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Query: hasReviewed' + ' ' + args.entityId);
const reviewed = await Reviews.query()
.where({ createdBy: args.userId, entity: args.entityId })
.first();
return reviewed ? true : false;
};
<file_sep>/src/resolvers/mutation/search/requestProfilePriority.ts
import ProfilePriorityRequests from '../../../db/models/ProfilePriorityRequests';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
export const requestProfilePriority: Resolvers.MutationResolvers['requestProfilePriority'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Mutation: requestProfilePriority');
verifyAuthentication(context);
await ProfilePriorityRequests.query().insert({
...args.request
});
return true;
};
<file_sep>/src/services/AuthenticationService.ts
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
export class AuthenticationService {
password: string;
constructor(password: string) {
this.password = password;
}
async hashPassword(): Promise<string> {
const salt = await bcrypt.genSaltSync(10);
return await bcrypt.hashSync(this.password, salt);
}
async verifyPassword(password: string) {
return await bcrypt.compareSync(password, this.password);
}
}
export const signJWT = async (
session: Services.ServerContext
): Promise<string> => {
const JWTOptions: jwt.SignOptions = {
expiresIn: '30d'
};
console.info('Creating JWT');
console.log(session.session);
const signed = await jwt.sign(
{ ...session.session },
process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'TEST'
? 'supersecret'
: process.env.SESSION_SECRET!,
JWTOptions
);
session.logger.info('JWT Created', signed.toString());
return signed;
};
<file_sep>/src/db/models/ProfilePriorityRequests.ts
import BaseModel from './BaseModel';
class ProfilePriorityRequests extends BaseModel {
id!: number;
requestedBy!: number;
entityId!: number;
why?: string;
static get tableName() {
return 'profile_priority_requests';
}
}
export default ProfilePriorityRequests;
<file_sep>/src/db/models/Reviews.ts
import BaseModel from './BaseModel';
class Reviews extends BaseModel {
id!: number;
type!: string;
title!: string;
createdBy!: number;
createdAt!: string;
body!: string;
tags: string[] = [];
rating!: number;
entity!: number;
// Json object including type specific data like location, teacher name etc.
specialContent?: string;
static get tableName() {
return 'reviews';
}
}
export default Reviews;
<file_sep>/src/resolvers/mutation/entity/updateEntityViews.ts
import { ApolloError } from 'apollo-server-express';
import Entity from '../../../db/models/Entity';
import Reviews from '../../../db/models/Reviews';
export const updateEntityViews: Resolvers.MutationResolvers['updateEntityViews'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info(
'Mutation: updateEntityViews' + ' ' + args.entityId
);
const viewCount = await Entity.query().findById(args.entityId);
if (viewCount) {
try {
await Entity.query().patchAndFetchById(args.entityId, {
views: (viewCount.views ?? 0) + args.viewCount
});
return true;
} catch (e) {
throw new ApolloError('Could not update view count', '500');
}
} else {
return false;
}
};
<file_sep>/src/resolvers/query/user/getUser.ts
import { ApolloError } from 'apollo-server-express';
import User from '../../../db/models/User';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
export const getUser: Resolvers.QueryResolvers['getUser'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Query: getUser', args.id);
verifyAuthentication(context);
const user = await User.query().findById(args.id);
if (!user) {
throw new ApolloError('User does not exist', '400');
}
return user;
};
<file_sep>/src/resolvers/query/search/search.ts
import { raw } from 'objection';
import Entity from '../../../db/models/Entity';
import Reviews from '../../../db/models/Reviews';
import SearchHistory from '../../../db/models/SearchHistory';
import { PopularSearchService } from '../../../services/PopularSearchService';
//@ts-ignore
export const search: Resolvers.QueryResolvers['search'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Query: search');
const { minRating, maxRating, sortyBy, categoryRestriction } = args.filters;
// User search history tracking
if (context.authenticated && context.session) {
const history = await SearchHistory.query()
.where({
user: context.session.userId
})
.orderBy('id', 'DESC');
if (history.length === 5) {
await SearchHistory.query().deleteById(
history[history.length - 1].id
);
}
await SearchHistory.query().insert({
query: args.query,
user: context.session.userId
});
}
// Popular searches tracking
const searchService = new PopularSearchService(args.query);
const hasBeenSearched = await searchService.exists();
if (hasBeenSearched) {
await searchService.update();
} else {
await searchService.insert();
}
let entities = [];
let total = 0;
let entityPool = [];
if (categoryRestriction && !args.first) {
total = (
await Reviews.query()
.where(
raw(
`rating >= ${minRating} AND rating <= ${maxRating} AND UPPER(title) LIKE UPPER('%${args.query}%')`
)
)
.where({ type: categoryRestriction })
.orderBy('rating', 'DESC')
).length;
entities = await Reviews.query()
.where(
raw(
`rating >= ${minRating} AND rating <= ${maxRating} AND UPPER(title) LIKE UPPER('%${args.query}%')`
)
)
.where({ type: categoryRestriction })
.orderBy('rating', 'DESC')
.limit(24);
entityPool = await Entity.query()
.where(raw(`UPPER(name) LIKE UPPER('%${args.query}%')`))
.where({ type: categoryRestriction })
.limit(150);
} else if (categoryRestriction && args.first) {
total = (
await Reviews.query()
.where(
raw(
`rating >= ${minRating} AND rating <= ${maxRating} AND UPPER(title) LIKE UPPER('%${args.query}%')`
)
)
.where({ type: categoryRestriction })
.orderBy('rating', 'DESC')
).length;
entities = await Reviews.query()
.where(
raw(
`rating >= ${minRating} AND rating <= ${maxRating} AND UPPER(title) LIKE UPPER('%${args.query}%')`
)
)
.where({ type: categoryRestriction })
.orderBy('rating', 'DESC')
.offset(args.first)
.limit(24);
entityPool = await Entity.query()
.where(raw(`UPPER(name) LIKE UPPER('%${args.query}%')`))
.where({ type: categoryRestriction })
.limit(150);
} else if (!categoryRestriction && args.first) {
total = (
await Reviews.query()
.where(
raw(
`rating >= ${minRating} AND rating <= ${maxRating} AND UPPER(title) LIKE UPPER('%${args.query}%')`
)
)
.orderBy('rating', 'DESC')
).length;
entities = await Reviews.query()
.where(
raw(
`rating >= ${minRating} AND rating <= ${maxRating} AND UPPER(title) LIKE UPPER('%${args.query}%')`
)
)
.orderBy('rating', 'DESC')
.offset(args.first)
.limit(24);
entityPool = await Entity.query()
.where(raw(`UPPER(name) LIKE UPPER('%${args.query}%')`))
.limit(150);
} else {
total = (
await Reviews.query()
.where(
raw(
`rating >= ${minRating} AND rating <= ${maxRating} AND UPPER(title) LIKE UPPER('%${args.query}%')`
)
)
.orderBy('rating', 'DESC')
).length;
entities = await Reviews.query()
.where(
raw(
`rating >= ${minRating} AND rating <= ${maxRating} AND UPPER(title) LIKE UPPER('%${args.query}%')`
)
)
.orderBy('rating', 'DESC')
.limit(24);
entityPool = await Entity.query()
.where(raw(`UPPER(name) LIKE UPPER('%${args.query}%')`))
.limit(150);
}
return { reviews: entities, total, entities: entityPool };
};
<file_sep>/src/db/models/EntityOwnershipRequest.ts
import BaseModel from './BaseModel';
class EntityOwnershipRequest extends BaseModel {
id!: number;
requestedBy!: number;
approved!: boolean;
entity!: number;
static get tableName() {
return 'entity_ownership_requests';
}
}
export default EntityOwnershipRequest;
<file_sep>/src/resolvers/mutation/user/sendPasswordReset.ts
import User from '../../../db/models/User';
import { v4 as uuidv4 } from 'uuid';
import sgMail from '@sendgrid/mail';
import { PasswordResets } from '../../../db/models/PasswordResets';
export const sendPasswordReset: Resolvers.MutationResolvers['sendPasswordReset'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Resolvers: Mutation: sendPasswordReset');
const user = await User.query().where({ email: args.email }).first();
if (!user) {
throw new Error('No User!');
}
const code = uuidv4();
try {
await PasswordResets.query()
.delete()
.where({ forEmail: user.email });
await PasswordResets.query().insert({
code,
forEmail: user.email
});
} catch (e) {
throw new Error('There was an error completing your request.');
}
sgMail.setApiKey(process.env.SENDGRID_API_KEY as string);
try {
await sgMail.send({
to: [user.email],
from: {
email: '<EMAIL>',
name: 'Rateit'
},
subject: 'You have requested to reset your password on Rateit',
templateId: 'd-efe00811b1b54649a970f34b09cca494',
personalizations: [
{
to: [{ email: user.email }],
subject:
'You have requested to reset your password on Rateit',
dynamicTemplateData: {
resetLink: `https://www.yourateit.io/forgot-password/reset/${code}`
},
//@ts-ignore
dynamic_template_data: {
resetLink: `https://www.yourateit.io/forgot-password/reset/${code}`
}
}
],
dynamicTemplateData: {
resetLink: `https://www.yourateit.io/forgot-password/reset/${code}`
}
});
} catch (e) {
throw new Error('There was an error completing your request.');
}
return true;
};
<file_sep>/src/resolvers/mutation/user/createUser.ts
import { ApolloError } from 'apollo-server-express';
import User from '../../../db/models/User';
import {
AuthenticationService,
signJWT
} from '../../../services/AuthenticationService';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
import sgMail from '@sendgrid/mail';
export const createUser: Resolvers.MutationResolvers['createUser'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Mutation: createUser');
verifyAuthentication(context, true);
const existing = await User.query()
.where({ email: args.user.email })
.first();
sgMail.setApiKey(process.env.SENDGRID_API_KEY as string);
if (existing) {
throw new ApolloError('A user with this name already exists.', '409');
}
const authService = new AuthenticationService(args.user.password);
const created = await User.query().insertAndFetch({
...args.user,
password: await authService.hashPassword(),
accountType: 'default'
});
await sgMail.send({
to: [created.email],
from: {
email: '<EMAIL>',
name: 'Rateit'
},
subject: 'Thank you for signing up for Rateit!',
templateId: 'd-029b5ef1fb8c473daa553028f48ccdd9'
});
context.session = {
username: created.email,
userId: created.id
};
const token = await signJWT(context);
return { user: created, token };
};
<file_sep>/src/resolvers/mutation/user/updateUserDetails.ts
import User from '../../../db/models/User';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
export const updateUserDetails: Resolvers.MutationResolvers['updateUserDetails'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Mutation: updateUserDetails');
verifyAuthentication(context);
const { fullName, accountType, birthday, userId } = args.patch;
try {
await User.query().patchAndFetchById(userId, {
fullName,
accountType,
birthday
});
} catch (e) {
throw new Error('Error processing your request.');
}
return true;
};
<file_sep>/src/db/models/User.ts
import BaseModel from './BaseModel';
type AccountType = 'DEFAULT' | 'VERIFIED' | 'SPONSORED';
class User extends BaseModel {
id!: number;
fullName?: string = '';
birthday?: string = '';
accountType!: string;
email!: string;
password!: string;
static get tableName() {
return 'users';
}
}
export default User;
<file_sep>/src/index.ts
import { ApolloServer } from 'apollo-server-express';
import express from 'express';
import e from 'express';
import { resolvers } from './resolvers';
// Other
import dotenv from 'dotenv';
import { logger } from './utils/logger';
import { createServer } from 'http';
import { initializeMiddleware } from './services/MiddlewareService';
import { createContext } from './services/ContextService';
import { typeDefs } from './schema';
import * as Sentry from '@sentry/node';
import * as Tracing from '@sentry/tracing';
Sentry.init({
dsn: process.env.SENTRY_DSN,
tracesSampleRate: 1.0
});
dotenv.config();
const PORT = process.env.PORT;
logger.info('Starting up...');
const server = new ApolloServer({
typeDefs: typeDefs,
resolvers,
context: async ({ req, res }: { req: e.Request; res: e.Response }) => {
logger.info('Running Context');
return await createContext(req, res);
},
subscriptions: {
path: '/subscriptions',
onConnect: (connectionParams, webSocket, context) => {
logger.info('Connected!');
},
onDisconnect: (webSocket, context) => {
logger.warn('Disconnected!');
}
}
});
const app = express();
initializeMiddleware(app);
server.applyMiddleware({ app: app as any });
const httpServer = createServer(app);
server.installSubscriptionHandlers(httpServer);
httpServer.listen(PORT, () => {
console.log(
`🚀 Subscription endpoint ready at ws://localhost:${PORT}${server.subscriptionsPath}`
);
console.info(
`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`
);
});
<file_sep>/@types/resolvers.d.ts
import { GraphQLResolveInfo } from 'graphql';
import gql from 'graphql-tag';
declare global { namespace Resolvers {
type Maybe<T> = T | undefined;
type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
export type RequireFields<T, K extends keyof T> = { [X in Exclude<keyof T, K>]?: T[X] } & { [P in K]-?: NonNullable<T[P]> };
/** All built-in and custom scalars, mapped to their actual values */
interface Scalars {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
}
interface AddCategoryInput {
title: Scalars['String'];
iconKey?: Maybe<Scalars['String']>;
caption: Scalars['String'];
approved: Scalars['Boolean'];
}
interface Category {
__typename?: 'Category';
id: Scalars['Int'];
title: Scalars['String'];
caption: Scalars['String'];
iconKey?: Maybe<Scalars['String']>;
approved: Scalars['Boolean'];
banner?: Maybe<Scalars['String']>;
topTen: CategoryTopTen;
}
interface CategoryTopTen {
__typename?: 'CategoryTopTen';
mostViewed: Array<Maybe<Entity>>;
mostRecent: Array<Maybe<Entity>>;
}
interface CreateEntityInput {
type: Scalars['String'];
ownedBy?: Maybe<Scalars['Int']>;
specialContent: Scalars['String'];
}
interface CreateUserInput {
fullName?: Maybe<Scalars['String']>;
birthday?: Maybe<Scalars['String']>;
email: Scalars['String'];
password: Scalars['String'];
}
interface CreateUserReturn {
__typename?: 'CreateUserReturn';
user: User;
token: Scalars['String'];
}
interface Entity {
__typename?: 'Entity';
id: Scalars['Int'];
type: Scalars['String'];
ownedBy?: Maybe<User>;
specialContent?: Maybe<Scalars['String']>;
name: Scalars['String'];
views?: Maybe<Scalars['Int']>;
}
interface EntityOwnershipRequest {
__typename?: 'EntityOwnershipRequest';
id: Scalars['Int'];
requestedBy: Scalars['Int'];
entity: Scalars['Int'];
approved: Scalars['Boolean'];
}
interface EntitySearchResponse {
__typename?: 'EntitySearchResponse';
entities: Array<Maybe<Entity>>;
total: Scalars['Int'];
}
interface LoginInput {
email: Scalars['String'];
password: Scalars['String'];
}
interface Mutation {
__typename?: 'Mutation';
addCategory: Category;
addReview: Review;
updateEntityViews: Scalars['Boolean'];
requestOwnership: Scalars['Boolean'];
voteReview: Scalars['Boolean'];
requestProfilePriority: Scalars['Boolean'];
createUser: CreateUserReturn;
login: CreateUserReturn;
sendPasswordReset: Scalars['Boolean'];
resetPassword: Scalars['Boolean'];
updateUserDetails: Scalars['Boolean'];
deleteSearchHistory: Scalars['Boolean'];
}
interface MutationAddCategoryArgs {
category: AddCategoryInput;
}
interface MutationAddReviewArgs {
review: ReviewInput;
hasReviewed: Scalars['Boolean'];
}
interface MutationUpdateEntityViewsArgs {
viewCount: Scalars['Int'];
entityId: Scalars['Int'];
}
interface MutationRequestOwnershipArgs {
entityId: Scalars['Int'];
userId: Scalars['Int'];
}
interface MutationVoteReviewArgs {
vote: VoteInput;
}
interface MutationRequestProfilePriorityArgs {
request: ProfilePriorityInput;
}
interface MutationCreateUserArgs {
user: CreateUserInput;
}
interface MutationLoginArgs {
credentials: LoginInput;
}
interface MutationSendPasswordResetArgs {
email?: Maybe<Scalars['String']>;
}
interface MutationResetPasswordArgs {
newCredentials: ResetPasswordCredentials;
}
interface MutationUpdateUserDetailsArgs {
patch: UpdateUserDetailsInput;
}
interface MutationDeleteSearchHistoryArgs {
id: Scalars['Int'];
}
interface PopularSearch {
__typename?: 'PopularSearch';
id: Scalars['Int'];
query: Scalars['String'];
searches: Scalars['Int'];
}
interface ProfilePriorityInput {
entityId: Scalars['Int'];
requestedBy: Scalars['Int'];
why?: Maybe<Scalars['String']>;
}
interface Query {
__typename?: 'Query';
getCategories: Array<Category>;
search: ReviewSearchResponse;
getEntity: Entity;
searchReviews: SearchReviewsResponse;
hasReviewed: Scalars['Boolean'];
getCategory: Category;
getEntityOwnershipRequests: Array<Maybe<EntityOwnershipRequest>>;
getPopularSearches: Array<Maybe<PopularSearch>>;
getUser: User;
getUserActivity: UserActivity;
getUserEntities: Array<Maybe<Entity>>;
getSearchHistory: Array<Maybe<SearchHistory>>;
getReviewVotes: Array<Maybe<ReviewVote>>;
hasRequestedProfilePriority: Scalars['Boolean'];
}
interface QuerySearchArgs {
filters: SearchFilters;
first?: Maybe<Scalars['Int']>;
query: Scalars['String'];
}
interface QueryGetEntityArgs {
id: Scalars['Int'];
}
interface QuerySearchReviewsArgs {
filters: ReviewSearchFilters;
entityId: Scalars['Int'];
first?: Maybe<Scalars['Int']>;
query?: Maybe<Scalars['String']>;
}
interface QueryHasReviewedArgs {
entityId: Scalars['Int'];
userId: Scalars['Int'];
}
interface QueryGetCategoryArgs {
id: Scalars['Int'];
}
interface QueryGetEntityOwnershipRequestsArgs {
id: Scalars['Int'];
}
interface QueryGetUserArgs {
id: Scalars['Int'];
}
interface QueryGetUserActivityArgs {
id: Scalars['Int'];
}
interface QueryGetUserEntitiesArgs {
id: Scalars['Int'];
}
interface QueryGetSearchHistoryArgs {
id: Scalars['Int'];
}
interface QueryGetReviewVotesArgs {
id: Scalars['Int'];
}
interface QueryHasRequestedProfilePriorityArgs {
entityId: Scalars['Int'];
}
interface ResetPasswordCredentials {
email: Scalars['String'];
newPassword: Scalars['String'];
token: Scalars['String'];
}
interface Review {
__typename?: 'Review';
id: Scalars['Int'];
type: Scalars['String'];
title: Scalars['String'];
createdBy: Scalars['Int'];
createdByUser: User;
createdAt: Scalars['String'];
body: Scalars['String'];
tags?: Maybe<Array<Maybe<Scalars['String']>>>;
rating: Scalars['Int'];
specialContent?: Maybe<Scalars['String']>;
entity: Scalars['Int'];
upvotes: Scalars['Int'];
downvotes: Scalars['Int'];
}
interface ReviewInput {
type: Scalars['String'];
title: Scalars['String'];
createdBy: Scalars['Int'];
body: Scalars['String'];
tags: Array<Maybe<Scalars['String']>>;
rating: Scalars['Int'];
specialContent?: Maybe<Scalars['String']>;
entity: Scalars['Int'];
}
interface ReviewSearchFilters {
minRating: Scalars['Int'];
maxRating: Scalars['Int'];
sortBy: Scalars['String'];
}
interface ReviewSearchResponse {
__typename?: 'ReviewSearchResponse';
reviews: Array<Maybe<Review>>;
entities: Array<Maybe<Entity>>;
total: Scalars['Int'];
}
interface ReviewVote {
__typename?: 'ReviewVote';
id: Scalars['Int'];
votedDate: Scalars['String'];
voteType?: Maybe<VoteType>;
reviewId: Scalars['Int'];
}
interface SearchFilters {
minRating: Scalars['Int'];
maxRating: Scalars['Int'];
sortyBy: Scalars['String'];
categoryRestriction?: Maybe<Scalars['String']>;
}
interface SearchHistory {
__typename?: 'SearchHistory';
id: Scalars['Int'];
query: Scalars['String'];
user: Scalars['Int'];
}
interface SearchReviewsResponse {
__typename?: 'SearchReviewsResponse';
reviews: Array<Maybe<Review>>;
total: Scalars['Int'];
}
interface UpdateUserDetailsInput {
userId: Scalars['Int'];
fullName?: Maybe<Scalars['String']>;
birthday?: Maybe<Scalars['String']>;
accountType?: Maybe<Scalars['String']>;
}
interface User {
__typename?: 'User';
id: Scalars['Int'];
fullName?: Maybe<Scalars['String']>;
birthday?: Maybe<Scalars['String']>;
accountType: Scalars['String'];
email: Scalars['String'];
}
interface UserActivity {
__typename?: 'UserActivity';
reviews: Array<Maybe<Review>>;
}
interface VoteInput {
userId: Scalars['Int'];
voteType: VoteType;
reviewId: Scalars['Int'];
}
type VoteType =
| 'UPVOTE'
| 'DOWNVOTE'
| 'REMOVE';
export type ResolverTypeWrapper<T> = Promise<T> | T;
export type ResolverWithResolve<TResult, TParent, TContext, TArgs> = {
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type LegacyStitchingResolver<TResult, TParent, TContext, TArgs> = {
fragment: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type NewStitchingResolver<TResult, TParent, TContext, TArgs> = {
selectionSet: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type StitchingResolver<TResult, TParent, TContext, TArgs> = LegacyStitchingResolver<TResult, TParent, TContext, TArgs> | NewStitchingResolver<TResult, TParent, TContext, TArgs>;
export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> =
| ResolverFn<TResult, TParent, TContext, TArgs>
| ResolverWithResolve<TResult, TParent, TContext, TArgs>
| StitchingResolver<TResult, TParent, TContext, TArgs>;
export type ResolverFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => Promise<TResult> | TResult;
export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>>;
export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>;
resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>;
}
export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
}
export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
| SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
| SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> =
| ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = (
parent: TParent,
context: TContext,
info: GraphQLResolveInfo
) => Maybe<TTypes> | Promise<Maybe<TTypes>>;
export type IsTypeOfResolverFn<T = {}, TContext = {}> = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise<boolean>;
export type NextResolverFn<T> = () => Promise<T>;
export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = (
next: NextResolverFn<TResult>,
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
/** Mapping between all available schema types and the resolvers types */
export type ResolversTypes = {
AddCategoryInput: AddCategoryInput;
String: ResolverTypeWrapper<Scalars['String']>;
Boolean: ResolverTypeWrapper<Scalars['Boolean']>;
Category: ResolverTypeWrapper<Category>;
Int: ResolverTypeWrapper<Scalars['Int']>;
CategoryTopTen: ResolverTypeWrapper<CategoryTopTen>;
CreateEntityInput: CreateEntityInput;
CreateUserInput: CreateUserInput;
CreateUserReturn: ResolverTypeWrapper<CreateUserReturn>;
Entity: ResolverTypeWrapper<Entity>;
EntityOwnershipRequest: ResolverTypeWrapper<EntityOwnershipRequest>;
EntitySearchResponse: ResolverTypeWrapper<EntitySearchResponse>;
LoginInput: LoginInput;
Mutation: ResolverTypeWrapper<{}>;
PopularSearch: ResolverTypeWrapper<PopularSearch>;
ProfilePriorityInput: ProfilePriorityInput;
Query: ResolverTypeWrapper<{}>;
ResetPasswordCredentials: ResetPasswordCredentials;
Review: ResolverTypeWrapper<Review>;
ReviewInput: ReviewInput;
ReviewSearchFilters: ReviewSearchFilters;
ReviewSearchResponse: ResolverTypeWrapper<ReviewSearchResponse>;
ReviewVote: ResolverTypeWrapper<ReviewVote>;
SearchFilters: SearchFilters;
SearchHistory: ResolverTypeWrapper<SearchHistory>;
SearchReviewsResponse: ResolverTypeWrapper<SearchReviewsResponse>;
UpdateUserDetailsInput: UpdateUserDetailsInput;
User: ResolverTypeWrapper<User>;
UserActivity: ResolverTypeWrapper<UserActivity>;
VoteInput: VoteInput;
VoteType: VoteType;
};
/** Mapping between all available schema types and the resolvers parents */
export type ResolversParentTypes = {
AddCategoryInput: AddCategoryInput;
String: Scalars['String'];
Boolean: Scalars['Boolean'];
Category: Category;
Int: Scalars['Int'];
CategoryTopTen: CategoryTopTen;
CreateEntityInput: CreateEntityInput;
CreateUserInput: CreateUserInput;
CreateUserReturn: CreateUserReturn;
Entity: Entity;
EntityOwnershipRequest: EntityOwnershipRequest;
EntitySearchResponse: EntitySearchResponse;
LoginInput: LoginInput;
Mutation: {};
PopularSearch: PopularSearch;
ProfilePriorityInput: ProfilePriorityInput;
Query: {};
ResetPasswordCredentials: ResetPasswordCredentials;
Review: Review;
ReviewInput: ReviewInput;
ReviewSearchFilters: ReviewSearchFilters;
ReviewSearchResponse: ReviewSearchResponse;
ReviewVote: ReviewVote;
SearchFilters: SearchFilters;
SearchHistory: SearchHistory;
SearchReviewsResponse: SearchReviewsResponse;
UpdateUserDetailsInput: UpdateUserDetailsInput;
User: User;
UserActivity: UserActivity;
VoteInput: VoteInput;
};
export type CategoryResolvers<ContextType = any, ParentType extends ResolversParentTypes['Category'] = ResolversParentTypes['Category']> = {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
title?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
caption?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
iconKey?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
approved?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
banner?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
topTen?: Resolver<ResolversTypes['CategoryTopTen'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type CategoryTopTenResolvers<ContextType = any, ParentType extends ResolversParentTypes['CategoryTopTen'] = ResolversParentTypes['CategoryTopTen']> = {
mostViewed?: Resolver<Array<Maybe<ResolversTypes['Entity']>>, ParentType, ContextType>;
mostRecent?: Resolver<Array<Maybe<ResolversTypes['Entity']>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type CreateUserReturnResolvers<ContextType = any, ParentType extends ResolversParentTypes['CreateUserReturn'] = ResolversParentTypes['CreateUserReturn']> = {
user?: Resolver<ResolversTypes['User'], ParentType, ContextType>;
token?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type EntityResolvers<ContextType = any, ParentType extends ResolversParentTypes['Entity'] = ResolversParentTypes['Entity']> = {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
ownedBy?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
specialContent?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
views?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type EntityOwnershipRequestResolvers<ContextType = any, ParentType extends ResolversParentTypes['EntityOwnershipRequest'] = ResolversParentTypes['EntityOwnershipRequest']> = {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
requestedBy?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
entity?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
approved?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type EntitySearchResponseResolvers<ContextType = any, ParentType extends ResolversParentTypes['EntitySearchResponse'] = ResolversParentTypes['EntitySearchResponse']> = {
entities?: Resolver<Array<Maybe<ResolversTypes['Entity']>>, ParentType, ContextType>;
total?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type MutationResolvers<ContextType = any, ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']> = {
addCategory?: Resolver<ResolversTypes['Category'], ParentType, ContextType, RequireFields<MutationAddCategoryArgs, 'category'>>;
addReview?: Resolver<ResolversTypes['Review'], ParentType, ContextType, RequireFields<MutationAddReviewArgs, 'review' | 'hasReviewed'>>;
updateEntityViews?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType, RequireFields<MutationUpdateEntityViewsArgs, 'viewCount' | 'entityId'>>;
requestOwnership?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType, RequireFields<MutationRequestOwnershipArgs, 'entityId' | 'userId'>>;
voteReview?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType, RequireFields<MutationVoteReviewArgs, 'vote'>>;
requestProfilePriority?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType, RequireFields<MutationRequestProfilePriorityArgs, 'request'>>;
createUser?: Resolver<ResolversTypes['CreateUserReturn'], ParentType, ContextType, RequireFields<MutationCreateUserArgs, 'user'>>;
login?: Resolver<ResolversTypes['CreateUserReturn'], ParentType, ContextType, RequireFields<MutationLoginArgs, 'credentials'>>;
sendPasswordReset?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType, RequireFields<MutationSendPasswordResetArgs, never>>;
resetPassword?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType, RequireFields<MutationResetPasswordArgs, 'newCredentials'>>;
updateUserDetails?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType, RequireFields<MutationUpdateUserDetailsArgs, 'patch'>>;
deleteSearchHistory?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType, RequireFields<MutationDeleteSearchHistoryArgs, 'id'>>;
};
export type PopularSearchResolvers<ContextType = any, ParentType extends ResolversParentTypes['PopularSearch'] = ResolversParentTypes['PopularSearch']> = {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
query?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
searches?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type QueryResolvers<ContextType = any, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = {
getCategories?: Resolver<Array<ResolversTypes['Category']>, ParentType, ContextType>;
search?: Resolver<ResolversTypes['ReviewSearchResponse'], ParentType, ContextType, RequireFields<QuerySearchArgs, 'filters' | 'query'>>;
getEntity?: Resolver<ResolversTypes['Entity'], ParentType, ContextType, RequireFields<QueryGetEntityArgs, 'id'>>;
searchReviews?: Resolver<ResolversTypes['SearchReviewsResponse'], ParentType, ContextType, RequireFields<QuerySearchReviewsArgs, 'filters' | 'entityId'>>;
hasReviewed?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType, RequireFields<QueryHasReviewedArgs, 'entityId' | 'userId'>>;
getCategory?: Resolver<ResolversTypes['Category'], ParentType, ContextType, RequireFields<QueryGetCategoryArgs, 'id'>>;
getEntityOwnershipRequests?: Resolver<Array<Maybe<ResolversTypes['EntityOwnershipRequest']>>, ParentType, ContextType, RequireFields<QueryGetEntityOwnershipRequestsArgs, 'id'>>;
getPopularSearches?: Resolver<Array<Maybe<ResolversTypes['PopularSearch']>>, ParentType, ContextType>;
getUser?: Resolver<ResolversTypes['User'], ParentType, ContextType, RequireFields<QueryGetUserArgs, 'id'>>;
getUserActivity?: Resolver<ResolversTypes['UserActivity'], ParentType, ContextType, RequireFields<QueryGetUserActivityArgs, 'id'>>;
getUserEntities?: Resolver<Array<Maybe<ResolversTypes['Entity']>>, ParentType, ContextType, RequireFields<QueryGetUserEntitiesArgs, 'id'>>;
getSearchHistory?: Resolver<Array<Maybe<ResolversTypes['SearchHistory']>>, ParentType, ContextType, RequireFields<QueryGetSearchHistoryArgs, 'id'>>;
getReviewVotes?: Resolver<Array<Maybe<ResolversTypes['ReviewVote']>>, ParentType, ContextType, RequireFields<QueryGetReviewVotesArgs, 'id'>>;
hasRequestedProfilePriority?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType, RequireFields<QueryHasRequestedProfilePriorityArgs, 'entityId'>>;
};
export type ReviewResolvers<ContextType = any, ParentType extends ResolversParentTypes['Review'] = ResolversParentTypes['Review']> = {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
title?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
createdBy?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
createdByUser?: Resolver<ResolversTypes['User'], ParentType, ContextType>;
createdAt?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
body?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
tags?: Resolver<Maybe<Array<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
rating?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
specialContent?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
entity?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
upvotes?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
downvotes?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type ReviewSearchResponseResolvers<ContextType = any, ParentType extends ResolversParentTypes['ReviewSearchResponse'] = ResolversParentTypes['ReviewSearchResponse']> = {
reviews?: Resolver<Array<Maybe<ResolversTypes['Review']>>, ParentType, ContextType>;
entities?: Resolver<Array<Maybe<ResolversTypes['Entity']>>, ParentType, ContextType>;
total?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type ReviewVoteResolvers<ContextType = any, ParentType extends ResolversParentTypes['ReviewVote'] = ResolversParentTypes['ReviewVote']> = {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
votedDate?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
voteType?: Resolver<Maybe<ResolversTypes['VoteType']>, ParentType, ContextType>;
reviewId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type SearchHistoryResolvers<ContextType = any, ParentType extends ResolversParentTypes['SearchHistory'] = ResolversParentTypes['SearchHistory']> = {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
query?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
user?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type SearchReviewsResponseResolvers<ContextType = any, ParentType extends ResolversParentTypes['SearchReviewsResponse'] = ResolversParentTypes['SearchReviewsResponse']> = {
reviews?: Resolver<Array<Maybe<ResolversTypes['Review']>>, ParentType, ContextType>;
total?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type UserResolvers<ContextType = any, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
fullName?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
birthday?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
accountType?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
email?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type UserActivityResolvers<ContextType = any, ParentType extends ResolversParentTypes['UserActivity'] = ResolversParentTypes['UserActivity']> = {
reviews?: Resolver<Array<Maybe<ResolversTypes['Review']>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type Resolvers<ContextType = any> = {
Category?: CategoryResolvers<ContextType>;
CategoryTopTen?: CategoryTopTenResolvers<ContextType>;
CreateUserReturn?: CreateUserReturnResolvers<ContextType>;
Entity?: EntityResolvers<ContextType>;
EntityOwnershipRequest?: EntityOwnershipRequestResolvers<ContextType>;
EntitySearchResponse?: EntitySearchResponseResolvers<ContextType>;
Mutation?: MutationResolvers<ContextType>;
PopularSearch?: PopularSearchResolvers<ContextType>;
Query?: QueryResolvers<ContextType>;
Review?: ReviewResolvers<ContextType>;
ReviewSearchResponse?: ReviewSearchResponseResolvers<ContextType>;
ReviewVote?: ReviewVoteResolvers<ContextType>;
SearchHistory?: SearchHistoryResolvers<ContextType>;
SearchReviewsResponse?: SearchReviewsResponseResolvers<ContextType>;
User?: UserResolvers<ContextType>;
UserActivity?: UserActivityResolvers<ContextType>;
};
/**
* @deprecated
* Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config.
*/
export type IResolvers<ContextType = any> = Resolvers<ContextType>;
} } export {};<file_sep>/@types/index.d.ts
import e from 'express';
declare global {
namespace Utilities {
type Logger = {
info: any;
warn: any;
err: any;
};
namespace Config {
type ENV = {
PORT: string;
DB_HOST: string;
DB_USERNAME: string;
DB_PASSWORD: string;
DB_NAME: string;
LOG_LEVEL: string;
SESSION_SECRET: string;
SENDGRID_TOKEN: string;
DB_URL: string;
SENTRY_DSN: string;
REDIS_HOST: string;
REDIS_PORT: string;
REDIS_PASSWORD: string;
};
}
}
namespace Authentication {
interface DecodedResult {
username: string;
userId: number;
}
}
namespace Services {
type SerializedContext = {
valid: boolean;
request: e.Request;
response: e.Response;
token?: string;
session?: Session;
};
type ServerContext = SerializedContext & {
logger: debugsx.IDefaultLogger & { err?: any };
authenticated: boolean;
};
}
type Session = {
username: string;
userId: number;
};
}
export {};
<file_sep>/scripts/generate-schema.ts
import { resolve } from "path";
import { readFileSync, writeFileSync } from "fs";
import { loadFilesSync } from "@graphql-tools/load-files";
import { mergeTypeDefs } from "@graphql-tools/merge";
import { print } from "graphql";
const schemaFolderPath = resolve(
__dirname,
"..",
"src",
"schema",
"schemaFiles"
);
const schemaOutputPath = resolve(__dirname, "..", "generated-schema.graphql");
const warningFilePath = resolve(__dirname, "..", "build", "warning.txt");
const typesArray = loadFilesSync(schemaFolderPath, {
recursive: true,
extensions: ["graphql"],
});
export const typeDefs = mergeTypeDefs([...typesArray], {
throwOnConflict: true,
});
const schema = print(typeDefs);
writeFileSync(schemaOutputPath, schema, "utf8");
<file_sep>/src/resolvers/mutation/user/login.ts
import { AuthenticationError } from 'apollo-server-express';
import User from '../../../db/models/User';
import {
AuthenticationService,
signJWT
} from '../../../services/AuthenticationService';
export const login: Resolvers.MutationResolvers['login'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Resolvers: Mutation: login');
if (context.authenticated) {
throw new AuthenticationError('Already logged in');
}
const userToLogin = await User.query()
.where({ email: args.credentials.email })
.first();
if (!userToLogin) {
context.logger.err('Invalid Credentials in Login Mutation');
throw new AuthenticationError(
'Unable to login user. Invalid Credentials'
);
}
const verified = await new AuthenticationService(
userToLogin.password
).verifyPassword(args.credentials.password);
if (!verified) {
throw new AuthenticationError(
'Unable to login user. Invalid Credentials'
);
}
context.session = {
userId: userToLogin.id,
username: userToLogin.email
};
const token = await signJWT(context);
if (!token) {
throw new AuthenticationError('Could not create JWT!');
}
context.response.setHeader('Authorization', token);
return { user: userToLogin, token };
};
<file_sep>/src/resolvers/query/review/searchReviews.ts
import { raw } from 'objection';
import Reviews from '../../../db/models/Reviews';
//@ts-ignore
export const searchReviews: Resolvers.QueryResolvers['searchReviews'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Query: searchReviews' + ' ' + args.entityId);
let reviews = [];
let total = 0;
if (args.first && !args.query) {
total = (await Reviews.query().where({ entity: args.entityId })).length;
reviews = await Reviews.query()
.where({ entity: args.entityId })
.offset(args.first)
.where(
raw(
`rating >= ${args.filters.minRating} AND rating <= ${args.filters.maxRating}`
)
)
.orderBy('rating', args.filters.sortBy === 'ASC' ? 'ASC' : 'DESC')
.limit(50);
} else if (args.first && args.query) {
total = (await Reviews.query().where({ entity: args.entityId })).length;
reviews = await Reviews.query()
.where({ entity: args.entityId })
.where(
raw(
`rating >= ${args.filters.minRating} AND rating <= ${args.filters.maxRating} AND UPPER(title) LIKE UPPER('%${args.query}%')`
)
)
.orderBy('rating', args.filters.sortBy === 'ASC' ? 'ASC' : 'DESC')
.offset(args.first)
.limit(50);
} else if (!args.first && args.query) {
total = (await Reviews.query().where({ entity: args.entityId })).length;
reviews = await Reviews.query()
.where({ entity: args.entityId })
.where(
raw(
`rating >= ${args.filters.minRating} AND rating <= ${args.filters.maxRating} AND UPPER(title) LIKE UPPER('%${args.query}%')`
)
)
.orderBy('rating', args.filters.sortBy === 'ASC' ? 'ASC' : 'DESC')
.limit(50);
} else {
total = (await Reviews.query().where({ entity: args.entityId })).length;
reviews = await Reviews.query()
.where({ entity: args.entityId })
.where(
raw(
`rating >= ${args.filters.minRating} AND rating <= ${args.filters.maxRating}`
)
)
.orderBy('rating', args.filters.sortBy === 'ASC' ? 'ASC' : 'DESC')
.limit(50);
}
return { total, reviews };
};
<file_sep>/src/resolvers/mutation/search/voteReview.ts
import { ApolloError } from 'apollo-server-errors';
import Category from '../../../db/models/Categories';
import { ReviewVotes } from '../../../db/models/ReviewVotes';
export const voteReview: Resolvers.MutationResolvers['voteReview'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Mutation: voteReview');
if (args.vote.voteType !== 'REMOVE') {
// Should never happen, frontend should make sure bad requests dont happen
const existing = await ReviewVotes.query()
.where({
reviewId: args.vote.reviewId,
votedBy: args.vote.userId
})
.first();
if (existing && existing.voteType === args.vote.voteType) {
// DO nothing.
return false;
} else {
try {
await ReviewVotes.query().delete().where({
reviewId: args.vote.reviewId,
votedBy: args.vote.userId
});
await ReviewVotes.query().insert({
votedBy: args.vote.userId,
votedDate: new Date().toString(),
voteType: args.vote.voteType,
reviewId: args.vote.reviewId
});
} catch (e) {
throw new ApolloError('Error adding your vote', '500');
}
}
}
if (args.vote.voteType === 'REMOVE') {
await ReviewVotes.query().delete().where({
reviewId: args.vote.reviewId,
votedBy: args.vote.userId
});
}
return true;
};
<file_sep>/scripts/generate-sitemap.ts
import Entity from '../src/db/models/Entity';
const fs = require('fs');
const DEFAULT_ROUTES = [
'about',
'about/partners',
'support',
'categories',
'search',
'search/results',
'login',
'signup',
'dashboard'
];
const ROOT_DOMAIN = 'https://www.yourateit.io/';
const modDate = '2021-09-09';
const main = async () => {
const entities = await Entity.query();
// Default Routes
await fs.writeFileSync(
'./scripts/sitemap.xml',
`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>${ROOT_DOMAIN}</loc>
<lastmod>${modDate}</lastmod>
<changefreq>yearly</changefreq>
</url>
`,
() => {}
);
const promises = [];
for (let i = 0; i < DEFAULT_ROUTES.length; i++) {
promises.push(
fs.appendFileSync(
'./scripts/sitemap.xml',
`
<url>
<loc>${ROOT_DOMAIN}${DEFAULT_ROUTES[i]}</loc>
<lastmod>${modDate}</lastmod>
<changefreq>monthly</changefreq>
</url>
`,
() => {}
)
);
}
await Promise.all(promises);
// Entity pages
const entityPromises = [];
for (let i = 0; i < entities.length; i++) {
entityPromises.push(
fs.appendFileSync(
'./scripts/sitemap.xml',
`
<url>
<loc>${ROOT_DOMAIN + `search/results/entity/${entities[i].id}`}</loc>
<lastmod>${modDate}</lastmod>
<changefreq>daily</changefreq>
</url>
`,
() => {
console.log('Parsed ' + i + '/' + entities.length);
}
)
);
}
await Promise.all(entityPromises);
fs.appendFileSync('./scripts/sitemap.xml', `</urlset>`, () => {});
};
main();
<file_sep>/src/resolvers/query/search/index.ts
import Entity from '../../../db/models/Entity';
import { getCategories } from './getCategories';
import { getCategory } from './getCategory';
import { getPopularSearches } from './getPopularSearches';
import { search } from './search';
export const searchQueryResolvers = {
getCategories,
search,
getCategory,
getPopularSearches
};
export const CategoryResolvers: Resolvers.CategoryResolvers = {
//@ts-ignore
topTen: async (parent, args, context) => {
const mostViewed = await Entity.query()
.where({ type: parent.title })
.orderBy('views', 'DESC')
.limit(10);
const mostRecent = await Entity.query()
.where({
type: parent.title
})
.orderBy('id', 'ASC')
.limit(10);
return { mostViewed, mostRecent };
}
};
<file_sep>/src/resolvers/query/search/getCategories.ts
import Category from '../../../db/models/Categories';
//@ts-ignore
export const getCategories: Resolvers.QueryResolvers['getCategories'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Query: getCategories');
const categories = await Category.query().where({ approved: true });
return categories;
};
<file_sep>/scripts/import-colleges.ts
import jsonData from './colleges.json';
import Entity from '../src/db/models/Entity';
type CollegeJSONType = {
name: string;
web_pages: string[];
'state-province': string | null;
country: string;
};
const main = async () => {
const json: CollegeJSONType[] = JSON.parse(JSON.stringify(jsonData as any));
for (let i = 0; i < json.length; i++) {
await Entity.query().insert({
name: json[i].name,
type: 'Schools',
specialContent: {
college: {
websites: json[i].web_pages,
country: json[i].country
}
}
});
console.log(`${i}/${json.length}`);
}
};
main();
<file_sep>/src/resolvers/query/user/getSearchHistory.ts
import { ApolloError } from 'apollo-server-express';
import SearchHistory from '../../../db/models/SearchHistory';
import User from '../../../db/models/User';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
export const getSearchHistory: Resolvers.QueryResolvers['getSearchHistory'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Query: getSearchHistory', args.id);
verifyAuthentication(context);
const history = await SearchHistory.query()
.where({ user: args.id })
.limit(5);
return history;
};
<file_sep>/src/db/models/PopularSearches.ts
import BaseModel from './BaseModel';
class PopularSearches extends BaseModel {
id!: number;
query!: string;
searches!: number;
static get tableName() {
return 'popular_searches';
}
}
export default PopularSearches;
<file_sep>/src/schema/index.ts
import { resolve } from 'path';
import { print } from 'graphql';
import { loadFilesSync } from '@graphql-tools/load-files';
import { mergeTypeDefs } from '@graphql-tools/merge';
const schemaFolderPath = resolve(__dirname, './', 'schemaFiles');
const typesArray = loadFilesSync(schemaFolderPath, {
recursive: true,
extensions: ['graphql']
});
export const typeDefs = mergeTypeDefs([...typesArray], {
throwOnConflict: true
});
export const schema = print(typeDefs);
<file_sep>/src/resolvers/mutation/search/index.ts
import { addCategory } from './addCategory';
import { requestProfilePriority } from './requestProfilePriority';
import { voteReview } from './voteReview';
export const searchMutationResolvers = {
addCategory,
voteReview,
requestProfilePriority
};
<file_sep>/scripts/import-countries.ts
import jsonData from './countries_cities.json';
import Entity from '../src/db/models/Entity';
type CountryJsonType = {
[key: string]: string[];
};
const main = async () => {
const json: CountryJsonType = JSON.parse(JSON.stringify(jsonData as any));
for (const [key, val] of Object.entries(json)) {
console.log(`${key} COUNTRY`);
const country = await Entity.query().insert({
name: key,
type: 'Countries'
});
for (let i = 0; i < val.length; i++) {
await Entity.query().insert({
name: val[i],
type: 'Cities',
specialContent: {
city: {
countryId: country.id,
countryName: country.name
}
}
});
}
}
};
main();
<file_sep>/src/resolvers/query/entity/getEntity.ts
import Entity from '../../../db/models/Entity';
import User from '../../../db/models/User';
export const getEntity: Resolvers.QueryResolvers['getEntity'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Query: getEntity: ' + args.id);
const entity = await Entity.query().findById(args.id);
let ownedBy;
if (entity.ownedBy) {
ownedBy = await User.query().findById(entity.ownedBy);
}
return { ...entity, ownedBy };
};
<file_sep>/src/resolvers/query/user/getReviewVotes.ts
import { ReviewVotes } from '../../../db/models/ReviewVotes';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
export const getReviewVotes: Resolvers.QueryResolvers['getReviewVotes'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Query: getReviewVotes', args.id);
verifyAuthentication(context);
const votes = await ReviewVotes.query().where({ votedBy: args.id });
return votes;
};
<file_sep>/scripts/import-movies.ts
import jsonData from './movies.json';
import Entity from '../src/db/models/Entity';
type MovieJSONType = {
title: string;
year: string;
runtime: string;
genres: string[];
director: string;
actors: string;
plot: string;
posterUrl: string;
};
const main = async () => {
const json: MovieJSONType[] = JSON.parse(JSON.stringify(jsonData as any));
for (let i = 0; i < json.length; i++) {
await Entity.query().insert({
name: json[i].title,
type: 'Movies',
specialContent: {
bio: json[i].plot,
movie: {
runtime: json[i].runtime,
genres: json[i].genres,
director: json[i].director,
actors: json[i].actors,
posterUrl: json[i].posterUrl
}
}
});
console.log(`${i}/${json.length}`);
}
};
main();
<file_sep>/src/services/ContextService.ts
import e from 'express';
import { logger } from '../utils/logger';
import { AuthenticationError } from 'apollo-server';
import jwt from 'jsonwebtoken';
export class Context {
valid: boolean;
request: e.Request;
response: e.Response;
token: string | undefined;
session: Session | undefined;
constructor(req: e.Request, res: e.Response) {
this.request = req;
this.response = res;
this.valid = false;
}
async Initialize(): Promise<Services.SerializedContext> {
this.session = await this.checkHeaders();
return this.serialize();
}
async checkHeaders(): Promise<Session | undefined> {
logger.info(
'Headers: Authorization: ' + this.request.headers.authorization
);
logger.info(
this.request.headers.authorization !== undefined &&
this.request.headers.authorization.length > 0 &&
this.request.headers.authorization !== null
);
if (
this.request.headers.authorization &&
this.request.headers.authorization.length > 0
) {
this.token = this.request.headers.authorization;
const decoded = await this.validateAndDecodeJWT();
return decoded as unknown as Session;
}
}
async validateAndDecodeJWT(): Promise<Authentication.DecodedResult> {
if (!this.token) {
logger.err('Error with token!');
throw new AuthenticationError('Error With Token!');
}
const decoded: any = jwt.decode(this.token);
if (!decoded) {
logger.err('Critical Server Error. No decoded JWT returned!');
throw new Error('Critical Server Error.');
}
return {
username: decoded.username,
userId: decoded.userId
};
}
serialize(): Services.SerializedContext {
return {
token: this.token,
request: this.request,
response: this.response,
valid: this.valid,
session: this.session
};
}
}
export const createContext = async (
req: e.Request,
res: e.Response
): Promise<Services.ServerContext> => {
if (!req) {
return {
token: '',
request: req,
response: res,
valid: false,
session: {} as any,
logger,
authenticated: false
};
}
const context = await new Context(req, res).Initialize();
return {
...context,
logger,
authenticated: context.session ? true : false
};
};
<file_sep>/src/resolvers/mutation/search/addCategory.ts
import Category from '../../../db/models/Categories';
//@ts-ignore
export const addCategory: Resolvers.MutationResolvers['addCategory'] = async (
parent,
args,
context: Services.ServerContext
) => {
context.logger.info('Mutation: addCategory');
const category = await Category.query().insertAndFetch({
...args.category
});
return category;
};
<file_sep>/src/resolvers/mutation/entity/requestOwnership.ts
import { ApolloError } from 'apollo-server-express';
import Entity from '../../../db/models/Entity';
import EntityOwnershipRequest from '../../../db/models/EntityOwnershipRequest';
import User from '../../../db/models/User';
export const requestOwnership: Resolvers.MutationResolvers['requestOwnership'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Mutation: requestOwnership' + ' ' + args.entityId);
const entityExists = await Entity.query().findById(args.entityId);
if (!entityExists) {
throw new ApolloError('Entity does not exist', '400');
}
const userExists = await User.query().findById(args.userId);
if (!userExists) {
throw new ApolloError('User does not exist', '400');
}
await EntityOwnershipRequest.query().insertAndFetch({
approved: false,
requestedBy: args.userId,
entity: args.entityId
});
return true;
};
<file_sep>/src/db/models/PasswordResets.ts
import BaseModel from './BaseModel';
export class PasswordResets extends BaseModel {
id!: number;
forEmail!: string;
code!: string;
static get tableName() {
return 'user_password_resets';
}
}
<file_sep>/src/resolvers/query/user/getUserEntities.ts
import { ApolloError } from 'apollo-server-express';
import Entity from '../../../db/models/Entity';
import Reviews from '../../../db/models/Reviews';
import User from '../../../db/models/User';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
//@ts-ignore
export const getUserEntities: Resolvers.QueryResolvers['getUserEntities'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Query: getUserEntities', args.id);
verifyAuthentication(context);
const entities = await Entity.query().where({ ownedBy: args.id });
return entities;
};
<file_sep>/@types/schema.d.ts
declare global { namespace Schema {
type Maybe<T> = T | undefined;
type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
interface Scalars {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
}
interface AddCategoryInput {
title: Scalars['String'];
iconKey?: Maybe<Scalars['String']>;
caption: Scalars['String'];
approved: Scalars['Boolean'];
}
interface Category {
__typename?: 'Category';
id: Scalars['Int'];
title: Scalars['String'];
caption: Scalars['String'];
iconKey?: Maybe<Scalars['String']>;
approved: Scalars['Boolean'];
banner?: Maybe<Scalars['String']>;
topTen: CategoryTopTen;
}
interface CategoryTopTen {
__typename?: 'CategoryTopTen';
mostViewed: Array<Maybe<Entity>>;
mostRecent: Array<Maybe<Entity>>;
}
interface CreateEntityInput {
type: Scalars['String'];
ownedBy?: Maybe<Scalars['Int']>;
specialContent: Scalars['String'];
}
interface CreateUserInput {
fullName?: Maybe<Scalars['String']>;
birthday?: Maybe<Scalars['String']>;
email: Scalars['String'];
password: Scalars['String'];
}
interface CreateUserReturn {
__typename?: 'CreateUserReturn';
user: User;
token: Scalars['String'];
}
interface Entity {
__typename?: 'Entity';
id: Scalars['Int'];
type: Scalars['String'];
ownedBy?: Maybe<User>;
specialContent?: Maybe<Scalars['String']>;
name: Scalars['String'];
views?: Maybe<Scalars['Int']>;
}
interface EntityOwnershipRequest {
__typename?: 'EntityOwnershipRequest';
id: Scalars['Int'];
requestedBy: Scalars['Int'];
entity: Scalars['Int'];
approved: Scalars['Boolean'];
}
interface EntitySearchResponse {
__typename?: 'EntitySearchResponse';
entities: Array<Maybe<Entity>>;
total: Scalars['Int'];
}
interface LoginInput {
email: Scalars['String'];
password: Scalars['String'];
}
interface Mutation {
__typename?: 'Mutation';
addCategory: Category;
addReview: Review;
updateEntityViews: Scalars['Boolean'];
requestOwnership: Scalars['Boolean'];
voteReview: Scalars['Boolean'];
requestProfilePriority: Scalars['Boolean'];
createUser: CreateUserReturn;
login: CreateUserReturn;
sendPasswordReset: Scalars['Boolean'];
resetPassword: Scalars['Boolean'];
updateUserDetails: Scalars['Boolean'];
deleteSearchHistory: Scalars['Boolean'];
}
interface MutationAddCategoryArgs {
category: AddCategoryInput;
}
interface MutationAddReviewArgs {
review: ReviewInput;
hasReviewed: Scalars['Boolean'];
}
interface MutationUpdateEntityViewsArgs {
viewCount: Scalars['Int'];
entityId: Scalars['Int'];
}
interface MutationRequestOwnershipArgs {
entityId: Scalars['Int'];
userId: Scalars['Int'];
}
interface MutationVoteReviewArgs {
vote: VoteInput;
}
interface MutationRequestProfilePriorityArgs {
request: ProfilePriorityInput;
}
interface MutationCreateUserArgs {
user: CreateUserInput;
}
interface MutationLoginArgs {
credentials: LoginInput;
}
interface MutationSendPasswordResetArgs {
email?: Maybe<Scalars['String']>;
}
interface MutationResetPasswordArgs {
newCredentials: ResetPasswordCredentials;
}
interface MutationUpdateUserDetailsArgs {
patch: UpdateUserDetailsInput;
}
interface MutationDeleteSearchHistoryArgs {
id: Scalars['Int'];
}
interface PopularSearch {
__typename?: 'PopularSearch';
id: Scalars['Int'];
query: Scalars['String'];
searches: Scalars['Int'];
}
interface ProfilePriorityInput {
entityId: Scalars['Int'];
requestedBy: Scalars['Int'];
why?: Maybe<Scalars['String']>;
}
interface Query {
__typename?: 'Query';
getCategories: Array<Category>;
search: ReviewSearchResponse;
getEntity: Entity;
searchReviews: SearchReviewsResponse;
hasReviewed: Scalars['Boolean'];
getCategory: Category;
getEntityOwnershipRequests: Array<Maybe<EntityOwnershipRequest>>;
getPopularSearches: Array<Maybe<PopularSearch>>;
getUser: User;
getUserActivity: UserActivity;
getUserEntities: Array<Maybe<Entity>>;
getSearchHistory: Array<Maybe<SearchHistory>>;
getReviewVotes: Array<Maybe<ReviewVote>>;
hasRequestedProfilePriority: Scalars['Boolean'];
}
interface QuerySearchArgs {
filters: SearchFilters;
first?: Maybe<Scalars['Int']>;
query: Scalars['String'];
}
interface QueryGetEntityArgs {
id: Scalars['Int'];
}
interface QuerySearchReviewsArgs {
filters: ReviewSearchFilters;
entityId: Scalars['Int'];
first?: Maybe<Scalars['Int']>;
query?: Maybe<Scalars['String']>;
}
interface QueryHasReviewedArgs {
entityId: Scalars['Int'];
userId: Scalars['Int'];
}
interface QueryGetCategoryArgs {
id: Scalars['Int'];
}
interface QueryGetEntityOwnershipRequestsArgs {
id: Scalars['Int'];
}
interface QueryGetUserArgs {
id: Scalars['Int'];
}
interface QueryGetUserActivityArgs {
id: Scalars['Int'];
}
interface QueryGetUserEntitiesArgs {
id: Scalars['Int'];
}
interface QueryGetSearchHistoryArgs {
id: Scalars['Int'];
}
interface QueryGetReviewVotesArgs {
id: Scalars['Int'];
}
interface QueryHasRequestedProfilePriorityArgs {
entityId: Scalars['Int'];
}
interface ResetPasswordCredentials {
email: Scalars['String'];
newPassword: Scalars['String'];
token: Scalars['String'];
}
interface Review {
__typename?: 'Review';
id: Scalars['Int'];
type: Scalars['String'];
title: Scalars['String'];
createdBy: Scalars['Int'];
createdByUser: User;
createdAt: Scalars['String'];
body: Scalars['String'];
tags?: Maybe<Array<Maybe<Scalars['String']>>>;
rating: Scalars['Int'];
specialContent?: Maybe<Scalars['String']>;
entity: Scalars['Int'];
upvotes: Scalars['Int'];
downvotes: Scalars['Int'];
}
interface ReviewInput {
type: Scalars['String'];
title: Scalars['String'];
createdBy: Scalars['Int'];
body: Scalars['String'];
tags: Array<Maybe<Scalars['String']>>;
rating: Scalars['Int'];
specialContent?: Maybe<Scalars['String']>;
entity: Scalars['Int'];
}
interface ReviewSearchFilters {
minRating: Scalars['Int'];
maxRating: Scalars['Int'];
sortBy: Scalars['String'];
}
interface ReviewSearchResponse {
__typename?: 'ReviewSearchResponse';
reviews: Array<Maybe<Review>>;
entities: Array<Maybe<Entity>>;
total: Scalars['Int'];
}
interface ReviewVote {
__typename?: 'ReviewVote';
id: Scalars['Int'];
votedDate: Scalars['String'];
voteType?: Maybe<VoteType>;
reviewId: Scalars['Int'];
}
interface SearchFilters {
minRating: Scalars['Int'];
maxRating: Scalars['Int'];
sortyBy: Scalars['String'];
categoryRestriction?: Maybe<Scalars['String']>;
}
interface SearchHistory {
__typename?: 'SearchHistory';
id: Scalars['Int'];
query: Scalars['String'];
user: Scalars['Int'];
}
interface SearchReviewsResponse {
__typename?: 'SearchReviewsResponse';
reviews: Array<Maybe<Review>>;
total: Scalars['Int'];
}
interface UpdateUserDetailsInput {
userId: Scalars['Int'];
fullName?: Maybe<Scalars['String']>;
birthday?: Maybe<Scalars['String']>;
accountType?: Maybe<Scalars['String']>;
}
interface User {
__typename?: 'User';
id: Scalars['Int'];
fullName?: Maybe<Scalars['String']>;
birthday?: Maybe<Scalars['String']>;
accountType: Scalars['String'];
email: Scalars['String'];
}
interface UserActivity {
__typename?: 'UserActivity';
reviews: Array<Maybe<Review>>;
}
interface VoteInput {
userId: Scalars['Int'];
voteType: VoteType;
reviewId: Scalars['Int'];
}
type VoteType =
| 'UPVOTE'
| 'DOWNVOTE'
| 'REMOVE';
} } export {};<file_sep>/src/resolvers/query/entity/index.ts
import { getEntity } from './getEntity';
import { getEntityOwnershipRequests } from './getEntityOwnershipRequests';
export const entityResolvers = {
getEntity,
getEntityOwnershipRequests
};
<file_sep>/src/resolvers/query/user/index.ts
import { getReviewVotes } from './getReviewVotes';
import { getSearchHistory } from './getSearchHistory';
import { getUser } from './getUser';
import { getUserActivity } from './getUserActivity';
import { getUserEntities } from './getUserEntities';
import { hasRequestedProfilePriority } from './hasRequestedProfilePriority';
export const userQueryResolvers = {
getUser: getUser,
getUserActivity,
getUserEntities,
getSearchHistory,
getReviewVotes,
hasRequestedProfilePriority
};
<file_sep>/src/resolvers/mutation/user/resetPassword.ts
import { PasswordResets } from '../../../db/models/PasswordResets';
import User from '../../../db/models/User';
import { AuthenticationService } from '../../../services/AuthenticationService';
export const resetPassword: Resolvers.MutationResolvers['resetPassword'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Resolvers: Mutation: resetPassword');
const existingCode = await PasswordResets.query()
.where({
code: args.newCredentials.token
})
.first();
if (!existingCode) {
throw new Error('Code has expired!');
}
await User.query()
.where({ email: existingCode.forEmail })
.first()
.patchAndFetch({
password: await new AuthenticationService(
args.newCredentials.newPassword
).hashPassword()
});
await PasswordResets.query().deleteById(existingCode.id);
return true;
};
<file_sep>/src/db/models/ReviewVotes.ts
import BaseModel from './BaseModel';
export type VoteType = 'UPVOTE' | 'DOWNVOTE' | 'REMOVE';
export class ReviewVotes extends BaseModel {
id!: number;
votedBy!: number;
votedDate!: string;
voteType!: VoteType;
reviewId!: number;
static get tableName() {
return 'review_votes';
}
}
<file_sep>/src/resolvers/query/entity/getEntityOwnershipRequests.ts
import EntityOwnershipRequest from '../../../db/models/EntityOwnershipRequest';
export const getEntityOwnershipRequests: Resolvers.QueryResolvers['getEntityOwnershipRequests'] =
async (parent, args, context: Services.ServerContext) => {
context.logger.info('Query: getEntityOwnershipRequests: ' + args.id);
const requests = await EntityOwnershipRequest.query().where({
requestedBy: args.id
});
return requests;
};
| f87a79b345a157ab63b74f129bbc3629231cfea0 | [
"TypeScript"
] | 62 | TypeScript | NateTheDev1/rateyours-server | 94687c03ae665305ed955e7f1c26b458ebe12cee | a70494644a2243d74c6478648b0251c27ea2eb59 |
refs/heads/master | <repo_name>willynilly/athens_greenway_by_housingtype<file_sep>/analysis.R
library(readr)
library(corrplot)
# https://hansenjohnson.org/post/sync-github-repository-with-existing-r-project/
plot_residuals <- function(residuals, file_prefix, method="circle", residuals.limit, title) {
print(corrplot(residuals,
is.cor = FALSE,
method=method,
tl.col="black",
cl.lim = residuals.limit,
tl.srt=45,
addgrid.col="black",
bg="black",
number.cex = .6,
cl.pos="b",
cl.length = 3,
title=title,
mar=c(0,0,4.5,0)))
dev.copy(png, paste('plots', paste(file_prefix, '_residuals_plot_by_', method , '.png', sep=''), sep="/"))
dev.off()
}
plot_contributions <- function(contributions, file_prefix, method="circle", contributions.limit, title) {
print(corrplot(contributions,
is.cor = FALSE,
method=method,
tl.col="black",
cl.lim = contributions.limit,
tl.srt=45,
addgrid.col="black",
bg="black",
number.cex = .6,
cl.pos="b",
cl.length = 3,
title=title,
mar=c(0,0,4.5,0)))
dev.copy(png, paste('plots', paste(file_prefix, '_contributions_plot_by_', method, '.png', sep=''), sep="/"))
dev.off()
}
analyze_trail_access <- function(file_name,
base_title,
residuals.limit = c(-25, 25),
contributions.limit = c(0,100),
housing_types = c('APT', 'CDO','COR', 'DUP', 'MOB', 'PCL', 'PUB', 'HSE')) {
file_name_without_ext <- tools::file_path_sans_ext(file_name)
d1 <- read.csv(file=paste('data', file_name, sep="/"), header=TRUE, sep=",", stringsAsFactors=FALSE)
m1 <- as.matrix(d1[,-1])
rownames(m1) <- d1[,1]
colnames(m1) <- c("0 to 0.25 mile", "0.25 to 0.5 mile", "0.50 to 1 mile")
m1 <- m1[which(rownames(m1) %in% housing_types),]
cht1 <- chisq.test(m1)
print(cht1)
# https://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html
# http://www.sthda.com/english/wiki/chi-square-test-of-independence-in-r
#cht1$observed
#round(cht1$expected,2)
print('residuals')
cht1$residuals <- round(cht1$residuals, 3)
print(cht1$residuals)
title <- c("Residuals for ", base_title, sep="")
plot_residuals(residuals = cht1$residuals, method="circle", file_prefix=file_name_without_ext, residuals.limit = residuals.limit, title=title)
plot_residuals(residuals = cht1$residuals, method="number", file_prefix=file_name_without_ext, residuals.limit = residuals.limit, title=title)
# print(corrplot(cht1$residuals, is.cor = FALSE, method="circle", tl.col="black", cl.lim = residual.lim,
# tl.srt=45, addgrid.col="black", bg="black", cl.pos="b", cl.length = 3, title=title, mar=c(0,0,4.5,0)))
# dev.copy(png,paste(file_name_without_ext, '_residuals_plot.png', sep=''))
# dev.off()
# Contibution in percentage (%)
cht1$contributions <- 100*cht1$residuals^2/cht1$statistic
cht1$contributions <- round(cht1$contributions, 3)
print('contributions')
print(cht1$contributions)
title <- c("Contributions for ", base_title, sep="")
plot_contributions(contributions = cht1$contributions, method="circle", file_prefix=file_name_without_ext, contributions.limit = contributions.limit, title=title)
plot_contributions(contributions = cht1$contributions, method="number", file_prefix=file_name_without_ext, contributions.limit = contributions.limit, title=title)
# print(corrplot(cht1$contributions, is.cor = FALSE, method="circle", tl.col="black", cl.lim = contribution.lim,
# tl.srt=45, addgrid.col="black", bg="black", cl.pos="b", cl.length = 3, title=title, mar=c(0,0,4.5,0)))
# dev.copy(png,paste(file_name_without_ext, '_contributions_plot.png', sep=''))
# dev.off()
return(cht1)
}
# plot existing and future trails
future_and_existing <- analyze_trail_access(file_name="existing_and_future_greenway.csv", base_title = "Existing and Future Greenway")
existing <- analyze_trail_access(file_name="existing_greenway.csv", base_title = "Existing Greenway")
# determine the observed existing plans
title <- "Housing Unit Counts for Existing Plans"
print(corrplot(existing$observed,
is.cor = FALSE,
method="number",
tl.col="black",
col = cm.colors(100),
bg="black",
cl.lim = c(0,3000),
number.cex = .6,
tl.srt=45,
addgrid.col="black",
cl.pos="b", cl.length = 3,
title=title,
mar=c(0,0,4.5,0)))
dev.copy(png,'plots/existing_counts_by_number.png')
dev.off()
title <- "Housing Unit Counts for Existing Plans"
print(corrplot(existing$observed,
is.cor = FALSE,
method="circle",
tl.col="black",
col = cm.colors(100),
bg="black",
cl.lim = c(0,3000),
number.cex = .6,
tl.srt=45,
addgrid.col="black",
cl.pos="b",
cl.length = 3,
title=title,
mar=c(0,0,4.5,0)))
dev.copy(png,'plots/existing_counts_by_circle.png')
dev.off()
# determine the observed differences between future and existing plans"
title <- "Housing Unit Count Changes between Future and Existing Plans"
print(corrplot(future_and_existing$observed - existing$observed, is.cor = FALSE, method="number", tl.col="black", col = cm.colors(100), bg="black", cl.lim = c(-800,800),
tl.srt=45, addgrid.col="black", cl.pos="b", cl.length = 3, title=title, mar=c(0,0,4.5,0)))
dev.copy(png,'plots/future_and_existing_changes_counts_by_number.png')
dev.off()
title <- "Housing Unit Count Changes between Future and Existing Plans"
print(corrplot(future_and_existing$observed - existing$observed, is.cor = FALSE, method="circle", tl.col="black", col = cm.colors(100), bg="black", cl.lim = c(-800,800),
tl.srt=45, addgrid.col="black", cl.pos="b", cl.length = 3, title=title, mar=c(0,0,4.5,0)))
dev.copy(png,'plots/future_and_existing_changes_counts_by_circle.png')
dev.off()
# plot other trails
norg <- analyze_trail_access(file_name="norg.csv",
base_title = "North Oconee River Greenway")
firefly <- analyze_trail_access(file_name="firefly.csv",
base_title = "Firefly Trail")
pulaski <- analyze_trail_access(file_name="pulaski.csv",
base_title = "Pulaski Heights Trail")
trlcrk <- analyze_trail_access(file_name="trlcrk.csv",
base_title = "Trail Creek Greenway",
housing_types=c('APT', 'CDO', 'DUP', 'MOB', 'PCL', 'PUB', 'HSE'))
mext <- analyze_trail_access(file_name="mext.csv",
base_title = "Milledge Extension Trail",
housing_types =c('APT','CDO', 'DUP', 'PCL', 'HSE')) | 22bb3c14d96276674598ac478aece4e9a5e935c6 | [
"R"
] | 1 | R | willynilly/athens_greenway_by_housingtype | 4c9de4d5d6eac5534114e953372ec1163f400582 | 9d7a206902d3cd6e64949159c1d751ad75aaa80c |
refs/heads/master | <file_sep>(function ($) {
function novaLoadFn(element, options) {
this.element = element;
this.defaults = {
size: 50,
border: 2,
layout: null,//布局模式-box-
modal: false//设置为模态窗口布局必须是"box"
}; //参数
this.version = 'v1.0.0';
this.settings = $.extend({}, this.defaults, options);
this.init();
}
novaLoadFn.prototype = {
//初始化方法
init: function () {
var self = this;
var $self = $(this);
self.style(self);
},
style: function (self) {
$(self.element).find(".nv-loop").css({
width: self.settings.size + 'px',
height: self.settings.size + 'px',
});
$(self.element).find(".nv-load-loop").css({
width: self.settings.size - self.settings.border * 2 + 'px',
height: self.settings.size - self.settings.border * 2 + 'px',
borderWidth: self.settings.border + 'px'
});
//布局
switch (self.settings.layout) {
case "transverse":
$(self.element).addClass("nv-load-transverse");
break;
case "box":
if (self.settings.modal) {
$(self.element).wrap('<div id="mask"></div>');
}
$(self.element).addClass("nv-load-box");
break;
default:
$(self.element).css({
"display": "block"
});
break;
}
}
};
$.fn.novaLoad = function (options) {
new novaLoadFn(this, options);
};
})(jQuery);
<file_sep>document.addEventListener('touchstart', function () {
return false;
}, true);
(function (jQuery) {
/*
单选框、复选框、开关
*/
var count = 0;
$.fn.checkBox = function (set) {
var defaults = {
check: false,
size: null,
Init: null,
theme: "defaults", //radius、radius-1
type: "defaults",
checkFn: null
};
var check = false;
var hasAll = false;
var elements = this;
set = $.extend(defaults, set);
return this.each(function () {
count++;
var $_this = $(this);
var theme = set.theme;
var html = null,
size = null;
switch (set.theme) {
case "radius":
theme = "c-radius";
break;
case "radius-1":
theme = "c-radius-1";
break;
default:
theme = null;
break;
}
if (set.type == "switch") {
theme = "c-radius-1";
$_this.wrap('<div class="c-switch"></div>');
} else {
$_this.wrap('<div class="c-box"></div>');
}
if (theme) {
html = '<label class="' + theme + '" for="c-' + count + '"></label>';
} else {
html = '<label for="c-' + count + '"></label>';
}
$_this.prop("id", "c-" + count);
if ($_this.data("type") == "c-all") {
$_this.after(html).addClass("_c_input_all");
hasAll = true;
} else if ($_this.data("type") == "") {} else {
$_this.after(html).addClass("_c_input");
}
if ($_this.data("text")) {
$_this.parent().append("<p>" + $_this.data("text") + "</p>");
}
if ($_this.is(":checked") && set.Init) {
set.Init.call(this, check);
}
$_this.on("change", function () {
if ($(this).is(":checked")) {
check = true;
} else {
check = false;
}
if (hasAll) {
$("._c_input_all").prop("checked", true);
}
elements.each(function () {
var _input = $(this);
if (!_input.is(":checked") && _input.data("type") != "c-all") {
$("._c_input_all").prop("checked", false);
}
});
if ($(this).data("type") == "c-all") {
$("._c_input,._c_input_all").prop("checked", check);
}
if (set.checkFn) {
set.checkFn.call(this, check);
}
});
});
};
var loads = {
text: "loading...",
layout: "line",
checkFn: null,
state:0,
size:50
}
var layout = null;
var loadInset = '<div class="load-box-inset"><div class="load-left"></div><div class="load-right"></div></div>';
$.fn.load = function (set) {
loads.text = "loading...";
var elements = this;
set = $.extend(loads, set);
return this.each(function () {
switch (set.layout) {
case "line":
layout = "loading-line";
break;
case "box":
layout = "loading-bg";
break;
default:
layout = "loading";
break;
}
var $_this = $(this);
var $_loadObj = $_this.parent().find("." + layout);
if ($_loadObj.length <= 0) {
$_this.after('<div class="c-load ' + layout + '">' + loadInset + '<p>' + set.text + '</p></div>');
} else {
if ($_loadObj.children().is("button.load-refresh-btn")) {
$_loadObj.find("button.load-refresh-btn").remove();
}
if ($_loadObj.find(".load-box-inset").length <= 0) {
$_loadObj.prepend(loadInset).find("p").text(set.text);
}
}
});
};
//载入结束
$.fn.loadend = function (set,callBack) {
loads.text = "loadend";
loads.state=1;
set = $.extend(loads, set);
return this.each(function () {
var $_this = $(this);
var $_loadObj = $_this.parent().find("." + layout);
if ($_loadObj.children().is("button.load-refresh-btn")) {
$_loadObj.find("button.load-refresh-btn").remove();
}
$_loadObj.find(".load-box-inset").remove();
$_loadObj.find("p").text(set.text);
if(callBack){
callBack.call(this,loads.state);
}
});
};
//载入失败
$.fn.loadfail = function (set) {
loads.text = "loadfail";
loads.checkFn = null;
set = $.extend(loads, set);
return this.each(function () {
var $_this = $(this);
var $_loadObj = $_this.parent().find("." + layout);
$_loadObj.find(".load-box-inset").remove();
$_loadObj.prepend('<button class="load-refresh-btn"></button>');
$_loadObj.children("p").text(set.text);
$(".c-load").on("click","button", set.checkFn);
});
};
$.fn.loadclose = function (set) {
set = $.extend(loads, set);
return this.each(function () {
var $_this = $(this);
var $_loadObj = $_this.parent().find("." + layout);
if (set.checkFn) {
set.checkFn.call(this);
}
$_loadObj.remove();
});
}
/*
centerImg-
-2017-01-28 17:47:37
-CODE0243
-Version:1.0.0
*/
$.fn.centerImg = function (set) {
var defaults = {
load: null, //载入回调事件
style: "full", //排版样式
scale: "4:3", //图片显示比例
};
var set = $.extend(defaults, set);
var elements = this;
var _index = 0;
var $_this = null;
var $_obj = null;
var time;
var $_win = $(window);
var $_imgBox = null;
$(window).on("resize", function () {
clearTimeout(time);
time = setTimeout(imgMath, 500);
});
imgMath();
return this.each(function () {
$_this = $(this);
$_this.one("load", loadImg);
//hezi
});
function imgMath() {
//boxScale();
elements.each(function () {
console.log(this.height + "--" + this.width);
var scale = set.scale;
var _width = $(this).parent().width();
var _height = $(this).parent().height();
scale = scale.split(":");
var _height = (_width * scale[1]) / scale[0];
$(this).parent().height(Math.ceil(_height));
if ($(this).width() < _width && $(this).width() != $(this).height()) {
//$(this).css(imgStyle("y"));
} else if ($(this).height() < _height && $(this).width() != $(this).height()) {
//$(this).css(imgStyle("x"));
}
});
}
function loadImg() {
var n = 10; //容差
var this_w = (n / 100) * this.width //计算图片宽度的百分比
var this_h = (n / 100) * this.height //计算图片高度的百分比
switch (set.style) {
case "auto":
//自动不会剪切图片
if (this_h > this_w) {
$(this).css(imgStyle("x"));
} else if (this_w > this_h) {
$(this).css(imgStyle("y"));
}
break;
case "full":
//铺满注:该属性会把图片剪切
if (this_h > this_w) {
$(this).css(imgStyle("y"));
} else if (this_w > this_h) {
$(this).css(imgStyle("x"));
}
break;
default:
if (this_h > this_w) {
$(this).css(imgStyle("x"));
} else if (this_w > this_h) {
$(this).css(imgStyle("y"));
}
break;
}
if (set.load) {
set.load.call(this);
}
}
function imgStyle(v) {
if (v == "y") {
v = {
"width": "100%",
"max-width": "none",
"height": "auto",
"top": "50%",
"left": "auto",
"position": "absolute",
"transform": "translateY(-50%)",
"-wekit-transform": "translateY(-50%)",
"-moz-transform": "translateY(-50%)",
"-ms-transform": "translateY(-50%)",
"-o-transform": "translateY(-50%)",
};
} else if (v == "x") {
v = {
"width": "auto",
"max-width": "none",
"height": "100%",
"top": "auto",
"left": "50%",
"position": "absolute",
"transform": "translateX(-50%)",
"-wekit-transform": "translateX(-50%)",
"-moz-transform": "translateX(-50%)",
"-ms-transform": "translateX(-50%)",
"-o-transform": "translateX(-50%)",
};
} else {
v = {
width: "auto",
height: "auto",
margin: "auto"
}
}
return v;
}
};
})(jQuery);
function rmoney(num) {
num = num.toString().replace(/\$|\,/g, '');
if (isNaN(num)) num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * 100 + 0.50000000001);
cents = num % 100;
num = Math.floor(num / 100).toString();
if (cents < 10) cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
return (((sign) ? '' : '-') + num + '.' + cents);
} | 5ff62bf45c6dbacc3fd47dec532f34ad207330f9 | [
"JavaScript"
] | 2 | JavaScript | daihao0243/novaUI | 028b1b48e1650e5e3ea6dffcb5d69c1e1c67221d | 31b5afb497f9e22a0487d07a5e6034c6c33fded1 |
refs/heads/master | <repo_name>eshimel/StorWe_API<file_sep>/db/seeds.rb
Outline.delete_all
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
%w(and dna dan nda).each do |name|
email = <EMAIL>"
next if User.exists? email: email
User.create!(email: email, password: '<PASSWORD>',
password_confirmation: '<PASSWORD>')
end
# Create a couple outlines
western = Outline.create!(subjects: 'Earl Jatters', settings: 'sleepy frontier town', themes: 'western')
suspense = Outline.create!(subjects: 'Our Hero', settings: 'Post-Apocalyptic Ocean City', themes: 'suspense')
fanfiction_one = Outline.create!(subjects:"Jareth", settings: "Toby's Wedding", themes: 'revenge')
grandma = Outline.create!(subjects: 'Grandma', settings: 'Her House', themes: 'big brother is watching you')
loss = Outline.create!(subjects: 'Foghorn Leghorn', settings: "The farm of course", themes: "loss and redeption")
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
include Authentication
has_many :contributions
has_many :clues
end
<file_sep>/app/models/outline.rb
class Outline < ActiveRecord::Base
belongs_to :outline
belongs_to :user
end
<file_sep>/app/serializers/contribution_serializer.rb
class ContributionSerializer < ActiveModel::Serializer
attributes :contribution, :outline_id, :user_id
belongs_to :user
belongs_to :outline, :counter_cache => true
def
end
<file_sep>/app/models/Story.rb
class Story < ActiveRecord::Base
MAXIMUM_CONTRIBUTIONS = 3
has_many :contributions
has_many :users, through: :contributions
has_many :clues
has_many :users, through: :clues
end
<file_sep>/README.md
# StorWe_API
StorWe Web App
About: StorWe is a collaborative storytelling site, that uses contributions from its users to write new stories. It’s a little like the game Telephone and a little like Exquisite Corpse. Each story begins with three prompts/clues: subject, setting, theme, and each story has exactly 10 contributors. Once ten contributions have been submitted, a new story prompt starts.
User Stories:
(Users are referred to by the game as contributors)
As a visitor to the site, I want to know what I can do, so I can choose whether to register or not.
Deliverables: A default page setting that includes a brief description of StorWe AND a full version of the most recent story.
As a contributor, I want to register a username and password, so I can login.
Deliverables: Login Button with new user Registration option linking to the appropriate form that gets posted/“getted" to/from a database.
As a contributor, I want to see a clue from the previous contributor, so I can keep the story on track.
Deliverables: A “read only” textbox with limited character inputs so contributors can see: the previous contributor’s clue before submitting their story contribution.
As a contributor, I want to know how many contributors have already added to the story, so I have understand how far along the story might be.
Deliverables: A counter that lets the contributor know what place their contribution will fall between 1-10.
As a contributor, I want to add content to the story, so I can contribute to it.
Deliverables: An editable text box for contributors to write up to 200 characters in to contribute to the story. A submit button, with a warning that explains, once you submit, you can’t change your contribution.
As a contributor, I want to see the the whole “in-progress” story after contributing, so I can read it.
Deliverables: A hidden “read only” text box that becomes unhidden after the contribution is submitting.
As a contributor, I want write a “keyword” clue for the next user, so they can keep the story on track.
Deliverables: “A “read and write” text box that contributors can provide their clues in after submitting their contribution AND seeing the whole story in progress.
As a contributor, I want to read the complete story, so I can know how it end.
Deliverables: A refresh button that reloads the limited contributor generated story.
I used the following template to make a paper prototype of my layout, to help me figure out my user stories.

Logic
Stories
The most recent completed story is available to read on the login/registration page
Stories are complete when Outline changes
The story in progress is visible only after a contribution is submitted
Outines
Outlines are provided from the database upon login
Outlines change every ten Contributions
Clues
Users receive clues from the previous user upon login, unless you are the first user
After they submit their contribution, users submit clues for the next user
Contributions
Users make a contribution and submit it upon login
A contribution is appended to the story in progress after submission
Stories are made up of ten contributions
New user
middle of one
completes one
This project is udergoing some changes. please come back and check it out at a later time. Check out progress at http://eshimel.github.io/StorWe_Front_End/
or checkout the front-end repo https://github.com/eshimel/StorWe_Front_End.
Notes about the USER authentication process
# User authentication
## Register
```
curl --include --request POST --header "Content-Type: application/json" -d '{
"credentials": {
"email": "<EMAIL>",
"password": "<PASSWORD>",
"password_confirmation": "<PASSWORD>"
}
}' http://localhost:3000/register
```
## Login
```
curl --request POST --header "Content-Type: application/json" -d '{
"credentials": {
"email": "<EMAIL>",
"password": "<PASSWORD>"
}
}' http://localhost:3000/login
```
## Logout
```
curl --request DELETE --header "Authorization: Token token=c017d611187e3350baffc52d35a4df69" http://localhost:3000/logout/1
```
# Users
## List
```
curl --header "Authorization: Token token=c017d611187e3350baffc52d35a4df69" http://localhost:3000/users
```
# Books
## List
```
curl --header "Authorization: Token token=c017d611187e3350baffc52d35a4df69" http://localhost:3000/users
```
**OR**
```
curl http://localhost:3000/users
```
## Create
```
curl --request POST --header "Authorization: Token token=<PASSWORD>" --header "Content-Type: application/json" -d '{
"book": {
"title":"The Hold",
"isbn":"abc123def456"
}
}' http://localhost:3000/books
```
<file_sep>/scripts/clue_pop.rb
r = Clue.create!(clue: 'Good luck sucker', outline_id: 1, user_id: 11)
e = Clue.create!(clue: 'Good luck sucker', outline_id: 1, user_id: 13)
t = Clue.create!(clue: 'Good luck sucker', outline_id: 1, user_id: 16)
<file_sep>/app/controllers/clues_controller.rb
#Users receive clues from the previous user.
#Users submit clues for the next user.
class CluesController < ProtectedController
before_action :set_clue, only: [:update, :destroy]
# GET clue
def index
if(current_user)
@clues = current_user.clues
else
@clues = Clue.all
end
render json: @clues
end
# GET clue/1
def show
# clue = clue.find(params[:id])
render json: current_user.clue
end
# POST clue
def create
clue = current_user.create_clue(clue_params) #makes this, this user' clue.
if clue.save
render json: clue, status: :created, location: clue
else
render json: clue.errors, status: :unprocessable_entity
end
end
# PATCH clue/1
def update
if @clue.update(clue_params)
head :no_content
else
render json: clue.errors, status: :unprocessable_entity
end
end
# DELETE clue/1
def destroy
clue.destroy
head :no_content
end
private
def set_clue
@clue = current_user.clue#.find(params[:id])
end
def clue_params
params.require(:clue).permit(:user, :outline)
end
end
<file_sep>/app/controllers/stories_controller.rb
# the previous story is set on the login/registration page
# stories are compiled every ten contributions
# the story in progress is visible after a contribution is submitted
class StoriesController < ProtectedController
before_action :set_story, only: [:show, :update, :destroy]
# GET /storys
def index
if(current_user)
@story = Story.all
else
@stories= current_user.stories
end
render json: @stories
end
# GET /storys/1
def show
@story = Story.find(params[:id])
render json: @story
end
# POST /storys
def create
@story = current_user.create_story(story_params) #makes this, this user's story.
if @stories.save
render json: @story, status: :created, location: @story
else
render json: @story.errors, status: :unprocessable_entity
end
end
# PATCH /storys/1
def update
if @story.update(story_params)
head :no_content
else
render json: @story.errors, status: :unprocessable_entity
end
end
# DELETE /storys/1
def destroy
@story.destroy
head :no_content
end
def set_story
@story = stories.find(params[:id])
end
def story_params
params.require(:contribution).permit(:clue, :user, :outline)
end
private :set_story, :story_params
end
<file_sep>/app/models/clue.rb
class Clue < ActiveRecord::Base
belongs_to :outline
belongs_to :user
end
<file_sep>/app/serializers/Story_serializer.rb
class StorySerializer < Contribution::Serializer
attributes :contribution, :clue, :outline_id, :user_id
MAXIMUM_CONTRIBUTIONS = 3
has_many :contributions
has_many :users, through: :contributions
has_many :clues
has_many :users, through: :clues
end
<file_sep>/app/serializers/clue_serializer.rb
#
class ClueSerializer < User::Serializer
attributes :clue, :outline_id, :user_id
end
<file_sep>/app/controllers/contributions_controller.rb
class ContributionsController < ProtectedController
skip_before_action :set_contribution, only: [:update, :destroy]
# GET /contributions
def index
@contributions = Contribution.all
render json: @contributions
end
# GET /contributions/1
def show
@contribution = Contribution.find(params[:id])
render json: @contribution
end
# POST /contributions
# def create
# @contribution = current_user.create.contribution(contribution_params) #makes this, this user's contribution.
def create
contribution = Contribution.new(submission: current_user)
save game, :created
end
# if @contribution.save
# render json: @contribution, status: :created
#else
# render json: @contribution.errors, status: :unprocessable_entity
#end
#end
# PATCH /contributions/1
def update
if @contribution.update(contribution_params)
head :no_content
else
render json: @contribution.errors, status: :unprocessable_entity
end
end
# DELETE /contributions/1
def destroy
@contribution.destroy
head :no_content
end
private
def set_contribution
@contribution = current_user.contributions.find(params[:id])
end
def contribution_params
params.require(:contribution).permit(:submission, :user_id, :outline_id)
end
end
<file_sep>/scripts/test_data.rb
one = Contribution.create!(submission: 'Earl was born <NAME>, but no one knows why he changed his name. Maybe, he was bored.', outline_id: 1, user_id: 1)
two = Contribution.create!(submission: 'Mostly I just want to write a sample to see if I can pull up a story index.', outline_id: 1, user_id: 2 )
three = Contribution.create!(submission: 'This better work, and by the way, Earl changed his name because there were too many Smiths around.', outline_id: 1, user_id: 3)
Story.create!(contribution: one)
Story.create!(contribution: two)
Story.create!(contribution: three)
<file_sep>/db/migrate/20151112161352_remove_count_column_from_outlines.rb
class RemoveCountColumnFromOutlines < ActiveRecord::Migration
def change
remove_column :outlines, :column_count, :integer
end
end
<file_sep>/app/models/contribution.rb
class Contribution < ActiveRecord::Base
belongs_to :outline
belongs_to :user
end
<file_sep>/app/serializers/current_user_serializer.rb
# Add to json of UserSerializer
class CurrentUserSerializer < UserSerializer
attributes :details
def details
'Details you only get if this is the current_user' if current_user
#person 1 has no user clues
#has an outline provided
#submits a contribution
#can see the story in progress after submission
#can leave a clue for the next user
#person 2 has previous user clue
#has the same outline as person 1 provided
#submits a contribution
#can see the story in progress after submission
#can leave a clue for the next user
#person 3 has previous user clue
#has the same outline as person's one and two
#submits a contribution to finish the story
#can see the story in progress after submission
#finishes the story upon submission
end
end
<file_sep>/db/migrate/20151109191956_addcount_column_to_outlines.rb
class AddcountColumnToOutlines < ActiveRecord::Migration
def self.up
add_column :outlines, :column_count, :integer, :default => 0
end
def self.down
remove_column :outlines, :column_count
end
end
<file_sep>/app/controllers/outlines_controller.rb
# Outlines are provided from the database upon login
#Outlines change when new stories change
#Outlines change every ten contributions
class OutlinesController < ProtectedController
before_action :set_outline, only: [:update, :destroy]
# GET outlines
def index
outlines = Outline.all
render json: outlines
end
# GET outlines/1
def show
outline = outline.find(params[:id])
render json: outline
end
# POST outlines
def create
outline = current_user.outlines.new.(outline_params) #makes this, this user'soutline.
if outline.save
render json: outline, status: :created, location: outline
else
render json: outline.errors, status: :unprocessable_entity
end
end
# PATCH outlines/1
def update
if @outline.update(outline_params)
head :no_content
else
render json: outline.errors, status: :unprocessable_entity
end
end
# DELETE outlines/1
def destroy
outline.destroy
head :no_content
end
def set_outline
outline = current_user.outlines.find(params[:id])
end
def outline_params
params.require(:theme).permit(:setting, :subject)
end
private :set_outline, :outline_params
end
<file_sep>/app/serializers/outline_serializer.rb
class OutlineSerializer < ActiveModel::Serializer
attributes :subject, :setting, :theme, :outline_id, :user_id
end
<file_sep>/app/controllers/application_controller.rb
#
class ApplicationController < ActionController::Base
# Defaults for API requests
before_action :api_request_settings
def api_request_settings
request.format = :json
end
# Use Token Authentication
include ActionController::HttpAuthentication::Token::ControllerMethods
before_action :authenticate
def authenticate
@current_user = authenticate_or_request_with_http_token do |token, _opts|
User.find_by token: token
end
end
# Controllers can use this to authorize actions
attr_reader :current_user
# Require SSL for deployed applications
force_ssl if: :ssl_configured?
def ssl_configured?
!Rails.env.development?
end
# Use enhanced JSON serialization
include ActionController::Serialization
# return 404 for failed search by id
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
def record_not_found
render json: { message: 'Not Found' }, status: :not_found
end
# Restrict visibility of these methods
private :authenticate, :current_user, :record_not_found
private :ssl_configured?, :api_request_settings
end
| 69cc418a860cd02450b954e0707ce7a17f71644c | [
"Markdown",
"Ruby"
] | 21 | Ruby | eshimel/StorWe_API | 809f75be974fcd9cdac6ecd6acc01b0e8ac1c21f | 78132ad297f72d02bf6fe24da4013fdbe86a512f |
refs/heads/master | <file_sep>import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Item } from '../models/Items';
import { HttpClient, HttpParams } from '@angular/common/http';
import { apiKey } from '../config/api';
@Injectable({
providedIn: 'root'
})
export class ItemService {
private selectedItem$: Subject<Item> = new Subject<Item>();
// Using the ApiKey from config api.ts
private apiKey: string = apiKey;
// Declaring the api url and configurations url
private baseConfigurationUrl: string = 'https://api.themoviedb.org/3/configuration';
private baseApiUrl: string = 'https://api.themoviedb.org/3/search/movie';
private imageBaseUrl: string = '';
private imageSize: { poster?: string[] } = {};
constructor(private http: HttpClient) {
// Setting the image configurations
this.setImageConfiguration();
}
// Retrieving the current item, from selected items
get currentItem() {
return this.selectedItem$;
}
// Searching function through API, and storing the results into Item
searchItem(query: string) {
//Using the API key
const params = new HttpParams().set('api_key', this.apiKey).set('query', query);
//Using the API URL
return this.http.get<any>(this.baseApiUrl, { params }).map((res) =>
//Responding with the results
res.results.map((result: Item) => {
return {
...result,
//Making Poster URL
posterUrl: this.createPhotoUrl(result.poster_path)
};
})
);
}
//Function to change the selected item
changeSelectedItem(item: Item) {
this.selectedItem$.next(item);
}
//Setting the image through configuration URL
setImageConfiguration() {
//Using the API key
const params = new HttpParams().set('api_key', this.apiKey);
//Using the Configuration URL
this.http.get<any>(this.baseConfigurationUrl, { params }).map((res) => res).subscribe((config) => {
//Retrieving the Image URL and the size
(this.imageBaseUrl = config.images.base_url),
(this.imageSize = {
poster: config.images.backdrop_sizes
});
});
}
//Creating The Image and if there is none, using the placeholder stored in assets
createPhotoUrl(path: string) {
if (!path) {
const placeholder = './assets/poster-placeholder.png';
return placeholder;
}
const { poster } = this.imageSize;
const imageSize = poster[poster.length - 1];
return `${this.imageBaseUrl}${imageSize}${path}`;
}
}
<file_sep>import { Component, OnInit, Input } from '@angular/core';
import mediumZoom from 'medium-zoom';
import { Router } from '@angular/router';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: []
})
export class CartComponent implements OnInit {
@Input() cartItem: any[] = [];
@Input() showDivCart: any = {};
constructor(private router: Router) {}
ngOnInit(): void {}
//Again zoom, but this time for the cart part ( TODO - move it to separate component)
zoom() {
const zoom = mediumZoom('.item-preview_poster', { background: 'rgba(41, 41, 41, 0.5)', margin: 24 });
addEventListener('click', () => zoom.close());
}
//Remove from Cart function, currently based on title (TODO add id's when localStorage will work)
removeItemFromCart(title: string) {
for (var i = 0; i < this.cartItem.length; i++) {
if (this.cartItem[i]['title'] === title) {
this.cartItem.splice(i, 1);
}
}
}
//Routing navigation
goToPage(pageName: string): void {
this.router.navigate([ `${pageName}` ]);
}
}
<file_sep>import { Component } from '@angular/core';
import { Item } from './models/Items';
import { ItemService } from './services/item.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
cartItems = [];
search: string;
currentItem: Item = null;
constructor(private itemService: ItemService) {
/*Setting the current item (Opening a display page) */
itemService.currentItem.subscribe((item) => {
this.currentItem = item;
});
}
/*Setting the selected items to be null (returning back to the search page) */
startNewSearch() {
this.itemService.changeSelectedItem(null);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SearchComponent } from './search/search.component';
import { CartComponent } from './search//cart-items/cart.component';
/*Just an example of route ( had some issues with retrieveing data from localStorage, and didn't use it as a main routing) */
const routes: Routes = [ { path: 'cart', component: CartComponent }, { path: 'search', component: SearchComponent } ];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Item } from '../../models/Items';
@Component({
selector: 'display-item',
templateUrl: './display-item.component.html',
styles: []
})
export class DisplayItemComponent implements OnInit {
//Event emitter of a new search, from nullifing the currentItem
@Output() startNewSearch = new EventEmitter();
@Input() item: Item;
constructor() {}
ngOnInit(): void {}
}
<file_sep>import { Component, OnInit, Input } from '@angular/core';
import { Item } from '../../models/Items';
import { ItemService } from '../../services/item.service';
import { MessengerService } from '../../services/messenger.service';
import mediumZoom from 'medium-zoom';
@Component({
selector: 'item-preview',
templateUrl: './item-preview.component.html',
styles: []
})
export class ItemPreviewComponent implements OnInit {
@Input() item: Item = {};
//Assigning the index as 1
@Input() index: number = 1;
constructor(private itemService: ItemService, private msg: MessengerService) {}
ngOnInit() {}
//Setting the current item
setCurrentItem(item: Item) {
this.itemService.changeSelectedItem(item);
}
//Small animation delay function for the data import
animationDelay = () => ({
'animation-delay': `${this.index * 0.1}s`
});
//Add to cart button function
handleAddToCart() {
this.msg.sendItem(this.item);
}
//Zooming to a poster from icon
zoom() {
const zoom = mediumZoom('.item-preview_poster', { background: 'rgba(41, 41, 41, 0.5)', margin: 24 });
addEventListener('click', () => zoom.close());
}
}
<file_sep>//Regular Item model with a removal of required status
export interface Item {
poster_path?:string|null
original_title?:string
overview?:string
title?:string
release_date?:string
posterUrl?:string
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { faSearch } from '@fortawesome/free-solid-svg-icons';
import { Item } from '../models/Items';
import { ItemService } from '../services/item.service';
import { Subject } from 'rxjs/Subject';
import { Router } from '@angular/router';
import { MessengerService } from '../services/messenger.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
@Component({
selector: 'search-item',
templateUrl: './search.component.html',
styles: []
})
export class SearchComponent implements OnInit {
item: Item = {};
cartItems = [];
searchResults: Item[] = [];
search$: Subject<string> = new Subject<string>();
fetching: boolean = false;
totalRecords: number;
page: number = 1;
faSearch = faSearch;
search: string = '';
constructor(
private itemService: ItemService,
private router: Router,
private msg: MessengerService,
private _flashMessagesService: FlashMessagesService
) {}
//Subscribing with the messenger the selected item and moving it to cartItem
ngOnInit(): void {
this.msg.getItem().subscribe((item: Item) => {
this.addItemToCart(item);
});
this.search$
//Delay effect for the search input
.debounceTime(500)
.map((query) => {
this.fetching = true;
return query;
})
//After the delay, subribing it
.subscribe(this.searchQuery.bind(this));
}
//Routing navigation
goToPage(pageName: string): void {
this.router.navigate([ `${pageName}` ]);
}
//Fetching the results
searchQuery(query: string) {
if (query.length > 0) {
this.itemService.searchItem(query).subscribe((results) => {
this.fetching = false;
this.searchResults = results;
this.totalRecords = results.length;
});
} else {
this.fetching = false;
this.searchResults = [];
}
}
//Hiding and showing pages boolean
showDiv = {
current: true,
next: false
};
//Add to cart function, with flash messages on error and success
addItemToCart(item: Item) {
let itemExists = false;
for (let i in this.cartItems) {
//Checking if the item is already in the cart
if (this.cartItems[i].title === item.title) {
this._flashMessagesService.show('You cannot add ' + this.cartItems[i].title + ' more than one time!', {
cssClass: 'alert-danger animated fadeIn',
timeout: 2000
});
itemExists = true;
break;
}
}
//TODO - add id and push it to localStorage
if (!itemExists) {
this.cartItems.push({
title: item.title,
posterUrl: item.posterUrl
});
this._flashMessagesService.show('You added ' + item.title + ' to your cart.', {
cssClass: 'alert-success animated fadeIn',
timeout: 2000
});
}
}
}
<file_sep>const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(__dirname + '/dist/WARM/'));
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname + '/dist/WARM/index.html'));
});
//Just configurations for the Deployment
app.listen(process.env.PORT || 5555, process.env.IP, function() {
console.log('Server is started');
});
<file_sep>import { Item } from './items'
//A model for the cart items (tried to make it work with the localStorage)
export class CartItems {
poster_path?: string | null;
original_title?: string;
overview?: string;
title?: string;
release_date?: string;
posterUrl?: string;
id?: number;
constructor (id: number, item: Item){
this.id = id;
this.title = item.title;
this.posterUrl = item.posterUrl;
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MessengerService {
subject = new Subject();
constructor() {}
//Simple messenger service, sending the subject of item, and also storing it to the localStorage as a JSON
//Need some extra help to make it actually work, currently using the subject only.
sendItem(item: any) {
this.subject.next(item);
localStorage.setItem('ordered', JSON.stringify(item));
if (localStorage.getItem('ordered') === null) {
item = [];
} else {
item = JSON.parse(localStorage.getItem('ordered'));
}
}
getItem() {
//Returning this item as Observable
//Also need some extra help to make to make it return from the localStorage and not subject
return this.subject.asObservable();
}
}
| f2e99030f65b9200a687ae6b38f223f0c7e45db5 | [
"JavaScript",
"TypeScript"
] | 11 | TypeScript | F0rty-Tw0/warmer | a972a7dc40ec1a156a71039577c3b0e4cf13cb1a | 71f75f8001929365a8dfe308fdea72509a36cc6b |
refs/heads/master | <repo_name>bruno1030/swift_ios<file_sep>/Filmes/Filmes/Director.swift
//
// Director.swift
// Filmes
//
// Created by <NAME> on 10/05/19.
// Copyright © 2019 FIAP. All rights reserved.
//
import Foundation
struct Director: Codable {
let name: String
let fullName: String
let birthdateYear: String
let id: Int
}
<file_sep>/Filmes/Filmes/MovieViewController.swift
//
// MovieViewController.swift
// Filmes
//
// Created by <NAME> on 10/05/19.
// Copyright © 2019 FIAP. All rights reserved.
//
import UIKit
class MovieViewController: UIViewController {
var movie: Movie!
@IBOutlet weak var lbTitle: UILabel!
@IBOutlet weak var lbRating: UILabel!
@IBOutlet weak var lbYear: UILabel!
@IBOutlet weak var tvSinopsis: UITextView!
@IBOutlet weak var ivPoster: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
showMovie()
}
func showMovie() {
if movie != nil {
lbTitle.text = movie.name
lbRating.text = "\(movie.rating)"
lbYear.text = movie.year
tvSinopsis.text = movie.sinopsis
ivPoster.image = UIImage(named: movie.image)
}
}
}
<file_sep>/Filmes/Filmes/Movie.swift
//
// Movie.swift
// Filmes
//
// Created by <NAME> on 10/05/19.
// Copyright © 2019 FIAP. All rights reserved.
//
import Foundation
struct Movie: Codable {
let name: String
let year: String
let rating: Double
let sinopsis: String
let image: String
}
| aecc9be29f7103136998d9005374443478a82262 | [
"Swift"
] | 3 | Swift | bruno1030/swift_ios | 0550ae7b5da2a6785f7e30c0a94a4d09e53c644c | ba884af86257d49dc18ae8c217474a098b1365e0 |
refs/heads/main | <repo_name>cro/prodev-conference-app<file_sep>/backend/start.sh
#!/usr/bin/env bash
set -euo pipefail
cd /app
npm install
npm run migrate up
npm run start
<file_sep>/backend-badges/Dockerfile
FROM node:14-buster
WORKDIR /app
COPY server.mjs /app
COPY package.json /app
RUN npm install
CMD ["npm", "run", "start"]
| f9dde599d0432db323095ea1a34cbf2471c06b3c | [
"Dockerfile",
"Shell"
] | 2 | Shell | cro/prodev-conference-app | e38044e87529d4bafe607418be8f9a919159068c | 84522a4751b9920800efbef43597fad82216d161 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class QuestManager : MonoBehaviour {
public struct ThoughtsList
{
public Sprite[] sprts;
public string[] subtitles;
public float period;
public float duration;
public bool isPeriodical;
public bool isOnlyWhenNear;
public ThoughtsList(Sprite[] _sprts, string[] _subtitles, float _period, float _duration, bool _isPeriodical, bool _isOnlyWhenNear)
{
sprts = _sprts;
subtitles = _subtitles;
period = _period;
duration = _duration;
isPeriodical = _isPeriodical;
isOnlyWhenNear = _isOnlyWhenNear;
}
}
public Quests.Quest[] questArray;
public GameObject[] PCGOs;
public GameObject[] cameras;
public AudioClip[] audios;
public GameObject audioMan;
public Sprite[] dialogIcons;
public int currentQuest;
public int currentCamera;
//public bool isPlayerOnTrigger;
public int extraVariable;
public bool autoNext;
public bool waitingForMovingEnd;
// Use this for initialization
void Start () {
questArray = Quests.GetQuestList();
currentQuest = (-1);
currentCamera = 0;
waitingForMovingEnd = true;
//Debug.Log(questArray.Length);
FinishedMoves(); //first launch
}
// Update is called once per frame
void Update () {
}
void OnTriggerEntered(PersonTrigger.Transit trans)
{
/*isPlayerOnTrigger = _isPlayerOnTrigger;
if (isPlayerOnTrigger)
{
}*/
cameras[trans.from].SetActive(false);
currentCamera = trans.to;
cameras[currentCamera].SetActive(true);
ChangePCGOs();
if (trans.from == 5 && trans.to == 6)
{
AudioSource aSo = audioMan.GetComponents<AudioSource>()[0];
aSo.Stop();
aSo = audioMan.GetComponents<AudioSource>()[1];
aSo.Stop();
}
}
void ChangePCGOs()
{
PCGOs = new GameObject[10];
Transform trans = cameras[currentCamera].transform.Find("Player");
if (trans != null)
{
PCGOs[0] = trans.gameObject;
PCGOs[0].SendMessage("SetQuestManager", gameObject);
}
trans = cameras[currentCamera].transform.Find("Mom");
/*if (currentCamera == 4)
{
Debug.Log(trans);
Debug.Log(trans.gameObject);
}*/
if (trans != null)
{
PCGOs[1] = trans.gameObject;
PCGOs[1].SendMessage("SetQuestManager", gameObject);
/*if (currentCamera == 4)
{
Debug.Log(PCGOs[1]);
}*/
}
trans = cameras[currentCamera].transform.Find("Papa");
if (trans != null)
{
PCGOs[2] = trans.gameObject;
PCGOs[2].SendMessage("SetQuestManager", gameObject);
}
}
void StartEvent(int questIndex)
{
currentQuest = questIndex;
FinishedMoves(false);
}
void FinishedMoves()
{
if (waitingForMovingEnd)
{
FinishedMoves(true);
}
}
void FinishedMoves(bool incr)
{
Debug.Log("FinishedMoves");
if (incr)
{
if (currentQuest >= 0)
{
if (questArray[questArray[currentQuest].nextQuest].resetPreviousDialogs)
{
Debug.Log("A1");
PCGOs[questArray[currentQuest].personID].SendMessage("ResetPreviousDialogs");
}
if (questArray[questArray[currentQuest].nextQuest].resetPreviousThoughts)
{
PCGOs[questArray[currentQuest].personID].SendMessage("ResetPreviousThoughts");
}
currentQuest = questArray[currentQuest].nextQuest;
}
else
{
currentQuest = 0;
}
}
autoNext = questArray[currentQuest].autoNext;
waitingForMovingEnd = true;
if (questArray[currentQuest].changeMusic)
{
AudioSource aSo = audioMan.GetComponents<AudioSource>()[0];
aSo.Stop();
aSo.clip = audios[(int)questArray[currentQuest].musicIndex];
aSo.loop = questArray[currentQuest].loopMusic;
aSo.Play();
}
if (questArray[currentQuest].changeSound)
{
AudioSource aSo = audioMan.GetComponents<AudioSource>()[1];
aSo.Stop();
aSo.clip = audios[(int)questArray[currentQuest].soundIndex];
aSo.loop = questArray[currentQuest].loopSound;
aSo.Play();
}
if (questArray[currentQuest].stopPrevMusic)
{
audioMan.GetComponents<AudioSource>()[0].Stop();
}
if (questArray[currentQuest].stopPrevSound)
{
audioMan.GetComponents<AudioSource>()[1].Stop();
}
if (questArray[currentQuest].changeScene)
{
Application.LoadLevel(questArray[currentQuest].sceneIndex);
}
else if (questArray[currentQuest].changeCamera)
{
cameras[currentCamera].SetActive(false);
currentCamera = questArray[currentQuest].cameraIndex;
cameras[currentCamera].SetActive(true);
ChangePCGOs();
}
if (questArray[currentQuest].isMoving)
{
//Debug.Log("B-1");
//Debug.Log("FinishedMoves-isMoving");
PCGOs[questArray[currentQuest].personID].SendMessage("SetMovingList", questArray[currentQuest].movings);
Debug.Log(waitingForMovingEnd);
waitingForMovingEnd = questArray[currentQuest].sendMovingEnd;
}
else
{
if (questArray[currentQuest].movings!=null && questArray[currentQuest].movings.Length > 0)
{
StartCoroutine(JustWaitHere(questArray[currentQuest].movings[0].value));
}
// else
// {
if (questArray[currentQuest].isThoughting)
{
//Debug.Log("FinishedMoves-isThoughting");
Quests.CloudSet cs = questArray[currentQuest].thoughtSeries;
Sprite[] sprts = new Sprite[cs.thoughtsIcons.Length];
Debug.Log("AAAAAAAAAAAAAAAAAAAAAAAAAAAAA " + sprts.Length);
//Debug.Log(sprts.Length);
for (int i = 0; i < sprts.Length; i++)
{
sprts[i] = dialogIcons[(int)cs.thoughtsIcons[i]];
}
PCGOs[questArray[currentQuest].personID].SendMessage("SetThoughtsList", new ThoughtsList(sprts, cs.subtitles, cs.period, cs.duration, cs.isPeriodical, cs.isOnlyWhenNear));
Debug.Log("THOU SET");
}
else if (questArray[currentQuest].dialogSeries != null)
{
Sprite[] sprts = new Sprite[questArray[currentQuest].dialogSeries.Length];
for (int i = 0; i < sprts.Length; i++)
{
sprts[i] = dialogIcons[(int)questArray[currentQuest].dialogSeries[i]];
}
PCGOs[questArray[currentQuest].personID].SendMessage("SetDialogList", sprts);
}
}
// }
}
IEnumerator JustWaitHere(float forHowMany)
{
yield return new WaitForSeconds(forHowMany);
if (autoNext)
{
FinishedMoves();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimToLeft : MonoBehaviour {
public GameObject qm;
public float duration = 8.5f;
public float xSrc;
public float xDest;
public bool getNext;
// Use this for initialization
void Start () {
xSrc = gameObject.transform.localPosition.x;
if (xSrc > xDest)
{
StartCoroutine(MoveObjToLeft());
}
else
{
StartCoroutine(MoveObjToRight());
}
}
// Update is called once per frame
void Update () {
}
IEnumerator MoveObjToLeft()
{
Vector3 pos = gameObject.transform.localPosition;
float speed = (xDest - xSrc) / duration;
while (pos.x > xDest)
{
pos.x += speed * Time.deltaTime;
gameObject.transform.localPosition = pos;
yield return new WaitForEndOfFrame();
}
pos.x = xDest;
gameObject.transform.localPosition = pos;
if (getNext)
{
qm.SendMessage("OnTriggerEntered", new PersonTrigger.Transit(6, 5));
}
}
IEnumerator MoveObjToRight()
{
Vector3 pos = gameObject.transform.localPosition;
float speed = (xDest - xSrc) / duration;
while (pos.x < xDest)
{
pos.x += speed * Time.deltaTime;
gameObject.transform.localPosition = pos;
yield return new WaitForEndOfFrame();
}
pos.x = xDest;
gameObject.transform.localPosition = pos;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ManuScript : MonoBehaviour {
public SpriteRenderer sr;
public bool isStartGame;
public bool isExitGame;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseUp()
{
if (isStartGame)
{
sr.enabled = true;
Application.LoadLevel(1);
}
else if (isExitGame)
{
Application.Quit();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OneTimeTrigger : MonoBehaviour {
public GameObject qm;
public bool alreadyActivated;
public int questIndex;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player")
{
if (!alreadyActivated)
{
qm.SendMessage("StartEvent", questIndex);
alreadyActivated = true;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ComiscScript : MonoBehaviour {
public SpriteRenderer sr;
public Sprite[] comicsSprites;
//public int curComics;
// Use this for initialization
void Start () {
//curComics = 0;
StartCoroutine(Comics());
}
// Update is called once per frame
void Update () {
}
IEnumerator Comics()
{
for (int i = 0; i < comicsSprites.Length; i++)
{
sr.sprite = comicsSprites[i];
yield return new WaitForSeconds(3.5f);
}
yield return new WaitForSeconds(10.0f);
Application.LoadLevel(0);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Quests {
public enum GameTexture { Spot, Tank, Tower, TowerExp, Rudes, NoSignal, TowerBroken,
Wrench, TowerSignal, Good, Happy, Phone, Question, Lamp, Spring, Screwdriver,
Wires, Button, Vase, Pillow, Clothes, Timer, Peace, Thoughts, Market, Plus,
Apple, Butter, Flour, Potato };
public enum GameAudio { TerribleDream, SawAButterfly, AlarmClockBell, Birds, HomeTheme, EndTheme };
public struct CloudSet
{
public GameTexture[] thoughtsIcons;
public string[] subtitles;
public float period;
public float duration;
public bool isPeriodical;
public bool isOnlyWhenNear;
public CloudSet(GameTexture[] _thoughtsIcons, string[] _subtitles, float _period, float _duration, bool _isPeriodical, bool _isOnlyWhenNear)
{
thoughtsIcons = _thoughtsIcons;
subtitles = _subtitles;
period = _period;
duration = _duration;
isPeriodical = _isPeriodical;
isOnlyWhenNear = _isOnlyWhenNear;
}
}
public struct Moving
{
public string name;
public float value;
public bool isX;
public bool isWaitFor;
/// <summary>
/// Full ctor
/// </summary>
public Moving(string _name, float _value, bool _isX, bool _isWaitFor)
{
name = _name;
value = _value;
isX = _isX;
isWaitFor = _isWaitFor;
}
/// <summary>
/// Dir changer
/// </summary>
public Moving(float _value, bool _isX, bool _isWaitFor)
{
name = "";
value = _value;
isX = false;
isWaitFor = true;
}
/// <summary>
/// Mover
/// </summary>
public Moving(float _value, bool _isX)
{
name = "";
value = _value;
isX = _isX;
isWaitFor = false;
}
/// <summary>
/// Waiter
/// </summary>
public Moving(float _value)
{
name = "";
value = _value;
isX = true;
isWaitFor = true;
}
}
public struct Quest
{
public string name;
public int personID; //0-Player 1-Mother 2-Father
public bool isMoving;
public bool isThoughting;
public Moving[] movings;
public GameTexture[] dialogSeries;
public CloudSet thoughtSeries;
public string endMessage;
public int nextQuest;
public bool resetPreviousDialogs;
public bool resetPreviousThoughts;
public bool changeCamera;
public int cameraIndex;
public bool changeScene;
public int sceneIndex; //(-1) if exit to menu
public bool changeMusic;
public GameAudio musicIndex;
public bool changeSound;
public GameAudio soundIndex;
public bool loopMusic;
public bool loopSound;
public bool stopPrevMusic;
public bool stopPrevSound;
public bool autoNext;
public bool sendMovingEnd;
}
public static Quest[] GetQuestList()
{
Quest[] questArray = new Quest[10];
questArray[0].name = "Nigthdream1";
questArray[0].personID = 0;
questArray[0].isMoving = true;
questArray[0].sendMovingEnd = true;
questArray[0].movings = new Moving[]{
new Moving(-1.0f, true),
new Moving(0.5f),
new Moving(0.0f, false, false),
new Moving(0.5f),
new Moving(0.0f, true),
new Moving(0.5f)
};
questArray[0].nextQuest = 1;
questArray[1].name = "Nigthdream2";
questArray[1].personID = 0;
questArray[1].isThoughting = true;
questArray[1].sendMovingEnd = true;
questArray[1].thoughtSeries = new CloudSet(
new GameTexture[] { GameTexture.Spot/*, GameTexture.Tank*/ },
new string[] { "Ow, a butterfly!" },
0.01f, 1.5f, false, false);
questArray[1].nextQuest = 2;
questArray[2].name = "Nigthdream3";
questArray[2].personID = 0;
questArray[2].isMoving = true;
questArray[2].movings = new Moving[]{
new Moving(0.5f),
new Moving(1.168f, true),
new Moving(0.2f),
new Moving(0.0f, false, false),
new Moving(0.5f)
};
questArray[2].sendMovingEnd = true;
questArray[2].resetPreviousThoughts = true;
questArray[2].nextQuest = 3;
questArray[3].name = "Nigthdream4";
questArray[3].isMoving = false;
questArray[3].autoNext = true;
questArray[3].movings = new Moving[]{
new Moving(4.5f)
};
questArray[3].changeCamera = true;
questArray[3].cameraIndex = 1;
questArray[3].nextQuest = 4;
questArray[4].name = "Nigthdream5";
questArray[4].isMoving = false;
questArray[4].autoNext = true;
questArray[4].movings = new Moving[]{
new Moving(3.5f)
};
questArray[4].changeCamera = true;
questArray[4].changeSound = true;
questArray[4].soundIndex = GameAudio.AlarmClockBell;
questArray[4].cameraIndex = 2;
questArray[4].nextQuest = 5;
questArray[5].name = "Home1";
questArray[5].isMoving = false;
questArray[5].movings = new Moving[]{
new Moving(2.0f)
};
questArray[5].changeCamera = true;
questArray[5].cameraIndex = 3;
//questArray[5].stopPrevMusic = true;
//questArray[5].stopPrevSound = true;
questArray[5].changeMusic = true;
questArray[5].musicIndex = GameAudio.HomeTheme;
questArray[5].loopMusic = true;
questArray[5].nextQuest = 6;
questArray[6].name = "Home2";
questArray[6].personID = 1;
/*questArray[6].isMoving = true;
questArray[6].movings = new Moving[]{
new Moving(3.0f),
new Moving(40.575f, true),
new Moving(-0.575f, false)
};*/
questArray[6].sendMovingEnd = true;
questArray[6].isThoughting = true;
questArray[6].thoughtSeries = new CloudSet(
new GameTexture[] { GameTexture.Thoughts },
new string[] { "[thinks]" },
0.5f, 1.5f, false, false);
questArray[6].nextQuest = 7;
questArray[7].name = "Home2";
questArray[7].personID = 1;
questArray[7].isMoving = true;
questArray[7].movings = new Moving[]{
new Moving(3.0f),
new Moving(40.575f, true),
new Moving(-0.575f, false)
};
questArray[7].sendMovingEnd = false;
questArray[7].nextQuest = 7;
/*questArray[1].name = "Nigthdream2";
questArray[1].personID = 0;
questArray[1].isThoughting = true;
questArray[1].sendMovingEnd = true;
questArray[1].thoughtSeries = new CloudSet(
new GameTexture[] { GameTexture.Spot },
new string[] { "Ow, a butterfly!" },
0.01f, 1.5f, false, false);
questArray[1].nextQuest = 2;*/
questArray[7].name = "Home3";
questArray[7].personID = 1;
questArray[7].resetPreviousThoughts = false;
questArray[7].nextQuest = 8;
return questArray;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PersonTrigger : MonoBehaviour {
public struct Transit
{
public int to;
public int from;
public Transit(int _to, int _from)
{
to = _to;
from = _from;
}
}
//public bool isOnTriggerStay;
public GameObject pl;
public bool isTransition;
public int toScene;
public int fromScene;
//public int spawnDirection;
public bool alreadyWas;
// Use this for initialization
void Start () {
//pl = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player")
{
if (isTransition)
{
if (!alreadyWas)
{
pl.SendMessage("OnTriggerEntered", new Transit(toScene, fromScene));
alreadyWas = true;
}
/*Vector2 pos = col.gameObject.transform.position;
Vector2 selfPos = gameObject.transform.position;
Vector2 selfScl = gameObject.transform.lossyScale;
switch (spawnDirection)
{
case 0:
pos.y += selfPos.y + selfScl.y + 0.001f;
break;
case 1:
pos.x += selfPos.x + selfScl.x + 0.001f;
break;
case 2:
pos.y -= selfPos.y + selfScl.y + 0.001f;
break;
case 3:
pos.x -= selfPos.x + selfScl.x + 0.001f;
break;
}
col.gameObject.transform.position = pos;*/
}
else
{
gameObject.transform.parent.gameObject.SendMessage("OnTriggerEntered", true);
//isOnTriggerStay = true;
pl = col.gameObject;
}
}
}
void OnTriggerExit2D(Collider2D col)
{
if (isTransition)
{
alreadyWas = false;
}
else
{
if (col.gameObject.tag == "Player")
{
gameObject.transform.parent.gameObject.SendMessage("OnTriggerEntered", false);
//isOnTriggerStay = true;
}
}
}
/*void Subs(string[] subtits)
{
pl.SendMessage("Subs", subtits);
}
void AllowMoving(bool _isAllowedToMove)
{
pl.SendMessage("AllowMoving", _isAllowedToMove);
}
void DialogIconIndex(int index)
{
pl.SendMessage("DialogIconIndex", index);
}*/
}
<file_sep># GGJ2019_SomethingSymbolic
"SomethingSymbolic" for Global Game Jam 2019
Something Symbolic
Creators:
Com&A Team
(ComAndA Team)
<NAME>: Game Design, Code
<NAME>: Texture Designer, Script
<NAME>: Texture Designer, Script, Audio
<NAME>: Script, Audio
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPCController : MonoBehaviour {
public GameObject questMan;
public Rigidbody2D rigid;
public SpriteRenderer sr;
public SpriteRenderer cloudSR;
public SpriteRenderer iconSR;
public GUISkin gs;
//public GameObject triggerObject;
public float speed = 1000.0f;
public Vector2 moveVelocity;
public Sprite[] horizontalWalkAnimation;
public Sprite[] downWalkAnimation;
public Sprite[] upWalkAnimation;
public float horAxis;
public float verAxis;
public int curAnimState = 0;
public float animTimer = 0.0f;
public int lastDirection = 2;
public Quests.Moving[] movingList;
public Sprite[] dialogIcons;
public bool isDialoging;
public int requestingDialogIcon;
public Sprite[] thoughtsIcons;
public string[] subStrings;
public float thoughtsTimer;
public float thoughtsPeriod;
public float thoughtsDuration;
public bool isThoughtsPeriodical; //or permanent
public bool isThoughtsOnlyWhenNear; //or always
public bool isPlayerStayOnTrigger;
public GameObject pl;
public Sprite thoughtSprite;
public Sprite dialogSprite;
// Use this for initialization
void Start () {
//moveNPCCords(1.12f, 0.35f, 1.0f);
moveNPCXCord(1.12f);
//moveNPCYCord(0.35f);
pl = GameObject.FindGameObjectWithTag("Player");
}
/*IEnumerator Start () {
//moveNPCCords(1.12f, 0.35f, 1.0f);
yield return StartCoroutine(moveNPCXCordCor(1.12f, 1.0f));
moveNPCYCord(0.35f);
}*/
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Use") && isPlayerStayOnTrigger)
{
requestingDialogIcon++;
if (requestingDialogIcon >= dialogIcons.Length)
{
requestingDialogIcon = (-1);
//triggerObject.SendMessage("AllowMoving", true);
pl.SendMessage("AllowMoving", true);
isDialoging = false;
}
else if (requestingDialogIcon == 0)
{
//triggerObject.SendMessage("AllowMoving", false);
pl.SendMessage("AllowMoving", false);
isDialoging = true;
}
//triggerObject.SendMessage("DialogIconIndex", requestingDialogIcon);
//pl.SendMessage("DialogIconIndex", requestingDialogIcon);
cloudSR.sprite = dialogSprite;
iconSR.sprite = thoughtsIcons[requestingDialogIcon];
cloudSR.enabled = isDialoging;
iconSR.enabled = isDialoging;
}
if (!isDialoging)
{
if (isThoughtsPeriodical)
{
if (cloudSR.enabled)
{
if (thoughtsTimer < thoughtsDuration)
{
thoughtsTimer += Time.deltaTime;
}
else
{
cloudSR.enabled = false;
iconSR.enabled = false;
thoughtsTimer = 0.0f;
requestingDialogIcon++;
if (requestingDialogIcon >= thoughtsIcons.Length)
{
requestingDialogIcon = 0;
}
iconSR.sprite = thoughtsIcons[requestingDialogIcon];
}
}
else
{
if (thoughtsTimer < thoughtsPeriod)
{
thoughtsTimer += Time.deltaTime;
}
else
{
cloudSR.sprite = thoughtSprite;
cloudSR.enabled = true;
iconSR.enabled = true;
thoughtsTimer = 0.0f;
}
}
}
else if (thoughtsIcons.Length > 0 && !isThoughtsOnlyWhenNear)
{
if (!cloudSR.enabled)
{
cloudSR.enabled = true;
}
if (cloudSR.sprite != thoughtSprite)
{
cloudSR.sprite = thoughtSprite;
}
if (iconSR.sprite != thoughtsIcons[requestingDialogIcon])
{
iconSR.sprite = thoughtsIcons[requestingDialogIcon];
}
}
}
}
void OnTriggerEntered(bool isIt)
{
isPlayerStayOnTrigger = isIt;
if (isIt)
{
if (isThoughtsOnlyWhenNear && !isDialoging)
{
cloudSR.enabled = true;
cloudSR.sprite = thoughtSprite;
iconSR.enabled = true;
iconSR.sprite = thoughtsIcons[requestingDialogIcon];
}
}
else
{
cloudSR.enabled = false;
iconSR.enabled = false;
}
}
/*void OnGUI()
{
GUI.skin = gs;
if (Input.GetKey("Use") && isPlayerStayOnTrigger)
{
GUI.Label(new Rect(0, Screen.height-50, Screen.width, 30), subStrings[requestingDialogIcon]);
}
}*/
void OnGUI()
{
GUI.skin = gs;
if (Input.GetButton("Subtitles") && requestingDialogIcon >= 0 && subStrings.Length > 0)
{
GUI.Label(new Rect(0, Screen.height - 50, Screen.width, 30), subStrings[requestingDialogIcon]);
}
}
/*void SetViewDirection(int dir)
{
lastDirection = dir;
}*/
void SetMovingList(Quests.Moving[] movings)
{
movingList = movings;
StartCoroutine(MoveInList());
}
IEnumerator MoveInList()
{
Debug.Log("1");
for (int i = 0; i < movingList.Length; i++)
{
Debug.Log("2");
if (movingList[i].isWaitFor)
{
if (movingList[i].isX)
{
yield return new WaitForSeconds(movingList[i].value); //just wait
}
else
{
lastDirection = Mathf.RoundToInt(movingList[i].value); //change view direction
computeMoveAnim();
}
}
else
{
Debug.Log("3 " + movingList[i].value);
if (movingList[i].isX)
{
Debug.Log("4-1-1");
yield return StartCoroutine(moveNPCXCordCor(movingList[i].value, 1.0f)); //move on X
Debug.Log("4-1-2");
}
else
{
Debug.Log("4-2-1");
yield return StartCoroutine(moveNPCYCordCor(movingList[i].value, 1.0f)); //move on Y
Debug.Log("4-2-2");
}
}
}
questMan.SendMessage("FinishedMoves");
}
void SetDialogList(Sprite[] _sprts)
{
requestingDialogIcon = (-1);
dialogIcons = _sprts;
}
void SetThoughtsList(QuestManager.ThoughtsList _thoughts)
{
cloudSR.enabled = false;
requestingDialogIcon = 0;
thoughtsIcons = _thoughts.sprts;
subStrings = _thoughts.subtitles;
thoughtsPeriod = _thoughts.period;
thoughtsDuration = _thoughts.duration;
isThoughtsPeriodical = _thoughts.isPeriodical;
isThoughtsOnlyWhenNear = _thoughts.isOnlyWhenNear;
//pl.SendMessage("Subs", subStrings);
//pl.SendMessage("DialogIconIndex", requestingDialogIcon);
}
public void moveNPC(float hor, float ver, float duration)
{
StartCoroutine(moveNPCCor(hor, ver, 1.0f, duration));
}
public void moveNPC(float hor, float ver, float speedMultiplier, float duration)
{
StartCoroutine(moveNPCCor(hor, ver, speedMultiplier, duration));
}
/*public void moveNPCCords(float toX, float toY)
{
StartCoroutine(moveNPCCordsCor(toX, toY, 1.0f));
}
public void moveNPCCords(float toX, float toY, float speedMultiplier)
{
StartCoroutine(moveNPCCordsCor(toX, toY, speedMultiplier));
}*/
public void moveNPCXCord(float toX)
{
StartCoroutine(moveNPCXCordCor(toX, 1.0f));
}
public void moveNPCXCord(float toX, float speedMultiplier)
{
StartCoroutine(moveNPCXCordCor(toX, speedMultiplier));
}
public void moveNPCYCord(float toY)
{
StartCoroutine(moveNPCYCordCor(toY, 1.0f));
}
public void moveNPCYCord(float toY, float speedMultiplier)
{
StartCoroutine(moveNPCYCordCor(toY, speedMultiplier));
}
IEnumerator moveNPCCor(float hor, float ver, float speedMultiplier, float duration)
{
float timer = 0.0f;
while (timer < duration)
{
horAxis = hor * Time.deltaTime * speed * speedMultiplier;
verAxis = ver * Time.deltaTime * speed * speedMultiplier;
computeMoveAnim();
UpdateLayer();
timer += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
verAxis = 0.0f;
horAxis = 0.0f;
}
/*IEnumerator moveNPCCordsCor(float toX, float toY, float speedMultiplier)
{
Vector3 pos = gameObject.transform.position;
float xMul = 1.0f / (toX - pos.x);
float yMul = 1.0f / (toY - pos.y);
//while (Mathf.Abs(toX - pos.x) > 0.05f)
float duration = new Vector2(toX - pos.x, toY - pos.y).magnitude / 0.4f;
Debug.Log(xMul);
Debug.Log(yMul);
Debug.Log(duration);
float timer = 0.0f;
while (timer < duration)
{
verAxis = xMul * 0.4f * Time.deltaTime * speed * speedMultiplier;
horAxis = yMul * 0.4f * Time.deltaTime * speed * speedMultiplier;
computeMoveAnim();
UpdateLayer();
timer += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
verAxis = 0.0f;
horAxis = 0.0f;
}*/
IEnumerator moveNPCXCordCor(float toX, float speedMultiplier)
{
yield return new WaitForSeconds(1.0f);
Vector3 pos = gameObject.transform.position;
float duration = (toX - pos.x) - 0.1f/* * 0.4f*/;
float timer = 0.0f;
//Debug.Log(duration);
while (timer < duration)
{
horAxis = Time.deltaTime * speed * speedMultiplier;
computeMoveAnim();
UpdateLayer();
timer += Time.deltaTime;
Debug.Log("timer " + timer);
yield return new WaitForEndOfFrame();
}
horAxis = 0.0f;
rigid.velocity = new Vector2(0.0f, rigid.velocity.y);
pos.x = toX;
gameObject.transform.position = pos;
computeMoveAnim();
UpdateLayer();
}
IEnumerator moveNPCYCordCor(float toY, float speedMultiplier)
{
yield return new WaitForSeconds(1.0f);
Vector3 pos = gameObject.transform.position;
float duration = (toY - pos.y) - 0.1f/* * 0.4f*/;
float timer = 0.0f;
//Debug.Log(duration);
while (timer < duration)
{
verAxis = Time.deltaTime * speed * speedMultiplier;
computeMoveAnim();
UpdateLayer();
timer += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
verAxis = 0.0f;
rigid.velocity = new Vector2(rigid.velocity.x, 0.0f);
pos.y = toY;
gameObject.transform.position = pos;
computeMoveAnim();
UpdateLayer();
}
void computeMoveAnim()
{
if (verAxis == 0.0f && horAxis == 0.0f)
{
switch (lastDirection)
{
case 0:
sr.sprite = upWalkAnimation[0];
break;
case 1:
case 3:
sr.sprite = horizontalWalkAnimation[0];
break;
case 2:
sr.sprite = downWalkAnimation[0];
break;
}
}
else
{
animTimer += Time.deltaTime;
if (animTimer >= 0.08f)
{
curAnimState++;
if (curAnimState >= 4)
{
curAnimState = 0;
}
animTimer = 0.0f;
}
if (Mathf.Abs(verAxis) < Mathf.Abs(horAxis))
{
sr.sprite = horizontalWalkAnimation[curAnimState];
sr.flipX = horAxis < 0.0f;
lastDirection = sr.flipX ? 3 : 1;
}
else
{
if (verAxis > 0.0f)
{
sr.sprite = upWalkAnimation[curAnimState];
lastDirection = 0;
}
else
{
sr.sprite = downWalkAnimation[curAnimState];
lastDirection = 2;
}
}
}
}
void FixedUpdate()
{
if (horAxis != 0.0f || verAxis != 0.0f)
{
rigid.AddForce(new Vector2(horAxis, verAxis), ForceMode2D.Force);
}
}
void UpdateLayer()
{
Vector3 pos = gameObject.transform.position;
pos.z = pos.y / 100.0f;
gameObject.transform.position = pos;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMovement : MonoBehaviour {
public GameObject questMan;
public Rigidbody2D rigid;
public SpriteRenderer sr;
public GUISkin gs;
public float speed = 1000.0f;
public Vector2 moveVelocity;
public Sprite[] horizontalWalkAnimation;
public Sprite[] downWalkAnimation;
public Sprite[] upWalkAnimation;
public float horAxis;
public float verAxis;
public int curAnimState = 0;
public float animTimer = 0.0f;
public int lastDirection = 2;
//public int secs;
public bool isPlayerStayOnTrigger;
public string[] subStrings;
public bool isAllowedToMove;
public int requestingDialogIcon;
public Quests.Moving[] movingList;
public float thoughtsTimer;
public float thoughtsPeriod;
public float thoughtsDuration;
public bool isThoughtsPeriodical; //or permanent
public bool isThoughtsOnlyWhenNear; //or always
public Sprite[] dialogIcons;
public Sprite[] thoughtsIcons;
public Sprite thoughtSprite;
public Sprite dialogSprite;
public SpriteRenderer cloudSR;
public SpriteRenderer iconSR;
public bool isDialoging;
public bool permanentIsAllowedToMove;
// Use this for initialization
void Start () {
}
/*void OnTriggerEntered(bool isIt)
{
isPlayerStayOnTrigger = isIt;
}
void Subs(string[] subtits)
{
subStrings = subtits;
}*/
void AllowMoving(bool _isAllowedToMove)
{
isAllowedToMove = _isAllowedToMove;
if (!isAllowedToMove)
{
rigid.velocity = Vector2.zero;
horAxis = 0.0f;
verAxis = 0.0f;
computeMoveAnim();
UpdateLayer();
}
}
void SetQuestManager(GameObject qm)
{
questMan = qm;
}
/*void DialogIconIndex(int index)
{
requestingDialogIcon = index;
}*/
void OnTriggerEntered(bool isIt)
{
isPlayerStayOnTrigger = isIt;
if (isIt)
{
if (isThoughtsOnlyWhenNear && !isDialoging)
{
cloudSR.enabled = true;
cloudSR.sprite = thoughtSprite;
iconSR.enabled = true;
iconSR.sprite = thoughtsIcons[requestingDialogIcon];
}
}
else
{
cloudSR.enabled = false;
iconSR.enabled = false;
}
}
void OnGUI()
{
GUI.skin = gs;
if (Input.GetButton("Subtitles") && requestingDialogIcon >= 0 && subStrings.Length > 0)
{
GUI.Label(new Rect(0, Screen.height - 30, Screen.width, 30), subStrings[requestingDialogIcon]);
}
}
// Update is called once per frame
void Update () {
/*if (Input.GetKeyDown(KeyCode.RightArrow))
{
secs = System.DateTime.Now.Millisecond;
}
if (Input.GetKeyUp(KeyCode.RightArrow))
{
secs -= System.DateTime.Now.Millisecond;
Debug.Log(secs);
}*/
//Debug.Log(Input.GetAxisRaw("Horizontal") + " " + Input.GetAxisRaw("Vertical"));
if (isAllowedToMove)
{
horAxis = Input.GetAxisRaw("Horizontal") * Time.deltaTime * speed;
verAxis = Input.GetAxisRaw("Vertical") * Time.deltaTime * speed;
//}
if (verAxis == 0.0f && horAxis == 0.0f)
{
//sr.sprite = downWalkAnimation[0];
switch (lastDirection)
{
case 0:
sr.sprite = upWalkAnimation[0];
break;
case 1:
case 3:
sr.sprite = horizontalWalkAnimation[0];
break;
case 2:
sr.sprite = downWalkAnimation[0];
break;
}
}
else
{
animTimer += Time.deltaTime;
if (animTimer >= 0.08f)
{
curAnimState++;
if (curAnimState >= 4)
{
curAnimState = 0;
}
animTimer = 0.0f;
}
if (Mathf.Abs(verAxis) < Mathf.Abs(horAxis))
{
sr.sprite = horizontalWalkAnimation[curAnimState];
sr.flipX = horAxis < 0.0f;
lastDirection = sr.flipX ? 3 : 1;
}
else
{
if (verAxis > 0.0f)
{
sr.sprite = upWalkAnimation[curAnimState];
lastDirection = 0;
}
else
{
sr.sprite = downWalkAnimation[curAnimState];
lastDirection = 2;
}
}
UpdateLayer();
}
}
Dialoging();
}
void FixedUpdate()
{
if (horAxis != 0.0f || verAxis != 0.0f)
{
rigid.AddForce(new Vector2(horAxis, verAxis), ForceMode2D.Force);
}
}
void UpdateLayer()
{
Vector3 pos = gameObject.transform.position;
pos.z = pos.y / 100.0f;
gameObject.transform.position = pos;
}
void SetMovingList(Quests.Moving[] movings)
{
//Debug.Log("B");
movingList = movings;
StartCoroutine(MoveInList());
}
IEnumerator MoveInList()
{
isAllowedToMove = false;
for (int i = 0; i < movingList.Length; i++)
{
if (movingList[i].isWaitFor)
{
if (movingList[i].isX)
{
yield return new WaitForSeconds(movingList[i].value); //just wait
}
else
{
lastDirection = Mathf.RoundToInt(movingList[i].value); //change view direction
computeMoveAnim();
}
}
else
{
if (movingList[i].isX)
{
yield return StartCoroutine(moveNPCXCordCor(movingList[i].value, 1.0f)); //move on X
}
else
{
yield return StartCoroutine(moveNPCYCordCor(movingList[i].value, 1.0f)); //move on Y
}
}
}
questMan.SendMessage("FinishedMoves");
isAllowedToMove = permanentIsAllowedToMove;
}
void SetDialogList(Sprite[] _sprts)
{
dialogIcons = _sprts;
}
void SetThoughtsList(QuestManager.ThoughtsList _thoughts)
{
Debug.Log("THOU GET");
cloudSR.enabled = false;
requestingDialogIcon = 0;
thoughtsIcons = _thoughts.sprts;
Debug.Log("THOU " + thoughtsIcons.Length);
subStrings = _thoughts.subtitles;
thoughtsPeriod = _thoughts.period;
thoughtsDuration = _thoughts.duration;
isThoughtsPeriodical = _thoughts.isPeriodical;
isThoughtsOnlyWhenNear = _thoughts.isOnlyWhenNear;
}
IEnumerator moveNPCXCordCor(float toX, float speedMultiplier)
{
yield return new WaitForSeconds(1.0f);
Vector3 pos = gameObject.transform.position;
float duration = (toX - pos.x) - 0.1f/* * 0.4f*/;
float timer = 0.0f;
//Debug.Log(duration);
while (timer < duration)
{
horAxis = Time.deltaTime * speed * speedMultiplier;
computeMoveAnim();
UpdateLayer();
timer += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
horAxis = 0.0f;
rigid.velocity = new Vector2(0.0f, rigid.velocity.y);
pos.x = toX;
gameObject.transform.position = pos;
computeMoveAnim();
UpdateLayer();
}
IEnumerator moveNPCYCordCor(float toY, float speedMultiplier)
{
yield return new WaitForSeconds(1.0f);
Vector3 pos = gameObject.transform.position;
float duration = (toY - pos.y) - 0.1f/* * 0.4f*/;
float timer = 0.0f;
//Debug.Log(duration);
while (timer < duration)
{
verAxis = Time.deltaTime * speed * speedMultiplier;
computeMoveAnim();
UpdateLayer();
timer += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
verAxis = 0.0f;
rigid.velocity = new Vector2(rigid.velocity.x, 0.0f);
pos.y = toY;
gameObject.transform.position = pos;
computeMoveAnim();
UpdateLayer();
}
void computeMoveAnim()
{
if (verAxis == 0.0f && horAxis == 0.0f)
{
switch (lastDirection)
{
case 0:
sr.sprite = upWalkAnimation[0];
break;
case 1:
case 3:
sr.sprite = horizontalWalkAnimation[0];
break;
case 2:
sr.sprite = downWalkAnimation[0];
break;
}
}
else
{
animTimer += Time.deltaTime;
if (animTimer >= 0.08f)
{
curAnimState++;
if (curAnimState >= 4)
{
curAnimState = 0;
}
animTimer = 0.0f;
}
if (Mathf.Abs(verAxis) < Mathf.Abs(horAxis))
{
sr.sprite = horizontalWalkAnimation[curAnimState];
//Debug.Log("horWalkAnim " + curAnimState);
sr.flipX = horAxis < 0.0f;
lastDirection = sr.flipX ? 3 : 1;
}
else
{
if (verAxis > 0.0f)
{
sr.sprite = upWalkAnimation[curAnimState];
//Debug.Log("upWalkAnim" + curAnimState);
lastDirection = 0;
}
else
{
sr.sprite = downWalkAnimation[curAnimState];
//Debug.Log("downWalkAnim" + curAnimState);
lastDirection = 2;
}
}
}
}
void ResetPreviousDialogs()
{
Debug.Log("ResetPreviousDialogs");
dialogIcons = new Sprite[0];
subStrings = new string[0];
requestingDialogIcon = (-1);
cloudSR.enabled = false;
iconSR.enabled = false;
thoughtsTimer = 0.0f;
}
void ResetPreviousThoughts()
{
Debug.Log("ResetPreviousThoughts");
thoughtsIcons = new Sprite[0];
subStrings = new string[0];
requestingDialogIcon = (-1);
cloudSR.enabled = false;
iconSR.enabled = false;
thoughtsTimer = 0.0f;
}
void Dialoging()
{
if (Input.GetButtonDown("Use") && isPlayerStayOnTrigger)
{
requestingDialogIcon++;
if (requestingDialogIcon >= dialogIcons.Length)
{
requestingDialogIcon = (-1);
AllowMoving(true);
isDialoging = false;
}
else if (requestingDialogIcon == 0)
{
AllowMoving(false);
isDialoging = true;
}
//triggerObject.SendMessage("DialogIconIndex", requestingDialogIcon);
//pl.SendMessage("DialogIconIndex", requestingDialogIcon);
cloudSR.sprite = dialogSprite;
iconSR.sprite = thoughtsIcons[requestingDialogIcon];
cloudSR.enabled = isDialoging;
iconSR.enabled = isDialoging;
}
if (!isDialoging)
{
if (isThoughtsPeriodical)
{
if (cloudSR.enabled)
{
if (thoughtsTimer < thoughtsDuration)
{
thoughtsTimer += Time.deltaTime;
}
else
{
cloudSR.enabled = false;
iconSR.enabled = false;
thoughtsTimer = 0.0f;
requestingDialogIcon++;
if (requestingDialogIcon >= thoughtsIcons.Length)
{
requestingDialogIcon = 0;
}
iconSR.sprite = thoughtsIcons[requestingDialogIcon];
}
}
else
{
if (thoughtsTimer < thoughtsPeriod)
{
thoughtsTimer += Time.deltaTime;
}
else
{
cloudSR.sprite = thoughtSprite;
cloudSR.enabled = true;
iconSR.enabled = true;
thoughtsTimer = 0.0f;
}
}
}
else if (thoughtsIcons.Length > 0 && !isThoughtsOnlyWhenNear)
{
if (!cloudSR.enabled)
{
cloudSR.enabled = true;
}
if (!iconSR.enabled)
{
iconSR.enabled = true;
}
if (cloudSR.sprite != thoughtSprite)
{
cloudSR.sprite = thoughtSprite;
}
if (requestingDialogIcon >= 0 && iconSR.sprite != thoughtsIcons[requestingDialogIcon])
{
iconSR.sprite = thoughtsIcons[requestingDialogIcon];
}
if (cloudSR.enabled)
{
if (thoughtsTimer < thoughtsDuration)
{
thoughtsTimer += Time.deltaTime;
}
else
{
cloudSR.enabled = false;
iconSR.enabled = false;
thoughtsTimer = 0.0f;
requestingDialogIcon++;
if (requestingDialogIcon >= thoughtsIcons.Length)
{
//thoughtsIcons = new Sprite[0];
requestingDialogIcon = (-1);
//requestingDialogIcon = 0;
Debug.Log("ACS");
questMan.SendMessage("FinishedMoves");
}
else
{
iconSR.sprite = thoughtsIcons[requestingDialogIcon];
}
}
}
else
{
if (thoughtsTimer < thoughtsPeriod)
{
thoughtsTimer += Time.deltaTime;
}
else
{
cloudSR.sprite = thoughtSprite;
cloudSR.enabled = true;
iconSR.enabled = true;
thoughtsTimer = 0.0f;
Debug.Log("AAAAAAAAAAAAAAAAAAAAAAAAAAAA");
}
}
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpriteAnimator : MonoBehaviour {
private SpriteRenderer sr;
public bool fromSideToSide;
public bool animateFrames;
public Sprite[] frames;
public float animTimer;
public int curAnimState;
public float animatingPeriod;
// Use this for initialization
void Start () {
sr = gameObject.GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update () {
animTimer += Time.deltaTime;
if (animTimer >= animatingPeriod)
{
doAnimation();
animTimer = 0.0f;
}
if (0 <= curAnimState && curAnimState < frames.Length)
{
sr.sprite = frames[curAnimState];
}
}
void doAnimation()
{
if (animateFrames)
{
curAnimState++;
if (curAnimState >= frames.Length)
{
curAnimState = 0;
}
}
if (fromSideToSide)
{
sr.flipX = !sr.flipX;
}
}
}
| 83a96e278738e86514a79516fb3d57cc60d271ab | [
"Markdown",
"C#"
] | 11 | C# | VladKoshelik/GGJ2019_SomethingSymbolic | 9a99c8d22c8ad895765ecaef49490a9367ec0839 | be1d95a677455bbc5d1549bf67b050355559441c |
refs/heads/master | <file_sep>class Category < ApplicationRecord
#las dos siguientes lineas es la asociacion de many_to_many de articulos y categorias
has_many :article_categories
has_many :articles, through: :article_categories
validates :name, presence: true, length: { minimum: 3, maximum: 25 }
validates_uniqueness_of :name
end | 62752e4c94d7efc6e39b405f7a1da73385e5c451 | [
"Ruby"
] | 1 | Ruby | pollocoder/alpha-blog | 8385c94ba664796675aef0d0416d5eeb4fdbb4e5 | 0b8f0d6e036bfccc2caf211824f160552ab7064b |
refs/heads/master | <file_sep>package seamus;
public class InstructionsSet {
}
| fdb10f44b0574498d3aa4684266e3fad765ba7e8 | [
"Java"
] | 1 | Java | hmaguilo/seamus | ced3c06649a07ff7cd5874a90f048400114ed52a | 37e165597e4f0930459f3afacac28a4da42fa65b |
refs/heads/master | <file_sep>using System;
public static class GameVariables
{
// Grid Size
public static int Rows = 12;
public static int Columns = 8;
//Animation Durations
public static float AnimationDuration = 0.2f;
public static float MoveAnimationDuration = 0.05f;
public static float ExplosionAnimationDuration = 0.3f;
public static float WaitBeforePotentialMatchesCheck = 2f;
public static float OpacityAnimationDelay = 0.05f;
//Minimum amount for matches
public static int MinimumMatches = 3;
public static int MinimumMatchesForBonus = 4;
//Scores
public static int Match3Score = 100;
//public static int Match4Score = 300;
//public static int MatchPlusScore = 500;
public static int SubsequelMatchScore = 1000;
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class MatchesInfo
{
private List<GameObject> matches;
private BonusType BonusesContained { get; set; }
public MatchesInfo()
{
matches = new List<GameObject>();
BonusesContained = BonusType.None;
}
//public IEnumerable<GameObject> MatchedCandy
//{
// get {
// }
//}
}
<file_sep># Match Animal (CCrush clone)
Match Animals is a candy crush clone
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MatchChecker
{
public static IEnumerator AnimatePotentialMatches(IEnumerable<GameObject> potentialMatches)
{
for (float i = 1.0f; i >= 0.3f; i -= 0.1f)
{
foreach(var item in potentialMatches)
{
Color c = item.GetComponent<SpriteRenderer>().color;
c.a = i;
item.GetComponent<SpriteRenderer>().color = c;
}
yield return new WaitForSeconds(GameVariables.OpacityAnimationDelay);
}
for (float i = 0.3f; i <= 1.0f; i += 0.1f)
{
foreach (var item in potentialMatches)
{
Color c = item.GetComponent<SpriteRenderer>().color;
c.a = i;
item.GetComponent<SpriteRenderer>().color = c;
}
yield return new WaitForSeconds(GameVariables.OpacityAnimationDelay);
}
}
public static bool AreHorizontalOrVerticalNeighbors( Tile t1, Tile t2 )
{
return (t1.Column == t2.Column || t1.Row == t2.Row)
&& (Mathf.Abs(t1.Column - t2.Column) <= 1)
&& (Mathf.Abs(t1.Row - t2.Row) <= 1);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tile : MonoBehaviour
{
public BonusType Bonus { get; set; }
public int Row { get; set; }
public int Column { get; set; }
//Which Type of Animal
public string Type { get; set; }
//public Tile() //Constructor
public void Awake()
{
Bonus = BonusType.None;
}
public bool IsSameType( Tile otherTile )
{
return string.Compare(this.Type, otherTile.Type) == 0;
}
public void Initialize(string type, int row, int column)
{
Type = type;
Row = row;
Column = column;
}
public static void SwapRowColumn( Tile t1, Tile t2 )
{
int temp = t1.Row;
t1.Row = t2.Row;
t2.Row = temp;
temp = t1.Column;
t1.Column = t2.Column;
t2.Column = temp;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;
using UnityEngine;
public class TileArray
{
GameObject[,] tiles = new GameObject[GameVariables.Rows, GameVariables.Columns];
//Backup Tiles during swap
private GameObject object1;
private GameObject object2;
public GameObject this[int row, int column] {
get {
try
{
return tiles[row, column];
}
catch (Exception e)
{
throw;
}
}
set {
tiles[row, column] = value;
}
}
public void Swap(GameObject g1, GameObject g2)
{
object1 = g1;
object2 = g2;
Tile g1Tile = g1.GetComponent<Tile>();
Tile g2Tile = g2.GetComponent<Tile>();
int g1Row = g1Tile.Row;
int g1Column = g1Tile.Column;
int g2Row = g2Tile.Row;
int g2Column = g2Tile.Column;
//Swap inside TileArray
var temp = tiles[g1Row, g1Column];
tiles[g1Row, g1Column] = tiles[g2Row, g2Column]; //Assign tile 1 to tile 2
tiles[g2Row, g2Column] = temp; //Assign tile 2 to tile 1 (stored)
//Swap Tile stored values
Tile.SwapRowColumn(g1Tile, g2Tile);
}
public void UndoSwap()
{
Swap(object1, object2);
}
private IEnumerable<GameObject> GetMatchesHorizontally(GameObject go)
{
List<GameObject> matches = new List<GameObject>();
matches.Add(go);
var goTile = go.GetComponent<Tile>();
if (goTile.Column != 0) //Search Left
{
for (int column = goTile.Column - 1; column >= 0; column--) //Check everything left of the tile
{
if (tiles[goTile.Row, column].GetComponent<Tile>().IsSameType(goTile)) //Check if it matches the type
{
matches.Add(tiles[goTile.Row, column]);
}
else break; //early exit
}
}
if (goTile.Column != GameVariables.Columns - 1) // Search Right
{
for (int column = goTile.Column + 1; column < GameVariables.Columns; column++) //Check everything right of the tile
{
if (tiles[goTile.Row, column].GetComponent<Tile>().IsSameType(goTile)) //Check if it matches the type
{
matches.Add(tiles[goTile.Row, column]);
}
else break; //early exit
}
}
if (matches.Count < GameVariables.MinimumMatches)
{
matches.Clear();
}
return matches.Distinct();
}
private IEnumerable<GameObject> GetMatchesVertically(GameObject go)
{
List<GameObject> matches = new List<GameObject>();
matches.Add(go);
var goTile = go.GetComponent<Tile>();
if (goTile.Row != 0) //Search Down
{
for (int row = goTile.Row - 1; row >= 0; row--) //Check everything left of the tile
{
if (tiles[row, goTile.Column].GetComponent<Tile>().IsSameType(goTile)) //Check if it matches the type
{
matches.Add(tiles[row, goTile.Column]);
}
else break; //early exit
}
}
if (goTile.Row != GameVariables.Rows - 1) // Search Up
{
for (int row = goTile.Row + 1; row < GameVariables.Rows; row++) //Check everything right of the tile
{
if (tiles[row, goTile.Column].GetComponent<Tile>().IsSameType(goTile)) //Check if it matches the type
{
matches.Add(tiles[row, goTile.Column]);
}
else break; //early exit
}
}
if (matches.Count < GameVariables.MinimumMatches)
{
matches.Clear();
}
return matches.Distinct();
}
private bool ContainsDestroyWholeRowColumnBonus(List<GameObject> matches)
{
if(matches.Count >= GameVariables.MinimumMatches)
{
foreach (var item in matches)
{
if (BonusTiles.ContainsDestroyWholeRowColumn(item.GetComponent<Tile>().Bonus))
{
return true;
}
}
}
return false;
}
private List<GameObject> GetEntireRow( GameObject tile )
{
List<GameObject> matches = new List<GameObject>();
int row = tile.GetComponent<Tile>().Row;
for ( int column = 0; column < GameVariables.Columns; column++)
{
matches.Add(tiles[row, column]);
}
return matches;
}
private List<GameObject> GetEntireColumn(GameObject tile)
{
List<GameObject> matches = new List<GameObject>();
int column = tile.GetComponent<Tile>().Column;
for (int row = 0; row < GameVariables.Rows; row++)
{
matches.Add(tiles[row, column]);
}
return matches;
}
public void Remove(GameObject tile)
{
tiles[tile.GetComponent<Tile>().Row, tile.GetComponent<Tile>().Column] = null;
}
public AlteredTileInfo Collapse(IEnumerable<int> columns)
{
AlteredTileInfo collapseInfo = new AlteredTileInfo();
foreach( var column in columns )
{
for( int row = 0; row < GameVariables.Rows - 1; row++)
{
if(tiles[row, column] == null)
{
for(int row2 = row + 1; row2 < GameVariables.Rows; row2++)
{
if(tiles[row2, column] != null)
{
tiles[row, column] = tiles[row2, column];
tiles[row2, column] = null;
if(row2 - row > collapseInfo.maxDistance)
{
collapseInfo.maxDistance = row2 - row;
}
tiles[row, column].GetComponent<Tile>().Row = row;
tiles[row, column].GetComponent<Tile>().Column = column;
collapseInfo.AddTile(tiles[row, column]);
break;
}
}
}
}
}
return collapseInfo;
}
public IEnumerable<EmptyTileInfo> GetEmptyItemsOnColumn(int column)
{
List<EmptyTileInfo> emptyItems = new List<EmptyTileInfo>();
for (int row = 0; row < GameVariables.Rows; row++)
{
if(tiles[row,column] == null)
{
emptyItems.Add(new EmptyTileInfo() { Row = row, Column = column });
}
}
return emptyItems;
}
}
| 95f46d26706b52ae1fb3a7693f3d43f635c43a1c | [
"Markdown",
"C#"
] | 6 | C# | zinGa1407/Match-Animals--CCrush-clone- | 0811eb2069d978ee4646acf0c837e2b70bc71c09 | 32c07d42587b4d9096f97cf9559a1c1b091269a9 |
refs/heads/master | <file_sep>package io.marketplace.api.trade.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class CompletedTrade {
private TradeOrder buyOrder;
private TradeOrder sellOrder;
public CompletedTrade() {
}
public CompletedTrade(TradeOrder buyOrder, TradeOrder sellOrder) {
this.buyOrder = buyOrder;
this.sellOrder = sellOrder;
}
public TradeOrder getBuyOrder() {
return buyOrder;
}
public TradeOrder getSellOrder() {
return sellOrder;
}
}<file_sep>package io.marketplace.api.error;
import io.marketplace.api.error.model.ValidationErrorResponse;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.HttpStatus;
import javax.inject.Provider;
import javax.validation.*;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Variant;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CustomValidationExceptionMapperTest {
@Mock
private Provider<Request> request;
@InjectMocks
private CustomValidationExceptionMapper exceptionMapper;
@Before
public void init() {
Request requestMock = mock(Request.class);
when(request.get()).thenReturn(requestMock);
when(requestMock.selectVariant(anyListOf(Variant.class)))
.thenReturn(new Variant(MediaType.APPLICATION_JSON_TYPE, "", ""));
}
@Test
public void testInternalErrorResponseIsBuiltIfExceptionIsNotConstraintViolationException() {
Response response = exceptionMapper.toResponse(new UnexpectedTypeException());
assertThat(response, notNullValue());
assertThat(response.getStatus(), is(HttpStatus.INTERNAL_SERVER_ERROR.value()));
}
@Test
public void testValidationErrorResponseIsBuiltForConstraintViolationException() {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<TestBean>> validate = validator.validate(new TestBean());
ConstraintViolationException exception = new ConstraintViolationException(validate);
Response response = exceptionMapper.toResponse(exception);
assertThat(response, notNullValue());
assertThat(response.getStatus(), is(HttpStatus.BAD_REQUEST.value()));
assertTrue(response.getEntity() instanceof ValidationErrorResponse);
ValidationErrorResponse errorResponse = (ValidationErrorResponse) response.getEntity();
assertThat(errorResponse.getErrors(), Matchers.not(empty()));
assertThat(errorResponse.getErrors().size(), is(1));
assertThat(errorResponse.getErrors().get(0).getMessage(), is("testValidationMessage"));
}
private class TestBean {
@NotNull(message = "testValidationMessage")
private String test;
}
}
<file_sep>package io.marketplace.api.error.model;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement
public class ValidationErrorResponse extends ErrorResponse {
private final List<ValidationError> errors;
public ValidationErrorResponse(List<ValidationError> errors) {
super(ErrorType.VALIDATION_ERROR, "One or more fields did not pass validation");
this.errors = errors;
}
public List<ValidationError> getErrors() {
return errors;
}
}<file_sep>package io.marketplace.api.config;
import io.marketplace.api.error.CustomValidationFeature;
import io.marketplace.api.trade.TradeResource;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;
import static org.glassfish.jersey.server.ServerProperties.BV_FEATURE_DISABLE;
@Component
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
// end points
register(TradeResource.class);
//features
register(CustomValidationFeature.class);
//properties
property(BV_FEATURE_DISABLE, true);
}
}<file_sep>TradeResource.order.null=order cannot be null
OrderRequest.item.null=product cannot be null
OrderRequest.type.null=type cannot be null
OrderRequest.price.null=price cannot be null
OrderRequest.price.min=price cannot be lower then {value}<file_sep>package io.marketplace.api;
import io.marketplace.api.trade.model.CompletedTrade;
import io.marketplace.api.trade.model.TradeOrder;
import io.marketplace.api.trade.model.TradeType;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.List;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
@RunWith(SpringRunner.class)
@FixMethodOrder(value = MethodSorters.NAME_ASCENDING)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MarketplaceAPIAcceptanceTest extends BaseTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void test0BuyOrderEnqueued() {
TradeOrder A_clientRequest = stubOrder(TradeType.BUY, BigDecimal.TEN);
ResponseEntity A_clientResponse = restTemplate.postForEntity("/trades", entity(A_clientRequest), ResponseEntity.class);
assertThat(A_clientResponse.getStatusCode(), equalTo(HttpStatus.ACCEPTED));
}
@Test
public void test1BuyOrderEnqueued() {
TradeOrder B_clientRequest = stubOrder(TradeType.BUY, BigDecimal.valueOf(11));
ResponseEntity B_clientResponse = restTemplate.postForEntity("/trades", entity(B_clientRequest), ResponseEntity.class);
assertThat(B_clientResponse.getStatusCode(), equalTo(HttpStatus.ACCEPTED));
}
@Test
public void test2SellOrderEnqueued() {
TradeOrder C_clientRequest = stubOrder(TradeType.SELL, BigDecimal.valueOf(15));
ResponseEntity C_clientResponse = restTemplate.postForEntity("/trades", entity(C_clientRequest), ResponseEntity.class);
assertThat(C_clientResponse.getStatusCode(), equalTo(HttpStatus.ACCEPTED));
}
@Test
public void test3SellOrderCompleted() {
TradeOrder D_clientRequest = stubOrder(TradeType.SELL, BigDecimal.valueOf(9));
ResponseEntity D_clientResponse = restTemplate.postForEntity("/trades", entity(D_clientRequest), ResponseEntity.class);
assertThat(D_clientResponse.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void test4CompletedOrderListContainsTradeBetweenDAndB() {
List<CompletedTrade> allOrders = restTemplate.exchange("/trades", HttpMethod.GET, null, new ParameterizedTypeReference<List<CompletedTrade>>() {
}).getBody();
assertThat(allOrders, hasItem(
allOf(
hasProperty("buyOrder", allOf(
hasProperty("price", equalTo(BigDecimal.valueOf(11))),
hasProperty("type", equalTo(TradeType.BUY)))
),
hasProperty("sellOrder", allOf(
hasProperty("price", equalTo(BigDecimal.valueOf(9))),
hasProperty("type", equalTo(TradeType.SELL))
))
)
));
}
@Test
public void test5BuyOrderEnqueued() {
TradeOrder E_clientRequest = stubOrder(TradeType.BUY, BigDecimal.TEN);
ResponseEntity E_clientResponse = restTemplate.postForEntity("/trades", entity(E_clientRequest), ResponseEntity.class);
assertThat(E_clientResponse.getStatusCode(), equalTo(HttpStatus.ACCEPTED));
}
@Test
public void test6SellOrderCompleted() {
TradeOrder F_clientRequest = stubOrder(TradeType.SELL, BigDecimal.TEN);
ResponseEntity F_clientResponse = restTemplate.postForEntity("/trades", entity(F_clientRequest), ResponseEntity.class);
assertThat(F_clientResponse.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void test7CompletedOrderListContainsTradeBetweenFAndA() {
List<CompletedTrade> allOrders = restTemplate.exchange("/trades", HttpMethod.GET, null, new ParameterizedTypeReference<List<CompletedTrade>>() {
}).getBody();
assertThat(allOrders, hasItem(
allOf(
hasProperty("buyOrder", allOf(
hasProperty("price", equalTo(BigDecimal.TEN)),
hasProperty("type", equalTo(TradeType.BUY)))
),
hasProperty("sellOrder", allOf(
hasProperty("price", equalTo(BigDecimal.TEN)),
hasProperty("type", equalTo(TradeType.SELL))
))
)
));
}
@Test
public void test8BuyOrderCompleted() {
TradeOrder G_clientRequest = stubOrder(TradeType.BUY, BigDecimal.valueOf(100));
ResponseEntity G_clientResponse = restTemplate.postForEntity("/trades", entity(G_clientRequest), ResponseEntity.class);
assertThat(G_clientResponse.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void test9CompletedOrderListContainsTradeBetweenCAndG() {
List<CompletedTrade> allOrders = restTemplate.exchange("/trades", HttpMethod.GET, null, new ParameterizedTypeReference<List<CompletedTrade>>() {
}).getBody();
assertThat(allOrders, hasItem(
allOf(
hasProperty("buyOrder", allOf(
hasProperty("price", equalTo(BigDecimal.valueOf(100))),
hasProperty("type", equalTo(TradeType.BUY)))
),
hasProperty("sellOrder", allOf(
hasProperty("price", equalTo(BigDecimal.valueOf(15))),
hasProperty("type", equalTo(TradeType.SELL))
))
)
));
}
private <T> HttpEntity<T> entity(T obj) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
return new HttpEntity<>(obj, headers);
}
}
<file_sep>package io.marketplace.api.error.model;
public enum ErrorType {
VALIDATION_ERROR,
INTERNAL_ERROR
}
<file_sep>package io.marketplace.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MarketplaceAPI {
public static void main(String[] args) {
SpringApplication.run(MarketplaceAPI.class, args);
}
}<file_sep>package io.marketplace.api.trade;
import io.marketplace.api.trade.model.TradeOrder;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
@Path("trades")
public class TradeResource {
@Inject
private TradeService service;
@GET
public Response completedTrades() {
return Response
.ok(service.completedTrades())
.build();
}
@POST
public Response placeOrder(@Valid @NotNull(message = "{TradeResource.order.null}") TradeOrder tradeOrder) {
boolean orderMatched = service.placeOrder(tradeOrder);
return Response
.status(resolveStatus(orderMatched))
.build();
}
private Response.Status resolveStatus(boolean orderMatched) {
return orderMatched ? Response.Status.OK : Response.Status.ACCEPTED;
}
}
<file_sep>package io.marketplace.api.error.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class ErrorResponse {
private final ErrorType type;
private final String description;
public ErrorResponse(ErrorType type, String description) {
this.type = type;
this.description = description;
}
public ErrorType getType() {
return type;
}
public String getDescription() {
return description;
}
}
<file_sep>## Running the app (multiple options)
- Using bash and gradle wrapper: ```./gradlew bootRun```
- Using gradle: ```gradle bootRun``` (requires gradle)
- Using IDE: Run the main class ```MarketplaceAPI``` as Java/Spring Boot application
## Running tests
- Using gradle: ```gradle test```
- Report can be found here: ```build/reports/tests/test/index.html```
## Endpoints (supports json/xml media types)
- localhost:8080/trades GET
- localhost:8080/trades POST
- see ```TradeResource``` and ```MarketplaceAPIAcceptanceTest``` for examples
## Description of the task
### PUMPKIN TRADING PLATFORM
Your task is to create a Java component for a pumpkin trading platform. The signature of the exposed class must contain “buy” and “sell” methods using which the client can submit the suggested price he wants to buy/sell one pumpkin for. The buy and sell orders must be matched by these rules:
- Buy and sell orders are matched if the buy price is not less than the sell price
- If client makes a buy/sell order and there are multiple suitable sell orders, the one with the lowest/highest price is chosen. Ties are resolved by order submission time, i.e. the earliest counter-order wins. The resulting trade price is the price specified by the buyer/seller.
PUMPKIN TRADING PLATFORM
Your task is to create a Java component for a pumpkin trading platform. The signature of the exposed class must contain “buy” and “sell” methods using which the client can submit the suggested price he wants to buy/sell one pumpkin for. The buy and sell orders must be matched by these rules:
- Buy and sell orders are matched if the buy price is not less than the sell price
- If client makes a buy/sell order and there are multiple suitable sell orders, the one with the lowest/highest price is chosen. Ties are resolved by order submission time, i.e. the earliest counter-order wins. The resulting trade price is the price specified by the buyer/seller.
- If there are no valid matching order for the order, it must remain in the system until a matching order is found (it might as well not happen).
- An order can be matched only once.
The exposed class must also provide a method to obtain the array of trades performed which can be output in human readable format.
Example
- Client A wants to buy a pumpkin for 10€. This is the first order so it can’t be satisfied yet.
* Client B wants to buy a pumpkin for 11€. Still no one wants to sell a pumpkin.
* Client C wants to sell a pumpkin for 15€. Neither A nor B wants such an expensive pumpkin.
* Client D wants to sell a pumpkin for 9€. Finally a trade can happen. Following the rules above, D will sell his pumpkin for 9€ to the client B.
* Client E wants to buy a pumpkin for 10€. Still no trade.
* Client F wants to sell a pumpkin for 10€. Trade is created. F sells his pumpkin for 10€ to the client A (as A stated his order earlier than E).
* Client G wants to buy a pumpkin for 100€. Client C is the only one selling a pumpkin now, so the deal is made for 100€.
Using the trade retrieval method, system should be able to output such 3 rows:
* D sold a pumpkin to B for 9€
* F sold a pumpkin to A for 10€
* G bought a pumpkin from C for 100€
Bonus points
Extra points will be given if
- Code is self-explanatory and doesn’t need comments;
- There are Unit tests;
- Code uses the best data structures for the job available found in java.util package;
- Component is thread safe, i.e. it will work correctly if used from multiple threads simultaneously;
- Component state is protected from illegal modifications, i.e. only adding orders should be possible;
- You can describe how you would implement these features:
- Add a parameter specifying the amount of pumpkins to buy or sell
- Add possibility to specify expiration time for the order
- Return an object which implements the java.util.concurrent.Future interface when buy/sell method is called.
If there are no valid matching order for the order, it must remain in the system until a matching order is found (it might as well not happen).
- An order can be matched only once.
The exposed class must also provide a method to obtain the array of trades performed which can be output in human readable format.
<file_sep>package io.marketplace.api.trade.model;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Objects;
@XmlRootElement
public class TradeOrder {
@NotNull(message = "{TradeOrder.product.null}")
private TradeProduct product;
@NotNull(message = "{TradeOrder.type.null}")
private TradeType type;
@NotNull(message = "{TradeOrder.price.null}")
@DecimalMin(value = "0.01", message = "{TradeOrder.price.min}")
private BigDecimal price;
private final LocalDateTime created = LocalDateTime.now();
public TradeProduct getProduct() {
return product;
}
public void setProduct(TradeProduct product) {
this.product = product;
}
public TradeType getType() {
return type;
}
public void setType(TradeType type) {
this.type = type;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public LocalDateTime getCreated() {
return created;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TradeOrder that = (TradeOrder) o;
return product == that.product &&
type == that.type &&
Objects.equals(price, that.price) &&
Objects.equals(created, that.created);
}
@Override
public int hashCode() {
return Objects.hash(product, type, price, created);
}
}
<file_sep>package io.marketplace.api.trade;
import io.marketplace.api.trade.model.CompletedTrade;
import io.marketplace.api.trade.model.TradeOrder;
import io.marketplace.api.trade.model.TradeType;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.stream.Stream;
@Component
public class TradeService {
private final Object syncObject = new Object();
private final BlockingQueue<TradeOrder> enqueued = new LinkedBlockingDeque<>();
private final LinkedList<CompletedTrade> completed = new LinkedList<>();
List<CompletedTrade> completedTrades() {
return Collections.unmodifiableList(completed);
}
boolean placeOrder(TradeOrder incomingOrder) {
synchronized (syncObject) {
boolean orderMatched;
Optional<TradeOrder> optionalMatch = findMatchingOrder(incomingOrder);
if (optionalMatch.isPresent()) {
TradeOrder matchingOrder = optionalMatch.get();
CompletedTrade completedTrade = buildCompletedTrade(incomingOrder, matchingOrder);
enqueued.remove(matchingOrder);
completed.addFirst(completedTrade);
orderMatched = true;
} else {
enqueued.add(incomingOrder);
orderMatched = false;
}
return orderMatched;
}
}
private CompletedTrade buildCompletedTrade(TradeOrder incomingOrder, TradeOrder matchingOrder) {
CompletedTrade completedTrade;
if (incomingOrder.getType() == TradeType.BUY) {
completedTrade = new CompletedTrade(incomingOrder, matchingOrder);
} else {
completedTrade = new CompletedTrade(matchingOrder, incomingOrder);
}
return completedTrade;
}
private Optional<TradeOrder> findMatchingOrder(TradeOrder incomingOrder) {
Stream<TradeOrder> matchingCandidates = enqueued
.stream()
.filter(existing -> filterByOppositeType(existing, incomingOrder))
.filter(existing -> filterByAcceptablePrice(existing, incomingOrder));
Optional<TradeOrder> optionalMatch;
if (incomingOrder.getType() == TradeType.BUY) {
optionalMatch = matchingCandidates.min(Comparator.comparing(TradeOrder::getPrice));
} else {
optionalMatch = matchingCandidates.max(Comparator.comparing(TradeOrder::getPrice));
}
return optionalMatch;
}
private boolean filterByAcceptablePrice(TradeOrder existingOrder, TradeOrder incomingOrder) {
boolean acceptablePrice;
if (existingOrder.getType() == TradeType.BUY) {
acceptablePrice = isSellPriceLessThenOrEqualToBuyPrice(existingOrder, incomingOrder);
} else {
acceptablePrice = isSellPriceLessThenOrEqualToBuyPrice(incomingOrder, existingOrder);
}
return acceptablePrice;
}
private boolean isSellPriceLessThenOrEqualToBuyPrice(TradeOrder buyOrder, TradeOrder sellOrder) {
return buyOrder.getPrice().compareTo(sellOrder.getPrice()) > -1;
}
private boolean filterByOppositeType(TradeOrder existing, TradeOrder newOrder) {
return existing.getType() != newOrder.getType();
}
}
| 86bc364a6c728fbe15dd588952a5c7c1357d3d5c | [
"Markdown",
"Java",
"INI"
] | 13 | Java | jvancans/marketplace | a5474dd76d17075e934d4fc759ae48c4b9a06b15 | 7640a6420bd52348757b126ca9a689510186fe29 |
refs/heads/master | <repo_name>zhengwantong/mywebsite<file_sep>/www/static/README.md
my python3 website
author:zhengwantong
date: 2017/3/8
python3.6
数据库:MySQL5.5
aiomysql0.0.7+PyMySQL0.6.7
编辑器:Sublime Text3<file_sep>/www/config_override.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
如果要部署到服务器时,通常需要修改数据库的host等信息
config_override.py,用来覆盖某些默认设置:
生产环境的标准配置
'''
__author__ = '<NAME>'
configs = {
'db': {
'host': '10.134.126.60'
}
}<file_sep>/README.md
my python3 website
author:zhengwantong
date: 2017/3/8 | 1a638d4aba34064e461ac4e24c9a824ebfd40fd7 | [
"Markdown",
"Python"
] | 3 | Markdown | zhengwantong/mywebsite | 3f6d32b409ddb59f9df29646b880a1d6ecd98428 | b0b8253de6fc6355305d8931e2fa81095492ca4b |
refs/heads/master | <repo_name>edjtscott/HToEE<file_sep>/python/PlottingUtils.py
import numpy as np
import yaml
import os
from sklearn.metrics import roc_auc_score, roc_curve
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
try:
plt.style.use("cms10_6_HP")
except IOError:
warnings.warn('Could not import user defined matplot style file. Using default style settings...')
import scipy.stats
from Utils import Utils
class Plotter(object):
'''
Class to plot input variables and output scores
'''
#def __init__(self, data_obj, input_vars, sig_col='forestgreen', normalise=False, log=False, norm_to_data=False):
def __init__(self, data_obj, input_vars, sig_col='red', normalise=False, log=False, norm_to_data=False):
self.sig_df = data_obj.mc_df_sig
self.bkg_df = data_obj.mc_df_bkg
self.data_df = data_obj.data_df
del data_obj
self.sig_labels = np.unique(self.sig_df['proc'].values).tolist()
self.bkg_labels = np.unique(self.bkg_df['proc'].values).tolist()
self.sig_colour = sig_col
self.bkg_colours = ['#91bfdb', '#ffffbf', '#fc8d59']
self.normalise = normalise
self.sig_scaler = 5*10**7
self.log_axis = log
#get xrange from yaml config
with open('plotting/var_to_xrange.yaml', 'r') as plot_config_file:
plot_config = yaml.load(plot_config_file)
self.var_to_xrange = plot_config['var_to_xrange']
missing_vars = [x for x in input_vars if x not in self.var_to_xrange.keys()]
if len(missing_vars)!=0: raise IOError('Missing variables in var_to_xrange.py: {}'.format(missing_vars))
@classmethod
def num_to_str(self, num):
'''
Convert basic number into scientific form e.g. 1000 -> 10^{3}.
Not considering decimal inputs for now. Also ignores first unit.
'''
str_rep = str(num)
if str_rep[0] == 0: return num
exponent = len(str_rep)-1
return r'$\times 10^{%s}$'%(exponent)
def plot_input(self, var, n_bins, out_label, ratio_plot=False, norm_to_data=False):
if ratio_plot:
plt.rcParams.update({'figure.figsize':(6,5.8)})
fig, axes = plt.subplots(nrows=2, ncols=1, dpi=200, sharex=True,
gridspec_kw ={'height_ratios':[3,0.8], 'hspace':0.08})
ratio = axes[1]
axes = axes[0]
else:
fig = plt.figure(1)
axes = fig.gca()
bkg_stack = []
bkg_w_stack = []
bkg_proc_stack = []
var_sig = self.sig_df[var].values
sig_weights = self.sig_df['weight'].values
for bkg in self.bkg_labels:
var_bkg = self.bkg_df[self.bkg_df.proc==bkg][var].values
bkg_weights = self.bkg_df[self.bkg_df.proc==bkg]['weight'].values
bkg_stack.append(var_bkg)
bkg_w_stack.append(bkg_weights)
bkg_proc_stack.append(bkg)
if self.normalise:
sig_weights /= np.sum(sig_weights)
bkg_weights /= np.sum(bkg_weights) #FIXME: set this up for multiple bkgs
bins = np.linspace(self.var_to_xrange[var][0], self.var_to_xrange[var][1], n_bins)
#add sig mc
axes.hist(var_sig, bins=bins, label=self.sig_labels[0]+r' ($\mathrm{H}\rightarrow\mathrm{ee}$) '+self.num_to_str(self.sig_scaler), weights=sig_weights*(self.sig_scaler), histtype='step', color=self.sig_colour, zorder=10)
#data
data_binned, bin_edges = np.histogram(self.data_df[var].values, bins=bins)
bin_centres = (bin_edges[:-1] + bin_edges[1:])/2
x_err = (bin_edges[-1] - bin_edges[-2])/2
data_down, data_up = self.poisson_interval(data_binned, data_binned)
axes.errorbar( bin_centres, data_binned, yerr=[data_binned-data_down, data_up-data_binned], label='Data', fmt='o', ms=4, color='black', capsize=0, zorder=1)
#add stacked bkg
if norm_to_data:
rew_stack = []
k_factor = np.sum(self.data_df['weight'].values)/np.sum(self.bkg_df['weight'].values)
for w_arr in bkg_w_stack:
rew_stack.append(w_arr*k_factor)
axes.hist(bkg_stack, bins=bins, label=bkg_proc_stack, weights=rew_stack, histtype='stepfilled', color=self.bkg_colours[0:len(bkg_proc_stack)], log=self.log_axis, stacked=True, zorder=0)
bkg_stack_summed, _ = np.histogram(np.concatenate(bkg_stack), bins=bins, weights=np.concatenate(rew_stack))
sumw2_bkg, _ = np.histogram(np.concatenate(bkg_stack), bins=bins, weights=np.concatenate(rew_stack)**2)
else:
axes.hist(bkg_stack, bins=bins, label=bkg_proc_stack, weights=bkg_w_stack, histtype='stepfilled', color=self.bkg_colours[0:len(bkg_proc_stack)], log=self.log_axis, stacked=True, zorder=0)
bkg_stack_summed, _ = np.histogram(np.concatenate(bkg_stack), bins=bins, weights=np.concatenate(bkg_w_stack))
sumw2_bkg, _ = np.histogram(np.concatenate(bkg_stack), bins=bins, weights=np.concatenate(bkg_w_stack)**2)
if self.normalise: axes.set_ylabel('Arbitrary Units', ha='right', y=1, size=13)
else: axes.set_ylabel('Events', ha='right', y=1, size=13)
#plot mc error
bkg_std_down, bkg_std_up = self.poisson_interval(bkg_stack_summed, sumw2_bkg)
axes.fill_between(bins, list(bkg_std_down)+[bkg_std_down[-1]], list(bkg_std_up)+[bkg_std_up[-1]], alpha=0.3, step="post", color="grey", lw=1, zorder=4, label='Simulation stat. unc.')
#change axes limits
current_bottom, current_top = axes.get_ylim()
axes.set_ylim(bottom=10, top=current_top*1.35)
#axes.set_xlim(left=self.var_to_xrange[var][0], right=self.var_to_xrange[var][1])
axes.legend(bbox_to_anchor=(0.97,0.97), ncol=2)
self.plot_cms_labels(axes)
var_name_safe = var.replace('_',' ')
if ratio_plot:
ratio.errorbar(bin_centres, (data_binned/bkg_stack_summed), yerr=[ (data_binned-data_down)/bkg_stack_summed, (data_up-data_binned)/bkg_stack_summed], fmt='o', ms=4, color='black', capsize=0)
bkg_std_down_ratio = np.ones_like(bkg_std_down) - ((bkg_stack_summed - bkg_std_down)/bkg_stack_summed)
bkg_std_up_ratio = np.ones_like(bkg_std_up) + ((bkg_std_up - bkg_stack_summed)/bkg_stack_summed)
ratio.fill_between(bins, list(bkg_std_down_ratio)+[bkg_std_down_ratio[-1]], list(bkg_std_up_ratio)+[bkg_std_up_ratio[-1]], alpha=0.3, step="post", color="grey", lw=1, zorder=4)
ratio.set_xlabel('{}'.format(var_name_safe), ha='right', x=1, size=13)
#ratio.set_xlim(left=self.var_to_xrange[var][0], right=self.var_to_xrange[var][1])
ratio.set_ylabel('Data/MC', size=13)
ratio.set_ylim(0, 2)
ratio.grid(True, linestyle='dotted')
else: axes.set_xlabel('{}'.format(var_name_safe), ha='right', x=1, size=13)
Utils.check_dir('{}/plotting/plots/{}'.format(os.getcwd(), out_label))
fig.savefig('{0}/plotting/plots/{1}/{1}_{2}.pdf'.format(os.getcwd(), out_label, var))
plt.close()
@classmethod
def plot_cms_labels(self, axes, label='Work in progress', energy='(13 TeV)'):
axes.text(0, 1.01, r'\textbf{CMS} %s'%label, ha='left', va='bottom', transform=axes.transAxes, size=14)
axes.text(1, 1.01, r'{}'.format(energy), ha='right', va='bottom', transform=axes.transAxes, size=14)
def plot_roc(self, y_train, y_pred_train, train_weights, y_test, y_pred_test, test_weights, out_tag='MVA'):
bkg_eff_train, sig_eff_train, _ = roc_curve(y_train, y_pred_train, sample_weight=train_weights)
bkg_eff_test, sig_eff_test, _ = roc_curve(y_test, y_pred_test, sample_weight=test_weights)
fig = plt.figure(1)
axes = fig.gca()
axes.plot(bkg_eff_train, sig_eff_train, color='red', label='Train')
axes.plot(bkg_eff_test, sig_eff_test, color='blue', label='Test')
axes.set_xlabel('Background efficiency', ha='right', x=1, size=13)
axes.set_xlim((0,1))
axes.set_ylabel('Signal efficiency', ha='right', y=1, size=13)
axes.set_ylim((0,1))
axes.legend(bbox_to_anchor=(0.97,0.97))
self.plot_cms_labels(axes)
axes.grid(True, 'major', linestyle='solid', color='grey', alpha=0.5)
self.fig = fig
np.savez('{}/models/{}_ROC_sig_bkg_arrays.npz'.format(os.getcwd(), out_tag), sig_eff_test=sig_eff_test, bkg_eff_test=bkg_eff_test)
return fig
def plot_output_score(self, y_test, y_pred_test, test_weights, proc_arr_test, data_pred_test, MVA='BDT', ratio_plot=False, norm_to_data=False):
if ratio_plot:
plt.rcParams.update({'figure.figsize':(6,5.8)})
fig, axes = plt.subplots(nrows=2, ncols=1, dpi=200, sharex=True,
gridspec_kw ={'height_ratios':[3,0.8], 'hspace':0.08})
ratio = axes[1]
axes = axes[0]
else:
fig = plt.figure(1)
axes = fig.gca()
bins = np.linspace(0,1,41)
bkg_stack = []
bkg_w_stack = []
bkg_proc_stack = []
sig_scores = y_pred_test.ravel() * (y_test==1)
sig_w_true = test_weights.ravel() * (y_test==1)
bkg_scores = y_pred_test.ravel() * (y_test==0)
bkg_w_true = test_weights.ravel() * (y_test==0)
if self.normalise:
sig_w_true /= np.sum(sig_w_true)
bkg_w_true /= np.sum(bkg_w_true)
for bkg in self.bkg_labels:
bkg_score = bkg_scores * (proc_arr_test==bkg)
bkg_weights = bkg_w_true * (proc_arr_test==bkg)
bkg_stack.append(bkg_score)
bkg_w_stack.append(bkg_weights)
bkg_proc_stack.append(bkg)
#sig
axes.hist(sig_scores, bins=bins, label=self.sig_labels[0]+r' ($\mathrm{H}\rightarrow\mathrm{ee}$) '+self.num_to_str(self.sig_scaler), weights=sig_w_true*(self.sig_scaler), histtype='step', color=self.sig_colour)
#data - need to take test frac of data
data_binned, bin_edges = np.histogram(data_pred_test, bins=bins)
bin_centres = (bin_edges[:-1] + bin_edges[1:])/2
x_err = (bin_edges[-1] - bin_edges[-2])/2
data_down, data_up = self.poisson_interval(data_binned, data_binned)
axes.errorbar( bin_centres, data_binned, yerr=[data_binned-data_down, data_up-data_binned], label='Data', fmt='o', ms=4, color='black', capsize=0, zorder=1)
if norm_to_data:
rew_stack = []
k_factor = np.sum(np.ones_like(data_pred_test))/np.sum(bkg_w_true)
for w_arr in bkg_w_stack:
rew_stack.append(w_arr*k_factor)
axes.hist(bkg_stack, bins=bins, label=bkg_proc_stack, weights=rew_stack, histtype='stepfilled', color=self.bkg_colours[0:len(bkg_proc_stack)], log=self.log_axis, stacked=True, zorder=0)
bkg_stack_summed, _ = np.histogram(np.concatenate(bkg_stack), bins=bins, weights=np.concatenate(rew_stack))
sumw2_bkg, _ = np.histogram(np.concatenate(bkg_stack), bins=bins, weights=np.concatenate(rew_stack)**2)
else:
axes.hist(bkg_stack, bins=bins, label=bkg_proc_stack, weights=bkg_w_stack, histtype='stepfilled', color=self.bkg_colours[0:len(bkg_proc_stack)], log=self.log_axis, stacked=True, zorder=0)
bkg_stack_summed, _ = np.histogram(np.concatenate(bkg_stack), bins=bins, weights=np.concatenate(bkg_w_stack))
sumw2_bkg, _ = np.histogram(np.concatenate(bkg_stack), bins=bins, weights=np.concatenate(bkg_w_stack)**2)
#plot mc error
bkg_std_down, bkg_std_up = self.poisson_interval(bkg_stack_summed, sumw2_bkg)
axes.fill_between(bins, list(bkg_std_down)+[bkg_std_down[-1]], list(bkg_std_up)+[bkg_std_up[-1]], alpha=0.3, step="post", color="grey", lw=1, zorder=4, label='Simulation stat. unc.')
axes.legend(bbox_to_anchor=(0.97,0.97), ncol=2)
current_bottom, current_top = axes.get_ylim()
axes.set_ylim(bottom=0, top=current_top*1.3)
if self.normalise: axes.set_ylabel('Arbitrary Units', ha='right', y=1, size=13)
else: axes.set_ylabel('Events', ha='right', y=1, size=13)
if ratio_plot:
ratio.errorbar(bin_centres, (data_binned/bkg_stack_summed), yerr=[ (data_binned-data_down)/bkg_stack_summed, (data_up-data_binned)/bkg_stack_summed], fmt='o', ms=4, color='black', capsize=0)
bkg_std_down_ratio = np.ones_like(bkg_std_down) - ((bkg_stack_summed - bkg_std_down)/bkg_stack_summed)
bkg_std_up_ratio = np.ones_like(bkg_std_up) + ((bkg_std_up - bkg_stack_summed)/bkg_stack_summed)
ratio.fill_between(bins, list(bkg_std_down_ratio)+[bkg_std_down_ratio[-1]], list(bkg_std_up_ratio)+[bkg_std_up_ratio[-1]], alpha=0.3, step="post", color="grey", lw=1, zorder=4)
ratio.set_xlabel('{} Score'.format(MVA), ha='right', x=1, size=13)
ratio.set_ylim(0, 2)
ratio.grid(True, linestyle='dotted')
else: axes.set_xlabel('{} Score'.format(MVA), ha='right', x=1, size=13)
self.plot_cms_labels(axes)
#ggH
#axes.axvline(0.751, ymax=0.75, color='black', linestyle='--')
#axes.axvline(0.554, ymax=0.75, color='black', linestyle='--')
#axes.axvline(0.331, ymax=0.75, color='black', linestyle='--')
#axes.axvspan(0, 0.331, ymax=0.75, color='grey', alpha=0.7)
#VBF BDT
#axes.axvline(0.884, ymax=0.75, color='black', linestyle='--')
#axes.axvline(0.612, ymax=0.75, color='black', linestyle='--')
#axes.axvspan(0, 0.612, ymax=0.75, color='grey', alpha=0.6)
#VBF DNN
#axes.axvline(0.907, ymax=0.70, color='black', linestyle='--')
#axes.axvline(0.655, ymax=0.70, color='black', linestyle='--')
#axes.axvspan(0, 0.655, ymax=0.70, color='grey', lw=0, alpha=0.5)
return fig
@classmethod
def cats_vs_ams(self, cats, AMS, out_tag):
fig = plt.figure(1)
axes = fig.gca()
axes.plot(cats,AMS, 'ro')
axes.set_xlim((0, cats[-1]+1))
axes.set_xlabel('$N_{\mathrm{cat}}$', ha='right', x=1, size=13)
axes.set_ylabel('Combined AMS', ha='right', y=1, size=13)
Plotter.plot_cms_labels(axes)
fig.savefig('{}/categoryOpt/nCats_vs_AMS_{}.pdf'.format(os.getcwd(), out_tag))
def poisson_interval(self, x, variance, level=0.68):
neff = x**2/variance
scale = x/neff
# CMS statcomm recommendation
l = scipy.stats.gamma.interval(
level, neff, scale=scale,
)[0]
u = scipy.stats.gamma.interval(
level, neff+1, scale=scale
)[1]
# protect against no effecitve entries
l[neff==0] = 0.
# protect against no variance
l[variance==0.] = 0.
u[variance==0.] = np.inf
return l, u
<file_sep>/python/variables.py
#electron vars
nominal_vars = ['weight', 'leadElectronIDMVA', 'subleadElectronIDMVA','leadElectronPToM*', 'subleadElectronPToM*',
'leadJetEn', 'leadElectronPt', 'leadElectronEta', 'leadElectronPhi',
'subleadJetEn', 'subleadElectronPt', 'subleadElectronEta', 'subleadElectronPhi',
'subsubleadJetEn', 'dielectronCosPhi','dielectronPt', 'dielectronMass',
'leadJetPt','leadJetEta', 'leadJetPhi','leadJetQGL', #add jet en
'subleadJetPt','subleadJetEta', 'subleadJetPhi', 'subleadJetQGL', #add sublead jet en
'subsubleadJetPt','subsubleadJetEta', 'subsubleadJetPhi', 'subsubleadJetQGL', #add subsublead jet en
'dijetAbsDEta', 'dijetMass', 'dijetDieleAbsDEta', 'dijetDieleAbsDPhiTrunc', # FIXME: dijetAbsDPhiTrunc is actually dijet_dphi. Still need 'dijet_dipho_dphi_trunc' (min dphi I think it is)
'dijetMinDRJetEle', 'dijetCentrality', 'dielectronSigmaMoM'
]
#for MVA training, hence not including masses
gev_vars = ['leadJetEn', 'leadJetPt', 'subleadJetEn', 'subleadJetPt', 'subsubleadJetEn', 'subsubleadJetPt',
'leadElectronEn', 'leadElectronPt', 'subleadElectronEn', 'subleadElectronPt',
'leadElectronPToM', 'subleadElectronPToM', 'dijetMass', 'dielectronPt'
]
gen_vars = [] #dont need any gen vars for now
<file_sep>/categoryOpt/make_tag_sequence_w_lstm.py
import argparse
import numpy as np
import yaml
import pickle
import pandas as pd
import root_pandas
from os import path, system
import keras
from DataHandling import ROOTHelpers
from NeuralNets import LSTM_DNN
def main(options):
with open(options.config, 'r') as config_file:
config = yaml.load(config_file)
output_tag = config['output_tag']
mc_dir = config['mc_file_dir']
mc_fnames = config['mc_file_names']
data_dir = config['data_file_dir']
data_fnames = config['data_file_names']
proc_to_tree_name = config['proc_to_tree_name']
proc_to_train_vars = config['train_vars']
object_vars = proc_to_train_vars['VBF']['object_vars']
flat_obj_vars = [var for i_object in object_vars for var in i_object]
event_vars = proc_to_train_vars['VBF']['event_vars']
#used to check all vars we need for categorisation are in our dfs
all_train_vars = proc_to_train_vars['ggH'] + flat_obj_vars + event_vars
vars_to_add = config['vars_to_add']
#Data handling stuff#
#apply loosest selection (ggh) first, else memory requirements are ridiculous. Fine to do this since all cuts all looser than VBF (not removing events with higher priority)
loosest_selection = 'dielectronMass > 110 and dielectronMass < 150'
#load the mc dataframe for all years. Do not apply any specific preselection
root_obj = ROOTHelpers(output_tag, mc_dir, mc_fnames, data_dir, data_fnames, proc_to_tree_name, all_train_vars, vars_to_add, loosest_selection)
root_obj.no_lumi_scale()
for sig_obj in root_obj.sig_objects:
root_obj.load_mc(sig_obj, reload_samples=options.reload_samples)
if not options.data_as_bkg:
for bkg_obj in root_obj.bkg_objects:
root_obj.load_mc(bkg_obj, bkg=True, reload_samples=options.reload_samples)
else:
for data_obj in root_obj.data_objects:
root_obj.load_data(data_obj, reload_samples=options.reload_samples)
#overwrite background attribute, for compat with DNN class
root_obj.mc_df_bkg = root_obj.data_df
root_obj.concat()
#Tag sequence stuff#
#NOTE: these must be concatted in the same way they are concatted in LSTM.create_X_y(), else predicts are misaligned
combined_df = pd.concat([root_obj.mc_df_sig, root_obj.mc_df_bkg])
#decide sequence of tags and specify preselection for use with numpy.select:
tag_sequence = ['VBF','ggH']
proc_to_preselection = {'VBF': [combined_df['dielectronMass'].gt(110) &
combined_df['dielectronMass'].lt(150) &
combined_df['leadElectronPToM'].gt(0.333) &
combined_df['subleadElectronPToM'].gt(0.25) &
combined_df['dijetMass'].gt(350) &
combined_df['leadJetPt'].gt(40) &
combined_df['subleadJetPt'].gt(30)
],
'ggH': [combined_df['dielectronMass'].gt(110) &
combined_df['dielectronMass'].lt(150) &
combined_df['leadElectronPToM'].gt(0.333) &
combined_df['subleadElectronPToM'].gt(0.25)
]
}
# GET MVA SCORES #
with open(options.mva_config, 'r') as mva_config_file:
config = yaml.load(mva_config_file)
proc_to_model = config['models']
proc_to_tags = config['boundaries']
#evaluate ggH BDT scores
print 'evaluating ggH classifier: {}'.format(proc_to_model['ggH'])
clf = pickle.load(open('models/{}'.format(proc_to_model['ggH']), "rb"))
train_vars = proc_to_train_vars['ggH']
combined_df['ggH_mva'] = clf.predict_proba(combined_df[train_vars].values)[:,1:].ravel()
#Evaluate VBF LSTM
print 'loading VBF DNN:'
with open('models/{}'.format(proc_to_model['VBF']['architecture']), 'r') as model_json:
model_architecture = model_json.read()
model = keras.models.model_from_json(model_architecture)
model.load_weights('models/{}'.format(proc_to_model['VBF']['model']))
LSTM = LSTM_DNN(root_obj, object_vars, event_vars, 1.0, False, True)
# set up X and y Matrices. Log variables that have GeV units
LSTM.var_transform(do_data=False)
X_tot, y_tot = LSTM.create_X_y()
X_tot = X_tot[flat_obj_vars+event_vars] #filter unused vars
print np.isnan(X_tot).any()
#scale X_vars to mean=0 and std=1. Use scaler fit during previous dnn training
LSTM.load_X_scaler(out_tag='VBF_DNN')
X_tot = LSTM.X_scaler.transform(X_tot)
#make 2D vars for LSTM layers
X_tot = pd.DataFrame(X_tot, columns=flat_obj_vars+event_vars)
X_tot_high_level = X_tot[event_vars].values
X_tot_low_level = LSTM.join_objects(X_tot[flat_obj_vars])
#predict probs. Corresponds to same events, since dfs are concattened internally in the same
combined_df['VBF_mva'] = model.predict([X_tot_high_level, X_tot_low_level], batch_size=1).flatten()
# TAG NUMBER #
#decide on tag
for proc in tag_sequence:
presel = proc_to_preselection[proc]
tag_bounds = proc_to_tags[proc].values()
tag_masks = []
for i_bound in range(len(tag_bounds)): #c++ type looping for index reasons
if i_bound==0: #first bound, tag 0
tag_masks.append( presel[0] & combined_df['{}_mva'.format(proc)].gt(tag_bounds[i_bound]) )
else: #intermed bound
tag_masks.append( presel[0] & combined_df['{}_mva'.format(proc)].lt(tag_bounds[i_bound-1]) &
combined_df['{}_mva'.format(proc)].gt(tag_bounds[i_bound])
)
mask_key = [icat for icat in range(len(tag_bounds))]
combined_df['{}_analysis_tag'.format(proc)] = np.select(tag_masks, mask_key, default=-999)
# PROC PRIORITY #
# deduce tag priority: if two or more tags satisfied then set final tag to highest priority tag. make this non hardcoded i.e. compare proc in position 1 to all lower prioty positions. then compare proc in pos 2 ...
tag_priority_filter = [ combined_df['VBF_analysis_tag'].ne(-999) & combined_df['ggH_analysis_tag'].ne(-999), # 1) if both filled...
combined_df['VBF_analysis_tag'].ne(-999) & combined_df['ggH_analysis_tag'].eq(-999), # 2) if VBF filled and ggH not, take VBF
combined_df['VBF_analysis_tag'].eq(-999) & combined_df['ggH_analysis_tag'].ne(-999), # 3) if ggH filled and VBF not, take ggH
]
tag_priority_key = [ 'VBF', #1) take VBF
'VBF', #2) take VBF
'ggH', #3) take ggH
]
combined_df['priority_tag'.format(proc)] = np.select(tag_priority_filter, tag_priority_key, default='NOTAG') # else keep -999 i.e. NOTAG
#some debug checks:
#print combined_df[['dipho_mass', 'dipho_leadIDMVA', 'dipho_subleadIDMVA', 'dipho_lead_ptoM', 'dipho_sublead_ptoM', 'dijet_Mjj', 'dijet_LeadJPt', 'dijet_SubJPt', 'ggH_bdt', 'VBF_bdt', 'VBF_analysis_tag', 'ggH_analysis_tag', 'priority_tag']]
#print combined_df[combined_df.VBF_analysis_tag>-1][['dipho_mass', 'dipho_leadIDMVA', 'dipho_subleadIDMVA', 'dipho_lead_ptoM', 'dipho_sublead_ptoM', 'dijet_Mjj', 'dijet_LeadJPt', 'dijet_SubJPt', 'ggH_bdt', 'VBF_bdt', 'VBF_analysis_tag', 'ggH_analysis_tag', 'priority_tag']]
#print combined_df[combined_df.ggH_analysis_tag>-1][['dipho_mass', 'dipho_leadIDMVA', 'dipho_subleadIDMVA', 'dipho_lead_ptoM', 'dipho_sublead_ptoM', 'dijet_Mjj', 'dijet_LeadJPt', 'dijet_SubJPt', 'ggH_bdt', 'VBF_bdt', 'VBF_analysis_tag', 'ggH_analysis_tag', 'priority_tag']]
# FILL TREES BASED ON BOTH OF ABOVE
tree_vars = ['dZ', 'CMS_hgg_mass', 'weight']
combined_df['dZ'] = float(0.)
combined_df['CMS_hgg_mass'] = combined_df['dielectronMass']
# FIXME: dont loop through events eventually but for now I cba to use numpy to vectorise it again
#for true_proc in tag_sequence+['Data']:
# #isolate true proc
# true_proc_df = combined_df[combined_df.proc==true_proc.lower()]
# #how much true proc landed in each of our analysis cats?
# for target_proc in tag_sequence: #for all events that got the proc tag, which tag did they fall into?
# true_proc_target_proc_df = true_proc_df[true_proc_df.priority_tag==target_proc]
# for i_tag in range(len(proc_to_tags[target_proc].values())):#for each tag corresponding to the category we target, which events go in which tag
# true_procs_target_proc_tag_i = true_proc_target_proc_df[true_proc_target_proc_df['{}_analysis_tag'.format(target_proc)].eq(i_tag)]
#
# branch_name = '{}_125_13TeV_{}cat{} :'.format(true_proc.lower(), target_proc.lower(), i_tag )
# print true_procs_target_proc_tag_i[['dipho_mass', 'dipho_leadIDMVA', 'dipho_subleadIDMVA', 'dipho_lead_ptoM', 'dipho_sublead_ptoM', 'dijet_Mjj', 'dijet_LeadJPt', 'dijet_SubJPt', 'ggH_bdt', 'VBF_bdt', 'VBF_analysis_tag', 'ggH_analysis_tag', 'priority_tag']].head(10)
# print branch_name
#get tree names
branch_names = {}
#print 'DEBUG: {}'.format(np.unique(combined_df['proc']))
for true_proc in tag_sequence+['Data']:
branch_names[true_proc] = []
for target_proc in tag_sequence: #for all events that got the proc tag, which tag did they fall into?
for i_tag in range(len(proc_to_tags[target_proc].values())):#for each tag corresponding to the category we target, which events go in which tag
if true_proc is not 'Data': branch_names[true_proc].append('{}_125_13TeV_{}cat{}'.format(true_proc.lower(), target_proc.lower(), i_tag ))
else: branch_names[true_proc].append('{}_13TeV_{}cat{}'.format(true_proc, target_proc.lower(), i_tag ))
#debug_procs = ['dipho_mass', 'dipho_leadIDMVA', 'dipho_subleadIDMVA', 'dipho_lead_ptoM', 'dipho_sublead_ptoM', 'dijet_Mjj', 'dijet_LeadJPt', 'dijet_SubJPt', 'ggH_bdt', 'VBF_bdt', 'VBF_analysis_tag', 'ggH_analysis_tag', 'priority_tag']
debug_vars = ['proc', 'VBF_analysis_tag', 'ggH_analysis_tag', 'priority_tag']
combined_df['tree_name'] = combined_df.apply(assign_tree, axis=1)
print combined_df[debug_vars+['tree_name']]
if not path.isdir('output_trees/'):
print 'making directory: {}'.format('output_trees/')
system('mkdir -p %s' %'output_trees/')
#have to save individual trees then hadd procs together on the command line.
for proc in tag_sequence+['Data']:
selected_df = combined_df[combined_df.proc==proc]
for bn in branch_names[proc]:
print bn
branch_selected_df = selected_df[selected_df.tree_name==bn]
print branch_selected_df[debug_vars+['tree_name']].head(20)
root_pandas.to_root(branch_selected_df[tree_vars], 'output_trees/{}.root'.format(bn), key=bn)
print
#if worst comes to worst then just iter over df rows and fill a root tree the old school way
def assign_tree(row):
if row['proc'] == 'VBF':
#for all true vbf processes, which went in what analysis category
if row['priority_tag'] == 'VBF':
if row['VBF_analysis_tag']==0 : return 'vbf_125_13TeV_vbfcat0'
elif row['VBF_analysis_tag']==1 : return 'vbf_125_13TeV_vbfcat1'
elif row['priority_tag'] == 'ggH':
if row['ggH_analysis_tag']==0 : return 'vbf_125_13TeV_gghcat0'
elif row['ggH_analysis_tag']==1 : return 'vbf_125_13TeV_gghcat1'
elif row['ggH_analysis_tag']==2 : return 'vbf_125_13TeV_gghcat2'
elif row['priority_tag'] == 'NOTAG': return 'NOTAG'
else: raise KeyError('Did not have one of the correct tags')
elif row['proc'] == 'ggH':
if row['priority_tag'] == 'VBF':
if row['VBF_analysis_tag']==0 : return 'ggh_125_13TeV_vbfcat0'
elif row['VBF_analysis_tag']==1 : return 'ggh_125_13TeV_vbfcat1'
elif row['priority_tag'] == 'ggH':
if row['ggH_analysis_tag']==0 : return 'ggh_125_13TeV_gghcat0'
elif row['ggH_analysis_tag']==1 : return 'ggh_125_13TeV_gghcat1'
elif row['ggH_analysis_tag']==2 : return 'ggh_125_13TeV_gghcat2'
elif row['priority_tag'] == 'NOTAG': return 'NOTAG'
else: raise KeyError('Did not have one of the correct tags')
#for all true ggh processes, which went in what analysis category
elif row['proc'] == 'Data':
if row['priority_tag'] == 'VBF':
if row['VBF_analysis_tag']==0 : return 'Data_13TeV_vbfcat0'
elif row['VBF_analysis_tag']==1 : return 'Data_13TeV_vbfcat1'
elif row['priority_tag'] == 'ggH':
if row['ggH_analysis_tag']==0 : return 'Data_13TeV_gghcat0'
elif row['ggH_analysis_tag']==1 : return 'Data_13TeV_gghcat1'
elif row['ggH_analysis_tag']==2 : return 'Data_13TeV_gghcat2'
elif row['priority_tag'] == 'NOTAG': return 'NOTAG'
else: raise KeyError('Did not have one of the correct tags')
#for all true data processes, which went in what analysis category
else: raise KeyError('Did not have one of the correct procs')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
required_args = parser.add_argument_group('Required Arguments')
required_args.add_argument('-c','--config', action='store', required=True)
required_args.add_argument('-B','--mva_config', action='store', required=True)
opt_args = parser.add_argument_group('Optional Arguements')
opt_args.add_argument('-r','--reload_samples', help='re-load the .root files and convert into pandas DataFrames', action='store_true', default=False)
opt_args.add_argument('-d','--data_as_bkg', action='store_true', default=False)
options=parser.parse_args()
main(options)
<file_sep>/README.md
# BDTs/DNNs for VBF and ggH H->ee searches
## Setup
* General information about setting up the cms area, if wanting to do so.
The first thing to do is: `source setup.sh`. This appends the appropriate pacakages to your `PYTHONPATH`. It also loads a cms environment; you may remove this line if already using a package manager like `conda`.
## BDT Training
To separate the VBF or ggH HToEE signal from the dominant Drell-Yan background, we may use a Boosted Decision Tree (BDT).
For this, you may use the `training/train_bdt.py` script. This requires a configuration file `-c bdt_config_<vbf/ggh>.yaml` which specifies:
* whether we are training on ggH or VBF processes
* the sample options (files dirs and names, tree names, years, ...)
* variables to train our BDT with
* preselection for all samples.
An example config for VBF training can be found here: `bdt_config_vbf.yaml`
The command to train a simple VBF vs Bkg BDT with a train-test splitting fraction of 0.7, is:
```
python training/train_bdt.py -c configs/bdt_config_vbf.yaml -t 0.7
```
You will notice that the performance training this simple BDT is poor; the classifier predicts only the background class, due to the massive class imbalance. To remedy this, try training with the sum of signal weights increased such that they equal the sum of background weights, by adding the option `-w`.
### optimising model parameters
To optimise the model hyper parameters (HP), use the option `-o`. This submits ~6000 jobs to the IC computing cluster, one for each hyper parameter configuration. If you want to change the HP space, modify the `BDT()` class constructor inside `HToEEML.py`. Each model is cross validated; the number of folds can be specified with the `-k` option. Note that to keep the optimisation fair, you should not run with the `-r` option, since this re-loads and *reshuffles* the dataset; we want each model to use the same sample set.
Once the best model has been found, you may train/test on the full sample by running with option `-b`. This will produce plots of the ROC score for the train and test set, and save it in the working directory in a `plots` folder. The output score for the two classes is also plot.
### background reweighting
To apply a rewighting of a given MC sample (Drell-Yan as default) to data, in bins of pT(ee), use the option `-P`. This is motivated by known disagreement between Drell-Yan simulation and data. The reweighting is derived in a dielectron mass control region around the Z-mass, before being applied in the signal region. An option to reweight double differentially in bins of jet multiplicity may also be configured in the training script.
An extra word of warning on this - reading in the control region to derive the rewighting requires much more memory than the nominal training. Therefore its best to submit the training to the IC batch, first time of running. Once the re-weighted dataframe has been saved once, it should be fine to run locally again.
## LSTM training
To use an LSTM neural network to perform separate VBF signal from background, we use the script `training/train_lstm.py`. This takes a separate config, similar to the BDT, but with a nested list of low-level variables to be used in the LSTM layers. High level variables are also used, interfaced with the outputs of the LSTM units in fully connected layers. For an example config, see: `configs/lstm_config.yaml`.
The training can be run with the same syntax used in the BDT training. For example, to train a simple LSTM with default architecture and equalised class weights:
```
python training/train_lstm.py -c configs/lstm_config_vbf.yaml -t 0.7 -w
```
To optimise network hyper paramters, add the `-o` option. This may take up to a day per job, since we perform a k-fold cross validation. Following the optimisation, if all jobs have finished, add `-b` to train with the best model and produce ROC plots for the classifier.
## Category Optimisation
Once a model has been trained and optimised, you may use the output score to construct categories targeting ggH/VBF production.
This is done by splitting the signal + background events into boundaries defined by the output classifier score, such that the average median significance (AMS) is optimised.
To perform the optimisation, which also optimises the number of categories (defaults to between 1 and 4) the following command can be run:
```
python categoryOpt/bdt_category_opt.py -c configs/bdt_config_ggh.yaml -m models/ggH_BDT_best_clf.pickle.dat -d
```
which runs an optimisation for ggH categories. Note that the `-d` option replaces background simulated samples with data. The `-m` option specified the pre-trained BDT; in this case we use the best model from earlier HP optimisation.If wanting to use the classifier from a pT(ee) reweighted sample, be aware that the model name will be different to the nominal models.
## Final Tag Producer
To produce the trees with the category information needed for final fits, we use `categoryOpt/make_tag_sequence.py`. This takes a config specifying the BDT boundaries for each set of tags (see `configs/bdt_boundaries_config.yaml` for an example). The script also requires an additional config with sample and training varaible info (see `configs/tag_seq_config.yaml` for info an example)
### To do:
* assert cut string vars are in nominal vars
* break plotting class up to avoid duplicating code
<file_sep>/python/DataHandling.py
#data handling imports
import uproot as upr
import numpy as np
import pandas as pd
import os
from numpy import pi
from os import path, system
from variables import nominal_vars, gen_vars, gev_vars
import yaml
import pickle
from pickle import load, dump
from Utils import Utils
class SampleObject(object):
'''
Book-keeping class to store attributes of each sample. One object to be used per year, per sample -
practically this means one per ROOT file
:param proc_tag: physics process name for the sample being read in
:type proc_tag: string
:param year: year for the sample being read in
:type year: int
:param file_name: name of the ROOT file being read in
:type file_name: string
:param tree_path: name of the TTree for the sample, contained in the ROOT TDirectory
:type tre_path: string
'''
def __init__(self, proc_tag, year, file_name, tree_path):
self.proc_tag = proc_tag
self.year = year
self.file_name = file_name
self.tree_name = tree_path
class ROOTHelpers(object):
"""
Class produce dataframes from any number of signal, background, or data processes
for multiple years of data taking
:param out_tag: output string to be added to saved objectsm e.g. plots, dataframes, models, etc.
:type out_tag: string
:param mc_dir: directory where root files for simulation are held. Files for all years should be in this directory
:type mc_dir: string
:param mc_fnames: file names for simulated signal and background samples. Each has its own process key.
Each process key has its own year keys. See any example training config for more detail.
:type mc_fnames: dict
:param data_dir: directory where root files for data are held. Files for all years should be in this directory
:type: data_dir: string
:param data_fnames: file names for Data samples. The key for all samples should be 'Data'.
This key has its own year keys. See any example training config for more detail.
:type data_fnames: dict
:param proc_to_tree_name: tree name split by physics process. Useful if trees have a process dependent name.
Should have one string per physics process name (per key)
:type proc_to_tree_name: dict
:param train_vars: variables to be used when training a classifier.
:type train_vars: list
:param vars_to_add: variables that are not in the input ROOT files, but will be added during sample processing.
Should become redundant when all variables are eventually in input files.
:type vars_to_add: list
:param presel_str: selection to be applied to all samples.
:type presel_str: string
"""
def __init__(self, out_tag, mc_dir, mc_fnames, data_dir, data_fnames, proc_to_tree_name, train_vars, vars_to_add, presel_str=''):
self.years = set()
self.lumi_map = {'2016':35.9, '2017':41.5, '2018':59.7}
self.lumi_scale = True
self.XS_map = {'ggH':48.58*5E-9, 'VBF':3.782*5E-9, 'DYMC': 6225.4, 'TT2L2Nu':86.61, 'TTSemiL':358.57} #all in pb. also have BR for signals
self.eff_acc = {'ggH':0.3736318, 'VBF':0.3766126, 'DYMC':0.0628066, 'TT2L2Nu':0.0165516, 'TTSemiL':0.0000897} #Pass5 from dumper. update if selection changes
#self.eff_acc = {'ggH':0.4515728, 'VBF':0.4670169, 'DYMC':0.0748512, 'TT2L2Nu':0.0405483, 'TTSemiL':0.0003810} #from dumper. Pass2
self.eff_acc = {'ggH':0.4014615, 'VBF':0.4044795, 'DYMC':0.0660393, 'TT2L2Nu':0.0176973, 'TTSemiL':0.0001307} #from dumper. Pass3
self.out_tag = out_tag
self.mc_dir = mc_dir #FIXME: remove '\' using if_ends_with()
self.data_dir = data_dir
self.sig_procs = []
self.sig_objects = []
for proc, year_to_file in mc_fnames['sig'].items():
if proc not in self.sig_procs: self.sig_procs.append(proc)
else: raise IOError('Multiple versions of same signal proc trying to be read')
for year, file_name in year_to_file.iteritems():
self.years.add(year)
self.sig_objects.append( SampleObject(proc, year, file_name, proc_to_tree_name[proc]) )
self.bkg_procs = []
self.bkg_objects = []
for proc, year_to_file in mc_fnames['bkg'].items():
if proc not in self.bkg_procs: self.bkg_procs.append(proc)
else: raise IOError('Multiple versions of same background proc trying to be read')
for year, file_name in year_to_file.iteritems():
if year not in self.years: raise IOError('Incompatible sample years')
self.bkg_objects.append( SampleObject(proc, year, file_name, proc_to_tree_name[proc]) )
self.data_objects = []
for proc, year_to_file in data_fnames.items():
for year, file_name in year_to_file.iteritems():
if year not in self.years: raise IOError('Incompatible sample years')
self.data_objects.append( SampleObject(proc, year, file_name, proc_to_tree_name[proc]) )
self.mc_df_sig = []
self.mc_df_bkg = []
self.data_df = []
if vars_to_add is None: vars_to_add = {}
self.vars_to_add = vars_to_add
missing_vars = [x for x in train_vars if x not in (nominal_vars+list(vars_to_add.keys()))]
if len(missing_vars)!=0: raise IOError('Missing variables: {}'.format(missing_vars))
self.nominal_vars = nominal_vars
self.train_vars = train_vars
self.cut_string = presel_str
def no_lumi_scale(self):
"""
Toggle lumi scaling on/off. Useful when producing ROOT files for worksapces/fits.
"""
self.lumi_scale=False
def load_mc(self, sample_obj, bkg=False, reload_samples=False):
"""
Try to load mc dataframe. If it doesn't exist, read in the root file.
This should be used once per year, if reading in multiple years.
Arguments
---------
sample_obj: SampleObject
an instance of the SampleObject class. Used to unpack attributes of the sample.
bkg: bool
indicates if the simulated sample being processed is background.
reload_samples: bool
force all samples to be read in from the input ROOT files, even if the dataframes already exist.
Useful if changes to input files have been made.
"""
try:
if reload_samples: raise IOError
elif not bkg: self.mc_df_sig.append( self.load_df(self.mc_dir+'DataFrames/', sample_obj.proc_tag, sample_obj.year) )
else: self.mc_df_bkg.append( self.load_df(self.mc_dir+'DataFrames/', sample_obj.proc_tag, sample_obj.year) )
except IOError:
if not bkg: self.mc_df_sig.append( self.root_to_df(self.mc_dir,
sample_obj.proc_tag,
sample_obj.file_name,
sample_obj.tree_name,
'sig', sample_obj.year
)
)
else: self.mc_df_bkg.append( self.root_to_df(self.mc_dir,
sample_obj.proc_tag,
sample_obj.file_name,
sample_obj.tree_name,
'bkg', sample_obj.year
)
)
def load_data(self, sample_obj, reload_samples=False):
"""
Try to load Data dataframe. If it doesn't exist, read in the root file.
This should be used once per year, if reading in multiple years.
Arguments
---------
sample_obj: SampleObject
an instance of the SampleObject class. Used to unpack attributes of the sample.
reload_samples: bool
force all samples to be read in from the input ROOT files, even if the dataframes alreadt exist.
Useful if changes to input files have been made.
"""
try:
if reload_samples: raise IOError
else: self.data_df.append( self.load_df(self.data_dir+'DataFrames/', 'Data', sample_obj.year) )
except IOError:
self.data_df.append( self.root_to_df(self.data_dir, sample_obj.proc_tag, sample_obj.file_name, sample_obj.tree_name, 'Data', sample_obj.year) )
def load_df(self, df_dir, proc, year):
"""
Load pandas dataframe, for a given process and year. Check all variables need for training are in columns.
Arguments
---------
df_dir: string
directory where pandas dataframes for each process x year are kept.
proc: string
physics process name for dataframe being read in
year: int
year for dataframe being read in
Returns
-------
df: pandas dataframe that was read in.
"""
#print 'loading {}{}_{}_df_{}.pkl'.format(df_dir, proc, self.out_tag, year)
#df = pd.read_hdf('{}{}_{}_df_{}.h5'.format(df_dir, proc, self.out_tag, year))
#df = pd.read_pickle('{}{}_{}_df_{}.pkl'.format(df_dir, proc, self.out_tag, year))
df = pd.read_csv('{}{}_{}_df_{}.csv'.format(df_dir, proc, self.out_tag, year))
missing_vars = [x for x in self.train_vars if x not in df.columns]
if len(missing_vars)!=0: raise IOError('Missing variables in dataframe: {}. Reload with option -r and try again'.format(missing_vars))
else: print('Sucessfully loaded DataFrame: {}{}_{}_df_{}.csv'.format(df_dir, proc, self.out_tag, year))
return df
def root_to_df(self, file_dir, proc_tag, file_name, tree_name, flag, year):
"""
Load a single root file for signal, background or data, for a given year. Apply any preselection.
If reading in simulated samples, apply lumi scaling and read in gen-level variables too
Arguments
---------
file_dir: string
directory that the ROOT file being read in is contained.
proc_tag: string
name of the physics process for the sample.
file_name: string
name of ROOT file being read in.
tree_name: string
name of TTree contrained within the ROOT file being read in.
flag: string
flag to indicate signal ('sig'), background ('bkg'), or Data ('Data')
Returns
-------
df: pandas dataframe created from the input ROOT file
"""
print('Reading {} file: {}, for year: {}'.format(proc_tag, file_dir+file_name, year))
df_file = upr.open(file_dir+file_name)
df_tree = df_file[tree_name]
del df_file
if flag == 'Data':
#can cut on data now as dont need to run MC_norm
data_vars = self.nominal_vars
#needed for preselection and training
#df = df_tree.pandas.df(data_vars.remove('genWeight')).query('dielectronMass>110 and dielectronMass<150 and dijetMass>250 and leadJetPt>40 and subleadJetPt>30')
#FIXME: temp fix until ptOm in samples. Then can just do normal query string again (which is set up to to only read wider mass range if pT reweighting)
#df = df_tree.pandas.df(data_vars.remove('genWeight')).query('dielectronMass>80 and dielectronMass<150')
df = df_tree.pandas.df(data_vars).query('dielectronMass>80 and dielectronMass<150')
df['leadElectronPToM'] = df['leadElectronPt']/df['dielectronMass']
df['subleadElectronPToM'] = df['subleadElectronPt']/df['dielectronMass']
df = df.query(self.cut_string)
#df['weight'] = np.ones_like(df.shape[0])
else:
#cant cut on sim now as need to run MC_norm and need sumW before selection!
df = df_tree.pandas.df(self.nominal_vars)
#needed for preselection and training
df['leadElectronPToM'] = df['leadElectronPt']/df['dielectronMass']
df['subleadElectronPToM'] = df['subleadElectronPt']/df['dielectronMass']
#NOTE: dont apply cuts yet as need to do MC norm!
if len(self.cut_string)>0:
if flag != 'Data':
df = self.MC_norm(df, proc_tag, year)
df = df.query(self.cut_string)
else:
if flag != 'Data':
df = self.MC_norm(df, proc_tag, year)
df = df.sample(frac=1).reset_index(drop=True)
df = df.dropna()
df['proc'] = proc_tag
df['year'] = year
print('Number of events in final dataframe: {}'.format(np.sum(df['weight'].values)))
#save everything
Utils.check_dir(file_dir+'DataFrames/')
df.to_csv('{}/{}_{}_df_{}.csv'.format(file_dir+'DataFrames', proc_tag, self.out_tag, year))
#df.to_pickle('{}/{}_{}_df_{}.pkl'.format(file_dir+'DataFrames', proc_tag, self.out_tag, year))
#df.to_hdf('{}/{}_{}_df_{}.h5'.format(file_dir+'DataFrames', proc_tag, self.out_tag, year), 'df', mode='w', format='t')
print('Saved dataframe: {}/{}_{}_df_{}.csv'.format(file_dir+'DataFrames', proc_tag, self.out_tag, year))
#print('Saved dataframe: {}/{}_{}_df_{}.pkl'.format(file_dir+'DataFrames', proc_tag, self.out_tag, year))
return df
def MC_norm(self, df, proc_tag, year):
"""
Apply normalisation to get expected number of events (perform before prelection)
Arguments
---------
:param df: pandas Dataframe
dataframe for simulated signal or background with weights to be normalised
:param proc_tag: string
name of the physics process for the dataframe
:param year: int
year corresponding to the dataframe being read in
Returns
-------
df: normalised dataframes
"""
#Do scaling that used to happen in flashgg: XS * BR(for sig only) eff * acc
sum_w_initial = np.sum(df['weight'].values)
print 'scaling by {} by XS: {}'.format(proc_tag, self.XS_map[proc_tag])
df['weight'] *= (self.XS_map[proc_tag])
if self.lumi_scale: #should not be doing this in the final Tag producer
print 'scaling by {} by Lumi: {} * 1000 /pb'.format(proc_tag, self.lumi_map[year])
df['weight'] *= self.lumi_map[year]*1000 #lumi is added earlier but XS is in pb, so need * 1000
print 'scaling by {} by eff*acc: {}'.format(proc_tag, self.eff_acc[proc_tag])
df['weight'] *= (self.eff_acc[proc_tag])
df['weight'] /= sum_w_initial
print 'sumW for proc {}: {}'.format(proc_tag, np.sum(df['weight'].values))
return df
def apply_more_cuts(self, cut_string):
"""
Apply some additional cuts, after nominal preselection (which was applied when file was read in)
Arguments
---------
cut_string: string
set of cuts to be applied to all variables
"""
self.mc_df_sig = self.mc_df_sig.query(cut_string)
self.mc_df_bkg = self.mc_df_bkg.query(cut_string)
self.data_df = self.data_df.query(cut_string)
def concat(self):
"""
Concat sample types (sig, bkg, data) together, if more than one df in the associated sample type list.
Years will also be automatically concatennated over. Could split this up into another function if desired
but year info is only needed for lumi scaling.
If the list is empty (not reading anything), leave it empty
"""
if len(self.mc_df_sig) == 1: self.mc_df_sig = self.mc_df_sig[0]
elif len(self.mc_df_sig) == 0: pass
else: self.mc_df_sig = pd.concat(self.mc_df_sig)
if len(self.mc_df_bkg) == 1: self.mc_df_bkg = self.mc_df_bkg[0]
elif len(self.mc_df_bkg) == 0: pass
else: self.mc_df_bkg = pd.concat(self.mc_df_bkg)
if len(self.data_df) == 1: self.data_df = self.data_df[0]
elif len(self.data_df) == 0 : pass
else: self.data_df = pd.concat(self.data_df)
def pt_reweight(self, bkg_proc, year, presel, norm_first=True):
"""
Derive a reweighting for a single bkg process in a m(ee) control region around the Z-peak, in bins on pT(ee),
to map bkg process to Data. Then apply this in the signal region
Arguments
---------
bkg_proc: string
name of the physics process we want to re-weight. Nominally this is for Drell-Yan.
year: float
year to be re-weighted (perform this separately for each year)
presel: string
preselection to apply to go from the CR -> SR
norm_first: bool
normalise the simulated background to data. Results in a shape-only correction
"""
pt_bins = np.linspace(0,180,101)
scaled_list = []
bkg_df = self.mc_df_bkg.query('proc=="{}" and year=="{}" and dielectronMass>80 and dielectronMass<100'.format(bkg_proc,year))
data_df = self.data_df.query('year=="{}" and dielectronMass>80 and dielectronMass<100'.format(year))
#FIXME: here only norming DY events to data...
if norm_first: bkg_df['weight'] *= (np.sum(data_df['weight'])/np.sum(bkg_df['weight']))
bkg_pt_binned, _ = np.histogram(bkg_df['dielectronPt'], bins=pt_bins, weights=bkg_df['weight'])
data_pt_binned, bin_edges = np.histogram(data_df['dielectronPt'], bins=pt_bins)
scale_factors = data_pt_binned/bkg_pt_binned
#now apply the proc targeting selection on all dfs, and re-save. Now samples are back in SR
self.apply_more_cuts(presel)
#FIXME: ... but here scaling DY + other backgrounds before doing pT reweighting? is this ok. Think so since in m_ee ctrl region we only have DY really
if norm_first: self.mc_df_bkg['weight'] *= (np.sum(self.data_df['weight'])/np.sum(self.mc_df_bkg['weight']))
self.mc_df_bkg['weight'] = self.mc_df_bkg.apply(self.pt_njet_reweight_helper, axis=1, args=[bkg_proc, year, bin_edges, scale_factors, False])
self.save_modified_dfs(year)
def pt_njet_reweight(self, bkg_proc, year, presel, norm_first=True):
"""
Derive a reweighting for a single bkg process in a m(ee) control region around the Z-peak, double differentially
in bins on pT(ee) and nJets, to map bkg process to Data. Then apply this in the signal region.
Arguments
---------
bkg_proc: string
name of the physics process we want to re-weight. Nominally this is for Drell-Yan.
year: float
year to be re-weighted (perform this separately for each year)
presel: string
preselection to apply to go from the CR -> SR
norm_first: bool
normalise the simulated background to data. Results in a shape-only correction
"""
#can remove this once nJets is put in ntuples from dumper
outcomes_mc_bkg = [ self.mc_df_bkg['leadJetPt'].lt(0),
self.mc_df_bkg['leadJetPt'].gt(0) & self.mc_df_bkg['subleadJetPt'].lt(0),
self.mc_df_bkg['leadJetPt'].gt(0) & self.mc_df_bkg['subleadJetPt'].gt(0)
]
outcomes_data = [ self.data_df['leadJetPt'].lt(0),
self.data_df['leadJetPt'].gt(0) & self.data_df['subleadJetPt'].lt(0),
self.data_df['leadJetPt'].gt(0) & self.data_df['subleadJetPt'].gt(0)
]
jets = [0, 1, 2] # 2 really means nJet >= 2
self.mc_df_bkg['nJets'] = np.select(outcomes_mc_bkg, jets)
self.data_df['nJets'] = np.select(outcomes_data, jets)
#apply re-weighting
pt_bins = np.linspace(0,200,101)
jet_bins = [0,1,2]
n_jets_to_sfs_map = {}
#derive pt and njet based SFs
for n_jets in jet_bins:
if not n_jets==jet_bins[-1]:
bkg_df = self.mc_df_bkg.query('proc=="{}" and year=="{}" and dielectronMass>80 and dielectronMass<100 and nJets=={}'.format(bkg_proc,year, n_jets))
data_df = self.data_df.query('year=="{}" and dielectronMass>80 and dielectronMass<100 and nJets=={}'.format(year,n_jets))
else:
bkg_df = self.mc_df_bkg.query('proc=="{}" and year=="{}" and dielectronMass>80 and dielectronMass<100 and nJets>={}'.format(bkg_proc,year, n_jets))
data_df = self.data_df.query('year=="{}" and dielectronMass>80 and dielectronMass<100 and nJets>={}'.format(year,n_jets))
if norm_first:
CR_norm_i_jet_bin = (np.sum(data_df['weight'])/np.sum(bkg_df['weight']))
bkg_df['weight'] *= CR_norm_i_jet_bin
bkg_pt_binned, _ = np.histogram(bkg_df['dielectronPt'], bins=pt_bins, weights=bkg_df['weight'])
data_pt_binned, bin_edges = np.histogram(data_df['dielectronPt'], bins=pt_bins)
n_jets_to_sfs_map[n_jets] = data_pt_binned/bkg_pt_binned
#now apply the proc targeting selection on all dfs, and re-save. Then apply derived SFs
self.apply_more_cuts(presel)
if norm_first:
SR_i_jet_to_norm = {}
for n_jets in jet_bins:
SR_i_jet_to_norm[n_jets] = np.sum(self.data_df['weight']) / np.sum(self.mc_df_bkg['weight'])
self.mc_df_bkg['weight'] = self.mc_df_bkg.apply(self.pt_njet_reweight_helper, axis=1, args=[bkg_proc, year, bin_edges, n_jets_to_sfs_map, True, SR_i_jet_to_norm])
else: self.mc_df_bkg['weight'] = self.mc_df_bkg.apply(self.pt_njet_reweight_helper, axis=1, args=[bkg_proc, year, bin_edges, n_jets_to_sfs_map, True, None])
self.save_modified_dfs(year)
def pt_njet_reweight_helper(self, row, bkg_proc, year, bin_edges, scale_factors, do_jets, norm_first_dict=None):
"""
Function called in pandas apply() function, looping over rows and testing conditions. Can be called for
single or double differential re-weighting.
Tests which pT a bkg proc is, and if it is the proc to reweight, before
applying a pT dependent scale factor to apply (derived from CR)
If dielectron pT is above the max pT bin, just return the nominal weight (very small num of events)
Arguments
---------
row: pandas Series
a single row of the dataframe being looped through. Automatically generated as first argument
when using pandas apply()
bkg_proc: string
name of the physics process we want to re-weight. Nominally this is for Drell-Yan.
year: float
year to be re-weighted (perform this separately for each year)
bin_edges: numpy array
edges of each pT bin, in which the re-weighting is applied
scale_factors: numpy array
scale factors to be applied in each pT bin
do_jets: bool
if true, perform double differential re-weighting in bins of pT and jet multiplicity
norm_first_dict: dict
optional dict that contains normalisations in the SR, for each jet bin
Returns
-------
row['weight'] * scale-factor : float of the (modified) MC weight for a single event/dataframe row
"""
if row['proc']==bkg_proc and row['year']==year and row['dielectronPt']<bin_edges[-1]:
if do_jets: rew_factors = scale_factors[row['nJets']]
else: rew_factors = scale_factors
for i_bin in range(len(bin_edges)):
if (row['dielectronPt'] > bin_edges[i_bin]) and (row['dielectronPt'] < bin_edges[i_bin+1]):
if norm_first_dict is not None:
if row['nJets'] >= 2: jet_bin = 2
else: jet_bin = row['nJets']
return row['weight'] * rew_factors[i_bin] * norm_first_dict[jet_bin]
else: return row['weight'] * rew_factors[i_bin]
else:
return row['weight']
def save_modified_dfs(self,year):
"""
Save dataframes again. Useful if modifications were made since reading in and saving e.g. pT reweighting or applying more selection
(or both).
Arguments
---------
year: int
year for which all samples being saved correspond to
"""
print 'saving modified dataframes...'
for sig_proc in self.sig_procs:
sig_df = self.mc_df_sig[np.logical_and(self.mc_df_sig.proc==sig_proc, self.mc_df_sig.year==year)]
#sig_df.to_hdf('{}/{}_{}_df_{}.h5'.format(self.mc_dir+'DataFrames', sig_proc, self.out_tag, year), 'df', mode='w', format='t')
#sig_df.to_pickle('{}/{}_{}_df_{}.pkl'.format(self.mc_dir+'DataFrames', sig_proc, self.out_tag, year))
sig_df.to_csv('{}/{}_{}_df_{}.csv'.format(self.mc_dir+'DataFrames', sig_proc, self.out_tag, year))
print('saved dataframe: {}/{}_{}_df_{}.csv'.format(self.mc_dir+'DataFrames', sig_proc, self.out_tag, year))
for bkg_proc in self.bkg_procs:
bkg_df = self.mc_df_bkg[np.logical_and(self.mc_df_bkg.proc==bkg_proc,self.mc_df_bkg.year==year)]
#bkg_df.to_hdf('{}/{}_{}_df_{}.h5'.format(self.mc_dir+'DataFrames', bkg_proc, self.out_tag, year), 'df', mode='w', format='t')
#bkg_df.to_pickle('{}/{}_{}_df_{}.pkl'.format(self.mc_dir+'DataFrames', bkg_proc, self.out_tag, year))
bkg_df.to_csv('{}/{}_{}_df_{}.csv'.format(self.mc_dir+'DataFrames', bkg_proc, self.out_tag, year))
print('saved dataframe: {}/{}_{}_df_{}.csv'.format(self.mc_dir+'DataFrames', bkg_proc, self.out_tag, year))
data_df = self.data_df[self.data_df.year==year]
#data_df.to_hdf('{}/{}_{}_df_{}.h5'.format(self.data_dir+'DataFrames', 'Data', self.out_tag, year), 'df', mode='w', format='t')
#data_df.to_pickle('{}/{}_{}_df_{}.pkl'.format(self.data_dir+'DataFrames', 'Data', self.out_tag, year))
data_df.to_csv('{}/{}_{}_df_{}.csv'.format(self.data_dir+'DataFrames', 'Data', self.out_tag, year))
print('saved dataframe: {}/{}_{}_df_{}.csv'.format(self.data_dir+'DataFrames', 'Data', self.out_tag, year))
| 32e0e838ccf2323f5418f64c5653d311ff7ed08c | [
"Markdown",
"Python"
] | 5 | Python | edjtscott/HToEE | b61b238823edac37e5d7916f90ec0f3586aa7a44 | faa3ee17758d18900c8b669d14bf1e4bbdae553b |
refs/heads/master | <file_sep>
public class Palindrome {
public static void main (String[] args) {
System.out.println("Tacocat is palindrome? " + isPal1("tacocat"));
System.out.print("Tacocat is palindrome? " + isPal2("tavtcat", 0));
}
public static boolean isPal1(String S) {
S = S.toLowerCase();
for(int i = 0, j = S.length()-1; i<=(S.length()/2); i++, j--) {
if(S.charAt(i)!=S.charAt(j)) {
return false;
}
}
return true;
}
public static boolean isPal2(String S, int i) {
int j = (S.length()-1)-i;
if(i >= j) return true;
if (S.charAt(i) != S.charAt(j)) return false;
return isPal2(S, ++i);
}
}<file_sep>
public class Fibonacci {
public static void main(String[] args) {
int n = 20;
System.out.print(fib(n));
int f_2 = 0;
int f_1 = 1;
int f = 1;
for(int i=0;i<=(n-2);i++) {
f = f_1 + f_2;
f_2 = f_1;
f_1=f;
}
int sum = f;
System.out.print(" "+sum+" ");
}
public static int fib(int num) {
return (num <= 1) ? num : (fib(num -1) + fib(num-2));
}
}
| 3511aebfc0201b3d9ef3f5fa61d434d9e6eea1f0 | [
"Java"
] | 2 | Java | Booglejr/CMPS | 6836ed9ef5d29f29d6210a6bfb14290251c480ec | 99be771673d224eb7373f72cc2c4a49fd2d68b4e |
refs/heads/master | <repo_name>GabrielDJB/EstruturasDiscretas<file_sep>/Primeiro Trabalho/src/jn.sh
#! /bin/bash
jupyter notebook --notebook-dir="$(cd "$(dirname "$0")"; pwd)"
| 42358494f5a73f92d5f975db412b3d697be5ffb5 | [
"Shell"
] | 1 | Shell | GabrielDJB/EstruturasDiscretas | d0e48d5c89aff4579cc7991a88352950b0fd39a3 | af6a5676433333e8c35e03c4a0961adc93e29fcd |
refs/heads/master | <file_sep><?php
// +----------------------------------------------------------------------
// | Curl.Curl的封装
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.yuemeet.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: vijay <<EMAIL>> 2018-01-11
// +----------------------------------------------------------------------
namespace Vijay\Curl;
use Exception;
class Curl
{
/**
* 执行请求
* Author: vijay <<EMAIL>>
* @param string $method 请求方式
* @param string $url 请求地址
* @param string|array $fields 附带参数,可以是数组,也可以是字符串
* @param string $userAgent 浏览器UA
* @param array $httpHeaders header头部,数组形式
* @param string $username 用户名
* @param string $password 密码
* @return array|bool|mixed
*/
public function execute($method, $url, $fields = '', $userAgent = '', $httpHeaders = [], $username = '', $password = '')
{
$ch = $this->create();
if (false === $ch) {
return false;
}
if (is_string($url) && strlen($url)) {
curl_setopt($ch, CURLOPT_URL, $url);
} else {
return false;
}
//是否显示头部信息
curl_setopt($ch, CURLOPT_HEADER, false);
//不直接输出
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//传递一个形如[username]:[password]风格的字符串
if (!empty($username)) {
curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
}
//ssl
if (false !== stripos($url, "https://")) {
//对认证证书来源的检查
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
$method = strtolower($method);
if ('post' == $method) {
curl_setopt($ch, CURLOPT_POST, true);
if (is_array($fields)) {
$fields = http_build_query($fields);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
} else if ('put' == $method) {
curl_setopt($ch, CURLOPT_PUT, true);
}
//curl_setopt($ch, CURLOPT_PROGRESS, true);
//curl_setopt($ch, CURLOPT_VERBOSE, true);
//curl_setopt($ch, CURLOPT_MUTE, false);
//设置curl超时秒数
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
//在HTTP请求中包含一个'user-agent'头的字符串
if (strlen($userAgent)) {
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
}
if (is_array($httpHeaders)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
}
try {
$ret = curl_exec($ch);
//返回最后一次的错误号
if (curl_errno($ch)) {
curl_close($ch);
return [curl_error($ch), curl_errno($ch)];
}
curl_close($ch);
if (!is_string($ret) || !strlen($ret)) {
return false;
}
return $ret;
} catch (Exception $e) {
return false;
}
}
/**
* POST请求
* Author: vijay <<EMAIL>>
* @param string $url 地址
* @param array|string $fields 附带参数,可以是数组,也可以是字符串
* @param string $userAgent 浏览器UA
* @param string $httpHeaders header头部,数组形式
* @param string $username 用户名
* @param string $password 密码
* @return bool
*/
public function post($url, $fields, $userAgent = '', $httpHeaders = '', $username = '', $password = '')
{
$ret = $this->execute('POST', $url, $fields, $userAgent, $httpHeaders, $username, $password);
if (false === $ret) {
return false;
}
if (is_array($ret)) {
return false;
}
return $ret;
}
/**
* GET请求
* Author: vijay <<EMAIL>>
* @param string $url 地址
* @param string $userAgent 浏览器UA
* @param array $httpHeaders header头部,数组形式
* @param string $username 用户名
* @param string $password 密码
* @return array|bool|mixed
*/
public function get($url, $userAgent = '', $httpHeaders = [], $username = '', $password = '')
{
$ret = $this->execute('GET', $url, "", $userAgent, $httpHeaders, $username, $password);
if (false === $ret) {
return false;
}
if (is_array($ret)) {
return false;
}
return $ret;
}
/**
* curl支持 检测
* Author: vijay <<EMAIL>>
* @return bool|null|resource
*/
public function create()
{
$ch = null;
if (!function_exists('curl_init')) {
return false;
}
$ch = curl_init();
if (!is_resource($ch)) {
return false;
}
return $ch;
}
}<file_sep># tools
一个php小工具,包含curl请求、queue封装等
<file_sep><?php
// +----------------------------------------------------------------------
// | Visitor.获取用户浏览信息
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.yuemeet.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: vijay <<EMAIL>> 2018-01-11
// +----------------------------------------------------------------------
namespace Vijay\Visitor;
class Visitor
{
/**
* 获取浏览器名称
* Author: vijay <<EMAIL>>
* @return string
*/
public static function getBrowser()
{
$br = '';
if (!empty($_SERVER['HTTP_USER_AGENT'])) {
$br = $_SERVER['HTTP_USER_AGENT'];
if (preg_match('/MSIE/i', $br)) {
$br = 'MSIE';
} elseif (preg_match('/Firefox/i', $br)) {
$br = 'Firefox';
} elseif (preg_match('/Chrome/i', $br)) {
$br = 'Chrome';
} elseif (preg_match('/Safari/i', $br)) {
$br = 'Safari';
} elseif (preg_match('/Opera/i', $br)) {
$br = 'Opera';
} else {
$br = 'Other';
}
}
return $br;
}
/**
* 获取客户端IP地址
* Author: vijay <<EMAIL>>
* @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数
* @param bool $adv 是否进行高级模式获取(有可能被伪装)
* @return mixed
*/
public static function getIp($type = 0, $adv = true)
{
$type = $type ? 1 : 0;
static $ip = null;
if ($ip !== null) {
return $ip[$type];
}
if ($adv) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown', $arr);
if (false !== $pos) {
unset($arr[$pos]);
}
$ip = trim($arr[0]);
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = sprintf("%u", ip2long($ip));
$ip = $long ? [$ip, $long] : ['0.0.0.0', 0];
return $ip[$type];
}
/**
* 获取阿里云通过SLB负载均衡取得客户端IP
* Author: vijay <<EMAIL>>
* @return mixed|string
*/
public static function getForwardedForIp()
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
$ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$ip = trim($ip[0]);
return $ip ? $ip : '127.0.0.1';
}
return self::getIp();
}
/**
* 获取字符类型
* Author: vijay <<EMAIL>>
* @return bool|string
*/
public static function getLang()
{
$lang = '未知';
if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$lang = substr($lang, 0, 5);
if (preg_match('/zh-cn/i', $lang)) {
$lang = '简体中文';
} elseif (preg_match("/zh/i", $lang)) {
$lang = '繁体中文';
} else {
$lang = 'English';
}
}
return $lang;
}
/**
* 获取操作系统名称
* Author: vijay <1<PASSWORD>19<EMAIL>>
* @return string
*/
public static function getOs()
{
$OS = '未知';
if (!empty($_SERVER['HTTP_USER_AGENT'])) {
$OS = $_SERVER['HTTP_USER_AGENT'];
if (preg_match('/win/i', $OS)) {
$OS = 'Windows';
} elseif (preg_match('/mac/i', $OS)) {
$OS = 'MAC';
} elseif (preg_match('/linux/i', $OS)) {
$OS = 'Linux';
} elseif (preg_match('/unix/i', $OS)) {
$OS = 'Unix';
} elseif (preg_match('/bsd/i', $OS)) {
$OS = 'BSD';
} else {
$OS = '未知';
}
}
return $OS;
}
/**
* 获取访客物理地址
* Author: vijay <<EMAIL>>
* @return string
*/
public static function getAddr()
{
$ip = self::getIp();
if ($ip == '127.0.0.1') {
$add = '未知地址';
} else {
//根据新浪api接口获取
if ($ipadd = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=' . $ip)) {
$ipadd = json_decode($ipadd);
if (!is_object($ipadd) or $ipadd->ret == '-1') {
$add = '未知地址';
} elseif (is_object($ipadd) and $ipadd->ret <> '-1') {
$add = $ipadd->province . $ipadd->isp;
} else {
$add = '未知地址';
}
} else {
$add = '未知地址';
}
}
return $add;
}
/**
* 获取访客来源地址
* Author: vijay <<EMAIL>>
* @return string
*/
public static function getReferer()
{
$Urs = isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : '';
return $Urs;
}
/**
* 获取当前访问地址
* Author: vijay <<EMAIL>>
* @return string
*/
public static function getUrl()
{
$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
$relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}
/**
* 获取访客GET查询
* Author: vijay <<EMAIL>>
* @return string
*/
public static function getQuery()
{
if (isset($_SERVER["QUERY_STRING"])) {
$uquery = addslashes($_SERVER["QUERY_STRING"]);
} else {
$uquery = '';
}
return $uquery;
}
/**
* 获取访客终端综合信息
* Author: vijay <<EMAIL>>
* @return string
*/
public static function getAgent()
{
if (isset($_SERVER["HTTP_USER_AGENT"])) {
$uagent = addslashes($_SERVER["HTTP_USER_AGENT"]);
} else {
$uagent = "未知终端";
}
return $uagent;
}
/**
* 是否手机访问
* Author: vijay <<EMAIL>>
* @return bool
*/
public static function isMobileRequest()
{
$_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
$_SERVER['HTTP_USER_AGENT'] = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
//如果是命令行模式下,UA尝试使用request的
if (IS_CLI) {
$_SERVER['HTTP_USER_AGENT'] = request()->server('HTTP_USER_AGENT');
}
$mobile_browser = 0;
if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
$mobile_browser++;
}
if ((isset($_SERVER['HTTP_ACCEPT'])) && (strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') !== false)) {
$mobile_browser++;
}
if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
$mobile_browser++;
}
if (isset($_SERVER['HTTP_PROFILE'])) {
$mobile_browser++;
}
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
$mobile_agents = [
'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
'wapr', 'webc', 'winw', 'winw', 'xda', 'xda-'
];
if (in_array($mobile_ua, $mobile_agents)) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false) {
$mobile_browser++;
}
// Pre-final check to reset everything if the user is on Windows
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false) {
$mobile_browser = 0;
}
// But WP7 is also Windows, with a slightly different characteristic
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false) {
$mobile_browser++;
}
if ($mobile_browser > 0) {
return true;
}
return false;
}
/**
* 判断是否蜘蛛访问
* Author: vijay <<EMAIL>>
* @return bool
*/
public static function isSpider()
{
$kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla|360Spider';
$kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla|360User-agent';
$spider = false;
if (!strpos($_SERVER['HTTP_USER_AGENT'], 'http://') && preg_match("/($kw_browsers)/i", $_SERVER['HTTP_USER_AGENT'])) {
$spider = false;
} elseif (preg_match("/($kw_spiders)/i", $_SERVER['HTTP_USER_AGENT'])) {
$spider = true;
}
return $spider;
}
/**
* 判断是否微信内置浏览器访问
* Author: vijay <<EMAIL>>
* @return bool
*/
public static function isWeixinRequest()
{
$userAgent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($userAgent, 'MicroMessenger') || strpos(strtolower($userAgent), 'micromessenger')) {
return true;
}
return false;
}
/**
* 根据淘宝接口获取手机归属地
* Author: vijay <<EMAIL>>
* @param $phone
* @return array|bool
*/
public static function getMobileLocalByTaobao($phone)
{
$res = [];
$url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=$phone" . "&t=" . time();
$contnet = iconv('GB2312', 'UTF-8', file_get_contents($url));
preg_match_all("/(\w+):'(\W+|\w+)'/", $contnet, $matches);
if (count($matches) == 3) {
foreach ($matches[1] as $k => $v) {
$res[$v] = $matches[2][$k];
}
if (isset($res['province'])) {
$data = [
'phone' => $phone,
'area' => $res['province'],
'operator' => $res['catName'],
'area_operator' => $res['carrier'],
];
return $data;
}
}
return false;
}
/**
* Author: vijay <<EMAIL>>
* @param $phone
* @return array|bool
*/
public static function getMobileLocalByBaifubao($phone)
{
$url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=$phone" . "&t=" . time();
$contnet = file_get_contents($url);//file_get_contents乱码,改用curl
$is = preg_match('/(\{\S+\})/i', $contnet, $matches);
if ($is) {
$res = json_decode($matches[0], true);
if (isset($res['data']['area'])) {
$data = [
'phone' => $phone,
'area' => $res['data']['area'],
'operator' => $res['data']['operator'],
'area_operator' => $res['data']['area_operator'],
];
return $data;
}
}
return false;
}
}<file_sep><?php
// +----------------------------------------------------------------------
// | Queue.队列封装
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.yuemeet.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: vijay <<EMAIL>> 2018-01-11
// +----------------------------------------------------------------------
namespace Vijay\Queue;
class Queue
{
/**
* @var null
*/
protected $handler = null;
/**
* @var string
*/
protected $error = '';
/**
* @var string
*/
protected $name = '';
/**
* Queue constructor.
* @param null $driver
*/
public function __construct($driver = null)
{
$this->setDriver($driver);
}
/**
* Instructions:获取列队
* User: Vijay <<EMAIL>>
* Time: 2018/7/28 11:29
* @param string $name 队列名称
* @return Queue
*/
public static function init($name)
{
static $handler;
if ($name && isset($handler[$name])) {
$object = $handler[$name];
} else {
$object = $handler[$name] = new self();
$object->name($name);
}
return $object;
}
/**
* Instructions:获取列队名称
* User: Vijay <<EMAIL>>
* Time: 2018/7/28 11:30
* @param null $name
* @return $this|string
*/
public function name($name = null)
{
if (is_null($name)) {
return $this->name;
} else {
$this->name = $name;
}
return $this;
}
/**
* Instructions:获取驱动类型(建议配置redis使用)
* User: Vijay <<EMAIL>>
* Time: 2018/7/28 11:30
* @param $driver
* @return $this|bool
*/
public function setDriver($driver = null)
{
if (!is_object($driver)) {
$this->error = '缓存驱动错误';
return false;
} else {
$this->handler = $driver;
}
return $this;
}
/**
* Instructions:获取队列载体对象
* User: Vijay <<EMAIL>>
* Time: 2018/7/28 11:33
* @return mixed
*/
public function handler()
{
return $this->handler->handler();
}
/**
* Instructions:把数据压入当前队列尾部
* User: Vijay <<EMAIL>>
* Time: 2018/7/28 11:35
* @param string|array|object $data
* @return bool
*/
public function push($data)
{
try {
foreach (func_get_args() as $value) {
$this->handler()->rPush($this->name(), serialize($value));
}
return true;
} catch (\Exception $e) {
$this->error = '压入队列失败';
}
return false;
}
/**
* Instructions:把数据压入当前队列开头
* User: Vijay <<EMAIL>>
* Time: 2018/7/28 11:36
* @param $data
* @return bool
*/
public function lPush($data)
{
try {
foreach (func_get_args() as $value) {
$this->handler()->lPush($this->name(), serialize($value));
}
return true;
} catch (\Exception $e) {
$this->error = '压入队列失败';
}
return false;
}
/**
* Instructions:获取队列中的数据
* User: Vijay <<EMAIL>>
* Time: 2018/7/28 11:36
* @param int $limit
* @return array|bool
*/
public function getData($limit = 100)
{
$dataList = [];
try {
$empty = 0;
for ($i = 0; $i < $limit; $i++) {
if ($empty > 10) {
break;
}
$data = $this->handler()->lPop($this->name());
if (empty($data)) {
$empty++;
continue;
}
$dataList[] = unserialize($data);
}
} catch (\Exception $e) {
$this->error = '从队列获取失败';
return false;
}
return $dataList;
}
/**
* Instructions:删除
* User: Vijay <<EMAIL>>
* Time: 2018/7/28 11:37
* @return mixed
*/
public function rm()
{
return $this->handler()->delete($this->name());
}
/**
* Instructions:获取队列长度
* User: Vijay <<EMAIL>>
* Time: 2018/7/28 11:37
* @return mixed
*/
public function length()
{
return $this->handler()->LLEN($this->name());
}
/**
* Instructions:获取错误信息
* User: Vijay <<EMAIL>>
* Time: 2018/7/28 11:37
* @return string
*/
public function getError()
{
return $this->error;
}
} | 8582356068d541f62a3dd1c533d9e6ccf3cea70f | [
"Markdown",
"PHP"
] | 4 | PHP | Galloping-Vijay/tools | 635159b6d5eaa0abcc5d626b2ea02c5630c8e67d | ca6e43fbd527c86de5ee38a029aad6b36f5ae1d9 |
refs/heads/master | <file_sep>package com.example.android.bakingapp;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.example.android.bakingapp.Adapters.RecipeAdapter;
import com.example.android.bakingapp.Utils.CheckConnection;
import com.example.android.bakingapp.Utils.JsonParsing;
import com.example.android.bakingapp.model.Recipe;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements RecipeAdapter.RecipeClickHandler {
RecyclerView recyclerView;
GridLayoutManager layoutManager;
public static RecipeAdapter recipeAdapter;
static Recipe[] recipes;
TextView tv_error;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_error = (TextView) findViewById(R.id.error);
recyclerView = (RecyclerView) findViewById(R.id.rc_recipe);
recyclerView.setHasFixedSize(true);
layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recipeAdapter = new RecipeAdapter(this);
recyclerView.setAdapter(recipeAdapter);
if (savedInstanceState != null) {
Parcelable p = savedInstanceState.getParcelable("RecState");
recyclerView.getLayoutManager().onRestoreInstanceState(p);
}
if (CheckConnection.isOnline(getApplicationContext())) {
FetchRecipes fetchRecipes = new FetchRecipes();
fetchRecipes.execute("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json");
} else {
tv_error.setVisibility(View.VISIBLE);
}
}
@Override
public void OnClick(Recipe recipe) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("recipe", recipe);
startActivity(intent);
}
public class FetchRecipes extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
StringBuilder stringBuilder = new StringBuilder();
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
@Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
recipes = JsonParsing.parseRecipe(json);
recipeAdapter.setRecipeData(recipes);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("RecState", recyclerView.getLayoutManager().onSaveInstanceState());
}
}
<file_sep>package com.example.android.bakingapp;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import com.example.android.bakingapp.Utils.JsonParsing;
import com.example.android.bakingapp.model.Recipe;
import com.example.android.bakingapp.model.Step;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class DetailActivity extends AppCompatActivity implements StepListFragment.OnStepItemClickedListener {
private Recipe recipe;
static int recipeID;
private boolean mTwopane;
private Step sStep;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
Intent intent = getIntent();
recipe = intent.getParcelableExtra("recipe");
recipeID = recipe.getId();
if (findViewById(R.id.detail_linearLayout) != null) {
mTwopane = true;
/* INGREDIENT */
IngredientListFragment ingredientListFragment = new IngredientListFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.add(R.id.ingredients_container, ingredientListFragment)
.commit();
FetchIngredients fetchIngredients = new FetchIngredients();
fetchIngredients.execute("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json");
/*STEP*/
StepListFragment stepListFragment = new StepListFragment();
FragmentManager manager1 = getSupportFragmentManager();
manager1.beginTransaction()
.add(R.id.steps_container, stepListFragment)
.commit();
FetchSteps fetchSteps = new FetchSteps();
fetchSteps.execute("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json");
/*Detail*/
StepDetailListFragment stepDetailListFragmentstFragment = new StepDetailListFragment();
stepDetailListFragmentstFragment.ReciveStep(sStep);
FragmentManager manager2 = getSupportFragmentManager();
manager2.beginTransaction()
.add(R.id.step_detail_container, stepDetailListFragmentstFragment)
.commit();
} else {
mTwopane = false;
/* INGREDIENT */
IngredientListFragment ingredientListFragment = new IngredientListFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.add(R.id.ingredients_container, ingredientListFragment)
.commit();
FetchIngredients fetchIngredients = new FetchIngredients();
fetchIngredients.execute("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json");
/*STEP*/
StepListFragment stepListFragment = new StepListFragment();
FragmentManager manager1 = getSupportFragmentManager();
manager1.beginTransaction()
.add(R.id.steps_container, stepListFragment)
.commit();
FetchSteps fetchSteps = new FetchSteps();
fetchSteps.execute("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json");
}
}
@Override
public void onStepClicked(Step step) {
if (mTwopane) {
StepDetailListFragment stepDetailListFragmentstFragment = new StepDetailListFragment();
stepDetailListFragmentstFragment.ReciveStep(step);
FragmentManager manager2 = getSupportFragmentManager();
manager2.beginTransaction()
.replace(R.id.step_detail_container, stepDetailListFragmentstFragment)
.commit();
} else {
Intent openStepDetailActivity = new Intent(this, StepDetailActivity.class);
openStepDetailActivity.putExtra("step", step);
startActivity(openStepDetailActivity);
}
}
public static class FetchIngredients extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
StringBuilder stringBuilder = new StringBuilder();
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
JsonParsing.parseIngredient(recipeID, s);
//recipeAdapter.setRecipeData(recipes);
}
}
private class FetchSteps extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
StringBuilder stringBuilder = new StringBuilder();
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
JsonParsing.parseSteps(recipeID, s);
//recipeAdapter.setRecipeData(recipes);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package com.example.android.bakingapp;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.android.bakingapp.model.Step;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
public class StepDetailListFragment extends Fragment {
TextView tvDes;
Step s;
private SimpleExoPlayer mExoplayer;
private SimpleExoPlayerView mExoPlayerView;
String videoUrl;
int mCurrentWindow = 0;
long mPlayBackPosition = 0;
boolean mPlayWhenReady = true;
public StepDetailListFragment() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (savedInstanceState != null) {
videoUrl = savedInstanceState.getString("url");
s = savedInstanceState.getParcelable("s");
mCurrentWindow = savedInstanceState.getInt("window");
mPlayBackPosition = savedInstanceState.getLong("pos");
mPlayWhenReady = savedInstanceState.getBoolean("r");
}
View rView = inflater.inflate(R.layout.fragment_step_detail_list, container, false);
tvDes = (TextView) rView.findViewById(R.id.tv_step_description);
mExoPlayerView = (SimpleExoPlayerView) rView.findViewById(R.id.playerView);
videoUrl = s.getVideoURL();
tvDes.setText(s.getDescription());
initializePlayer(Uri.parse(videoUrl));
return rView;
}
private void initializePlayer(Uri mediaUri) {
if (mExoplayer == null) {
TrackSelector trackSelector = new DefaultTrackSelector();
LoadControl loadControl = new DefaultLoadControl();
mExoplayer = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector, loadControl);
mExoPlayerView.setPlayer(mExoplayer);
String userAgent = Util.getUserAgent(getContext(), "BakingApp");
MediaSource mediaSource = new ExtractorMediaSource(mediaUri, new DefaultDataSourceFactory(getContext(), userAgent)
, new DefaultExtractorsFactory(), null, null);
mExoplayer.prepare(mediaSource);
mExoplayer.setPlayWhenReady(mPlayWhenReady);
mExoplayer.seekTo(mCurrentWindow, mPlayBackPosition);
}
}
public void ReciveStep(Step step) {
s = step;
}
@Override
public void onDestroy() {
super.onDestroy();
releasePlayer();
}
private void releasePlayer() {
mExoplayer.stop();
if (mExoplayer != null) {
mExoplayer.release();
mExoplayer = null;
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("url", videoUrl);
outState.putParcelable("s", s);
outState.putInt("window", mCurrentWindow);
outState.putLong("pos", mPlayBackPosition);
outState.putBoolean("r", mPlayWhenReady);
}
}
<file_sep>Project Overview
You will productionize an app, taking it from a functional state to a production-ready state. This will involve finding and handling error cases, adding accessibility features, allowing for localization, adding a widget, and adding a library.
Why this Project?
As a working Android developer, you often have to create and implement apps where you are responsible for designing and planning the steps you need to take to create a production-ready app. Unlike Popular Movies where we gave you an implementation guide, it will be up to you to figure things out for the Baking App.
What Will I Learn?
In this project you will:
Use MediaPlayer/Exoplayer to display videos.
Handle error cases in Android.
Add a widget to your app experience.
Leverage a third-party library in your app.
Use Fragments to create a responsive design that works on phones and tablets.
App Description
Your task is to create a Android Baking App that will allow Udacity’s resident baker-in-chief, Miriam, to share her recipes with the world. You will create an app that will allow a user to select a recipe and see video-guided steps for how to complete it.



| 5476b68b7d3039e7a87041c3792d1f3ba2a532a8 | [
"Markdown",
"Java"
] | 4 | Java | mgida/BakingApp | 6a1cf17f738da84b3aeabfc9346804d22e0b9b24 | 0c4d2d9bb351d344caf33b8a713d72694aed0a52 |
refs/heads/master | <repo_name>sesp13/Trabajo-2-SO<file_sep>/ip/js/index.js
$(document).ready(function () {
function number_format(amount, decimals) {
amount += ''; // por si pasan un numero en vez de un string
amount = parseFloat(amount.replace(/[^0-9\.]/g, '')); // elimino cualquier cosa que no sea numero o punto
decimals = decimals || 0; // por si la variable no fue fue pasada
// si no es un numero o es igual a cero retorno el mismo cero
if (isNaN(amount) || amount === 0)
return parseFloat(0).toFixed(decimals);
// si es mayor o menor que cero retorno el valor formateado como numero
amount = '' + amount.toFixed(decimals);
var amount_parts = amount.split(','),
regexp = /(\d+)(\d{3})/;
while (regexp.test(amount_parts[0]))
amount_parts[0] = amount_parts[0].replace(regexp, '$1' + '.' + '$2');
return amount_parts.join(',');
}
function verificacionBinario(bin) {
while (bin.length < 8){
bin = "0" + bin;
}
return bin;
}
function completarIp(red) {
while(red.length < 32){
red += "0";
}
return red;
}
function completarIpBroadcast(red) {
while(red.length < 32){
red += "1";
}
return red;
}
$( "#form-ip" ).submit(function( event ) {
event.preventDefault();
var ip1 = $("#ip1").val();
var ip2 = $("#ip2").val();
var mascara = $("#mascara").val();
if (ip1 != "" && ip2 != "" && mascara != "") {
try{
var arrayIp1 = ip1.split(".");
var arrayIp2 = ip2.split(".");
var arrayMascara = mascara.split(".");
var c = "";
arrayMascara.forEach( x => {
c += verificacionBinario(parseInt(x).toString(2));
});
var mask = 0;
for (var i = 0; i < c.length; i++) {
if(c[i] == "1"){
mask += 1;
}
}
var binIp1 = "";
arrayIp1.forEach( x => {
binIp1 += verificacionBinario(parseInt(x).toString(2));
});
var binIp2 = "";
arrayIp2.forEach( x => {
binIp2 += verificacionBinario(parseInt(x).toString(2));
});
var red1 = binIp1.substring(0, mask);
var red2 = binIp2.substring(0, mask);
if(red1 == red2){
var red = completarIp(red1);
var redCompleta = parseInt(red.substring(0,8),2).toString()+
"." + parseInt(red.substring(8,16),2).toString() +
"." + parseInt(red.substring(16,24),2).toString() +
"." + parseInt(red.substring(24,32),2).toString() +
"/" + mask.toString();
var ipBroadcast = completarIpBroadcast(red1);
var broadcast = parseInt(ipBroadcast.substring(0,8),2).toString()+
"." + parseInt(ipBroadcast.substring(8,16),2).toString() +
"." + parseInt(ipBroadcast.substring(16,24),2).toString() +
"." + parseInt(ipBroadcast.substring(24,32),2).toString();
var numeroDeUsuarios = number_format(Math.pow(2, (32 - mask)) - 2);
Swal.fire({
icon: 'success',
title: 'Respuesta',
html: `<h4>redes pertenecen a la misma red:</h4><ul><li>DIRECCION DE RED: ${redCompleta}</li><li>BROADCAST: ${broadcast}</li><li>USUARIOS: ${numeroDeUsuarios}</li></ul>`
})
/*
datos a imprimir:
redCompleta
broadcast
numeroDeUsuarios
*/
}else{
Swal.fire({
icon: 'error',
title: 'Error',
text: 'Las redes no pertenecen a la misma red'
})
}
}catch(error){
console.error(error);
}
}else if((ip1 != "" && mascara != "")){
try{
var arrayIp1 = ip1.split(".");
var arrayMascara = mascara.split(".");
var c = "";
arrayMascara.forEach( x => {
c += verificacionBinario(parseInt(x).toString(2));
});
var mask = 0;
for (var i = 0; i < c.length; i++) {
if(c[i] == "1"){
mask += 1;
}
}
var binIp1 = "";
arrayIp1.forEach( x => {
binIp1 += verificacionBinario(parseInt(x).toString(2));
});
var red1 = binIp1.substring(0, mask);
var red = completarIp(red1);
var redCompleta = parseInt(red.substring(0,8),2).toString()+
"." + parseInt(red.substring(8,16),2).toString() +
"." + parseInt(red.substring(16,24),2).toString() +
"." + parseInt(red.substring(24,32),2).toString() +
"/" + mask.toString();
var ipBroadcast = completarIpBroadcast(red1);
var broadcast = parseInt(ipBroadcast.substring(0,8),2).toString()+
"." + parseInt(ipBroadcast.substring(8,16),2).toString() +
"." + parseInt(ipBroadcast.substring(16,24),2).toString() +
"." + parseInt(ipBroadcast.substring(24,32),2).toString();
var numeroDeUsuarios = number_format(Math.pow(2, (32 - mask)) - 2);
Swal.fire({
icon: 'success',
title: 'Respuesta',
html: `<ul><li>DIRECCION DE RED: ${redCompleta}</li><li>BROADCAST: ${broadcast}</li><li>USUARIOS: ${numeroDeUsuarios}</li></ul>`
})
/*
datos a imprimir:
redCompleta
broadcast
numeroDeUsuarios
*/
}catch(error){
console.error(error);
}
}
});
});<file_sep>/README.md
# Trabajo-2-SO
IMPORTANTE
Para ejecutar la pagina web de las ip hay que ejecutar el archivo index que esta en la carpeta ip
<file_sep>/notas2.sh
#!/bin/bash
# Use espacios!!
if [ $1 == "" ] || [ $1 == "-h" ];then
echo "Pantalla de ayuda"
else if [ $1 == "-v" ];then
carpetas=$(ls ~/Documentos)
for i in $carpetas;do
if [ -d ~/Documentos/$i ];then
#Cantidad de archivos
totaldearchivos=$(ls ~/Documentos/$i |wc -w)
#echo $totaldearchivos
echo "En la carpeta $i hay $totaldearchivos archivos "
fi
done
else
if [ -d ~/Documentos/$1 ];then
if [ -e ~/Documentos/$1/$2 ];then
#Directorio y archivo existen
nano ~/Documentos/$1/$2
else
#Directorio existe pero archivo no
touch ~/Documentos/$1/$2
echo 'Archivo creado'
nano ~/Documentos/$1/$2
fi
else
#Ni directorio ni archivo existen
mkdir ~/Documentos/$1
echo 'Directorio creado'
touch ~/Documentos/$1/$2
echo 'Archivo creado'
nano ~/Documentos/$1/$2
fi
fi
fi | 816aa1003302f89c50033e5e325b3741e348373c | [
"JavaScript",
"Markdown",
"Shell"
] | 3 | JavaScript | sesp13/Trabajo-2-SO | cf590b2e82650fbc81a0f268bc8c79347e9d9bf5 | fa2f29df4c87f8dd3827ed319419345741a0003a |
refs/heads/main | <file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.terjouxanthony</groupId>
<artifactId>adopt.openjdk.downloader</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<name>adopt-openjdk-downloader</name>
<description>Java library to ease downloading and installation of AdoptOpenJdk java JDK's and JRE's</description>
<url>https://github.com/terjouxanthony/adopt-openjdk-downloader</url>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<main.class>io.github.terjouxanthony.adopt.openjdk.downloader.examples.Main</main.class>
</properties>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.20</version>
</dependency>
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<!-- TEST dependencies below : -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>2.23.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.17.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.7.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<licenses>
<license>
<name>MIT License</name>
<url>http://www.opensource.org/licenses/mit-license.php</url>
</license>
</licenses>
<developers>
<developer>
<name><NAME></name>
<email><EMAIL></email>
<organization>Github</organization>
<organizationUrl>https://github.com/terjouxanthony</organizationUrl>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com:terjouxanthony/adopt-openjdk-downloader.git</connection>
<developerConnection>scm:git:ssh://github.com:terjouxanthony/adopt-openjdk-downloader.git</developerConnection>
<url>https://github.com/terjouxanthony/adopt-openjdk-downloader/tree/main/</url>
</scm>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://s01.oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.7</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://s01.oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<!-- Profile for building an executable for local testing -->
<id>build-executable</id>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>${main.class}</mainClass>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<version>2.1.0</version>
<configuration>
<includeConfigurationDirectoryInClasspath>true</includeConfigurationDirectoryInClasspath>
<extraJvmArguments>-Xmx20m</extraJvmArguments>
<repositoryLayout>flat</repositoryLayout>
<repositoryName>lib</repositoryName>
<useWildcardClassPath>true</useWildcardClassPath>
<configurationSourceDirectory>src/main/resources</configurationSourceDirectory>
<configurationDirectory>etc</configurationDirectory>
<copyConfigurationDirectory>true</copyConfigurationDirectory>
<includeConfigurationDirectoryInClasspath>true</includeConfigurationDirectoryInClasspath>
<programs>
<program>
<mainClass>${main.class}</mainClass>
</program>
</programs>
</configuration>
<executions>
<execution>
<goals>
<goal>assemble</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project><file_sep>package io.github.terjouxanthony.adopt.openjdk.downloader;
import io.github.terjouxanthony.adopt.openjdk.downloader.HttpRequester.HttpStatusException;
import io.github.terjouxanthony.adopt.openjdk.downloader.Model.ImageType;
import io.github.terjouxanthony.adopt.openjdk.downloader.Model.InstallJavaParams;
import io.github.terjouxanthony.adopt.openjdk.downloader.Model.JavaInstallDescription;
import io.github.terjouxanthony.adopt.openjdk.downloader.Model.ReleaseInfo;
import io.github.terjouxanthony.adopt.openjdk.downloader.Model.ReleaseNamesRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Headers;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static io.github.terjouxanthony.adopt.openjdk.downloader.Utils.transferTo;
import static java.util.Objects.requireNonNull;
@Slf4j
@AllArgsConstructor
public class JavaDownloader {
private static final Pattern JDK_RELEASE_NAME_REGEX = Pattern.compile("^\\D+(\\d+)");
private static final String SEPARATOR_IN_FILENAMES = "--";
private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH-mm-ssz");
private final ArchiveUnpacker archiveUnpacker;
private final FileSystemHandler fileSystemHandler;
private final HttpRequester httpRequester;
private final AdoptOpenJdkApi adoptOpenJdkApi;
public JavaDownloader() {
this.archiveUnpacker = new ArchiveUnpacker();
this.fileSystemHandler = new FileSystemHandler();
this.httpRequester = new HttpRequester();
this.adoptOpenJdkApi = new AdoptOpenJdkApi(this.httpRequester);
}
public List<String> listAllReleases() throws HttpStatusException, IOException {
return adoptOpenJdkApi.listAllReleases(ReleaseNamesRequest.builder()
.releaseType(Model.ReleaseType.GENERAL_AVAILABILITY)
.vendor(Model.Vendor.ADOPT_OPENJDK)
.build());
}
public JavaInstallDescription installJava(InstallJavaParams params) throws IOException, InterruptedException, URISyntaxException, HttpStatusException {
final Path installPath = installJavaWithoutCleaning(params);
if (params.isCleanExistingSameMajorVersion()) {
log.info("Flag 'cleanExistingSameMajorVersion' enabled, cleaning {} folders other than {} ...", params.getImageType(), installPath);
fileSystemHandler.listFolder(installPath.getParent())
.stream()
.filter(path -> !path.equals(installPath))
.forEach(path -> {
log.info("Deleting other {} {} ...", params.getImageType(), path);
fileSystemHandler.deleteRecursively(path);
});
log.info("{} folders Cleaning done", params.getImageType());
}
return new JavaInstallDescription(installPath, findJavaHomeFolder(installPath, params.getOs()).get());
}
private Path installJavaWithoutCleaning(InstallJavaParams params) throws IOException, InterruptedException, URISyntaxException, HttpStatusException {
if (params.getJavaVersion() == null && params.getFullJavaReleaseName() == null) {
throw new IllegalArgumentException("Either java version (eg. 16) or full java release name (eg. 16.0.1+9) must be provided");
}
if (params.getFullJavaReleaseName() != null) {
final Matcher matcher = JDK_RELEASE_NAME_REGEX.matcher(params.getFullJavaReleaseName());
if (!matcher.find()) {
throw new IllegalArgumentException("Invalid fullJavaReleaseName, examples: jdk-16.0.1+9, jdk8u292-b10");
}
params.setJavaVersion(Integer.parseInt(matcher.group(1)));
}
final Path installRootFolder = params.getJavaDownloaderDir().resolve(params.getImageType().getValue());
fileSystemHandler.mkdir(installRootFolder);
final Path installParentFolder = installRootFolder.resolve(String.valueOf(params.getJavaVersion()))
.resolve(osArchString(params.getOs(), params.getArch()));
Optional<Path> installPathOpt = tryFindJavaLocally(params, installParentFolder);
if (installPathOpt.isPresent()) {
return installPathOpt.get();
}
final ReleaseInfo releaseInfo = (params.getFullJavaReleaseName() != null) ?
adoptOpenJdkApi.getJavaReleaseInfo(params.getFullJavaReleaseName(), params.getArch(), params.getOs(), params.getImageType()) :
adoptOpenJdkApi.getLatestJavaRelaseInfo(params.getJavaVersion(), params.getArch(), params.getOs(), params.getImageType());
log.info("Java release is {}", releaseInfo);
final Path installFolder = installParentFolder.resolve(createInstallName(params.getOs(), params.getArch(), releaseInfo));
if (params.isDownloadLatest() && isValidJavaInstall(installFolder, params.getOs())) {
log.info("Latest {} is already installed for java {} os {} arch {} : {}",
params.getImageType(), params.getJavaVersion(), params.getOs(), params.getArch(), installFolder);
return installFolder;
}
final Path downloadsFolder = installRootFolder.resolve("downloads");
fileSystemHandler.mkdir(downloadsFolder);
final Path archivePath = downloadsFolder.resolve(releaseInfo.getPackageName());
final Path tmpExtractFolder = installFolder.getParent().resolve(installFolder.getFileName().toString() + "_temporary");
try {
log.info("Downloading {} {} os {} arch {} ...", params.getImageType(), releaseInfo.getReleaseName(), params.getOs(), params.getArch());
downloadJava(releaseInfo, archivePath);
checkSha256Hash(releaseInfo, archivePath);
log.info("Checksum is valid for {} {} os {} arch {}", params.getImageType(), releaseInfo.getReleaseName(), params.getOs(), params.getArch());
log.info("Extracting compressed archive for {} {} os {} arch {}", params.getImageType(), releaseInfo.getReleaseName(), params.getOs(), params.getArch());
extractArchive(archivePath, tmpExtractFolder, params.getImageType());
putToFinalDestination(installFolder, tmpExtractFolder);
log.info("Installation done for {} {} os {} arch {}", params.getImageType(), releaseInfo.getReleaseName(), params.getOs(), params.getArch());
} finally {
fileSystemHandler.deleteFile(archivePath);
}
return installFolder;
}
private static String createInstallName(String os, String arch, ReleaseInfo releaseInfo) {
return releaseInfo.getReleaseName()
+ SEPARATOR_IN_FILENAMES
+ releaseInfo.getTimestamp().replace(":", "-")
+ SEPARATOR_IN_FILENAMES
+ osArchString(os, arch);
}
private static String osArchString(String os, String arch) {
return os + "_" + arch;
}
private Optional<Path> tryFindJavaLocally(InstallJavaParams params, Path parentFolder) throws IOException {
if (params.getFullJavaReleaseName() == null && params.isDownloadLatest()) {
return Optional.empty();
}
if (!fileSystemHandler.fileOrFolderExists(parentFolder)) {
return Optional.empty();
}
final String osArchString = osArchString(params.getOs(), params.getArch());
try (Stream<Path> fileStream = fileSystemHandler.listFolderAsStream(parentFolder)) {
final Optional<Path> latestFolder = fileStream
.filter(path -> {
final String fileName = path.getFileName().toString();
if (params.getFullJavaReleaseName() != null) {
return fileName.startsWith(params.getFullJavaReleaseName()) && fileName.endsWith(SEPARATOR_IN_FILENAMES + osArchString);
} else {
return fileName.endsWith(SEPARATOR_IN_FILENAMES + osArchString);
}
})
.max(Comparator.comparing(p -> {
final String fileName = p.getFileName().toString();
final String date = fileName.substring(
fileName.indexOf(SEPARATOR_IN_FILENAMES) + SEPARATOR_IN_FILENAMES.length(),
fileName.lastIndexOf(SEPARATOR_IN_FILENAMES));
return ZonedDateTime.parse(date, TIMESTAMP_FORMATTER);
}));
if (latestFolder.isPresent() && isValidJavaInstall(latestFolder.get(), params.getOs())) {
log.info("Found existing {} for java {} os {} arch {} : {}",
params.getImageType(), params.getJavaVersion(), params.getOs(), params.getArch(), latestFolder.get());
return latestFolder;
} else {
return Optional.empty();
}
}
}
private void putToFinalDestination(Path installFolder, Path tmpExtractFolder) throws IOException {
try {
if (fileSystemHandler.fileOrFolderExists(installFolder)) {
fileSystemHandler.deleteRecursively(installFolder);
}
fileSystemHandler.mkdir(installFolder);
try (Stream<Path> files = fileSystemHandler.listFolderAsStream(tmpExtractFolder)) {
files.forEach(file -> {
try {
fileSystemHandler.move(file, installFolder.resolve(file.getFileName()));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
} catch (Exception ex) {
fileSystemHandler.deleteRecursively(installFolder);
throw ex;
} finally {
fileSystemHandler.deleteRecursively(tmpExtractFolder);
}
}
private void extractArchive(Path archivePath, Path destinationFolder, ImageType imageType) throws IOException {
final String fileName = archivePath.getFileName().toString();
if (fileName.endsWith(".zip")) {
log.info("Extracting .zip archive {} ...", archivePath);
archiveUnpacker.unZip(archivePath, destinationFolder);
} else if (fileName.endsWith(".tar.gz")) {
log.info("Extracting .tar.gz archive {} ...", archivePath);
archiveUnpacker.unTarGz(archivePath, destinationFolder);
} else {
throw new IllegalStateException("Invalid " + imageType + " archive " + archivePath + " , extension must be either .zip or .tar.gz");
}
}
private void checkSha256Hash(ReleaseInfo releaseInfo, Path archivePath) throws IOException {
try (InputStream in = fileSystemHandler.inputStream(archivePath)) {
final String sha256Hex = DigestUtils.sha256Hex(in);
if (!sha256Hex.equals(releaseInfo.getChecksum())) {
throw new RuntimeException(String.format(
"Invalid checksum when downloading file %s : %s != %s",
releaseInfo.getPackageName(), releaseInfo.getChecksum(), sha256Hex));
}
}
}
private void downloadJava(ReleaseInfo releaseInfo, Path archivePath) throws IOException, HttpStatusException {
final long start = System.nanoTime();
final InputStream packageInputStream = requireNonNull(httpRequester.httpGet(
releaseInfo.getPackageLink(),
Collections.emptyMap(),
Headers.of()).body()).byteStream();
ProgressBarPrinter progressBar = new ProgressBarPrinter(
releaseInfo.getSize(),
"Downloading " + releaseInfo.getPackageName());
try (OutputStream outputStream = fileSystemHandler.outputStream(archivePath)) {
transferTo(packageInputStream, outputStream, 8192, progressBar::update);
}
final long end = System.nanoTime();
log.info("Successfully downloaded {} in {} ms to {}",
releaseInfo.getPackageName(),
Duration.ofNanos(end - start).toMillis(),
archivePath);
}
private Optional<Path> findJavaHomeFolder(Path javaInstallFolder, String os) throws IOException {
if (!fileSystemHandler.fileOrFolderExists(javaInstallFolder)) {
return Optional.empty();
}
final List<Path> installFiles = fileSystemHandler.listFolder(javaInstallFolder);
final Optional<Path> firstFolder = installFiles.stream().filter(Files::isDirectory).findFirst();
if (os.equalsIgnoreCase("mac")) {
return firstFolder.map(path -> path.resolve("Contents/Home"));
} else {
return firstFolder;
}
}
private boolean isValidJavaInstall(Path javaInstallFolder, String os) throws IOException {
return findJavaHomeFolder(javaInstallFolder, os)
.map(path -> {
final Path binFolder = path.resolve("bin");
try {
return fileSystemHandler.fileOrFolderExists(binFolder) &&
fileSystemHandler.listFolder(binFolder).stream().anyMatch(f -> f.getFileName().toString().contains("java"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}).orElse(false);
}
}
<file_sep>package io.github.terjouxanthony.adopt.openjdk.downloader;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Slf4j
public class FileSystemHandler {
public void move(Path source, Path target) throws IOException {
Files.move(source, target);
}
/**
* !Warning! enclose the return Stream in a try-with-resources to close the associated operating system resources.
*
* @param folder folder to list.
* @return a Stream of files/folders in this folder.
*/
public Stream<Path> listFolderAsStream(Path folder) throws IOException {
return Files.list(folder);
}
public OutputStream outputStream(Path path) throws IOException {
return Files.newOutputStream(path);
}
public InputStream inputStream(Path path) throws IOException {
return Files.newInputStream(path);
}
public boolean fileOrFolderExists(Path path) {
return Files.exists(path);
}
public void mkdir(Path dir) throws IOException {
Files.createDirectories(dir);
}
public List<Path> listFolder(Path folder) throws IOException {
try (Stream<Path> fileStream = Files.list(folder)) {
return fileStream.collect(Collectors.toList());
}
}
public void deleteFile(Path path) {
try {
Files.delete(path);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
public void deleteRecursively(Path path) {
try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!file.toFile().setWritable(true)) {
throw new IOException("Impossible to set writable file " + file);
}
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
<file_sep>package io.github.terjouxanthony.adopt.openjdk.downloader;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class ArchiveUnpacker {
public void unZip(Path source, Path target) throws ZipException {
new ZipFile(toAbsolutePath(source)).extractAll(toAbsolutePath(target));
}
public void unTarGz(Path source, Path target) throws IOException {
if (Files.notExists(source)) {
throw new IOException("File doesn't exists!");
}
try (InputStream fi = Files.newInputStream(source);
BufferedInputStream bi = new BufferedInputStream(fi);
GzipCompressorInputStream gzi = new GzipCompressorInputStream(bi);
TarArchiveInputStream ti = new TarArchiveInputStream(gzi)) {
ArchiveEntry entry;
while ((entry = ti.getNextEntry()) != null) {
// create a new path, zip slip validate
Path newPath = zipSlipProtect(entry, target);
if (entry.isDirectory()) {
Files.createDirectories(newPath);
} else {
// check parent folder again
Path parent = newPath.getParent();
if (parent != null) {
if (Files.notExists(parent)) {
Files.createDirectories(parent);
}
}
// copy TarArchiveInputStream to Path newPath
Files.copy(ti, newPath, StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
private static Path zipSlipProtect(ArchiveEntry entry, Path targetDir)
throws IOException {
Path targetDirResolved = targetDir.resolve(entry.getName());
// make sure normalized file still has targetDir as its prefix,
// else throws exception
Path normalizePath = targetDirResolved.normalize();
if (!normalizePath.startsWith(targetDir)) {
throw new IOException("Bad entry: " + entry.getName());
}
return normalizePath;
}
private static String toAbsolutePath(Path path) {
return path.toAbsolutePath().toString();
}
}
<file_sep># AdoptOpenJDK downloader
Java library to ease downloading and installation of AdoptOpenJdk java JDK's and JRE's.
It can be useful in a gradle build or a maven plugin, in order to automate the packaging of a java application for multiple platforms.
##### Dependency:
```
<dependency>
<groupId>io.github.terjouxanthony</groupId>
<artifactId>adopt.openjdk.downloader</artifactId>
<version>0.0.1</version>
</dependency>
```
##### Usage:
```java
public static void main(String[] args) throws HttpStatusException, IOException, URISyntaxException, InterruptedException {
final JavaDownloader javaDownloader = new JavaDownloader();
// Downloads and installs a GA hotspot JDK/JRE from AdoptOpenJDK vendor.
// If the JDK/JRE is already present, no download is performed, except if the flag 'downloadLatest' is true and if there are minor/bug fixes for the java version supplied.
final JavaInstallDescription installation = javaDownloader.installJava(
InstallJavaParams.builder()
.arch("x64") // "x64", "x32", "ppc64", "arm" ...
.os("windows") // "linux", "windows", "mac", "solaris" ...
.javaVersion(16) // 11, 12, 13 ...
//.fullJavaReleaseName("jdk-16.0.1+9") // you can choose an exact version, it takes precedence over the parameter 'javaVersion'
.downloadLatest(false) // set to true to always fetch the latest version with bugfixes
.cleanExistingSameMajorVersion(true) // delete the previously downloaded versions for java 16 here
.imageType(Model.ImageType.JRE) // can also be JDK
.javaDownloaderDir(Paths.get("G:\\projects\\java\\test")) // root folder to store JRE's and JDK's, defaults to $HOME/.m2/java
.build());
System.out.println(installation.getInstallPath()); // Folder containing the downloaded JDK/JRE
System.out.println(installation.getJdkHomePath()); // JAVA_HOME path for this JDK/JRE
}
```
##### Build:
```
mvn clean compile test
```
##### Run example:
```
mvn -q clean compile exec:java
```
##### Related links:
https://adoptopenjdk.net/
<file_sep>
Usage:
```xml
<plugin>
<groupId>io.github.terjouxanthony</groupId>
<artifactId>jdk-downloader-maven-plugin</artifactId>
<version>0.0.1</version>
<executions>
<execution>
<goals>
<goal>download-java</goal>
</goals>
</execution>
</executions>
<configuration>
<imageType>jre</imageType>
<os>windows</os>
<architecture>x64</architecture>
</configuration>
</plugin>
```
<file_sep>package io.github.terjouxanthony.jdk.downloader.maven.plugin;
import io.github.terjouxanthony.adopt.openjdk.downloader.HttpRequester;
import io.github.terjouxanthony.adopt.openjdk.downloader.JavaDownloader;
import io.github.terjouxanthony.adopt.openjdk.downloader.Model;
import io.github.terjouxanthony.adopt.openjdk.downloader.Model.ImageType;
import io.github.terjouxanthony.adopt.openjdk.downloader.Model.InstallJavaParams.InstallJavaParamsBuilder;
import io.github.terjouxanthony.adopt.openjdk.downloader.Model.JavaInstallDescription;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.time.Duration;
/**
* Downloads and installs a general availability hotspot JDK/JRE from AdoptOpenJDK vendor.
* <p>
* If the JDK/JRE is already present, no download is performed, except if the flag 'downloadLatest' is true and if there is a newer minor/bugfix version for the supplied java version.
* The JDK/JREs are installed by default under the folder $HOME/.m2/java. This can be configured by the rootDir parameter.
* <p>
* After execution, the plugin sets the following project properties:
* <ul>
* <li><b>jdk-downloader-maven-plugin.jdk-install-path</b>: Absolute path to the folder containing the JDK/JRE</li>
* <li><b>jdk-downloader-maven-plugin.jdk-home</b>: Absolute path to the JDK/JRE</li>
* </ul>
* The plugin executes in the PREPARE_PACKAGE lifecycle phase, so other plugins can use the above properties if they are bound to the PACKAGE phase.
* Example of properties usage: ${jdk-downloader-maven-plugin.jdk-home}.
* <p>
* Example of the plugin's usage:
* <pre>
* {@code
* <plugin>
* <groupId>io.github.terjouxanthony</groupId>
* <artifactId>jdk-downloader-maven-plugin</artifactId>
* <version>0.0.1</version>
* <executions>
* <execution>
* <goals>
* <goal>download-java</goal>
* </goals>
* </execution>
* </executions>
* <configuration>
* <imageType>jre</imageType>
* <os>windows</os>
* <architecture>x64</architecture>
* </configuration>
* </plugin>
* }
* </pre>
*/
@Mojo(name = "download-java", defaultPhase = LifecyclePhase.PREPARE_PACKAGE)
public class JdkDownloaderMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", required = true, readonly = true)
MavenProject project;
// Mandatory params:
/**
* Architecture, example: x64, x32, ppc64, arm
*/
@Parameter(property = "architecture", required = true)
String architecture;
/**
* Operating system, example: linux, windows, mac, solaris
*/
@Parameter(property = "os", required = true)
String os;
/**
* jre or jdk
*/
@Parameter(property = "imageType", required = true)
String imageType;
// Optional params:
/**
* Optional flag. If true, always request AdoptOpenJdk API to get the latest version with bugfixes.
* If there is a minor/bugfix version, it is downloaded alongside the previous ones. To clean them, use the flag cleanExistingSameMajorVersion.
*/
@Parameter(property = "downloadLatest", defaultValue = "false")
Boolean downloadLatest;
/**
* Optional flag. If true, delete the previously downloaded artifacts for the supplied java version.
*/
@Parameter(property = "cleanExistingSameMajorVersion", defaultValue = "true")
Boolean cleanExistingSameMajorVersion;
/**
* Optional value. Root folder to store JRE's and JDK's, defaults to $HOME/.m2/java
*/
@Parameter(property = "rootDir")
String rootDir; // root folder to store JRE's and JDK's, defaults to $HOME/.m2/java
/**
* Optional value. Example: 11, 12, 13, 17 ...
* By default use the version set in project property 'maven.compiler.target'
*/
@Parameter(property = "javaVersion")
Integer javaVersion; // optional
/**
* Optional value. You can choose an exact version, it takes precedence over the parameter 'javaVersion'.
* Example: jdk-16.0.1+9
*/
@Parameter(property = "fullJavaReleaseName")
String fullJavaReleaseName; // optional
public void execute() throws MojoExecutionException, MojoFailureException {
try {
final long start = System.nanoTime();
JavaDownloader javaDownloader = new JavaDownloader();
InstallJavaParamsBuilder builder = Model.InstallJavaParams.builder()
.arch(architecture)
.os(os)
.imageType(getImageType())
.downloadLatest(downloadLatest)
.cleanExistingSameMajorVersion(cleanExistingSameMajorVersion);
if (rootDir != null) {
builder = builder.javaDownloaderDir(Paths.get(rootDir));
}
if (fullJavaReleaseName != null) {
builder = builder.fullJavaReleaseName(fullJavaReleaseName);
} else {
builder = builder.javaVersion(getJavaVersion());
}
final JavaInstallDescription installation = javaDownloader.installJava(builder.build());
project.getProperties().setProperty("jdk-downloader-maven-plugin.jdk-install-path",
installation.getInstallPath().toAbsolutePath().toString()); // Folder containing the downloaded JDK/JRE
project.getProperties().setProperty("jdk-downloader-maven-plugin.jdk-home",
installation.getJdkHomePath().toAbsolutePath().toString()); // JAVA_HOME path for this JDK/JRE
final long end = System.nanoTime();
final long elapsedMillis = Duration.ofNanos(end - start).toMillis();
getLog().info(getImageType() + " HOME is " + installation.getJdkHomePath() + " , took " + elapsedMillis + " ms");
} catch (IOException | InterruptedException | URISyntaxException | HttpRequester.HttpStatusException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
private int getJavaVersion() throws MojoExecutionException {
if (javaVersion != null) {
return javaVersion;
}
final Object targetVersion = project.getProperties().get("maven.compiler.target");
if (targetVersion != null) {
return Integer.parseInt((String) targetVersion);
}
throw new MojoExecutionException("No java version, you must either set the parameter 'javaVersion' or set the property 'maven.compiler.target'");
}
private ImageType getImageType() throws MojoExecutionException {
if ("jdk".equalsIgnoreCase(imageType)) {
return ImageType.JDK;
}
if ("jre".equalsIgnoreCase(imageType)) {
return ImageType.JRE;
}
throw new MojoExecutionException("Invalid 'imageType' parameter, must be either jdk or jre");
}
}
<file_sep>#!/bin/bash
MAVEN_OPTS="-Xmx30m" mvn -q compile exec:java -Dexec.args="hello world"
| 32affdd525968a495f95ccd904ac784705a696a0 | [
"Markdown",
"Java",
"Maven POM",
"Shell"
] | 8 | Maven POM | terjouxanthony/adopt-openjdk-downloader | eb908122ae1eac9cec6fab52d9345c1cf4d6ee4b | e951b411f70780dd8bea324d4f2ef362e1c8afa2 |
refs/heads/main | <repo_name>Henry-Cho/hanghae_stagram<file_sep>/henrystagram/src/redux/modules/like.js
import { createAction, handleActions } from "redux-actions";
import { produce } from "immer";
import firebase from "firebase/app";
import { firestore } from "../../shared/firebase";
import { actionCreators as postActions } from "./post";
const ADD_LIKE = "ADD_LIKE";
const GET_LIKE = "GET_LIKE";
const DELETE_LIKE = "DELETE_LIKE";
const addLike = createAction(ADD_LIKE, (post_id, like_info) => ({
post_id,
like_info,
}));
const getLike = createAction(GET_LIKE, (post_id, user_list) => ({
post_id,
user_list,
}));
const deleteLike = createAction(DELETE_LIKE, (doc_id) => ({
doc_id,
}));
const initialState = {
post_id: null,
user_id: null,
user_list: [],
};
const addLikeFB = (post_id) => {
return function (dispatch, getState, { history }) {
if (!post_id) {
return;
}
const user_info = getState().user.user;
const likeDB = firestore.collection("like");
//const likeInfo = getState().like.user_list[]
let like_info = {
post_id: post_id,
user_id: user_info.uid,
};
likeDB.add(like_info).then((doc) => {
const postDB = firestore.collection("post");
const post = getState().post.list.find((l) => l.id === post_id);
const increment = firebase.firestore.FieldValue.increment(1);
like_info = { ...like_info, id: doc.id };
postDB
.doc(post_id)
.update({ like_cnt: increment })
.then((_post) => {
dispatch(addLike(post_id, like_info));
if (post) {
dispatch(
postActions.editPost(post_id, {
like_cnt: parseInt(post.like_cnt) + 1,
is_like: true,
})
);
}
});
});
};
};
const deleteLikeFB = (post_id, doc_id) => {
return function (dispatch, getState, { history }) {
const likeDB = firestore.collection("like");
const postDB = firestore.collection("post");
const post = getState().post.list.find((l) => l.id === post_id);
console.log(doc_id);
likeDB
.doc(doc_id)
.delete()
.then((doc) => {
const increment = firebase.firestore.FieldValue.increment(-1);
postDB.doc(post_id).update({ like_cnt: increment });
dispatch(deleteLike(doc_id));
if (post) {
dispatch(
postActions.editPost(post_id, {
like_cnt: parseInt(post.like_cnt) - 1,
is_like: false,
})
);
}
});
};
};
const getLikeFB = (post_id, user_id) => {
return function (dispatch, getState, { history }) {
const likeDB = firestore.collection("like");
if (!post_id) {
return;
}
let post_list = getState().post.list;
let post_ids = getState().post.list.map((l) => {
return l.id;
});
likeDB
.where("post_id", "in", post_ids)
.get()
.then((docs) => {
let like_list = [];
docs.forEach((doc) => {
like_list.push({ ...doc.data(), id: doc.id });
});
const user_id = getState().user.user.uid;
const new_post_list = post_list.map((l) => {
let is_like = like_list.filter((m) => {
return m.user_id === user_id && l.id === m.post_id;
});
console.log(is_like);
//if (user_id === )
return { ...l, is_like: is_like.length > 0 ? true : false };
});
dispatch(postActions.setPost(new_post_list));
dispatch(getLike(post_id, like_list));
})
.catch((err) => {
console.log("좋아요 정보를 확인할 수 없습니다!");
});
};
};
export default handleActions(
{
[ADD_LIKE]: (state, action) =>
produce(state, (draft) => {
if (!draft.user_list) {
draft.user_list = [action.payload.user_list];
}
draft.user_list.unshift(action.payload.like_info);
}),
[GET_LIKE]: (state, action) =>
produce(state, (draft) => {
// let data = {[post_id]: com_list, ...}
draft.user_list = action.payload.user_list;
console.log(action.payload.user_list);
}),
[DELETE_LIKE]: (state, action) =>
produce(state, (draft) => {
const index = draft.user_list.findIndex((l) => {
return l.id === action.payload.doc_id;
});
console.log(index);
draft.user_list.splice(index, 1);
}),
},
initialState
);
const actionCreators = {
//clickLike,
getLike,
getLikeFB,
addLikeFB,
deleteLikeFB,
deleteLike,
};
export { actionCreators };
<file_sep>/henrystagram/src/pages/PostList.js
import React from "react";
import Post from "../components/Post";
import styled from "styled-components";
import { Grid } from "../elements";
import { useSelector, useDispatch } from "react-redux";
import { actionCreators as postActions } from "../redux/modules/post";
import InfinityScroll from "../shared/InfinityScroll";
const PostList = (props) => {
const dispatch = useDispatch();
const post_list = useSelector((state) => state.post.list);
const is_loading = useSelector((state) => state.post.is_loading);
const paging = useSelector((state) => state.post.paging);
React.useEffect(() => {
if (post_list.length === 0) {
dispatch(postActions.getPostFB());
}
}, []);
console.log(post_list);
return (
<PostListFrame>
<InfinityScroll
callNext={() => {
console.log("next!!");
console.log(paging);
dispatch(postActions.getPostFB(true));
}}
is_next={paging.next ? true : false}
is_loading={is_loading}
>
{post_list.map((p, idx) => {
return <Post post_id={p.id} key={p.id} {...p} />;
})}
</InfinityScroll>
</PostListFrame>
);
};
const PostListFrame = styled.div`
display: flex;
flex-direction: column;
padding: 12px 0;
`;
export default PostList;
<file_sep>/henrystagram/src/shared/App.js
import "./App.css";
import React from "react";
import Header from "../components/Header";
import styled from "styled-components";
import { Button } from "../elements";
import { BrowserRouter, Route } from "react-router-dom";
import { ConnectedRouter } from "connected-react-router";
import { history } from "../redux/configStore";
import PostList from "../pages/PostList";
import Login from "../pages/Login";
import Signup from "../pages/Signup";
import Permit from "./Permit";
import PostWrite from "../pages/PostWrite";
import PostDetail from "../pages/PostDetail";
import { actionCreators as userActions } from "../redux/modules/user";
import { useDispatch } from "react-redux";
import { apiKey } from "./firebase";
function App() {
const dispatch = useDispatch();
const _session_key = `firebase:authUser:${apiKey}:[DEFAULT]`;
const is_session = sessionStorage.getItem(_session_key) ? true : false;
React.useEffect(() => {
if (is_session) {
dispatch(userActions.loginCheckFB());
}
}, []);
return (
<AppFrame>
<Header></Header>
<ConnectedRouter history={history}>
<Route exact path="/" component={PostList} />
<Route exact path="/login" component={Login} />
<Route exact path="/signup" component={Signup} />
<Route exact path="/write" component={PostWrite} />
<Route exact path="/write/:id" component={PostWrite} />
<Route exact path="/post/:id" component={PostDetail} />
</ConnectedRouter>
<Permit>
<Button
text="+"
is_float
_onClick={() => {
history.push("/write");
}}
/>
</Permit>
</AppFrame>
);
}
const AppFrame = styled.div`
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
overflow-x: hidden;
`;
export default App;
<file_sep>/henrystagram/src/components/Header.js
import React from "react";
import { Grid, Text, Button } from "../elements/index";
import styled from "styled-components";
import logoBg from "../HenryStagam.png";
import { getCookie, deleteCookie } from "../shared/Cookie";
import { useSelector, useDispatch } from "react-redux";
import { actionCreators as userActions } from "../redux/modules/user";
import { history } from "../redux/configStore";
import { apiKey } from "../shared/firebase";
const Header = (props) => {
const dispatch = useDispatch();
const is_login = useSelector((state) => state.user.is_login);
const _session_key = `firebase:authUser:${apiKey}:[DEFAULT]`;
const is_session = sessionStorage.getItem(_session_key) ? true : false;
if (is_login && is_session) {
return (
<React.Fragment>
<Grid
height="14vh"
bg="white"
padding="14px"
is_flex
border={"1px solid #dbdbdb"}
>
<Logo />
<Grid width="40%" is_flex>
<Button
_onClick={() => {
dispatch(userActions.logOutFB());
}}
>
로그아웃
</Button>
</Grid>
</Grid>
</React.Fragment>
);
}
return (
<React.Fragment>
<Grid
height="14vh"
bg="white"
padding="14px"
is_flex
border={"1px solid #dbdbdb"}
>
<Logo />
<Grid width="40%" is_flex>
<Button
_onClick={() => {
history.push("/login");
}}
>
로그인
</Button>
<Button
_onClick={() => {
history.push("/signup");
}}
>
회원가입
</Button>
</Grid>
</Grid>
</React.Fragment>
);
};
const Logo = styled.div`
background-image: url("${logoBg}");
width: 15vw;
height: 100%;
background-size: cover;
background-position: center;
`;
const Border = styled.div`
border: 1px solid #dbdbdb;
`;
export default Header;
| bf7fe3fdab9b7bd1ad75dd74393ee3c0d49b2726 | [
"JavaScript"
] | 4 | JavaScript | Henry-Cho/hanghae_stagram | 7b7e73ddc7b0640b9d8e584e5562a9a2d3fc6276 | 58f6eb446a8db41fe109d9d64d3537d6e63b352c |
refs/heads/master | <file_sep>##XMPP/Jabber client with CLI and GUI.
---
Uses PLAIN auithorization method. Use at your own risks. Implements basics registration and authorization method. Can send and recieve messages. Also it's possible to work with roster.
usage: xmppclient [-h] [--version] [-s server_name:port]
[-r username:password] [-l username:password] [-c] [-a JID]
[-m message] [-u JID] [-w ss] [-i]
-h, --help show this help message and exit
--version show program's version number and exit
-s server_name:port, --server server_name:port
specifis XMPP server address
-r username:password, --register-user username:password
register new user
-l username:password, --log-user username:password
login as a user
-c, --show-contactlist
show user contact list
-a JID, --add-user JID
adds user to contact list
-m message, --message message
specify message text
-u JID, --user JID specify JID of a recipient
-w ss, --wait ss wait for response ss seconds before exit
-i, --interactive enables interactive mode
###Usage examples:
./xmppclient -s netfox.fit.vutbr.cz:5222 -r xlogin00:pass
./xmppclient -s netfox.fit.vutbr.cz:5222 -l xlogin00:pass -c -a <EMAIL>
./xmppclient -s netfox.fit.vutbr.cz:5222 -l xlogin00:pass -m "<PASSWORD>" -u <EMAIL>
./xmppclient -s netfox.fit.vutbr.cz:5222 -r xlogin00:pass -l xlogin00:pass -w 60
./xmppclient -s netfox.fit.vutbr.cz:5222 -l xlogin00:pass -u <EMAIL> -i
Use `init.sh` to install Tkinter, and set permissions.
`manual.pdf` contains documentation in Czech language.
*<NAME> (xbirge00)*
*8 October 2014 - 30 October 2014*<file_sep>#!/usr/bin/env bash
# install tkinter if it's not available
sudo apt-get -y install python3-tk
# set the file to executable
chmod +x ./xmppclient<file_sep>#!/usr/bin/env python3
"""
XMPP/Jabber client with CLI and GUI.
Uses PLAIN auithorization method.
Use at your own risks. Implements basics
registration and authorization method.
Can send and recieve messages. Also it's
possible to work with roster.
"""
__author__ = "<NAME>"
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
__date__ = "8 October 2014"
import argparse, socket, base64, re, time, multiprocessing
try:
from tkinter import *
except ImportError:
TK_AVAILABLE = False
else:
TK_AVAILABLE = True
class Configuration:
"""
Class, which creates object of argument parser.
Validates input data. Setups Client class object.
Class needed for extra static methods.
"""
def __init__(self):
self.parser = argparse.ArgumentParser(
description=__doc__,
epilog=__author__+" "+__date__)
self.parser.add_argument(
'--version',
action='version',
version='%(prog)s '+__version__)
self.parser.add_argument(
'-s',
'--server',
action='store',
nargs=1,
type=self.validate_server,
required=False,
help='specifis XMPP server address',
metavar='server_name:port',
dest='server')
self.parser.add_argument(
'-r',
'--register-user',
action='store',
nargs=1,
type=self.validate_auth,
required=False,
help='register new user',
metavar='username:password',
dest='register')
self.parser.add_argument(
'-l',
'--log-user',
action='store',
nargs=1,
type=self.validate_auth,
required=False,
help='login as a user',
metavar='username:password',
dest='login')
self.parser.add_argument(
'-c',
'--show-contactlist',
action='store_true',
required=False,
help='show user contact list',
dest='contacts')
self.parser.add_argument(
'-a',
'--add-user',
action='store',
nargs=1,
type=str,
required=False,
help='adds user to contact list',
metavar='JID',
dest='add')
self.parser.add_argument(
'-m',
'--message',
action='store',
nargs=1,
type=str,
required=False,
help='specify message text',
metavar='message',
dest='message')
self.parser.add_argument(
'-u',
'--user',
action='store',
nargs=1,
type=str,
required=False,
help='specify JID of a recipient',
metavar='JID',
dest='user')
self.parser.add_argument(
'-w',
'--wait',
action='store',
nargs=1,
type=int,
required=False,
help='wait for response ss seconds before exit',
metavar='ss',
dest='wait')
self.parser.add_argument(
'-i',
'--interactive',
action='store_true',
required=False,
help='enables interactive mode',
dest='interactive')
self.parser.parse_args(namespace=self)
@staticmethod
def validate_server(string):
"""
Method splits input server and port
for Client class configuration.
If port isn't defined deafaults to 5222.
"""
server = string.split(':')
if len(server) == 1:
server.append(5222)
else:
server[1] = int(server[1])
return server
@staticmethod
def validate_auth(string):
"""
Method splits user and password
input string. Login can't containt
':' symbol, so split to first.
Default password is empty.
"""
data = string.split(':', 1)
if len(data) == 1:
data.append("")
return data
class Client:
"""
XMPP client class. Implements most of features.
Full description in help and documentation.
"""
def __init__(self, config):
"""
Defines all client class behavior.
Parses configuration object to define methods parameters.
"""
self.log = open('log.txt', 'w')
print('<!-- Logging started. -->', file=self.log)
self.errors = open('error_log.txt', 'w')
print('Logging started.', file=self.errors)
# print(config.__dict__)
self.mid = 0 # XMPP message iq id
if config.server is not None:
self.server = config.server[0][0]
self.port = config.server[0][1]
self.socket = None
if self.connect():
self.loggedin = False
self.jid = None
if config.register is not None:
self.user = config.register[0][0]
self.password = config.register[0][1]
if self.register() and config.login is None:
self.auth()
if config.login is not None:
self.user = config.login[0][0]
self.password = config.login[0][1]
self.auth()
if self.loggedin:
if config.contacts != False:
self.roster()
if config.add is not None:
user = config.add[0]
self.add(user)
if config.message is not None and config.user is not None:
self.message(config.user[0], config.message[0])
elif config.message is not None and config.user is None:
print("User is not specified.", file=self.errors)
print("Please specify target user.")
if config.interactive == False and config.wait is not None:
if config.wait[0] <= 0:
print("Make sure, that waittime is under zero.")
self.wait(config.wait[0])
elif config.interactive == True and config.wait is None:
if config.user is not None:
if TK_AVAILABLE:
self.interactive(config.user[0])
else:
print("Please install python3-tk package \
with apt-get.")
else:
print("User is not specified.", file=self.errors)
print("Please specify target user.")
elif config.interactive == True and config.wait is not None:
print("Wrong options.", file=self.errors)
print("User interactive mode OR wait before exit.")
self.exit()
else:
if config.register is None and \
config.login is None and \
config.contacts == False and \
config.add is None and \
config.message is None and \
config.user is None and \
config.wait is None and \
config.interactive == False:
print("Nothing to do.")
else:
print("Server is not specified.", file=self.errors)
print("Please specify a server.")
def connect(self):
"""
Creates socket and connects to selected server and port.
"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(
"Connecting to %s at port %i... "%(self.server, self.port),
end="")
try:
self.socket.connect((self.server, self.port))
except socket.error as exception:
print("Can't connect to server.\n%s"%(exception), file=self.errors)
print("failed")
return False
print("connected")
return True
def send(self, data):
"""
Method send data to server.
Socket should be connected to server before.
"""
total = 0
while total < len(data):
sent = self.socket.send(data[total:])
if sent == 0:
print("Can't send to socket.", file=self.errors)
total = total + sent
print(data.decode('utf-8'), file=self.log)
def recieve(self, pattern, timeout=5):
"""
Method recieves data from socket and detects needed data.
If patter is False, uses <iq> id to detect needed message.
Else looking for pattern string, for exaple closing tag.
Returns data in any case.
"""
self.socket.settimeout(timeout)
data = b''
start = time.time()
try:
while True:
chunk = self.socket.recv(2048)
if len(chunk) == 0:
print(data.decode('utf-8'), file=self.log)
return str(data)
else:
data += chunk
if isinstance(pattern, bool):
if 'id="'+str(self.mid)+'"' in str(data):
print(data.decode('utf-8'), file=self.log)
return str(data)
else:
if pattern in str(data):
print(data.decode('utf-8'), file=self.log)
return str(data)
if (time.time() - start) > timeout:
print(data.decode('utf-8'), file=self.log)
return str(data)
except socket.timeout:
print(data.decode('utf-8'), file=self.log)
return str(data)
def new_id(self):
"""
Method generates new identifier for <iq> stanza.
"""
self.mid += 1
return str(self.mid)
def greet(self):
"""
Send and recives greeting XMPP messages.
Includes XML and stream.
"""
message = """
<?xml version="1.0"?>
<stream:stream xmlns:stream="http://etherx.jabber.org/streams"
version="1.0" xmlns="jabber:client" to="%s">
""" % (self.server)
self.send(message.encode("utf-8"))
return self.recieve("</stream:features>")
def register(self):
"""
Registers new user at XMPP server.
"""
response = self.greet()
if not 'register' in response:
msg = "Registration is not available at the server."
print(msg, file=self.errors)
print(msg)
return False
print(
"Registering %s with password %s... " % (self.user, self.password),
end="")
message = """
<iq xmlns="jabber:client" type="get" to="%s">
<query xmlns="jabber:iq:register"/>
</iq>
""" % (self.server)
self.send(message.encode("utf-8"))
if not '<iq type="result"' in self.recieve(""):
print("problems with registration", file=self.errors)
print("failed")
return False
message = """
<iq xmlns="jabber:client" type="set" to="%s">
<query xmlns="jabber:iq:register">
<x xmlns="jabber:x:data" type="form">
<field type="hidden" var="FORM_TYPE">
<value>jabber:iq:register</value>
</field>
<field type="text-single" var="username">
<value>%s</value>
</field>
<field type="text-private" var="password">
<value>%s</value>
</field>
</x>
</query>
</iq>
""" % (self.server, self.user, self.password)
self.send(message.encode("utf-8"))
response = self.recieve("</iq>")
if '<iq type="result"' in response:
print('registered')
return True
else:
print("Registration failed.", file=self.errors)
print('failed')
return False
def auth(self):
"""
Method implements PLAIN authorization at the server.
"""
self.greet()
print(
"Logging in as %s with password %s... " % \
(self.user, self.password),
end="")
key = b'\x00'+self.user.encode("utf-8")
key += b'\x00'+self.password.encode("utf-8")
key = base64.b64encode(key)
message = """
<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="PLAIN">%s</auth>
""" % (key.decode("utf-8"))
self.send(message.encode("utf-8"))
response = self.recieve("urn:ietf:params:xml:ns:xmpp-sasl")
if "success" in response:
print("success")
self.bind_session()
self.loggedin = True
return True
else:
print("Authorization failed.", file=self.errors)
print("failed")
def bind_session(self):
"""
This method called after successfull authorization.
Uses bind and session of XMPP protocol.
"""
message = """
<stream:stream xmlns="jabber:client"
to="%s"
version="1.0"
xmlns:stream="http://etherx.jabber.org/streams" >
""" % (self.server)
self.send(message.encode("utf-8"))
self.recieve("</stream:features>")
message = """
<iq type="set" id="%s"><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">
<resource>xmppclient</resource></bind></iq>
"""%(self.new_id())
self.send(message.encode("utf-8"))
response = self.recieve(False)
try:
self.jid = re.search(r"<jid>(.*)</jid>", response).group(1)
print("Got a JID: %s" % (self.jid))
except AttributeError:
msg = "Failed JID recognition."
print(msg, file=self.errors)
print(msg)
message = """
<iq type="set" id="%s">
<session xmlns="urn:ietf:params:xml:ns:xmpp-session" /></iq>
"""%(self.new_id())
self.send(message.encode("utf-8"))
response = self.recieve(False)
self.presence()
def presence(self):
"""
Send presence report to the server.
Needed to start recieve messages.
"""
message = """
<presence xmlns="jabber:client"></presence>
"""
self.send(message.encode("utf-8"))
def roster(self):
"""
Requests and recives roster (XMPP contact list).
"""
print("Loading contacts list... ", end="")
message = """
<iq type="get" id="%s">
<query xmlns="jabber:iq:roster"/>
</iq>
"""%(self.new_id())
self.send(message.encode("utf-8"))
response = self.recieve(False)
contacts = re.findall(r'<item.*?jid="(.*?)".*?\/>', response)
if len(contacts) == 0:
print("empty")
else:
print("loaded:")
for contact in contacts:
print('\t'+contact)
def add(self, user):
"""
Method adds user by JID in variable user to roster.
"""
print("Adding %s to your contact list... " % (user), end="")
message = """
<iq xmlns="jabber:client" type="set" id="%s">
<query xmlns="jabber:iq:roster">
<item jid="%s"/>
</query></iq>
"""%(self.new_id(), user)
self.send(message.encode("utf-8"))
response = self.recieve(False)
if 'type="result"' in response and \
not 'type="error"' in response:
print("added")
else:
print("Failed to add user to contacts.", file=self.errors)
print("failed")
def message(self, user, message):
"""
Method send message to specified user.
"""
print("Sending message to %s... "%(user), end="")
message = """
<message to="%s" from="%s" type="chat" id="%s">
<body>%s</body></message>
"""%(user, self.jid, self.new_id(), message)
self.send(message.encode("utf-8"))
print("sent")
def wait(self, wait):
"""
Method implements waiting for incoming message.
Uses self.incoming method called in another process.
"""
print("Waiting for a message... ", end="")
incoming_queue = multiprocessing.Queue(maxsize=0)
log_queue = multiprocessing.Queue(maxsize=0)
incoming_process = multiprocessing.Process(
target=self.incoming,
args=(incoming_queue, log_queue, ))
incoming_process.start()
start = time.time()
while True:
if not log_queue.empty():
response = log_queue.get()
print(response.decode('utf-8'), file=self.log)
continue
if not incoming_queue.empty():
response = incoming_queue.get()
print("recieved")
msg_from, msg_body = self.parse_message(response)
print(self.print_message(time.localtime(), msg_from, msg_body))
break
if time.time() - start > wait:
print("timeouted")
break
incoming_process.terminate()
def parse_message(self, response):
"""
Method parses incoming XML data, and returns
parsed message target and message body.
"""
response = str(response)
response = re.search(r'<message.*?<\/message>', response).group(0)
msg_to = re.search(r'to="(.*?)"', response).group(1)
if msg_to != self.jid:
print("Wrong message destination.", file=self.errors)
msg_from = re.search(r'from="(.*?)"', response).group(1)
msg_body = re.search(r'<body>(.*?)<\/body>', response).group(1)
return msg_from, msg_body
@staticmethod
def print_message(localtime, msg_from, message):
"""
Method creates string, which contains message info.
Used in wait and interactive methods.
"""
msg_from = re.search(r'(.*?)@', msg_from).group(1)
return "[%s] <%s> %s" % \
(time.strftime("%H:%M:%S", localtime), msg_from, message)
def incoming(self, incoming_queue, log_queue):
"""
Method recieves data from socket and sends it to the Queue.
Another queue needed to log data, send to this queue for
example presence tags too.
Works in another process.
"""
self.socket.settimeout(None)
data = b''
try:
while True:
chunk = self.socket.recv(2048)
log_queue.put(chunk)
data += chunk
if "error" in str(data):
pass
elif "</message>" in str(data):
# print(data.decode('utf-8'), file=self.log)
incoming_queue.put(data)
data = b''
if "urn:xmpp:ping" in str(data):
# print(data.decode('utf-8'), file=self.log)
mid = re.search(r'id="(.*?)"', str(data)).group(1)
message = """
<iq id="%s" type="result">
<ping xmlns='urn:xmpp:ping'/></iq>
"""%(mid)
self.send(message.encode("utf-8"))
except socket.timeout:
message = """
<iq id="%s" type="get">
<ping xmlns='urn:xmpp:ping'/></iq>
"""%(self.new_id())
self.send(message.encode("utf-8"))
print("Updating socket")
def interactive(self, user):
"""
Method implements GUI. Uses incoming method in another process.
Allows user to send and recieve messages.
"""
incoming_queue = multiprocessing.Queue(maxsize=0)
log_queue = multiprocessing.Queue(maxsize=0)
incoming_process = multiprocessing.Process(
target=self.incoming,
args=(incoming_queue, log_queue, ))
incoming_process.start()
def interactive_send(event):
"""
This is callback function for clicking Send button.
Uses socket in the same process. Send message to server.
"""
typed = field.get()
if typed == "":
return
field.delete(0, END)
message = """
<message to="%s" from="%s" type="chat" id="%s">
<body>%s</body></message>
"""%(user, self.jid, self.new_id(), typed)
self.send(message.encode("utf-8"))
log.configure(state=NORMAL)
log.insert(
INSERT,
self.print_message(time.localtime(), self.jid, typed)+'\n')
log.configure(state=DISABLED)
root = Tk()
def update():
"""
This function check queues for new meessages.
Updates GUI if new message available.
Sheduled by GUI.
"""
if not log_queue.empty():
while not log_queue.empty():
response = log_queue.get()
print(response.decode('utf-8'), file=self.log)
if not incoming_queue.empty():
income = incoming_queue.get()
msg_from, msg_body = self.parse_message(income)
log.configure(state=NORMAL)
log.insert(
INSERT,
self.print_message(
time.localtime(),
msg_from,
msg_body)+'\n')
log.configure(state=DISABLED)
root.after(100, update)
root.wm_title("xmppclient - %s"%(self.jid))
root.geometry('{}x{}'.format(600, 400))
frame_top = Frame(root, heigh=40, bd=0, bg='#f9f9f9', relief=SOLID)
frame_center = Frame(root, background='#e5e5e5', borderwidth=1)
frame_bottom = Frame(root, heigh=40, bd=0, bg='#f9f9f9', relief=FLAT)
scrollbar = Scrollbar(frame_center)
scrollbar.pack(side=RIGHT, fill=Y)
label = Label(
frame_top,
text="Chat with: %s"%(user),
bg='#f9f9f9')
log = Text(frame_center, width=60, height=20, state=DISABLED)
log.config(yscrollcommand=scrollbar.set)
field = Entry(frame_bottom, width=50)
btn = Button(
frame_bottom,
text="Send",
width=10,
height=5,
highlightbackground='#f9f9f9')
btn.bind("<Button-1>", interactive_send)
field.bind("<Return>", interactive_send)
frame_top.pack(fill=X, expand=False)
frame_center.pack(fill=BOTH, expand=True)
frame_bottom.pack(fill=X, expand=False)
label.pack(fill=X, side=LEFT, padx=5, pady=5)
log.pack(fill=BOTH, expand=True)
field.pack(fill=X, side=LEFT, expand=True, padx=5, pady=5)
btn.pack(fill=X, side=RIGHT, padx=5, pady=5)
root.update()
root.minsize(root.winfo_width(), root.winfo_height())
root.after(100, update)
root.mainloop()
incoming_process.terminate()
def exit(self):
"""
Send end of stream message. Closes socket.
"""
print("Closing connection... ", end="")
message = """
</stream:stream>
"""
self.send(message.encode("utf-8"))
self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
print("closed")
if __name__ == "__main__":
CONFIG = Configuration()
CLIENT = Client(CONFIG)
| 601bcf615de2dd07bad5791eec445ba8e73d9088 | [
"Markdown",
"Python",
"Shell"
] | 3 | Markdown | kusha/xmppclient | e9faac85fc511c9442f554d697d33bedb3e11180 | f6dede28fef774effb46fe5a41d56d5676c3c5ec |
refs/heads/master | <file_sep>import test from 'ava';
import arget from '.';
function genArg() {
return arget(arguments);
}
test('Arget.prototype.first', t => {
t.deepEqual(genArg(1, 2, 3, 4).first(), 1);
t.deepEqual(genArg(2, 3, 4, 5).first(), 2);
t.deepEqual(genArg(null, 2, 3).first(), null);
t.deepEqual(genArg().first(), undefined);
});
test('Arget.prototype.last', t => {
t.deepEqual(genArg(1, 2, 3, 4).last(), 4);
t.deepEqual(genArg(2, 3, 4, 5).last(), 5);
t.deepEqual(genArg(3, 2, null).last(), null);
t.deepEqual(genArg().last(), undefined);
});
test('Arget.prototype.get', t => {
var f = function () {};
t.deepEqual(genArg(1, 2, 3, 4).get(0), 1);
t.deepEqual(genArg(2, 3, 4, 5).get(6), undefined);
t.deepEqual(genArg(2, 3, 4, 5).get(0, Number), 2);
t.deepEqual(genArg(2, 3, 4, 5).get(0, Function), undefined);
t.deepEqual(genArg(2, 3, 4, f).get(0, Function), f);
t.deepEqual(genArg(2, ()=>{}, 4, f).get(1, Function), f);
t.deepEqual(genArg(2, ()=>{}, 4, {}, f).get(1, Object), undefined);
});
test('Arget.prototype.getRight', t => {
var f = function () {};
t.deepEqual(genArg(1, 2, 3, 4).getRight(0), 4);
t.deepEqual(genArg(2, 3, 4, 5).getRight(6), undefined);
t.deepEqual(genArg(2, 3, 4, 5).getRight(0, Number), 5);
t.deepEqual(genArg(2, 3, 4, 5).getRight(0, Function), undefined);
t.deepEqual(genArg(2, 3, 4, f).getRight(0, Function), f);
t.deepEqual(genArg(2, f, 4, ()=>{}).getRight(1, Function), f);
t.deepEqual(genArg(2, ()=>{}, 4, {}, f).getRight(1, Object), undefined);
});
test('Arget.prototype.all', t => {
var f = function () {};
t.deepEqual(genArg(1, 2, 3, 4).all(), [1, 2, 3, 4]);
t.deepEqual(genArg(2, 3, 4, 5).all(Number), [2, 3, 4, 5]);
t.deepEqual(genArg(2, 3, 4, 5).all(Object), []);
t.deepEqual(genArg(2, [], {}, 5).all(Object), [{}]);
t.deepEqual(genArg(2, [2, 3], {}, [4, 5]).all(Array), [[2, 3], [4, 5]]);
t.deepEqual(genArg(2, 3, 4, f).all(Function), [f]);
});
test('Arget.prototype.toArray', t => {
var array = [1, 2, 3, 4]
, wrapper = genArg.apply(this, array);
t.deepEqual(wrapper.toArray(), array);
});
test('Arget.prototype.forEach', t => {
var array = [1, 2, 3, 4]
, wrapper = genArg.apply(this, array);
wrapper.forEach((e, i, a) => {
t.deepEqual(array, a);
t.deepEqual(array[i], e);
});
});
test('Arget.prototype.each', t => {
var wrapper = genArg();
t.deepEqual(wrapper.forEach, wrapper.each);
});
test('Arget.prototype.filter', t => {
var array = [1, 2, 3, 4]
, wrapper = genArg.apply(this, array)
, result = wrapper.filter((e, i, a) => {
t.deepEqual(array, a);
t.deepEqual(array[i], e);
return e%2 == 0;
});
t.deepEqual(result, [2, 4]);
});
test('Arget.prototype.map', t => {
var array = [1, 2, 3, 4]
, wrapper = genArg.apply(this, array)
, result = wrapper.map((e, i, a) => {
t.deepEqual(array, a);
t.deepEqual(array[i], e);
return e*2;
});
t.deepEqual(result, [2, 4, 6, 8]);
});
test('Arget.prototype.pick', t => {
var f = function () {}
, C = function () {}
, c = new C;
t.deepEqual(genArg(1, 2, 3, 4).pick(Number), [1, 2, 3, 4]);
t.deepEqual(genArg(2, 3, 4, 5).pick(Object), []);
t.deepEqual(genArg(2, [], {}, 5).pick(Object, Array), [[], {}]);
t.deepEqual(genArg(2, [2, 3], {}, [4, 5]).pick(Array, Function), [[2, 3], [4, 5]]);
t.deepEqual(genArg(2, 3, 4, f).pick(Function), [f]);
t.deepEqual(genArg(2, 3, c, f).pick(C), [c]);
});
test('Arget.prototype.omit', t => {
var f = function () {}
, C = function () {}
, c = new C;
t.deepEqual(genArg(1, 2, 3, 4).omit(Number), []);
t.deepEqual(genArg(2, 3, 4, 5).omit(Object), [2, 3, 4, 5]);
t.deepEqual(genArg(2, [], {}, 5).omit(Object, Array), [2, 5]);
t.deepEqual(genArg(2, [2, 3], {}, [4, 5]).omit(Array, Function), [2, {}]);
t.deepEqual(genArg(2, 3, 4, f).omit(Function), [2, 3, 4]);
t.deepEqual(genArg(2, 3, c, f).omit(C), [2, 3, f]);
});
test('Arget.prototype.match', t => {
var f = function () {}
, C = function () {}
, c = new C;
t.deepEqual(genArg(1, 2, 3, 4).match(Number), [1]);
t.deepEqual(genArg(2, 3, 4, 5).match(Object), [undefined]);
t.deepEqual(genArg(2, [], {}, 5).match(Object, Array), [{}, []]);
t.deepEqual(genArg(2, [2, 3], {}, [4, 5]).match(Array, Function), [[2, 3], undefined]);
t.deepEqual(genArg(2, 3, 4, f).match(Function), [f]);
t.deepEqual(genArg(2, 3, c, f).match(C), [c]);
t.deepEqual(genArg(2, 3, {}, 4, {a : 1}, f).match(null, Object, null, Function), [2, {}, 3, f]);
t.deepEqual(genArg(2, f).match(null, null, Function), [2, undefined, f]);
});
test('Arget.prototype.matchRight', t => {
var f = function () {}
, C = function () {}
, c = new C;
t.deepEqual(genArg(1, 2, 3, 4).matchRight(Number), [4]);
t.deepEqual(genArg(2, 3, 4, 5).matchRight(Object), [undefined]);
t.deepEqual(genArg(2, [], {}, 5).matchRight(Object, Array), [{}, []]);
t.deepEqual(genArg(2, [2, 3], {}, [4, 5]).matchRight(Array, Function), [[4, 5], undefined]);
t.deepEqual(genArg(2, 3, 4, f).matchRight(Function), [f]);
t.deepEqual(genArg(2, 3, c, f).matchRight(C), [c]);
t.deepEqual(genArg(2, () => {}, 3, {}, 4, {a : 1}, f).matchRight(null, Object, null, Function), [{}, {a: 1}, 4, f]);
t.deepEqual(genArg(2, f).matchRight(null, null, Function), [undefined, 2, f]);
});
test('Arget.prototype.length', t => {
t.deepEqual(genArg(1, 2, 3, 4).length, 4);
t.deepEqual(genArg().length, 0);
});<file_sep># 
> A JavaScript utility library to manipulate Function.arguments

A nice library to deal with most of arguments annoying usecases. A first Error object, a second optional argument or a last function as a callback... Arget helps solve all these issues in one line of code. Ex:
```javascript
function fn () {
var args = arget(arguments);
args.toArray(); // => [1, 'str', 2, true]
args.pick(Number); // => [1, 2]
args.match(null, Boolean, String); // => [1, true, 'str']
}
fn(1, 'str', 2, true);
```
Second example :
```javascript
function fn () {
var [foo, bar, foobar] = arget(arguments).match(null, null, Function);
console.log(foo, bar, foobar);
}
fn({}, () => {}); // ==> {}, undefined, () => {}
fn({}, 'value', () => {}); // ==> {}, 'value', () => {}
```
## Content
- [Install](#install)
- [Usage](#usage)
- [Arget wrapper](#arget-wrapper)
- [.first( )](#first-)
- [.last( )](#last-)
- [.get( )](#get-)
- [.getRight( )](#getRight-)
- [.all( )](#all-)
- [.toArray( )](#toarray-)
- [.forEach( )](#foreach-)
- [.each( )](#each-)
- [.filter( )](#filter-)
- [.map( )](#map-)
- [.pick( )](#pick-)
- [.omit( )](#omit-)
- [.match( )](#match-)
- [.matchRight( )](#matchright-)
- [.length](#length)
- [License](#license)
## Install
```
npm install --save arget
```
## Usage
When requiring the arget module, you'll get a function that instanciates the [Arget wrapper](#arget-wrapper) using the arguments you are passing.
```javascript
var arget = require('arget');
function fn () {
var wrapper = arget(arguments);
}
```
> /!\ arget instanciates the wrapper whether you pass arguments as argument to arget or not, but you need to keep in mind that there is a huge performance issue if you don't.
## Arget wrapper
### .first( )
Returns the first argument
```javascript
function fn () {
return arget(arguments).first();
}
fn(1, 2, 3, 4); // ==> 1
fn(); // ==> undefined
```
### .last( )
Returns the last argument
```javascript
function fn () {
return arget(arguments).last();
}
fn(1, 2, 3, 4); // ==> 4
fn(); // ==> undefined
```
### .get( )
> .get(position, [constructor = undefined])
Returns element with the constructor and the position specified
```javascript
function fn () {
return arget(arguments).get(1);
}
fn(true, 2, 3, 4); // ==> 2
fn(); // ==> undefined
function fn () {
return arget(arguments).get(1, Number);
}
fn(true, 2, 3, 4); // ==> 3
```
### .getRight( )
> .getRight(position, [constructor = undefined])
Returns element with the constructor and the position from the right specified
```javascript
function fn () {
return arget(arguments).get(1);
}
fn(true, 2, 3, 4); // ==> 3
fn(); // ==> undefined
function fn () {
return arget(arguments).get(0, Number);
}
fn(true, 2, 3, 4); // ==> 4
```
### .all( )
> .all([constructor = undefined])
Returns elements with the constructor specified
```javascript
function fn () {
return arget(arguments).all(Number);
}
fn(true, 2, 3, 4); // ==> [2, 3, 4]
fn(); // ==> []
```
### .toArray( )
Converts arguments object to array
```javascript
function fn () {
return arget(arguments).toArray();
}
fn(1, 2, 3, 4); // ==> [1, 2, 3, 4]
fn(); // ==> []
```
### .forEach( )
> .forEach(iteratee)
Iterates over the arguments
```javascript
function fn () {
arget(arguments).forEach(e => console.log(e));
}
fn(1, 2, 3, 4); // ==> prints 1 2 3 4
```
The `iteratee` takes 3 arguments :
> iteratee(item, index, array)
- `item` : The element
- `index` : The element index on the arguments
- `array` : The arguments as array
```javascript
function fn () {
arget(arguments).forEach((item, index, array) => {
console.log(item, index, array)
});
}
fn(1, 2, 3);
// prints :
// 1 0 [1, 2, 3]
// 2 1 [1, 2, 3]
// 3 2 [1, 2, 3]
```
### .each( )
Alias of [.forEach( )](#foreach)
### .filter( )
> .filter(predicate)
Returns an array filtred depending on the returned value of the predicate for each item. The result contains items that the predicate returned a truthy value for.
```javascript
function fn () {
return arget(arguments).filter(e => e != 3);
}
fn(1, 2, 3, 4); // ==> 1 2 4
```
The `predicate` takes 3 arguments :
> predicate(item, index, array)
- `item` : The element
- `index` : The element index on the arguments
- `array` : The arguments as array
### .map( )
> .map(predicate)
Returns an array containing the result of the predicate for each element
```javascript
function fn () {
return arget(arguments).map(e => e * 2);
}
fn(1, 2, 3, 4); // ==> 2 4 6 8
```
The `iteratee` takes 3 arguments :
> iteratee(item, index, array)
- `item` : The element
- `index` : The element index on the arguments
- `array` : The arguments as array
### .pick( )
> .pick(contructor[, constructor[, ...]])
Returns an array of elements with the constructors specified
```javascript
function fn () {
return arget(arguments).pick(Number)
}
fn(true, 1, 2, 'str'); // ==> [1, 2]
function fn () {
return arget(arguments).pick(Number, String)
}
fn(true, 1, {}, 'str'); // ==> [1, 'str']
```
### .omit( )
> .omit(contructor[, constructor[, ...]])
Returns an array of elements without those with the constructors specified
```javascript
function fn () {
return arget(arguments).omit(Number)
}
fn(true, 1, 2, 'str'); // ==> [true, 'str']
function fn () {
return arget(arguments).omit(Number, String)
}
fn(true, 1, {}, 'str'); // ==> [true, {}]
```
### .match( )
> .match(contructor[, constructor[, ...]])
Returns an array of elements depending in the pattern of constructors specified.
When a falsy value is given instead of a constructor, the position is filled with an elements not matched yet.
```javascript
function fn () {
return arget(arguments).match(null, null, Function);
}
fn(1, () => {}); // ==> [1, undefined, () => {}]
fn(1, 'value', () => {}); // ==> [1, 'value', () => {}]
function fn () {
return arget(arguments).match(Array, null, Number, null, Function);
}
fn(1, 2, 3, () => {}, []) // ==> [ [], 2, 1, 3, () => {} ]
```
> /!\ : Note that the match method starts first by putting the items with the constructors specified on their position, then it fills the falsy positions with the rest.
### .matchRight( )
> .matchRight(contructor[, constructor[, ...]])
Similar to [.match( )](#match-) but it loops **from right to left**.
Returns an array of elements depending in the pattern of constructors specified.
When a falsy value is given instead of a constructor, the position is filled with an elements not matched yet.
```javascript
function fn () {
return arget(arguments).matchRight(null, null, Function);
}
fn(1, () => {}); // ==> [undefined, 1, () => {}]
fn(1, 'value', () => {}); // ==> [1, 'value', () => {}]
function fn () {
return arget(arguments).matchRight(Array, null, Number, null, Function);
}
fn(1, 2, 3, () => {}, []) // ==> [ [], 1, 3, 2, () => {} ]
```
> /!\ : Note that the matchRight method starts first by putting the items with the constructors specified on their position, then it fills the falsy positions with the rest.
### .length
Returns the number of elements
```javascript
function fn () {
return arget(arguments).length
}
fn(); // ==> 0
fn(1, () => {}); // ==> 2
fn(1, 'value', () => {}); // ==> 3
```
## License
MIT<file_sep>function hashByType (argsObject) {
var hash = {};
for(var obj of argsObject) {
var type = getType(obj.arg);
if(hash[type]) {
hash[type].push(obj);
} else {
hash[type] = [obj];
}
}
return hash;
}
function getType (value) {
try {
return Object.getPrototypeOf(value).constructor.name;
} catch (ex) {
return Symbol();
}
}
function hashRightByType (argsObject) {
var hash = {};
for(var obj of argsObject) {
var type = getType(obj.arg);
if(hash[type]) {
hash[type].unshift(obj);
} else {
hash[type] = [obj];
}
}
return hash;
}
function matchFromHash (payload, hash) {
for(var i = 0, neutral = []; i < payload.length; i++) {
if(payload[i]) {
var obj = (hash[payload[i]] || []).shift() || {};
payload[i] = obj.arg;
obj.matched = true;
} else {
neutral.push(i);
}
}
return neutral;
}
function matchRightFromHash (payload, hash) {
for(var i = payload.length - 1, neutral = []; i >= 0 ; i--) {
if(payload[i]) {
var obj = (hash[payload[i]] || []).shift() || {};
payload[i] = obj.arg;
obj.matched = true;
} else {
neutral.push(i);
}
}
return neutral;
}
function toKeys (array) {
return array.reduce((obj, el) => {
obj[el] = true;
return obj;
}, {});
}
module.exports = {
hashByType,
hashRightByType,
matchFromHash,
matchRightFromHash,
getType,
toKeys
};<file_sep>var _util = require('./lib/_util');
var Arget = function (args) {
this._args = args;
};
Arget.prototype.first = function (type) {
if(type) return this.get(0, type);
return this._args[0];
};
Arget.prototype.last = function (type) {
if(type) return this.getRight(0, type);
return this._args[this._args.length - 1];
};
Arget.prototype.get = function (index, type) {
if(!type) return this._args[index];
for(var i = 0; i<this.length; i++) {
if(_util.getType(this._args[i]) == type.name && index-- == 0) {
return this._args[i];
}
}
};
Arget.prototype.getRight = function (index, type) {
if(!type) return this._args[this.length - index - 1];
for(var i = this.length - 1; i >= 0; i--) {
if(_util.getType(this._args[i]) == type.name && index-- == 0) {
return this._args[i];
}
}
};
Arget.prototype.all = function (type) {
if(!type) return this.toArray();
var args = [];
for(var i = 0; i<this.length; i++) {
if(_util.getType(this._args[i]) == type.name) {
args.push(this._args[i]);
}
}
return args;
};
Arget.prototype.toArray = function () {
if(this._array) return this._array;
return this._array = Array.prototype.slice.call(this._args);
};
Arget.prototype.forEach = function (iteratee) {
this.toArray().forEach(iteratee);
};
Arget.prototype.each = Arget.prototype.forEach;
Arget.prototype.filter = function (predicate) {
return this.toArray().filter(predicate);
};
Arget.prototype.map = function (iteratee) {
return this.toArray().map(iteratee);
};
Arget.prototype.pick = function () {
var hash = _util.toKeys(( new Arget(arguments) ).map(type => type.name));
return this.filter(function (arg) {
return hash[_util.getType(arg)];
});
};
Arget.prototype.omit = function () {
var hash = _util.toKeys(( new Arget(arguments) ).map(type => type.name));
return this.filter(function (arg) {
return !hash[_util.getType(arg)];
});
};
Arget.prototype.match = function () {
var argsObject = this.map(arg => { return { arg }; })
, hash = _util.hashByType(argsObject)
, payload = ( new Arget(arguments) ).map(type => type && type.name)
, neutral = _util.matchFromHash(payload, hash);
for(var i = 0, obj; i < neutral.length; i++) {
do { obj = argsObject.shift(); } while (obj && obj.matched);
payload[neutral[i]] = obj ? obj.arg : undefined;
}
return payload;
};
Arget.prototype.matchRight = function () {
var argsObject = this.map(arg => { return { arg }; })
, hash = _util.hashRightByType(argsObject)
, payload = ( new Arget(arguments) ).map(type => type && type.name)
, neutral = _util.matchRightFromHash(payload, hash);
for(var i = 0, obj; i < neutral.length ; i++) {
do { obj = argsObject.pop(); } while (obj && obj.matched);
payload[neutral[i]] = obj ? obj.arg : undefined;
}
return payload;
};
Object.defineProperty(Arget.prototype, 'length', {
get : function () {
return this._args.length;
}
});
module.exports = function arget (args) {
return new Arget(args || arget.caller.arguments);
}; | 01c37548ad8e84f30b6e335d35f6fb7b1e9cc5d8 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | Javascipt/arget | 6960a6dff63bfe462d9026d3e5e7319623a19bab | 8d3ae733c02f250d7843e8009f40d43d84ae2396 |
refs/heads/main | <file_sep>
# ringcentral-notification-demo-ui-app
A demo integration(notification app) for RingCentral desktop/web app, as a demo, shows you how to create a notification app with UI to config for RingCentral.
Created with [notification-app-js](https://github.com/ringcentral/notification-app-js)
## DEV Prerequisites
- Download and install RingCentral app and login: https://www.ringcentral.com/apps/rc-app
- Nodejs 8.10+/npm, recommend using [nvm](https://github.com/creationix/nvm) to install nodejs/npm.
- If you want to create RingCentral Glip integration that can show in RingCentral Glip apps list, you need a RingCentral developer account that can create Glip integration: you need [sign up](https://developers.ringcentral.com/) and apply for the permission to create Glip integration.
- Need a account that can login to [app.ringcentral.com](https://app.ringcentral.com)
## Quick start
Let's start this simple RingCentral Glip integration that post messages to a Glip team you selected.
```bash
# install dependecies
npm i
# start proxy server, this will make your local bot server can be accessed by RingCentral service
npm run ngrok
# will show
Forwarding https://xxxx.ap.ngrok.io -> localhost:6066
# Remember the https://xxxx.ap.ngrok.io, we will use it later
```
Goto RingCentral app's App list, select **Incoming Webhook** app, and choose a team, and copy the webhook url for later use, and confirm install.
```bash
# create env file
cp .env.sample .env
# then edit .env,
# set https://xxxx.ap.ngrok.io as RINGCENTRAL_APP_SERVER
# set webhook url copied as STATIC_WEBHOOK
# run local dev server
npm start
# run client
npm run c
```
Then visit `https://ringcentral.github.io/ringcentral-notification-app-developer-tool?frameName=my-app&webhook=YOUR_WEBHOOK_URL&appUrl=https://xxxx.ap.ngrok.io` to check how would it work in RingCentral app.
## Deploy to AWS Lambda
```bash
cp deploy/env.sample.yml deploy/env.yml
cp deploy/serverless.sample.yml deploy/serverless.yml
# then edit deploy/env.yml and deploy/serverless.yml
# deploy
npm run deploy
```
More detail: https://github.com/ringcentral/glip-integration-js/blob/master/docs/deploy-to-lambda.md
<file_sep>import { useEffect, useRef, useState } from 'react'
import { Form, Button, Input } from 'antd'
import { RingCentralNotificationIntegrationHelper } from 'ringcentral-notification-integration-helper'
import qs from 'query-string'
const FormItem = Form.Item
const inIframe = window.top !== window
function getQuery () {
return qs.parse(window.location.search)
}
function getFrameName () {
const arr = window.location.href.match(/frameName=([\w-_\d]+)/)
return arr
? arr[1]
: ''
}
const q = getQuery()
export default function Options () {
const ref = useRef(null)
const [form] = Form.useForm()
const [authed, setter] = useState(false)
const state = {
msg: '',
webhook: q.webhook || ''
}
function onFinish (res) {
return window.axios.post(
window.rc.server + '/api/action',
res
)
}
function nofitfyCanSubmit (canSubmit) {
ref.current.send({ canSubmit })
}
function onChange () {
const values = form.getFieldsValue(true)
console.log('values', values)
nofitfyCanSubmit(!!(values.msg && values.webhook))
}
async function submit () {
const values = form.getFieldsValue(true)
await onFinish(values)
return {
status: true
}
}
function auth () {
window.open(window.rc.server + '/auth', getFrameName())
}
function onAuthCallack (e) {
console.log(e)
if (e && e.data && e.data.authDone) {
setter(true)
}
}
function init () {
window.addEventListener('message', onAuthCallack)
ref.current = new RingCentralNotificationIntegrationHelper()
ref.current.on('submit', submit)
}
useEffect(() => {
init()
}, [])
if (!authed) {
return (
<div className='wrap'>
<h1>Demo RingCentral notification app with UI</h1>
<p>
<Button type='primary' onClick={auth}>
Authorize
</Button>
</p>
</div>
)
}
return (
<div className='wrap'>
<h1>Demo RingCentral notification app with UI</h1>
<Form
form={form}
onFinish={onFinish}
initialValues={state}
>
<FormItem
label='Webhook'
hasFeedback
name='webhook'
rules={[{
required: true, message: 'webhook url required'
}]}
>
<Input
placeholder='Webhook url'
onChange={onChange}
/>
</FormItem>
<FormItem
label='Message'
hasFeedback
name='msg'
rules={[{
max: 128, message: '128 chars max'
}, {
required: true, message: 'message required'
}]}
>
<Input
placeholder='message will be send to RingCentral team'
onChange={onChange}
/>
</FormItem>
{
!inIframe
? (
<p className='pd1 hide'>
<Button
type='primary'
htmlType='submit'
>
Submit
</Button>
</p>
)
: null
}
</Form>
</div>
)
}
<file_sep>/**
* The most simple Glip integration
* Do not use it in production, demo only
* demo integration that send time stamp every one minute
*/
import func from './app'
// extends or override express app as you need
export const appExtend = func
| ee102dcf046727f50b4cd58cd81e83a37dfebfac | [
"Markdown",
"JavaScript"
] | 3 | Markdown | ringcentral/ringcentral-notification-demo-ui-app | cc0f39476dd865366768cffed1b3c13789fd5a72 | 8a49c41804c262449fc840e679a969aa5a52cce1 |
refs/heads/master | <file_sep>import hashlib,random, string
def verifyUserName(userName):
if len(userName)<3:
return False
elif len(userName)>20:
return False
else:
return True
def verifyPassword(password, password2):
count = 0
#Rule 1
for item in password:
if item == " ":
return False
break
else:
for item in password2:
if item == " ":
return False
break
# Rule 2
for p in password:
pas = [password, password2]
for p in pas:
if len(p)<3:
return False
break
elif len(p)>20:
return False
break
else: pass
if password==password2:
return True
else:
return False
def verifyEmail(email):
if len(email) == 0:
return True
countAt = 0
countDot = 0
# rule 1
if len(email)<3:
return False
elif len(email) > 20 :
return False
else:
for item in email:
if item == "@" :
countAt += 1
elif item == ".":
countDot += 1
elif item ==" ":
return False
else:
continue
if countAt != 1:
return False
elif countDot != 1:
return False
else:
return True
def makeSalt():
return "".join([random.choice(string.ascii_letters) for i in range(5)]).encode()
def hashPassword(password, salt = None):
if not salt:
salt = makeSalt()
return hashlib.sha256(password.encode() + salt).hexdigest(),salt.decode()
<file_sep>from flask import Flask, request, redirect, render_template, session,flash
import cgi
from flask_sqlalchemy import SQLAlchemy
from validateCode import * # this file contians all the verification codes
from datetime import datetime
app = Flask(__name__)
app.config["DEBUG"] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://Blogz:beHappy@localhost:8889/Blogz'
app.config["SQLALCHEMY_ECHO"] = True
db = SQLAlchemy(app)
app.secret_key = "<KEY>"
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(120),unique=True) #unique
hashPassword = db.Column(db.String(120))
saltPassword = db.Column(db.String(5))
email = db.Column(db.String(120))
record = db.Column(db.String(40))
blogs = db.relationship('Blog', backref='owner') # links class Blog to class User
def __init__(self, username,hashPassword, saltPassword, email = None):
self.username = username
self.hashPassword = <PASSWORD>
self.saltPassword = <PASSWORD>
self.email = email
self.record = datetime.now().strftime("%B - %d - %Y %H:%M:%S")
class Blog(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(120), unique=True) #unique
body = db.Column(db.String(1000))
record = db.Column(db.String(40))
owner_id = db.Column(db.Integer, db.ForeignKey('user.id')) # links class Blog to class User
def __init__(self, title, body, owner):
self.title = title
self.body =body
self.record = datetime.now().strftime("%B - %d - %Y %H:%M:%S")
self.owner = owner
@app.route("/signUp")
def signUpPage():
return render_template("signUp.html")
@app.route("/validate_signUP", methods = ["POST"])
def validateSignUp():
userName = request.form["username"]
passWord = request.form["password"]
passWord2 = request.form["<PASSWORD>2"]
email = request.form["email"]
if verifyUserName(userName) and verifyPassword(passWord,passWord2) and verifyEmail(email):
duplicate= ""
if not User.query.filter_by(username = userName).first():
hashedPassword, salt = hashPassword(passWord)
new_user = User( userName, hashedPassword, salt)
db.session.add(new_user)
db.session.commit()
session["user"] = userName
return redirect ("/welcome")
else:
duplicate = "User Name not avaliable. Please Choose a different User Name"
error1 = ""
error2 = ""
error3 = ""
if not verifyUserName(userName):
error1 = "invalid username"
if not verifyPassword(passWord, passWord2):
error2 = "invalid password"
if not verifyEmail(email):
error3 = "invalid email address"
return render_template("signUp.html", duplicate_error = duplicate, password_error = error2, name_error = error1, email_error = error3)
#welcome message after login
@app.route("/welcome")
def welcomeMsg():
del session["user"] # not sure if this is the right thing to do here but it gets the job done on so there's no stored session["user"] see base.html if statement
return render_template("welcome.html")
@app.before_request
def require_login():
allowed_routes = ["loginPage","signUpPage","validateLogin","validateSignUp","welcomeMsg"]
if request.endpoint not in allowed_routes and "user" not in session:
return redirect("/")
# shows the login page as the default page before login
@app.route("/")
def loginPage():
return render_template("login.html")
# validates login
@app.route("/validate_login", methods = ["POST"])
def validateLogin():
userName = request.form["username"]
passWord = request.form["password"]
user = User.query.filter_by(username = userName).first()
if user:
hashed_pw = user.hashPassword
salt_pw = user.saltPassword
if hashPassword(passWord, salt_pw.encode()) == (hashed_pw, salt_pw):
session["user"] = user.username
flash ("logged in as "+ session["user"])
all_blogs = Blog.query.all()
return render_template("allBlogs.html",all_blogs = all_blogs)
return render_template("login.html", error_message= "invalid login information")
#logout
@app.route("/logout")
def logout():
del session["user"]
flash ("you logged out")
return redirect("/")
#default addForm
@app.route("/newPost")
def addPostDefault():
return render_template("addPost.html")
#used to add individual posts after login
@app.route("/addPost", methods = ["POST"])
def addPost():
if request.form["blogTitle"] and request.form["blogBody"]:
title = request.form["blogTitle"]
body = request.form["blogBody"]
user = User.query.filter_by(username = session["user"]).first()
new_blog = Blog(title, body, user)
db.session.add(new_blog)
db.session.commit()
return render_template("newPost.html",pageTitle ="Blog Added Page", blogTitle = title, blogBody = body, record = new_blog.record )
else:
title_error = ""
body_error= ""
if not request.form["blogTitle"]:
title_error = "Please provide a title"
if not request.form["blogBody"]:
body_error = "Please provide a body"
return render_template("addPost.html",pageTitle ="Blog Added Page", title_error = title_error, body_error = body_error)
#show individual blog when link is clicked on
@app.route("/show")
def showPost():
blogID = request.args.get("id")
new_blog = Blog.query.filter_by(id = blogID).first()
return render_template("newPost.html",pageTitle ="requested post", blogTitle = new_blog.title, blogBody = new_blog.body, record = new_blog.record )
#displays all posted blogs by user and is also the main page after login
@app.route("/main")
def displayAllPost():
all_blogs = Blog.query.all()
return render_template("allBlogs.html", all_blogs = all_blogs)
@app.route("/show_user")
def display_user():
username = request.args.get("username")
user = User.query.filter_by(username = username).first()
return render_template ("allBlogs.html", all_blogs = user.blogs)
@app.route("/show_singel_users")
def displayAllUsers():
users = User.query.order_by(User.username).all()
return render_template ("singleusers.html", all_users = users)
if __name__ == "__main__":
app.run()
| a71e9554865a2cb3acdb93f782f57ecf2a523ee4 | [
"Python"
] | 2 | Python | IkeAndLogic/Blogz | 3b8add902ad396c1f82836dc07b2ff3442d1744d | f9fffef67a1b6d22154ffe1c94813e66a8d81896 |
refs/heads/master | <repo_name>zjupure/HttpCrawler<file_sep>/src/example/utils/UrlQueue.java
package example.utils;
import java.util.LinkedList;
/**
* Url队列,用来存放没有访问过的URL队列
* @author zjupure
*
*/
public class UrlQueue {
//队列中最多的超链接数量
public static final int MAX_SIZE = 10000;
//超链接队列
public LinkedList<String> urlQueue = new LinkedList<String>();
//入队
public void addElem(String url){
synchronized (this) {
urlQueue.add(url);
}
}
//出队
public String outElem(){
synchronized (this) {
return urlQueue.removeFirst();
}
}
//判空
public boolean isEmpty(){
synchronized (this) {
return urlQueue.isEmpty();
}
}
//返回队列的长度
public int size(){
synchronized (this) {
return urlQueue.size();
}
}
}
<file_sep>/src/example/http/Crawler.java
package example.http;
import java.util.ArrayList;
import example.sql.SqlHelper;
import example.utils.PageParser;
import example.utils.SimpleBloomFilter;
import example.utils.UrlQueue;
public class Crawler {
private String base_url;
private String base_img;
private String site_tags;
//链接队列,
public UrlQueue urlQueue = new UrlQueue(); //超链接的队列
public UrlQueue imgQueue = new UrlQueue(); //图片地址的队列
//bloom filter
public SimpleBloomFilter urlFilter = new SimpleBloomFilter();
public SimpleBloomFilter imgFilter = new SimpleBloomFilter();
//爬虫搜索深度,页面个数
public volatile int page_num = 0;
//数据库对象
public SqlHelper mSqlHelper;
//网络下载器
public HttpDownLoader mDownLoader;
//页面解析器
public PageParser mPageParser;
//特定标签
public String image_lable;
public Crawler(String url, String domain, String tags)
{
base_url = url;
base_img = domain;
site_tags = tags;
mSqlHelper = new SqlHelper();
mDownLoader = new HttpDownLoader(site_tags);
}
/**
* 执行线程
*/
public void execute(){
//先把站点首页下载下来,并解析出来,保证队列中有内容
String site_src = mDownLoader.downLoadPage(base_url);
mPageParser = new PageParser(site_src);
//处理链接
AddSuperLink();
AddImageLink(image_lable);
//建立任务并启动线程
for(int i = 1; i <= 2; i++){
UrlCrawlerTask urlTask = new UrlCrawlerTask();
Thread urlThread = new Thread(urlTask,"urlTask" + i);
urlThread.start();
ImgCrawlerTask imgTask = new ImgCrawlerTask();
Thread imgThread = new Thread(imgTask,"ImgTask" + i);
imgThread.start();
}
}
/**
* 设置标签属性
* @param lable
*/
public void setImageLable(String lable)
{
image_lable = lable;
}
/**
* 添加超链接
*/
public void AddSuperLink()
{
ArrayList<String> urlList = mPageParser.getSuperLink();
for(String url:urlList)
{
if(!urlFilter.contains(url))
{
urlQueue.addElem(base_url + url);
urlFilter.add(url);
//log out
System.out.println(url);
}
}
}
/**
* 添加图片链接
* @param attr
*/
public void AddImageLink(String attr)
{
ArrayList<String> urlList = mPageParser.getImageLink(attr);
for(String url:urlList)
{
if(url.contains(base_img) && !imgFilter.contains(url))
{
imgQueue.addElem(url);
imgFilter.add(url);
//log out
System.out.println(url);
}
}
}
/**
* 下载Url任务
*/
public class UrlCrawlerTask implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
//队列不为空,且没有达到搜索深度
while(!urlQueue.isEmpty()){
String url = urlQueue.outElem(); //取出链接
String site_src = mDownLoader.downLoadPage(url);
mPageParser.setPage(site_src);
AddSuperLink();
AddImageLink(image_lable);
}
}
}
/**
* 下载图片任务类
*
*/
public class ImgCrawlerTask implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
//超链接队列不为空,一直循环等待图片队列获取数据位置
while(!urlQueue.isEmpty()){
//当图片队列不为空,开始下载任务
while(!imgQueue.isEmpty()){
String url = imgQueue.outElem();
mDownLoader.downLoadImage(url);
}
}
}
}
}
<file_sep>/src/example/sql/SqlHelper.java
package example.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 数据库连接帮助类
* @author liuchun
*
*/
public class SqlHelper {
private Connection conn = null;
PreparedStatement statement = null;
private static String format = "INSERT INTO save_url "
+ "(name,type,url) "
+ "VALUES(\'%s\',\'%s\',\'%s\')";
public static void main(String[] args){
SqlHelper helper = new SqlHelper();
String sql = String.format(format, "abc","url","http://www.meizitu.com");
System.out.println(sql);
helper.updateSQL(sql);
}
//构造方法
public SqlHelper() {
// TODO Auto-generated constructor stub
String creatTable = "CREATE TABLE IF NOT EXISTS save_url(id int NOT NULL AUTO_INCREMENT,"
+ "name varchar(100) NOT NULL,"
+ "type char(10) NOT NULL,"
+ "url varchar(255) NOT NULL,"
+ "PRIMARY KEY (id))";
connSQL(); //连接数据库
updateSQL(creatTable); //第一次构造时自动创建一个表
}
/**
* 连接数据库
*/
public void connSQL(){
String driver = "com.mysql.jdbc.Driver"; //驱动名
String url = "jdbc:mysql://localhost:3306/spider?characterEncoding=UTF-8"; //连接地址
String username = "root";
String password = "<PASSWORD>";
//加载驱动程序以连接数据库
try{
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
}catch(ClassNotFoundException e){ //捕获加载驱动异常
// TODO: handle exception
System.err.println("装载 JDBC/ODBC 驱动程序失败");
e.printStackTrace();
}catch (SQLException e) { //捕获连接数据库异常
// TODO: handle exception
System.err.println("无法连接数据库");
e.printStackTrace();
}
}
/**
* 关闭数据库连接
*/
public void disConnSQL(){
try{
if(conn != null){
conn.close();
}
}catch(Exception e){
System.out.println("关闭数据库出现问题");
e.printStackTrace();
}
}
/**
* 执行SQL SELECT语句,返回结果集
* @param sql
* @return
*/
public ResultSet selectSQL(String sql){
ResultSet rs = null;
try{
//线程同步
synchronized (this) {
statement = conn.prepareStatement(sql);
rs = statement.executeQuery(sql);
}
}catch(SQLException e){
e.printStackTrace();
}
return rs;
}
/**
* 用于执行INSERT,UPDATE或DELETE语句以及SQL DDL语句
* 如 CREATE TABLE和DROP TABLE等
* @param sql
* @return
*/
public int updateSQL(String sql){
int res = 0;
try{
//线程同步
synchronized (this) {
statement = conn.prepareStatement(sql);
res = statement.executeUpdate(sql);
}
}catch(SQLException e){
e.printStackTrace();
}
return res;
}
}
<file_sep>/src/example/utils/PageParser.java
package example.utils;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import example.http.Crawler;
/**
* 页面解析,获取站点的url链接和图片链接
* @author zjupure
*
*/
public class PageParser {
//页面解析的Document模型
private Document doc;
/* 构造函数 */
public PageParser(String page) {
// TODO Auto-generated constructor stub
doc = Jsoup.parse(page);
}
/* 设置页面源代码 */
public void setPage(String page)
{
doc = Jsoup.parse(page);
}
/**
* 获取页面内的超链接
* @return
*/
public ArrayList<String> getSuperLink()
{
ArrayList<String> urlList = new ArrayList<String>();
Elements links = doc.select("a[href]"); // 获取所有的超链接
for(Element link: links)
{
String url = link.attr("href");
if(!url.startsWith("http") && !url.startsWith("https"))
urlList.add(url);
}
return urlList;
}
/**
* 获取特定标签下的图片链接
* @param attr
* @return
*/
public ArrayList<String> getImageLink(String attr)
{
ArrayList<String> urlList = new ArrayList<String>();
Elements links = doc.select(attr); // 获取所有标签
for(Element link: links)
{
String url = link.attr("abs:src");
urlList.add(url);
}
return urlList;
}
/**
* 获取特定标签下的文本
* @param attr
* @return
*/
public ArrayList<String> getText(String attr)
{
ArrayList<String> urlList = new ArrayList<String>();
Elements links = doc.select(attr); // 获取所有标签
for(Element link: links)
{
String url = link.text();
urlList.add(url);
}
return urlList;
}
}
| 0bc2cc2645102214e30d5878a775dae7fe946fb6 | [
"Java"
] | 4 | Java | zjupure/HttpCrawler | 77b5e276e05dc1ca76b25e21551ba1db48328617 | 424f4cce1e22c6f263ebeff3b51dda51cfca2bb4 |
refs/heads/master | <file_sep>#include <stdexcept>
#include "Header.h"
template <class T = int>
class Queue : public IQ<T>
{
bool isFull;
const size_t size;
size_t top_, bottom;
T *arr;
public:
Queue(size_t n = 100)
: isFull(false), size(n), top_(0), bottom(0), arr(new T[size])
{
}
bool empty()
{
return top_ == bottom && !isFull;
}
/*
void push(const T &val) {
if (isFull)
return;
arr[bottom] = val;
bottom = (bottom + 1) % size;
if (top_ == bottom)
isFull = true;
}
void pop() {
if (empty())
return;
isFull = false;
top_ = (top_ + 1) % size;
}
T &top() {
if (!empty())
return arr[top_];
else
throw std::out_of_range("queue is empty");
}
~Queue() {
delete[] arr;
}
};
extern "C"
{
__declspec(dllexport) IQ<> *GetSomeIQ()
{
return new Queue<>();
}
}
<file_sep># rep1
<file_sep>template <class T = int>
__interface __declspec(dllexport) IQ
{
void push(const T &val);
void pop();
T &top();
};
| 4efa3f42501baa02364c769f96d94d1539ef4a6d | [
"Markdown",
"C++"
] | 3 | C++ | 1998bagaev/rep1 | 31dd2734bf59c2e8b4a46642dfbe6357a3309bc0 | 9f4dbf9aee302325107063d3754c74ef58f31d39 |
refs/heads/master | <repo_name>addaskogberg/1dv23Exa2<file_sep>/models/snippet.js
/**
* model for snippets in mongodb
* author <NAME>
* ref
*/
const mongoose = require('mongoose')
const Schema = mongoose.Schema
// Create a schema, with customized error messages.
const snippetSchema = new Schema({
snippet: String,
user: String
})
// Create a model using the schema.
const Snippet = mongoose.model('Snippet', snippetSchema)
// Export the model.
module.exports = Snippet
<file_sep>/routes/routes.js
/**
* routes for snippets
* @author <NAME>
* @version 1.0
*/
const router = require('express').Router()
const Snippet = require('../models/snippet')
const User = require('../models/user')
/* Finds all snippets in db and returns them */
router.route('/')
.get(async (req, res) => {
try {
const snippets = await Snippet.find({}).exec()
res.render('layouts/home', { snippets, user: req.session.user })
} catch (error) {
res.render('layouts/home', {
flash: { type: 'danger', text: error.message },
snippets: []
})
}
})
// login user
router.route('/login')
.get((req, res) => {
try {
res.render('layouts/login', {user: req.session.user})
} catch (error) {
res.render('layouts/login', {
flash: { type: 'danger', text: error.message }
})
}
})
.post(async(req, res, next) => {
try {
let formusername = req.body.username
let formpassword = encrypt(req.body.password)
User.findOne({ username: formusername }, function (err, user) {
if (err) throw err
// test matching password
if (user.comparePassword(formpassword)) {
// Save to session
req.session.user = formusername
res.render('layouts/login', { user: req.session.user })
} else {
res.render('layouts/login', {
flash: { type: 'danger', text: 'Something went wrong signing in' }
})
}
})
} catch (error) {
return res.render('layouts/login', {
validationErrors: [error.message] || [error.errors.snippet.message],
username: req.body.username,
password: <PASSWORD>
})
}
})
// logout the user
router.route('/logout')
.get(async (req, res) => {
try {
delete req.session.user
res.render('layouts/home', {
flash: { type: 'success', text: 'Successfully logged out' }
})
} catch (error) {
res.render('layouts/home', {
flash: { type: 'danger', text: error.message }
})
}
})
/**
* create and save a snippet in mongodb
*/
router.route('/createsnippet')
.get(async (req, res) => {
if (req.session.user) {
res.render('layouts/createsnippet', {snippet: undefined, user: req.session.user})
} else {
req.session.flash = {type: 'danger', text: 'you need to login to create snippet'}
res.redirect('/login')
}
})
.post(async(req, res, next) => {
try {
let snippet = new Snippet({
snippet: req.body.snippet,
user: req.session.user
})
console.log(req.body.snippet)
await snippet.save()
req.session.flash = {type: 'success', text: 'Your snippet is saved'}
res.redirect('.')
} catch (error) {
return res.render('layouts/createsnippet', {
validationErrors: [error.message] || [error.errors.snippet.message],
snippet: req.body.snippet
})
}
})
// view snippet
router.route('/viewsnippet/:id')
.get(async (req, res) => {
const snippet = await Snippet.findOne({ _id: req.params.id })
if (req.session.user === snippet.user) {
res.render('layouts/viewsnippet', { snippet: snippet.snippet, id: snippet._id, user: req.session.user })
} else {
res.render('layouts/viewsnippet', { snippet: snippet.snippet, id: snippet._id })
}
})
// update snippet
router.route('/updatesnippet/:id')
.get(async (req, res) => {
const snippet = await Snippet.findOne({ _id: req.params.id })
if (req.session.user === snippet.user) {
res.render('layouts/updatesnippet', { snippet: snippet.snippet, id: snippet._id, user: req.session.user })
} else {
res.render('error/403')
}
})
.post(async(req, res, next) => {
try {
const snippet = await Snippet.findOne({ _id: req.body.dbid })
snippet.snippet = req.body.snippet
await snippet.save()
req.session.flash = {type: 'success', text: 'Your snippet was updated'}
res.redirect('/')
} catch (error) {
return res.render('layouts/updatesnippet', {
validationErrors: [error.message] || [error.errors.snippet.message],
snippet: req.body.snippet
})
}
})
// delete snippet
router.route('/deletesnippet/:id')
.get(async(req, res) => {
const snippet = await Snippet.findOne({ _id: req.params.id })
if (req.session.user === snippet.user) {
Snippet.deleteOne({ _id: req.params.id }, function (err) {
if (err) throw err
req.session.flash = {type: 'success', text: 'Your snippet was deleted'}
res.redirect('/')
})
} else {
res.render('error/403')
}
})
// create user
router.route('/user')
.get(async (req, res) => {
try {
res.render('layouts/user')
} catch (error) {
res.render('layouts/user', {
flash: { type: 'danger', text: error.message }
})
}
})
.post((req, res, next) => {
try {
let formusername = req.body.username
User.findOne({ username: formusername }, function (err, user) {
if (err) throw err
if (user === null) {
let user = new User({
username: req.body.username,
password: <PASSWORD>(<PASSWORD>)
})
user.save()
req.session.flash = {type: 'success', text: 'Your account has been created'}
res.redirect('.')
} else {
res.render('layouts/user', {
flash: {type: 'danger', text: 'Username Taken'}
})
}
})
} catch (error) {
return res.render('layouts/user', {
validationErrors: [error.message] || [error.errors.snippet.message],
username: req.body.username,
password: req.body.<PASSWORD>
})
}
})
// encrypt and add salt to password
function encrypt (password) {
password = password + '<PASSWORD>'
password = hashCode(password)
return String(password)
}
function hashCode (str) {
let len = str.length
let hash = 0
for (let i = 1; i <= len; i++) {
let char = str.charCodeAt((i - 1))
hash += char * Math.pow(31, (len - i))
hash = hash & hash // javascript limitation to force to 32 bits
}
return hash
}
// Exports.
module.exports = router
<file_sep>/app.js
/**
*
* @author <NAME>
* @version 1.0
*/
const express = require('express')
const bodyParser = require('body-parser')
const handlebars = require('express-handlebars')
const mongoose = require('./config/mongoose.js')
const session = require('express-session')
const helmet = require('helmet')
const app = express()
const path = require('path')
app.use(helmet())
app.set('port', process.env.PORT || 3000)
// Connect to mongodb.
mongoose.run().catch(error => {
console.error(error)
process.exit(1)
})
// set upp handlebars and view engine
app.engine('handlebars', handlebars({
defaultLayout: 'main'
}))
app.set('view engine', 'handlebars')
// Parse application encoding
app.use(bodyParser.urlencoded({ extended: true }))
// Setup session
const sessionOptions = {
name: 'authenticated user', // my reason to coookie
secret: 'myUser', // my secret
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
maxAge: 1000 * 60 * 30 // 30 minutes
}
}
if (app.get('env') === 'production') {
app.set('trust proxy', 1) // trust first proxy
sessionOptions.cookie.secure = true // serve secure cookies
}
// sessions
app.use(session(sessionOptions))
// Flash message
app.use((req, res, next) => {
res.locals.flash = req.session.flash
delete req.session.flash
next()
})
// Serve static files.
app.use(express.static(path.join(__dirname, 'public')))
// Define routes
app.use('/', require('./routes/routes.js'))
// 404 page
app.use(function (req, res, next) {
res.status(404)
res.render('error/404')
})
// 400 page
app.use(function (req, res, next) {
res.status(400)
res.render('error/400')
})
// 500 page
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500)
res.render('error/500')
})
// body-Parser
app.use(bodyParser.urlencoded({extended: true}))
app.listen(app.get('port'), function () {
console.log('Express started on http://localhost:' + app.get('port') + ' ; press ctrl-c to terminate')
})
<file_sep>/models/user.js
/**
* model for schemas in mongodb
* author <NAME>
* ref
* https://www.mongodb.com/blog/post/password-authentication-with-mongoose-part-1
*/
const mongoose = require('mongoose')
const Schema = mongoose.Schema
// user schema for mongodb
var userSchema = new Schema({
username: {
type: String,
required: true,
index: { unique: true }
},
password: {
type: String,
required: true }
})
// password schema for mongodb
userSchema.methods.comparePassword = function (candidatePassword) {
if (candidatePassword === this.password) {
return true
} else {
return false
}
}
const User = mongoose.model('User', userSchema)
// module.exports = mongoose.model(User&, UserSchema);
module.exports = User
| 624abc05c94695ee5a8609aec65a6fa0bb4d1379 | [
"JavaScript"
] | 4 | JavaScript | addaskogberg/1dv23Exa2 | fbe3a6882d505af6509222d143151830e9e23b5e | b552c4e2bc2c8591280049a7c1d83c6a1ac05dcf |
refs/heads/master | <file_sep>/** @format */
import React from 'react';
import { Text, View, AppRegistry } from 'react-native';
import { name as appName } from './app.json';
import Header from './src/components/header';
const App = () => (
<View style={{ flex: 1 }}>
<Header title="I care because you do" />
<Text>Hello</Text>
</View>
);
AppRegistry.registerComponent(appName, () => App);
| 7ba0749e924b159d7b9a9b28470f8d8b34c85854 | [
"JavaScript"
] | 1 | JavaScript | sukhajata/albums | b6ffba4bc9ea57ac381921c07af02bd0c3e1d8c6 | e45fbbddd8d6b6044d2cd16921bacb5535b917ae |
refs/heads/master | <repo_name>ilk15/FireEmblem<file_sep>/FireEmblemGame/Assets/_Scripts/TileGridEditor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TileGrid))]
[CanEditMultipleObjects]
public class TileGridEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
TileGrid maker = (TileGrid)target;
if (GUILayout.Button("make grid"))
{
maker.make();
}
}
}
<file_sep>/README.md
# FireEmblem
Fan project
<file_sep>/FireEmblemGame/Assets/_Scripts/CameraController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public GameObject target;
private float vSize, hSize;
private GameObject tile;
void Start()
{
vSize = 2*gameObject.GetComponent<Camera>().orthographicSize;
hSize = vSize * gameObject.GetComponent<Camera>().aspect;
tile = Adjacency.TileOf(gameObject);
transform.position = new Vector3(tile.transform.position.x, tile.transform.position.y, transform.position.z);
}
// Update is called once per frame
void Update()
{
if (target.transform.position.x< transform.position.x - hSize/2)
{
tile = Adjacency.TileLeft(tile);
transform.position = new Vector3(tile.transform.position.x, tile.transform.position.y, transform.position.z);
}
else if (target.transform.position.x > transform.position.x + hSize / 2)
{
tile = Adjacency.TileRight(tile);
transform.position = new Vector3(tile.transform.position.x, tile.transform.position.y, transform.position.z);
}
else if (target.transform.position.y < transform.position.y - vSize / 2)
{
tile = Adjacency.TileDown(tile);
transform.position = new Vector3(tile.transform.position.x, tile.transform.position.y, transform.position.z);
}
else if (target.transform.position.y > transform.position.y + vSize / 2)
{
tile = Adjacency.TileUp(tile);
transform.position = new Vector3(tile.transform.position.x, tile.transform.position.y, transform.position.z);
}
}
}
<file_sep>/FireEmblemGame/Assets/_Scripts/Cursor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cursor : MonoBehaviour
{
public GameObject currentTile, currentUnit, selectedUnit;
private float timePassed;
private float delay = 0.3f;
private bool active, selected = false;
// Start is called before the first frame update
void Start()
{
currentTile = Adjacency.TileOf(gameObject);
currentUnit = Adjacency.UnitOn(currentTile);
}
private void Update()
{
transform.position = currentTile.transform.position;
currentTile = Adjacency.TileOf(gameObject);
currentUnit = Adjacency.UnitOn(currentTile);
timePassed = timePassed + Time.deltaTime;
if (!active)
{
active = true;
if (Input.GetAxis("Vertical") > 0 && Adjacency.TileUp(currentTile) != null && timePassed > delay)
{
currentTile = Adjacency.TileUp(currentTile);
timePassed = 0;
}
else if (Input.GetAxis("Horizontal") < 0 && Adjacency.TileLeft(currentTile) != null && timePassed > delay)
{
currentTile = Adjacency.TileLeft(currentTile);
timePassed = 0;
}
else if (Input.GetAxis("Vertical") < 0 && Adjacency.TileDown(currentTile) != null && timePassed > delay)
{
currentTile = Adjacency.TileDown(currentTile);
timePassed = 0;
}
else if (Input.GetAxis("Horizontal") > 0 && Adjacency.TileRight(currentTile) != null && timePassed > delay)
{
currentTile = Adjacency.TileRight(currentTile);
timePassed = 0;
}
if (Input.GetButtonDown("Submit") && currentUnit != null && ! selected && ! currentUnit.GetComponent<Unit>().HasActed())
{
selected = true;
selectedUnit = currentUnit;
Debug.Log("selected");
foreach (GameObject tile in (selectedUnit.GetComponent<Unit>() as Unit).ReachableTiles())
{
tile.GetComponent<SpriteRenderer>().enabled = true;
}
}
if (Input.GetButtonDown("Submit") && currentUnit == null && selected)
{
if ((selectedUnit.GetComponent<Unit>() as Unit).ReachableTiles().Contains(currentTile))
{
foreach (GameObject tile in (selectedUnit.GetComponent<Unit>() as Unit).ReachableTiles())
{
tile.GetComponent<SpriteRenderer>().enabled = false;
}
selectedUnit.transform.position = currentTile.transform.position;
selected = false;
selectedUnit.GetComponent<Unit>().EndAction();
}
else
Debug.Log("not in range");
}
active = false;
}
}
}
<file_sep>/FireEmblemGame/Assets/_Scripts/TileGrid.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class TileGrid : MonoBehaviour
{
public float gridSize;
private int hCells, vCells;
public GameObject bottomLeft, topRight;
public GameObject tilePrefab;
private GameObject[,] grid;
bool active;
public void make()
{
if (active)
return;
else
{
active = true;
hCells = (int)(Math.Abs(bottomLeft.transform.position.x - topRight.transform.position.x) / gridSize);
vCells = (int)(Math.Abs(bottomLeft.transform.position.y - topRight.transform.position.y) / gridSize);
grid = new GameObject[hCells+1, vCells+1];
for (int i = 0; i <= hCells; i++)
{
for (int j = 0; j <= vCells; j++)
{
grid[i, j] = Instantiate(tilePrefab, new Vector3(bottomLeft.transform.position.x + i * gridSize, bottomLeft.transform.position.y + j * gridSize, bottomLeft.transform.position.z), Quaternion.identity, transform) as GameObject;
}
}
}
}
}
<file_sep>/FireEmblemGame/Assets/_Scripts/Unit.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Unit : MonoBehaviour
{
public string Name;
public string Class;
public GameObject currentTile;
public int Level;
public int Exp;
public int HP;
public int Luck;
public int Str;
public int Def;
public int Skill;
public int Res;
public int Spd;
public int Con;
public int Aid;
public int HPGrw;
public int LuckGrw;
public int StrGrw;
public int DefGrw;
public int SkillGrw;
public int ResGrw;
public int SwordExp;
public int AxeExp;
public int LanceExp;
public int BowExp;
public int DarkExp;
public int LightExp;
public int AnimaExp;
public int StaffExp;
public GameObject item_1;
public GameObject item_2;
public GameObject item_3;
public GameObject item_4;
public GameObject item_5;
private bool isDead;
private bool hasActed;
public static char WeaponRank(int WExp)
{
if (WExp >= 1 && WExp < 31)
return 'E';
else if (WExp >= 31 && WExp < 71)
return 'D';
else if (WExp >= 71 && WExp < 121)
return 'C';
else if (WExp >= 121 && WExp < 181)
return 'B';
else if (WExp >= 181 && WExp < 251)
return 'A';
else if (WExp >= 251)
return 'S';
else
return '-';
}
private static int TileCost(GameObject tile)
{
if (tile.tag == "Plain")
return 1;
else if (tile.tag == "River")
return int.MaxValue;
else if (tile.tag == "Cliff")
return int.MaxValue;
else
return 1;
}
public void Damage(int dmg)
{
HP = HP - dmg;
if (HP <= 0)
isDead = true;
}
public void Attack(GameObject unit)
{
if (unit.layer != 9)
{
Debug.Log("thats no unit...");
}
else
{
unit.GetComponent<Unit>().Damage(1);
}
}
public bool IsDead()
{
return isDead;
}
public bool HasActed()
{
return hasActed;
}
public void EndAction()
{
hasActed = true;
}
public void Refresh()
{
hasActed = false;
}
public List<GameObject> ReachableTiles()
{
return TilesReachableFrom(currentTile, Spd);
}
private List<GameObject> TilesReachableFrom(GameObject tile, int movement)
{
if (tile.layer != 8)
return null;
else
{
List<GameObject> output = new List<GameObject>();
output.Add(tile);
if (Adjacency.TileUp(tile) != null && movement >= TileCost(Adjacency.TileUp(tile)))
{
output.AddRange(TilesReachableFrom(Adjacency.TileUp(tile), movement- TileCost(Adjacency.TileUp(tile))));
}
if (Adjacency.TileDown(tile) != null && movement >= TileCost(Adjacency.TileDown(tile)))
{
output.AddRange(TilesReachableFrom(Adjacency.TileDown(tile), movement - TileCost(Adjacency.TileDown(tile))));
}
if (Adjacency.TileLeft(tile) != null && movement >= TileCost(Adjacency.TileLeft(tile)))
{
output.AddRange(TilesReachableFrom(Adjacency.TileLeft(tile), movement - TileCost(Adjacency.TileLeft(tile))));
}
if (Adjacency.TileRight(tile) != null && movement >= TileCost(Adjacency.TileRight(tile)))
{
output.AddRange(TilesReachableFrom(Adjacency.TileRight(tile), movement - TileCost(Adjacency.TileRight(tile))));
}
return output;
}
}
private void Update()
{
currentTile = Adjacency.TileOf(gameObject);
if (HasActed())
{
GetComponent<SpriteRenderer>().material.color = Color.grey;
}
else
{
GetComponent<SpriteRenderer>().material.color = Color.white;
}
}
}
<file_sep>/FireEmblemGame/Assets/_Scripts/adjacency.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Adjacency
{
public static float gridSize = 0.16f;
public static List<GameObject> AdjacentTiles(GameObject currentTile)
{
List<GameObject> list = new List<GameObject>();
if (currentTile.layer != 8)
{
return null;
}
else
{
foreach (Collider2D col in Physics2D.OverlapCircleAll(currentTile.transform.position, gridSize * 0.6f))
{
if (col.gameObject.layer == 8)
{
list.Add(col.gameObject);
}
}
return list;
}
}
public static GameObject TileUp(GameObject currentTile)
{
GameObject output = null;
foreach (Collider2D col in Physics2D.OverlapCircleAll(currentTile.transform.position+new Vector3(0, gridSize,0), gridSize * 0.2f))
{
if (col.gameObject.layer == 8)
{
output = col.gameObject;
}
}
return output;
}
public static GameObject TileDown(GameObject currentTile)
{
GameObject output = null;
foreach (Collider2D col in Physics2D.OverlapCircleAll(currentTile.transform.position - new Vector3(0, gridSize, 0), gridSize * 0.2f))
{
if (col.gameObject.layer == 8)
{
output = col.gameObject;
}
}
return output;
}
public static GameObject TileLeft(GameObject currentTile)
{
GameObject output = null;
foreach (Collider2D col in Physics2D.OverlapCircleAll(currentTile.transform.position - new Vector3(gridSize, 0, 0), gridSize * 0.2f))
{
if (col.gameObject.layer == 8)
{
output = col.gameObject;
}
}
return output;
}
public static GameObject TileRight(GameObject currentTile)
{
GameObject output = null;
foreach (Collider2D col in Physics2D.OverlapCircleAll(currentTile.transform.position + new Vector3(gridSize, 0, 0), gridSize * 0.2f))
{
if (col.gameObject.layer == 8)
{
output = col.gameObject;
}
}
return output;
}
public static GameObject UnitOn(GameObject currentTile)
{
GameObject output = null;
foreach (Collider2D col in Physics2D.OverlapCircleAll(currentTile.transform.position, gridSize * 0.2f))
{
if (col.gameObject.layer == 9)
{
output = col.gameObject;
}
}
return output;
}
public static GameObject TileOf(GameObject currentTile)
{
GameObject output = null;
foreach (Collider2D col in Physics2D.OverlapCircleAll(currentTile.transform.position, gridSize * 0.2f))
{
if (col.gameObject.layer == 8)
{
output = col.gameObject;
}
}
return output;
}
}
| 86472ca94463ee96db329d2d6e7516d79d27b888 | [
"Markdown",
"C#"
] | 7 | C# | ilk15/FireEmblem | f3ce80abb82c13a9a4e62cc5ac64ce1a58da71b9 | 93367b66820be1ad6af59b78d691998efb9e4df2 |
refs/heads/master | <file_sep>var Dragify, Handler, MiniEventEmitter,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
MiniEventEmitter = require("mini-event-emitter");
Handler = require("./handler");
Dragify = (function(superClass) {
extend(Dragify, superClass);
function Dragify(containers, options) {
var msg, ref, ref1, x, y;
this.containers = containers;
Dragify.__super__.constructor.apply(this, arguments);
if (!options) {
if (!!this.containers && this.containers.constructor === Object) {
options = this.containers;
this.containers = [];
} else if (!!this.containers && this.containers.constructor === Array) {
options = {};
} else {
this.containers = [];
options = {};
}
} else {
if (!this.containers || this.containers.constructor !== Array) {
this.containers = [];
}
if (options.containers) {
this.containers = this.containers.concat(options.containers);
}
}
if (this.containers.length === 0 && (options.isContainer == null)) {
msg = "Dragify ~ You provided neither the `containers` array nor the 'isContainer` function. At least one is required.";
if (console.warn) {
console.warn(msg);
} else {
console.log(msg);
}
return;
}
this.options = {
threshold: {
x: 3,
y: 3
},
transition: true,
isContainer: function(el) {
return false;
},
excludes: ["INPUT", "TEXTAREA", "LABEL"]
};
if (options.transition != null) {
this.options.transition = options.transition;
}
if ((x = (ref = options.threshold) != null ? ref.x : void 0) != null) {
this.options.threshold.x = x;
}
if ((y = (ref1 = options.threshold) != null ? ref1.y : void 0) != null) {
this.options.threshold.y = y;
}
if (options.isContainer != null) {
this.options.isContainer = options.isContainer;
}
if (options.excludes != null) {
this.options.excludes = options.excludes;
}
new Handler(this);
}
return Dragify;
})(MiniEventEmitter);
module.exports = Dragify;
<file_sep><p align="center">
<a target="_blank" href="https://travis-ci.org/hawkerboy7/dragify">
<img src="https://img.shields.io/travis/hawkerboy7/dragify.svg?branch=master">
</a>
<a target="_blank" href="https://david-dm.org/hawkerboy7/dragify#info=devDependencies&view=table">
<img src="https://img.shields.io/david/hawkerboy7/dragify.svg">
</a>
<a target="_blank" href="https://www.codacy.com/app/dunk_king7/dragify/dashboard">
<img src="https://img.shields.io/codacy/grade/8cd2ff21ecb545d9b378336a26704532.svg">
</a>
<a target="_blank" href="https://gitter.im/hawkerboy7/dragify">
<img src="https://img.shields.io/badge/Gitter-JOIN%20CHAT%20%E2%86%92-1dce73.svg">
</a>
</p>
# Dragify
> Turn your plain DOM elements into drag queens
## What is it?
`Dragify` will turn elements in the DOM into dragable elements.
It triggers hardware acceleration by using the css3 `transform` and `will-change`.
This should help to optimize performance when dragging elements with a lot of content on large pages.
## Features
- Easy to set up
- Uses hardware acceleration
- The possibility to provide a [**threshold**][1]
- The 'to-be-dragged' element provide a clean visual feedback while dragging and dropping
## Install
```
npm install dragify --save
```
## Usage
```js
// Only containers
var dragify = new Dragify(containers);
// Only options
var dragify = new Dragify(options);
// Both containers and options
var dragify = new Dragify(containers,options);
```
### `Containers`
`containers` is an array of the parents of the DOM elements you wish to `Dragify`.
```html
<div class="parent-one">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
<div class="parent-two">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
```
```js
containers = [
document.getElementsByClassName("parent-one")[0],
document.getElementsByClassName("parent-two")[0]
]
var dragify = new Dragify(containers);
```
### `Options`
#### `Options.threshold`
The threshold option was created to make sure a **click** on a element **does not turn into a drag** because the user cannot keep the mouse steady during the click.
Lots of users want to click on an element but instead drag it, even though it is just a little distance.
This threshold option allows you to determine how much a user is allowed to move **before** the actual drag starts.
As long as the drag does not start all events the element is listening for will still be triggered as if the drag attempt has not happened yet.
By default a threshold of `3px` is applied in both directions.
```js
options = {
threshold: {
x: 20,
y: 20
}
}
var dragify = new Dragify(options);
```
*The user can now mousedown on an element and move the mouse 20px left right up and down from its original starting point before the actual drag will start.*
#### `Options.transition`
While dragging an element that element will be in transition. Its opacity will drop to `0.3`. When the element is dropped the element's opacity will become `1.0` again.
By default this change in opacity will have a transition. However on `drop` the className `dragify--transition` (which enables this transition) will still be shown on the element due to the time it
takes for the transition to finish. If you do not want this class to be added you can disable the transition class by setting this value to `false`.
By default the transition is set to `true`.
```js
options = {
transition: false
}
var dragify = new Dragify(options);
```
*Now the transitions class will not be added. Ofcourse you can still add the transition properties to the element directly.*
#### `Options.isContainer`
When you initialize `Dragify` you provide containers which contain children to be dragged. However if you have dynamic children and or containers the new elements will not be `Dragified`.
If you provide the `isContainer` options you can define a function which determines if an element is a valid `Dragify` parent.
The first argument `el` in `isContainer` can be used to check the DOM elements up the tree from the click target.
The second argument `ev` can be used to investigate the mousedown event on the target.
```js
options = {
isContainer: function (el, ev) {
return el.classList.contains('dragify--container') && ev.ctrlKey;
}
}
var dragify = new Dragify(options);
```
*Now any element at any point in time will be a valid Dragify container if it contains the class `dragify--container` and crtl is pressed while attempting to drag*
#### `Options.excludes`
Excludes are DOM elements dragify will ignore. By default `excludes` contains `[INPUT, TEXTAREA, LABEL]`.
```js
options = {
excludes: ["DIV"]
}
var dragify = new Dragify(options);
```
*Now all DIV's will be ignored by Dragify while attempting to drag*
### Events
You can listen to the following events
```js
var dragify = new Dragify(containers,options);
dragify.on('drag', function(){console.log('drag');});
dragify.on('move', function(){console.log('move');});
dragify.on('drop', function(){console.log('drop');});
dragify.on('cancel', function(){console.log('cancel');});
dragify.on('end', function(){console.log('end');});
```
Event Name | Listener Arguments | Event Description
-----------|--------------------------------|-------------------
`drag` | `el, source` | `el` was lifted from `source`
`move` | `el, parent, source, replaced` | `el` changed position and now has parent `parent` and originally came from `source`. If defined `replaced` was replaced by `el`.
`drop` | `el, parent, source` | `el` was dropped into `parent`, and originally came from `source`
`cancel` | `el, source` | `el` was dragged but ended up at it's original position in the original `source`
`end` | `el` | Dragging event for `el` ended with either `cancel` or `drop`
## Inspiration
I have used [Dragula][2] and liked its simplicity but I wanted hardware acceleration and a threshold.
The lack of these functionalities in dragula causes some discomfort for my own use cases.
If required I will try to add more of the functionality that Dragula provides, however I do not focus on supporting < IE11.
PR's for supporting < IE11 however I will take into consideration.
[1]: #optionsthreshold
[2]: https://github.com/bevacqua/dragula/
<file_sep>require('de-builder')({
browserSync: {
enabled: false
},
type: 3
});
<file_sep>var Error, Handler,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Error = require("./error");
Handler = (function() {
function Handler(dragify) {
this.dragify = dragify;
this.mousemove = bind(this.mousemove, this);
this.mousedown = bind(this.mousedown, this);
this.mouseup = bind(this.mouseup, this);
this.load();
this.setup();
this.listeners();
}
Handler.prototype.load = function() {
return this.error = (new Error({
dragify: this.dragify
})).error;
};
Handler.prototype.setup = function() {
this.dragify.settings.name = "Dragify";
if (!this.dragify.containers) {
this.dragify.containers = [];
}
if (this.dragify.containers.constructor !== Array) {
return this.error(1.1);
}
if (!typeof this.dragify.options.isContainer === "function") {
return this.error(1.2);
}
this.setData();
return this.create();
};
Handler.prototype.setData = function() {
this.data = {
index: null,
start: {},
offset: {},
source: null,
parent: null,
treshhold: {}
};
return this.previous = {};
};
Handler.prototype.listeners = function() {
window.addEventListener("mouseup", this.mouseup);
return window.addEventListener("mousedown", this.mousedown);
};
Handler.prototype.mouseup = function(e) {
if (e.button !== 0) {
return;
}
window.removeEventListener("mousemove", this.mousemove);
if (this.active) {
return this.reset();
}
};
Handler.prototype.mousedown = function(ev) {
var check, exclude, found, i, len, ref, x, y;
this.ev = ev;
if (this.ev.button !== 0 || this.active) {
return;
}
ref = this.dragify.options.excludes;
for (i = 0, len = ref.length; i < len; i++) {
exclude = ref[i];
if (this.ev.target.tagName === exclude) {
return;
}
}
if (!(this.node = this.validMousedown(this.ev.target))) {
return;
}
this.data.source = this.node.parentNode;
this.data.index = this.getIndex(this.node);
this.data.start.x = this.ev.clientX;
this.data.start.y = this.ev.clientY;
x = this.ev.offsetX;
y = this.ev.offsetY;
found = false;
check = (function(_this) {
return function(target) {
if (target === _this.node) {
return;
}
x += target.offsetLeft;
y += target.offsetTop;
if (target.parentNode) {
return check(target.parentNode);
}
return true;
};
})(this);
if (check(this.ev.target)) {
return this.error(2.1);
}
this.data.offset = {
x: x,
y: y
};
return window.addEventListener("mousemove", this.mousemove);
};
Handler.prototype.validMousedown = function(target) {
var check, validate;
check = (function(_this) {
return function(el) {
var e;
try {
return _this.validContainer(el);
} catch (error) {
e = error;
return false;
}
};
})(this);
validate = function(node) {
if (check(node.parentNode)) {
return node;
}
if (node.parentNode) {
return validate(node.parentNode);
}
return false;
};
return validate(target);
};
Handler.prototype.validContainer = function(el) {
if (!el || el === document) {
return false;
}
return this.dragify.containers.indexOf(el) !== -1 || this.dragify.options.isContainer(el, this.ev);
};
Handler.prototype.getIndex = function(node) {
var child, i, index, len, ref;
ref = node.parentNode.childNodes;
for (index = i = 0, len = ref.length; i < len; index = ++i) {
child = ref[index];
if (child === node) {
return index;
}
}
return null;
};
Handler.prototype.mousemove = function(e1) {
this.e = e1;
this.e.preventDefault();
this.e.X = this.e.clientX;
this.e.Y = this.e.clientY;
if (!this.active) {
if (Math.abs(this.e.X - this.data.start.x) > this.dragify.options.threshold.x) {
this.active = true;
}
if (Math.abs(this.e.Y - this.data.start.y) > this.dragify.options.threshold.y) {
this.active = true;
}
if (!this.active) {
return;
}
this.set();
}
if (this.active) {
return this.position();
}
};
Handler.prototype.position = function() {
var target;
this.mirror.style.transform = "translate(" + (this.e.X - this.data.offset.x) + "px," + (this.e.Y - this.data.offset.y) + "px)";
target = document.elementFromPoint(this.e.X, this.e.Y);
if (target && target === this.previous.target) {
return;
}
this.previous.target = target;
if (!(target = this.validParent(target))) {
return;
}
if (target === this.previous.valid) {
return;
}
if (this.node === target) {
return;
}
this.previous.valid = target;
return this["switch"](target);
};
Handler.prototype.validParent = function(target) {
var find, valid;
if (!target) {
return;
}
valid = false;
if (this.validContainer(target)) {
valid = target;
}
find = (function(_this) {
return function(el) {
if (_this.validContainer(el.parentNode)) {
return valid = el;
} else {
if (el.parentNode) {
return find(el.parentNode);
}
}
};
})(this);
if (!valid) {
find(target);
}
return valid;
};
Handler.prototype["switch"] = function(target1) {
this.target = target1;
if (this.validContainer(this.target)) {
if (this.node.parentNode !== this.target) {
this.transfer();
}
return;
}
if (this.target.parentNode !== this.node.parentNode || (this.getIndex(this.node)) > (this.getIndex(this.target))) {
return this.insert(this.target.parentNode, this.node, this.target);
} else {
return this.insert(this.target.parentNode, this.node, this.target.nextSibling);
}
};
Handler.prototype.insert = function(parent, node, target) {
var replaced;
parent.insertBefore(node, target);
replaced = this.target !== parent ? this.target : void 0;
return this.dragify.emitIf("move", this.node, this.node.parentNode, this.data.source, replaced);
};
Handler.prototype.transfer = function() {
var below, child, i, index, len, lower, lowest, ref, ref1, target, val;
lowest = null;
ref = this.target.childNodes;
for (index = i = 0, len = ref.length; i < len; index = ++i) {
child = ref[index];
ref1 = this.distance({
top: child.offsetTop,
bottom: child.offsetTop + child.clientHeight
}), val = ref1[0], lower = ref1[1];
if (!lowest || val < lowest) {
lowest = val;
target = child;
below = lower;
}
}
if (this.target.childNodes[this.target.childNodes.length - 1] === target && below) {
target = null;
}
return this.insert(this.target, this.node, target);
};
Handler.prototype.distance = function(pos) {
var below, bottom, val, y;
below = false;
y = this.e.offsetY;
val = Math.abs(y - pos.top);
if (val > (bottom = Math.abs(y - pos.bottom))) {
val = bottom;
}
return [val, y > pos.bottom];
};
Handler.prototype.create = function() {
this.mirror = document.createElement("div");
this.mirror.tabIndex = 0;
return this.mirror.className = "dragify--mirror";
};
Handler.prototype.set = function() {
var clone;
this.previous.valid = this.node.parentNode;
this.dragify.emitIf("drag", this.node, this.node.parentNode);
this.mirror.appendChild(clone = this.node.cloneNode(true));
clone.style.width = this.node.offsetWidth + "px";
clone.style.height = this.node.offsetHeight + "px";
document.body.appendChild(this.mirror);
this.mirror.focus();
this.addClass(document.body, "dragify--body");
if (this.dragify.options.transition) {
this.addClass(this.node, "dragify--transition");
}
return this.addClass(this.node, "dragify--opaque");
};
Handler.prototype.reset = function() {
var remove;
this.active = false;
while (this.mirror.firstChild) {
this.mirror.removeChild(this.mirror.firstChild);
}
document.body.removeChild(this.mirror);
this.mirror.removeAttribute("style");
this.removeClass(document.body, "dragify--body");
this.removeClass(this.node, "dragify--opaque");
remove = (function(_this) {
return function(node) {
return setTimeout(function() {
return _this.removeClass(node, "dragify--transition");
}, 500);
};
})(this);
if (this.dragify.options.transition) {
remove(this.node);
}
if (this.data.source === this.node.parentNode && this.data.index === this.getIndex(this.node)) {
this.dragify.emitIf("cancel", this.node, this.node.parentNode);
} else {
this.dragify.emitIf("drop", this.node, this.node.parentNode, this.data.source);
}
this.dragify.emitIf("end", this.node);
this.node = null;
this.target = null;
return this.setData();
};
Handler.prototype.addClass = function(node, className) {
var classes;
classes = [];
if (node.className) {
classes = node.className.split(" ");
}
classes.push(className);
return node.className = classes.join(" ");
};
Handler.prototype.removeClass = function(node, className) {
var classes;
classes = node.className.split(" ");
classes.splice(classes.indexOf(className), 1);
if (classes.length === 0) {
return node.removeAttribute("class");
} else {
return node.className = classes.join(" ");
}
};
return Handler;
})();
module.exports = Handler;
<file_sep>var Error;
Error = (function() {
function Error(dragify) {
var ref;
this.dragify = dragify;
this.block = !((ref = this.dragify.options) != null ? ref.error : void 0);
}
Error.prototype.error = function(id) {
var msg;
if (this.block) {
return;
}
msg = "Dragify ~ ";
if (id === 1.1) {
msg += "First argument 'Containers' must be an array";
}
if (id === 1.2) {
msg += "'isContainer' must be a function";
}
if (id === 2.1) {
msg += "Dragify was unable to find the correct offset, please report an issue on https://github.com/hawkerboy7/dragify/issues/new. Please provide an example in which this error occurs";
}
if (console.warn) {
return console.warn(msg);
} else {
return console.log(msg);
}
};
return Error;
})();
module.exports = Error;
| f62383934ada4c5f7abca76a63f06495b4008141 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | hawkerboy7/dragify | dc4290e653a8edce996ea53fa692d073c539e056 | 7d8247df7f55c29f3871bcf04399d6f00c8336a6 |
refs/heads/master | <repo_name>Kushagraupadhyay/Guvi<file_sep>/Beginner/Set1/helloprint.cpp
#include<iostream>
#include<cstdio>
using namespace std;
bool arraypass(char x[])
{
int i = 0,j,flag=0;
while (x[i] != '\0')
{
++i;
}
for(j=0;j<i;j++)
{
if(isdigit(x[j])==0)
{
flag=1;
break;
}
}
if(flag==0)
{
return true;
}
else
return false;
}
int main()
{
int a,i;
char x[10],y;
scanf("%s",&x);
if(arraypass(x))
{
a=atoi(x);
if(a<0)
{
printf("Invalid Input");
}
else if(a==0)
{
printf("");
}
else {
for(i=0;i<a;i++)
{
printf("Hello\n");
}
}
}
else
printf("Invalid Input");
return 0;
}
<file_sep>/Hunter/pickcurrentdeleteneighbour.cpp
#include<iostream>
int main()
{
int n,a[50],sum=0,i,flag=0,max,index;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
while(flag==0)
{
max=0;
for(i=0;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
index=i;
}
}
a[index]=0;
a[index+1]=0;
a[index-1]=0;
if(max==0)
{
flag=1;
break;
}
else
{
sum+=max;
}
}
printf("%d",sum);
return 0;
}
<file_sep>/Beginner/Set1/vowelorconsonent.cpp
#include <iostream>
int main()
{
char x;
scanf("%c",&x);
if((x>='a' && x<='z')||(x>='A' && x<='Z'))
{
if(x=='a'||x=='A'||x=='e'||x=='E'||x=='i'||x=='I'||x=='o'||x=='O'||x=='u'||x=='U')
printf("Vowel");
else
printf("Consonent");
}
else
printf("Invalid Input");
return 0;
}
<file_sep>/Hunter/longestincreasingsusequence.cpp
#include<iostream>
int main()
{
int a[50],n,noe=0,i,count,maxsubset,b[50],z;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
count=1;
maxsubset=a[0];
for(i=1;i<n;i++)
{
if(a[i]>=maxsubset)
{
maxsubset=a[i];
count++;
}
else
{
maxsubset=a[i];
b[noe]=count;
noe++;
count=1;
}
}
b[noe]=count;
z=b[0];
for(i=1;i<=noe;i++)
{
if(b[i]>z)
{
z=b[i];
}
}
printf("%d",z);
return 0;
}
<file_sep>/player/appentfullstopatend ofstring.cpp
#include<stdio.h>
#include<string.h>
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str;
int n,i;
cin>>str;
n=str.size();
for(i=0;i<n;i++)
{
cout<<str[i];
}
cout<<".";
return 0;
}
<file_sep>/player/reversestringandleavevowels.cpp
#include<stdio.h>
#include<string.h>
#include<bits/stdc++.h>
using namespace std;
int main()
{
char a[100];
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%c",&a[i]);
}
for(i=n-1;i>=0;i--)
{
if(a[i]=='a' || a[i]=='e' || a[i]=='i' || a[i]=='o' || a[i]=='u' || a[i]=='A' || a[i]=='E' || a[i]=='I' || a[i]=='O' || a[i]=='U')
{
continue;
}
else
{
printf("%c",a[i]);
}
}
}
<file_sep>/Beginner/Set1/positivenegativenumber.cpp
#include <iostream>
int main() {
int x;
scanf("%d",&x);
if(x>0)
printf("Positive");
else if (x==0)
printf("Zero");
else
printf("Negative");
return 0;
}
<file_sep>/Beginner/Set2/palindromecheck.cpp
#include<bits/stdc++.h>
#include<cstdio>
using namespace std;
bool arraypass(char x[])
{
int i = 0,j,flag=0;
while (x[i] != '\0')
{
++i;
}
for(j=0;j<i;j++)
{
if(isdigit(x[j])==0)
{
flag=1;
break;
}
}
if(flag==0)
{
return true;
}
else
return false;
}
int main()
{
int a,start,end,div,flagg=0;
char x[10],y;
scanf("%s",&x);
if(arraypass(x))
{
a=atoi(x);
div=1;
while(a/div>=10)
{
div*=10;
}
while(a!=0)
{
start=a/div;
end=a%10;
if(start!=end)
{
flagg=1;
break;
}
a=(a%div)/10;
div=div/100;
}
if(flagg==1)
{
printf("No");
}
else
{
printf("Yes");
}
}
else
printf("Invalid Input");
return 0;
}
<file_sep>/Beginner/Set2/primecheck.cpp
#include<bits/stdc++.h>
#include<cstdio>
using namespace std;
bool arraypass(char x[])
{
int i = 0,j,flag=0;
while (x[i] != '\0')
{
++i;
}
for(j=0;j<i;j++)
{
if(isdigit(x[j])==0)
{
flag=1;
break;
}
}
if(flag==0)
{
return true;
}
else
return false;
}
int main()
{
int a,i,flag=0;
char x[10],y;
scanf("%s",&x);
if(arraypass(x))
{
a=atoi(x);
if(a<=10000)
{
for(i=2;i<=a/2;i++)
{
if(a%i==0)
{
flag=1;
break;
}
}
if(flag==1)
{
printf("no");
}
else
{
printf("yes");
}
}
else
printf("Invalid Input");
}
else
printf("Invalid Input");
return 0;
}
<file_sep>/player/sumofsquareofindividualdigits.cpp
#include<stdio.h>
#include<string.h>
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long int n,sum=0,n1;
cin>>n;
if(n<0)
{
printf("Enter positive numbetr");
}
else
{
if(n==0)
{
printf("0");
}
else
{
while(n!=0)
{
n1=n%10;
n=n/10;
sum=sum+(n1*n1);
}
cout<<sum;
}
}
return 0;
}
<file_sep>/Pro/Set1/printonlyonceapperno.cpp
#include<bits/stdc++.h>
int main()
{
int a[50],b,i,j,flag,pos,n;
scanf("%d",&n);
if(n>0 && n<100000)
{
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(j=0;j<n;j++)
{
flag=0;
for(i=0;i<n;i++)
{
if(a[i]==a[j])
{
flag++;
if(flag==1)
{
pos=i;
}
}
}
if(flag==1)
{
b=a[pos];
printf("%d",b);
break;
}
}
}
else
{
printf("Invalid Input");
}
return 0;
}
<file_sep>/Beginner/Set1/Evenodd.cpp
#include<iostream>
int main()
{
int x;
scanf("%d",&x);
if(x<0)
printf("Invalid");
else if (x%2!=0)
printf("Odd");
else
printf("Even");
return 0;
}
<file_sep>/Hunter/circulartarversaornot.cpp
#include<iostream>
#include<bits/stdc++.h>
#define north 0
#define east 90
#define south 180
#define west 270
bool is_circular(char arr[])
{
int x=0,y=0,l,dir=north,i;
l=strlen(arr);
for(i=0;i<l;i++)
{
if(arr[i]=='R')
{
dir=(dir+90)%360;
}
else if(arr[i]=='L')
{
dir=(360+dir-90)%360;
}
else if(arr[i]=='G')
{
if(dir == north)
{
y++;
}
else if(dir == east)
{
x++;
}
else if(dir == south)
{
y--;
}
else if(dir == west)
{
x--;
}
}
}
if(x==0 && y==0)
{
return true;
}
else
{
return false;
}
}
int main()
{
char arr[50];
scanf("%s",arr);
if(is_circular(arr))
{
printf("yes");
}
else
{
printf("no");
}
return 0;
}
<file_sep>/player/factorial.cpp
#include<stdio.h>
#include<string.h>
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long int a[50],n,i,fact;
cin>>n;
if(n<0)
{
printf("Enter a positive number");
}
else
{
if(n==0)
{
printf("0");
}
else
{
fact=1;
for(i=n;i>=1;i--)
{
fact*=i;
}
cout<<fact;
}
}
return 0;
}
<file_sep>/Beginner/Set1/largestamong3numbers.cpp
#include<iostream>
int main()
{
int a,b,c,largest;
scanf("%d%d%d",&a,&b,&c);
largest=a;
if(b>largest)
{
largest=b;
}
if(c>largest)
{
largest=c;
}
printf("%d",largest);
return 0;
}
<file_sep>/Hunter/arrayintoequalaverage.cpp
#include<iostream>
int main()
{
int n,a[50],isum,jsum,i,j,count1=0,count2,avgi,avgj,flag=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
isum=0;
for(i=0;i<n-1;i++)
{
jsum=0;
count2=0;
count1++;
isum+=a[i];
avgi=isum/count1;
for(j=i+1;j<n;j++)
{
jsum+=a[j];
count2++;
}
avgj=jsum/count2;
if(avgi==avgj)
{
flag=1;
break;
}
}
if(flag==1)
{
printf("yes");
}
else
{
printf("no");
}
return 0;
}
<file_sep>/Pro/Set1/LargestIncreasingSubArray.cpp
//Longest increasing sequencce in an array
#include<iostream>
#include<stdio.h>
#include<malloc.h>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,max,count;
scanf("%d",&n);
int *a=(int *)malloc(n*sizeof(int));
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
if(n==0)
{
printf("0");
}
else
{
max=0;
count=0;
for(int i=2;i<n;i++)
{
if(a[i]>a[i-1])
{
count++;
}
else
{
if(count>max)
{
max=count;
}
count=0;
}
}
if(count>max)
{
max=count;
}
max++;
printf("%d",max);
}
return 0;
}
<file_sep>/Pro/Set1/noequalindexvalue.cpp
#include<bits/stdc++.h>
int main()
{
int a[50],b[50],i,j,count=0,n;
scanf("%d",&n);
if(n>0 && n<100000)
{
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
if(a[i]==i)
{
b[count]=a[i];
count++;
}
}
if(count==0)
{
printf("-1");
}
else
{
for(i=0;i<count;i++)
{
printf("%d ",b[i]);
}
}
}
else
{
printf("Invalid Input");
}
return 0;
}
<file_sep>/Beginner/Set1/sumoffirst[k]elements.cpp
#include<iostream>
#include<cstdio>
using namespace std;
bool arraypass(char x[])
{
int i = 0,j,flag=0;
while (x[i] != '\0')
{
++i;
}
for(j=0;j<i;j++)
{
if(isdigit(x[j])==0)
{
flag=1;
break;
}
}
if(flag==0)
{
return true;
}
else
return false;
}
int main()
{
int a,b,i,ai[50],sum=0;
char n[10],k[10],ac[10],y;
scanf("%s",&n);
scanf("%s",&k);
if(arraypass(n))
{
if(arraypass(k))
{
a=atoi(n);
b=atoi(k);
}
}
else
printf("Invalid Input");
for(i=0;i<a;i++)
{
scanf("%s",&ac);
if(arraypass(ac))
{
ai[i]=atoi(ac);
}
else{
printf("Invalid Input");
break;
}
}
for(i=0;i<b;i++)
{
sum+=ai[i];
}
printf("%d",sum);
return 0;
}
<file_sep>/player/stringreverse.cpp
#include<stdio.h>
#include<string.h>
#include<bits/stdc++.h>
using namespace std;
int main()
{
char a[100],count,i,flag;
scanf("%s",&a);
count=0;
flag=0;
i=0;
while(flag!=1)
{
if(a[i]=='\0')
{
flag=1;
}
else
{
count++;
}
i++;
}
for(i=count-1;i>=0;i--)
{
printf("%c",a[i]);
}
}
<file_sep>/Beginner/Set1/noofdigitsininput.cpp
#include<iostream>
int main()
{
int n,nod=0;
scanf("%d",&n);
while(n!=0)
{
nod+=1;
n=n/10;
}
printf("%d",nod);
}
<file_sep>/Beginner/Set1/aphabetornot.cpp
#include <iostream>
int main()
{
char x;
scanf("%c",&x);
if((x>='a' && x<='z')||(x>='A' && x<='Z'))
{
printf("Alphabet");
}
else
printf("No");
return 0;
}
<file_sep>/Beginner/Set2/powercalculation.cpp
#include<bits/stdc++.h>
#include<cstdio>
using namespace std;
bool arraypass(char x[])
{
int i = 0,j,flag=0;
while (x[i] != '\0')
{
++i;
}
for(j=0;j<i;j++)
{
if(isdigit(x[j])==0)
{
flag=1;
break;
}
}
if(flag==0)
{
return true;
}
else
return false;
}
int main()
{
int m,n,ans;
char mc[10],xc[10];
scanf("%s",&mc);
scanf("%s",&xc);
if(arraypass(mc))
{
if(arraypass(xc))
{
m=atoi(mc);
n=atoi(xc);
ans=pow(m,n);
printf("%d",ans);
}
else
printf("Invaid Input");
}
else
printf("Invalid Input");
return 0;
}
<file_sep>/Pro/Set1/repetedelementsdisplay.cpp
#include<bits/stdc++.h>
bool check(int b[],int n,int m)
{
int i;
for(i=0;i<n;i++)
{
if(b[i]==m)
return false;
else
return true;
}
}
int main()
{
int a[50],b[50],i,j,count=0,n;
scanf("%d",&n);
if(n>0 && n<100000)
{
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(j=0;j<n;j++)
{
for(i=j+1;i<n;i++)
{
if(a[j]==a[i])
{
if(check(b,n,a[i]))
{
b[count]=a[j];
count++;
}
else
continue;
}
}
}
if(count==0)
{
printf("Unique");
}
else
{
for(i=0;i<count;i++)
printf("%d ",b[i]);
}
}
else
{
printf("Invalid Input");
}
return 0;
}
<file_sep>/Beginner/Set2/oddnobwinterval.cpp
#include<bits/stdc++.h>
#include<cstdio>
using namespace std;
bool arraypass(char x[])
{
int i = 0,j,flag=0;
while (x[i] != '\0')
{
++i;
}
for(j=0;j<i;j++)
{
if(isdigit(x[j])==0)
{
flag=1;
break;
}
}
if(flag==0)
{
return true;
}
else
return false;
}
int main()
{
int a,b,i;
char x[10],y[10];
scanf("%s",&x);
scanf("%s",&y);
if(arraypass(x))
{ if(arraypass(y))
{
a=atoi(x);
b=atoi(y);
if(a<=1000000 && b<=100000)
{
for(i=a+1;i<b;i++)
{
if(i%2!=0)
printf("%d ",i);
}
}
else
printf("Invalid Input");
}
}
else
printf("Invalid Input");
return 0;
}
<file_sep>/Beginner/Set1/leapyear.cpp
#include<iostream>
#include<cstdio>
using namespace std;
bool arraypass(char x[])
{
int i = 0,j,flag=0;
while (x[i] != '\0')
{
++i;
}
for(j=0;j<i;j++)
{
if(isdigit(x[j])==0)
{
flag=1;
break;
}
}
if(flag==0)
{
return true;
}
else
return false;
}
int main()
{
int a;
char x[10],y;
scanf("%s",&x);
if(arraypass(x))
{
a=atoi(x);
if(a<0)
printf("Invalid Input");
else{
if(a%400==0)
printf("Leap Year");
else if (a%100==0)
printf("Not a Leap Year");
else if(a%4==0)
printf("Leap Year");
else
printf("Not a Leap Year");
}
}
else
printf("Invalid Input");
return 0;
}
<file_sep>/Pro/Set1/maxnofrominputarray.cpp
#include<bits/stdc++.h>
int main()
{
int a[50],i,j,max,pos,n;
scanf("%d",&n);
if(n>0 && n<100000)
{
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
max=a[i];
for(j=i+1;j<n;j++)
{
if(a[j]>max)
{
max=a[j];
pos=j;
}
}
if(a[i]!=max)
{
a[pos]=a[i];
a[i]=max;
}
}
for(i=0;i<n;i++)
{
printf("%d",a[i]);
}
}
else
{
printf("Invalid Input");
}
return 0;
}
| 8f39794d6204b3ba0973590a5777f38377f0fe55 | [
"C++"
] | 27 | C++ | Kushagraupadhyay/Guvi | 6c22b8dd598c944a21330aa4683d911cb67939a8 | a2fcbf1ad084e58f04e3535bfbbbf6e7a080b7a3 |
refs/heads/master | <file_sep>---
id:
created_date: {{date:DD/MM/YYYY}}
updated_date: {{date:DD/MM/YYYY}}
type: resource
tags:
- resource
- review
---
# 📦 {{date:YYYYMMDDHHmmss}} - {{title}}
## 🔗 Links
<!-- The List of resource-->
- <file_sep>---
id:
created_date: {{date:DD/MM/YYYY}}
updated_date: {{date:DD/MM/YYYY}}
type: reading_list
tags:
- reading_list
- review
---
# 📑 {{title}}
## 🔗 Links
- <file_sep>---
kanban-plugin: basic
---
## TODO
- [ ] Some task
## IN PROGRESS
## DONE
**Complete**
<file_sep>[ ](#anki-card)<file_sep>---
id: 20210829093623
created_date: 29/08/2021
updated_date: 29/08/2021
tags:
- review
---
# 20210829093439 - A sample note
[ ](#anki-card)
## 📝 Notes
- What is zettelkasten
## 🔗 Links
- <file_sep>import { App, FileSystemAdapter, Notice, Plugin, PluginSettingTab, Setting, Workspace } from 'obsidian';
import ChatView from 'view';
interface MyPluginSettings {
customName: string;
}
const DEFAULT_SETTINGS: MyPluginSettings = {
customName: 'Dual'
}
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
async onload() {
await this.loadSettings();
this.registerView('chat', (leaf) => {
return new ChatView(leaf, this.settings.customName);
});
this.app.workspace.layoutReady && this.initLeaf(this.app.workspace)
this.registerEvent(this.app.workspace.on('layout-ready', () => this.initLeaf(this.app.workspace)))
this.addSettingTab(new SampleSettingTab(this.app, this));
this.addCommand({
id: 'focus-dual-input',
name: 'Focus Dual input box',
callback: () => {
document.getElementById('dual-input-box').focus();
}
});
}
initLeaf(workspace: Workspace): void {
if (workspace.getLeavesOfType('chat').length == 0) {
workspace.getRightLeaf(false).setViewState({
type: 'chat'
})
}
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin);
this.app = app;
this.plugin = plugin;
}
display(): void {
let {containerEl} = this;
containerEl.empty();
containerEl.createEl('h3', {text: 'Follow these instructions to set up your Dual:'});
new Setting(containerEl)
.setName('0. Install Python (3.8+).')
.setDesc('Press the button to head over to the download page.')
.addButton(cb => cb
.setButtonText('Install Python')
.setClass('mod-cta')
.onClick(() => {
window.open('https://www.python.org/downloads/')
}));
new Setting(containerEl)
.setName('1. Copy snapshot.')
.setDesc('Press the button to copy the entire vault as concatenated plain text.')
.addButton(cb => cb
.setButtonText('Copy snapshot')
.setClass('mod-cta')
.onClick(() => {
new Notice('Loading files...');
let concatenated = '';
this.app.vault.getMarkdownFiles().forEach(element => {
this.app.vault.cachedRead(element)
.then((res) => {
res = res
.replace(/^---[\s\S]*---\n*/g, '')
.replace(/\[\[[^\|\[\]]*\|([^\|\[\]]*)\]\]/g, '$1')
.replace(/\[\[(.*)\]\]/g, '$1')
.replace(/```([^`])*```\n*/g, '')
.replace(/\$([^$])*\$*/g, '')
concatenated = concatenated.concat(res, '\n\n');
});
});
let copyPromise = new Promise(resolve => setTimeout(resolve, 3000)).then(() => {
concatenated = concatenated.slice(0, 5000000);
concatenated = this.removeMd(concatenated, {});
this.copyStringToClipboard(concatenated);
new Notice('Snapshot successfully copied to clipboard!');
});
}));
new Setting(containerEl)
.setName('2. Derive the essence.')
.setDesc('After following the online instructions, extract \'essence.zip\' in \'.obsidian/plugins/Dual/\'.')
.addButton(cb => cb
.setButtonText('Start alignment')
.setClass('mod-cta')
.onClick(() => {
window.open('https://colab.research.google.com/drive/1CObehan5gmYO-TvyyYq973a3h-_EYr9_?usp=sharing')
}));
new Setting(containerEl)
.setName('3. Configure the skeleton.')
.setDesc('Run \'python3 -m pip install -r requirements.txt\' in \'.obsidian/plugins/Dual/skeleton/\'.');
new Setting(containerEl)
.setName('4. Run the skeleton after you configured the essence.')
.setDesc('Run \'python3 server.py --path /path/to/your/vault/\' in \'.obsidian/plugins/Dual/skeleton/\'.');
new Setting(containerEl)
.setName('5. Restart Obsidian.')
.setDesc('Head over to the right side panel to talk with your Dual!');
containerEl.createEl('h3', {text: 'Congratulations on setting up your Dual!'});
new Setting(containerEl)
.setName('Custom name')
.setDesc('Customize your Dual\'s name using the input box. Reload Obsidian for this to take effect.')
.addText(text => text
.setPlaceholder('Dual')
.setValue('')
.onChange(async (value) => {
this.plugin.settings.customName = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Get involved!')
.addButton(cb => cb
.setButtonText('Report bugs')
.setClass('mod-cta')
.onClick(() => {
window.open('https://github.com/Psionica/Dual/issues')
}))
.addButton(cb => cb
.setButtonText('Join Psionica')
.setClass('mod-cta')
.onClick(() => {
window.open('https://psionica.org/')
}))
}
private copyStringToClipboard (content: string) {
var el = document.createElement('textarea');
el.value = content;
el.setAttribute('readonly', '');
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
private removeMd(md: string, options: any) {
options = options || {};
options.listUnicodeChar = options.hasOwnProperty('listUnicodeChar') ? options.listUnicodeChar : false;
options.stripListLeaders = options.hasOwnProperty('stripListLeaders') ? options.stripListLeaders : true;
options.gfm = options.hasOwnProperty('gfm') ? options.gfm : true;
options.useImgAltText = options.hasOwnProperty('useImgAltText') ? options.useImgAltText : true;
var output = md || '';
// Remove horizontal rules (stripListHeaders conflict with this rule, which is why it has been moved to the top)
output = output.replace(/^(-\s*?|\*\s*?|_\s*?){3,}\s*$/gm, '');
try {
if (options.stripListLeaders) {
if (options.listUnicodeChar)
output = output.replace(/^([\s\t]*)([\*\-\+]|\d+\.)\s+/gm, options.listUnicodeChar + ' $1');
else
output = output.replace(/^([\s\t]*)([\*\-\+]|\d+\.)\s+/gm, '$1');
}
if (options.gfm) {
output = output
// Header
.replace(/\n={2,}/g, '\n')
// Fenced codeblocks
.replace(/~{3}.*\n/g, '')
// Strikethrough
.replace(/~~/g, '')
// Fenced codeblocks
.replace(/`{3}.*\n/g, '');
}
output = output
// Remove HTML tags
.replace(/<[^>]*>/g, '')
// Remove setext-style headers
.replace(/^[=\-]{2,}\s*$/g, '')
// Remove footnotes?
.replace(/\[\^.+?\](\: .*?$)?/g, '')
.replace(/\s{0,2}\[.*?\]: .*?$/g, '')
// Remove images
.replace(/\!\[(.*?)\][\[\(].*?[\]\)]/g, options.useImgAltText ? '$1' : '')
// Remove inline links
.replace(/\[(.*?)\][\[\(].*?[\]\)]/g, '$1')
// Remove blockquotes
.replace(/^\s{0,3}>\s?/g, '')
// Remove reference-style links?
.replace(/^\s{1,2}\[(.*?)\]: (\S+)( ".*?")?\s*$/g, '')
// Remove atx-style headers
.replace(/^(\n)?\s{0,}#{1,6}\s+| {0,}(\n)?\s{0,}#{0,} {0,}(\n)?\s{0,}$/gm, '$1$2$3')
// Remove emphasis (repeat the line to remove double emphasis)
.replace(/([\*_]{1,3})(\S.*?\S{0,1})\1/g, '$2')
.replace(/([\*_]{1,3})(\S.*?\S{0,1})\1/g, '$2')
// Remove code blocks
.replace(/(`{3,})(.*?)\1/gm, '$2')
// Remove inline code
.replace(/`(.+?)`/g, '$1')
// Replace two or more newlines with exactly two? Not entirely sure this belongs here...
.replace(/\n{2,}/g, '\n\n');
} catch(e) {
console.error(e);
return md;
}
return output;
};
}<file_sep>from flask import Flask
from flask_cors import CORS, cross_origin
from conversational_wrapper import ConversationalWrapper
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--path', help='The path to your collection of Markdown files.', type=str)
args = parser.parse_args()
app = Flask(__name__)
cors = CORS(app)
cw = ConversationalWrapper(args.path)
@app.route('/query/<query>')
@cross_origin()
def respond_query(query):
return cw.respond(query)
if __name__ == '__main__':
app.run()<file_sep>---
id:
created_date: {{date:DD/MM/YYYY}}
updated_date: {{date:DD/MM/YYYY}}
type: book
tags:
- book
- review
---
# 📚 {{title}}
- Link:
## 📝 Notes
-
## ❓ Questions
-
## 🔗 Related links
<file_sep># Obsidian-template
My personal templates for [Obsidian](https://obsidian.md).
## Motivation
I started new note-taking method after reading an interesting post about Zettelkasten method in [Hacker News](https://news.ycombinator.com/item?id=25803132). For many years, I was struggling about how to organizing my reading list as well as what I learned. I tried many tools & approaches like using Pocket, using browser bookmark, Medium, Trello, Twitter likes,... Nothing worked. I kept forgetting about what I has read. Our memory isn't reliable as we might think. Building Second Brain idea has changed the way I learn. Obsidian is my favorite tool to build it. I keep changing how I get the most out of Obsidian.
I would love to share my templates with others, who are interested in learning and want to organizing your learning process better.
## What is inside this template ?
### Theme
I creates modified version of Dracula theme. It has better line-spacing between heading and content, better front matter styling, better font-scale so you can have better writing experience.
Here is the screenshot of the main screen:

I think [Typora like editor](https://trello.com/c/pXHHXIzj/18-wysiwyg-editor-like-typora) would be better, but it's for the future :).
### Templates
There are various templates I often use that you can find in [templates folder](notes/templates).
- `Term` : can be used to define specific term. should be short, simple, atomic.
- `Resource`: A type of entry notes about any topic, contains many related terms, links about one topic. You can use this as an entry points to explore other concepts in a topic.
- `Quote File`: Quote said by famous people.
- `Create Anki Card`: Used to mark a card as anki card. See more details in section bellow.
- `ID`: Generate unique Zettelkasten ID for current note.
- `Book`: Summary about a book.
- `Thought`: used to capture my ideas.
- ...
### Extensions
I use some extensions, some are public extensions, some are mine, some are modified by me based on the original obsidian plugins.
- [Dual](https://github.com/Psionica/dual-obsidian-client): A skilled virtual assistant for Obsidian.
- [Emoji Shortcodes](https://github.com/phibr0/obsidian-emoji-shortcodes) and [Emoji Toolbar](https://github.com/oliveryh/obsidian-emoji-toolbar): to add new icon to your notes.
- [Kanban](https://github.com/mgmeyers/obsidian-kanban): To manage your reading list.
- [Spaced Repetition](https://github.com/st3v3nmw/obsidian-spaced-repetition): to create anki cards .
- [Monthly review](https://github.com/tuan3w/monthly-review-obsidian): To link your notes to monthly note.
- Markdown prettifier (modified): Fix and reformat your markdown notes, keep it clean, add modified date to your notes.
- [Smart Random Note](https://github.com/erichalldev/obsidian-smart-random-note) : Random visit notes from your search result.
- [Tag Wrangler](https://github.com/pjeby/tag-wrangler): rename, merge, search tags from Obsidian tag pane.
### Taking notes tips
1. Creating notes
- Create new Zettelkasten notes when you want to take note about new thing by hot key `Ctrl+Shift+N` and pick a template by using hot key `Ctrl+T`
- Reformat your note after edit: `Ctrl+Alt+L`
- Create new refer link to monthly note for later review: `Ctrl+Shift+L`.
- For books, you might want to add [link to local file](https://forum.obsidian.md/t/how-to-link-a-local-file-in-obsidian/5815) so that you can open book from your note quickly.
- If you want to add content later, just add a `todo` tag in the front matter.
2. Review a topic/notes
- Notes are organized by topics. Open search and search for tag you want to review. Press `Ctrl+Tab` to view a random note from your search result.
- Every month, a monthly note is created under `notes/monthly` folder. You can review list of notes linked to it.
- Any new note should add a `review` tag and remove it as soon as you think it's good enough. To visit a note that need to be reviewed, enter `Ctrl+R` or exec command `Spaced Repetition: Open a note for review`.
3. Track your reading
- I created two Kanban boards to track my regular reading and book reading. I think it really helps when you have multiple things in your reading list. Again, don't trust your memory.
4. Naming file
- One tip I regularly find useful is adding type of notes in the file name to make them clear, so you can navigate file later easier. For example:
- Resource notes: `(Resource) Topic name`
- Kanban board: `(Kanban) Books`
- Book: `(Book) product`
5. Anki card
- Overtime, you will create new cluster of knowledge. You might want to review this topic using better way than visiting them randomly. So [Anki is your friend](https://aliabdaal.com/spaced-repetition/). Creating new anki deck is simple enough:
- Add new desk: Add tag about topic in [Spaced repetition plugin setting](https://github.com/st3v3nmw/obsidian-spaced-repetition). I prefer this approach more than turning folder name into deck name because it provides more better control.
- Add new card: I only used [multiple-line card style](https://github.com/st3v3nmw/obsidian-spaced-repetition/wiki/Flashcard-Types#multi-line-basic) . I choose `[ ](#anki-card)` as separator because it's invisible in preview mode. To add separator, just use template `Create Anki Card` to insert the separator after the first heading of the note. By default, `Term` card is an anki card.
6. Virtual Assistant
I do explore [Dual assistant plugin](https://github.com/Psionica/dual-obsidian-client). I love the works by <NAME>. AI assistants will be powerful tools to support us to exploring new ideas in our modern world. Just follow the guide if you want to try it.
7. Hot keys
I use a number of hot keys to make quick actions. You can see them in `Hotkeys` section in the setting.
### Stats tracking (optional)
I also provide some [script](./update_stats.py) to update your reading stats (how many notes you have taken over time). Everytime you want to update git, just run command:
```bash
$ ./update your message without quote here
```
It will add all the new notes, update note stats, generate a picture of your progress and create new commit with your message. Your stats will look like this:

### Screenshots
- Edit mode:

- Preview mode:

- Front matter:

- Monthly note:

- Kanban board:

- Anki deck list:

## FAQs
If you wanted to know more about Zettelkasten method, I recommend book [How to Take Smart Notes: One Simple Technique to Boost Writing, Learning and Thinking – for Students, Academics and Nonfiction Book Writers](https://www.amazon.com/gp/product/1542866502/) as a good start.
Happy learning :).
## License
[MIT](LICENSE)
<file_sep>#!/bin/bash
if [ $# -eq 0 ]
then
echo "Usage: ./run_dual.sh big|small"
exit 1
fi
model_type=$1
echo $model_type
if [ $model_type == "small" ]
then
echo "Runing dual server with small pretrained model..."
cd ./.obsidian/plugins/Dual
rm essence
ln -s "`pwd`/essence_small" essence
cd skeleton
/usr/bin/python3 server.py --path ../../../../
else
echo "Running dual server with large pretrained model..."
cd ./.obsidian/plugins/Dual
rm essence
ln -s "`pwd`/essence_big" essence
cd skeleton
/usr/bin/python3 server.py --path ../../../../
fi
<file_sep>---
id: 20210829094933
created_date: 29/08/2021
updated_date: 29/08/2021
type: book
tags:
- book
- review
---
# 📚 20210829094933 - (Book) The war of art
- Link: <https://www.amazon.com/War-Art-Steven-Pressfield-ebook/dp/B007A4SDCG/>
## 📝 Notes
-
## ❓ Questions
-
## 🔗 Related links
<file_sep>#!/usr/bin/python3
from pathlib import Path
import os
from datetime import datetime
from collections import defaultdict
from matplotlib import pyplot as plt
from dateutil import parser
import subprocess
import pandas as pd
def get_ctime(p):
rs = subprocess.check_output(["stat", "-c" "\'%w\'", p]).split()[0]
# extract path from filename as possible
file_name = os.path.basename(p)
if file_name.startswith('2021'):
try:
return datetime.strptime(file_name[:8], '%Y%m%d')
except Exception as e:
# print(e)
pass
return parser.parse(rs)
# exclude README.md
c = 0
mtime_group = defaultdict(int)
ctime_group = defaultdict(int)
for file_path in Path('./notes').glob('**/*.md'):
c_time = get_ctime(str(file_path))
# c_time = datetime.fromtimestamp(p.st_mtime).replace(hour=0, minute=0, second=0, microsecond=0).strftime(('%d/%m/%y'))
ctime_group[c_time] += 1
c += 1
# mtime_group = list([[k, v] for k, v in mtime_group.items()])
ctime_group = list([[k, v] for k, v in ctime_group.items()])
ctime_group = sorted(ctime_group, key=lambda x: x[0])
# import ipdb; ipdb.set_trace()
data = pd.DataFrame(ctime_group)
data[1] = data[1].cumsum()
fig = plt.figure(figsize=(32, 18), dpi=64)
# fig, ax = plt.subplots()
plt.plot(data[0], data[1], marker='o', color='tab:gray')
fig.autofmt_xdate()
plt.title('Number of notes', fontsize=14)
plt.savefig('stats.png')
#with open('README.md.tmp', 'w') as f:
# f.write('# Less\n')
# f.write('More is less.\n')
# f.write('\n')
# f.write('## Stats\n')
# f.write('- Number of notes: {}'.format(c))
# f.write('\n\n')
#os.rename('README.md.tmp', 'README.md')
<file_sep>---
id: {{date:YYYYMMDDHHmmss}}
created_date: {{date:DD/MM/YYYY}}
updated_date: {{date:DD/MM/YYYY}}
tags:
- review
---
# {{date:YYYYMMDDHHmmss}} - {{newTitle}}
[ ](#anki-card)
## Notes
{{content}}
## Links
- <file_sep>---
id: 20210801093836
created_date: 01/08/2021
updated_date: 01/08/2021
type: monthly-note
tags:
- monthly-note
- review
- reading-list
---
# 📅 2021-08
## Links
- [[20210829094148 - (Book) Range - Why Generalists Triumph in a Specialized World]]
- [[20210829094933 - (Book) The war of art]]
- [[20210829093738 - Kerning (typography)]]
## Thoughts
<file_sep>from core import Core
import re
class ConversationalWrapper:
def __init__(self, root_dir):
self.core = Core(root_dir)
def respond(self, query):
query = query.strip()
if query == '':
return None
if re.match(r'.*[copy|get]\s+snapshot.*', query.lower()):
return {
'intent': 'COPY_SNAPSHOT',
'input': query,
'output': self.core.copy_snapshot()
}
elif '?' in query or re.match(r'^(why|what|when|where|who|how).*', query.lower()):
return {
'intent': 'OPEN_DIALOGUE',
'input': query,
'output': self.core.open_dialogue(query)
}
elif re.match(r'.*(this\s+(text|note|entry)).*', query.lower()):
return {
'intent': 'DESCRIPTIVE_SEARCH',
'input': query,
'output': self.core.descriptive_search(query)
}
elif m := re.match(r'.*(([Ss]earch\s+for|[Ll]ook\s+for|[Ff]ind)\s+(a\s+text|a\s+note|an\s+entry)\s+(that|which))\s+(.*)', query):
return {
'intent': 'DESCRIPTIVE_SEARCH',
'input': 'This text ' + m.group(5),
'output': self.core.descriptive_search('This text ' + m.group(5))
}
else:
if m:= re.match(r'.*(([Ss]earch\s+for|[Ll]ook\s+for|[Ll]ook\s+up|[Ff]ind)\s*(a\s+note|an\s+entry|a\s+text|notes|entries|texts)?\s*(on|about|related\s+to)?)\s+([^\.]*)', query):
query = m.group(5)
return {
'intent': 'FLUID_SEARCH',
'input': query,
'output': self.core.fluid_search(query)
}
<file_sep>---
id:
created_date: {{date:DD/MM/YYYY}}
updated_date: {{date:DD/MM/YYYY}}
type: post
tags:
- review
---
# {{title}}
- Link:
## Notes
-
## Questions
-
## Related links
- <file_sep>---
id: {{date:YYYYMMDDHHmmss}}
created_date: {{date:DD/MM/YYYY}}
updated_date: {{date:DD/MM/YYYY}}
type: monthly-note
tags:
- monthly-note
- review
- reading-list
---
# 📅 {{title}}
## Links
-
## Thoughts
- <file_sep>from sentence_transformers import SentenceTransformer, CrossEncoder, util
import pickle
import os
import glob
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer, Trainer, TrainingArguments, TextDataset, DataCollatorForLanguageModeling
from util import md_to_text
import json
import random
import re
class Core:
def __init__(self, root_dir):
self.root_dir = root_dir
self.cache_address = os.path.join(root_dir, '.obsidian/plugins/Dual/skeleton/cache.pickle')
self.entry_regex = os.path.join(root_dir, '**/*md')
self.skeleton_ready = False
self.essence_ready = False
self.load_skeleton()
self.load_essence()
if os.path.isfile(self.cache_address) is False:
self.create_cache()
else:
self.load_cache()
self.sync_cache()
def fluid_search(self, query, considered_candidates=50, selected_candidates=5, second_pass=True):
self.load_essence()
if self.essence_ready == False:
return ['The essence is not present at the required location.']
self.sync_cache()
selected_candidates = min(selected_candidates, considered_candidates)
query_embedding = self.text_encoder.encode(query, convert_to_tensor=True)
hits = util.semantic_search(query_embedding, torch.Tensor(self.entry_embeddings), top_k=considered_candidates)[0]
if second_pass:
cross_scores = self.pair_encoder.predict([[query, self.entry_contents[hit['corpus_id']]] for hit in hits])
for idx in range(len(cross_scores)):
hits[idx]['cross-score'] = cross_scores[idx]
hits = sorted(hits, key=lambda x: x['cross-score'], reverse=True)
return [self.entry_filenames[hit['corpus_id']] for hit in hits[:selected_candidates] if hit['cross-score'] > 1e-3]
else:
return [self.entry_filenames[hit['corpus_id']] for hit in hits[:selected_candidates]]
def descriptive_search(self, claim, polarity=True, target='premise', considered_candidates=50, selected_candidates=5):
self.load_essence()
if self.essence_ready == False:
return ['The essence is not present at the required location.']
selected_candidates = min(selected_candidates, considered_candidates)
considered_candidates = min(considered_candidates, len(self.entry_filenames))
candidate_entry_filenames = self.fluid_search(claim, selected_candidates=considered_candidates, second_pass=False)
candidate_entry_contents = [self.entries[e][0] for e in candidate_entry_filenames]
if target == 'premise':
cross_encoder_input = [(e, claim) for e in candidate_entry_contents]
elif target == 'conclusion':
cross_encoder_input = [(claim, e) for e in candidate_entry_contents]
cross_encoder_output = self.nli.predict(cross_encoder_input, apply_softmax=False)
if polarity == True:
cross_encoder_output = [e[1] for e in cross_encoder_output]
else:
cross_encoder_output = [e[0] for e in cross_encoder_output]
results = [(candidate_entry_filenames[idx], cross_encoder_output[idx]) for idx in range(considered_candidates)]
results = sorted(results, key=lambda x: x[1], reverse=True)[:selected_candidates]
results = [e[0] for e in results]
return results
def open_dialogue(self, question, considered_candidates=3):
self.load_essence()
if self.essence_ready == False:
return ['The essence is not present at the required location.']
candidate_entry_filenames = self.fluid_search(question, selected_candidates=considered_candidates)
candidate_entry_contents = reversed([self.entries[e][0] for e in candidate_entry_filenames])
generator_prompt = '\n\n'.join(candidate_entry_contents) + '\n\nQ: ' + question + '\nA: '
input_ids = self.gen_tokenizer.encode(generator_prompt, return_tensors='pt')
generator_output = self.gen_model.generate(
input_ids,
do_sample=True,
max_length=len(input_ids[0]) + 100,
top_p=0.9,
top_k=40,
temperature=0.9
)
output_sample = self.gen_tokenizer.decode(generator_output[0], skip_special_tokens=True)[len(generator_prompt):]
output_sample = re.sub(r'^[\W_]+|[\W_]+$', '', output_sample)
output_sample = re.sub(r'[^a-zA-Z0-9\s]{3,}', '', output_sample)
output_sample = output_sample.split('Q:')[0].split('\n\n')[0].strip()
output_sample += '...'
return [output_sample]
def load_skeleton(self):
print('Loading skeleton...')
self.text_encoder = SentenceTransformer('msmarco-distilbert-base-v2')
self.pair_encoder = CrossEncoder('cross-encoder/ms-marco-TinyBERT-L-4')
self.nli = CrossEncoder('cross-encoder/nli-distilroberta-base')
self.skeleton_ready = True
def load_essence(self):
tentative_folder_path = os.path.join(self.root_dir, '.obsidian/plugins/Dual/essence')
tentative_file_path = os.path.join(tentative_folder_path, 'pytorch_model.bin')
if self.essence_ready == False and os.path.isfile(tentative_file_path):
print('Loading essence...')
self.gen_tokenizer = GPT2Tokenizer.from_pretrained('gpt2-medium')
self.gen_model = GPT2LMHeadModel.from_pretrained(pretrained_model_name_or_path=tentative_folder_path, pad_token_id=self.gen_tokenizer.eos_token_id)
self.essence_ready = True
def copy_snapshot(self):
return {
'output': '\n\n'.join(self.entry_contents)
}
def create_cache(self):
print('Cache file doesn\'t exist, creating a new one...')
self.entry_filenames = glob.glob(self.entry_regex, recursive=True)
self.entry_contents = [md_to_text(
file) for file in self.entry_filenames]
self.entry_embeddings = list(self.text_encoder.encode(
self.entry_contents))
self.create_entries_dict()
pickle.dump(self.entries, open(self.cache_address, 'wb'))
def create_entries_dict(self):
self.entries = {}
for entry_idx in range(len(self.entry_filenames)):
self.entries[self.entry_filenames[entry_idx]] = (
self.entry_contents[entry_idx], self.entry_embeddings[entry_idx])
def load_cache(self):
print('Previous cache file exists, loading it...')
self.entries = pickle.load(open(self.cache_address, 'rb'))
self.entry_filenames = list(self.entries.keys())
self.entry_contents = [e[0] for e in self.entries.values()]
self.entry_embeddings = [e[1] for e in self.entries.values()]
def sync_cache(self):
self.prune_cache_entries()
self.update_cache_entries()
self.add_cache_entries()
def prune_cache_entries(self):
print('Pruning cached entries which have been removed in the meanwhile...')
actual_entry_filenames = glob.glob(self.entry_regex)
new_entry_filenames = []
new_entry_contents = []
new_entry_embeddings = []
for entry_idx, entry_filename in enumerate(self.entry_filenames):
if entry_filename in actual_entry_filenames:
new_entry_filenames += [self.entry_filenames[entry_idx]]
new_entry_contents += [self.entry_contents[entry_idx]]
new_entry_embeddings += [self.entry_embeddings[entry_idx]]
self.entry_filenames = new_entry_filenames
self.entry_contents = new_entry_contents
self.entry_embeddings = new_entry_embeddings
self.create_entries_dict()
pickle.dump(self.entries, open(self.cache_address, 'wb'))
def add_cache_entries(self):
print('Caching new entries...')
actual_entry_filenames = glob.glob(self.entry_regex)
for entry_idx, entry_filename in enumerate(actual_entry_filenames):
if entry_filename not in self.entry_filenames:
self.entry_filenames.append(entry_filename)
self.entry_contents.append(md_to_text(entry_filename))
self.entry_embeddings.append(
self.text_encoder.encode(md_to_text(entry_filename)))
self.create_entries_dict()
pickle.dump(self.entries, open(self.cache_address, 'wb'))
def update_cache_entries(self):
print('Updating cached entries which have been modified in the meanwhile')
for entry_idx, entry_filename in enumerate(self.entry_filenames):
if self.entry_contents[entry_idx] != md_to_text(entry_filename):
self.entry_contents[entry_idx] = md_to_text(entry_filename)
self.entry_embeddings[entry_idx] = self.text_encoder.encode(self.entry_contents[entry_idx])
self.create_entries_dict()
pickle.dump(self.entries, open(self.cache_address, 'wb'))
<file_sep>---
kanban-plugin: basic
---
## TODO
- [ ] [[20210829094148 - (Book) Range - Why Generalists Triumph in a Specialized World]]
- [ ] [[20210829094933 - (Book) The war of art]]
## IN PROCESS
## DONE
**Complete**
<file_sep>import { ItemView, WorkspaceLeaf, Notice, TextAreaComponent } from 'obsidian';
export default class ChatView extends ItemView {
customName = '';
constructor(leaf: WorkspaceLeaf, customName: string) {
super(leaf);
this.customName = customName;
}
getViewType(): string {
return "chat"
}
getDisplayText(): string {
return "Dual"
}
getIcon(): string {
return "info"
}
sendMessage(): void {
let input = <HTMLInputElement> document.getElementById('dual-input-box');
let replied = false;
if (input.value != '') {
this.drawMessage(input.value, 'right');
let typingPromise = new Promise(resolve => setTimeout(resolve, 3000)).then(() => {
if (replied == false) {
this.setStatus('typing...');
}
});
this.makeRequest(input.value).then((response: any) => {
if (response['intent'] == 'DESCRIPTIVE_SEARCH' || response['intent'] == 'FLUID_SEARCH') {
if (response['output'].length > 0) {
response['output'].forEach((element: string) => {
this.drawMessage(element.split('\\').pop().split('/').pop(), 'left');
});
} else {
this.drawMessage('I can\'t find any relevant entries. Try a different search.', 'left');
}
} else {
this.drawMessage(response['output'], 'left');
}
replied = true;
this.setStatus('online');
});
input.value = '';
}
}
async makeRequest(query: string): Promise<JSON> {
const response = await fetch('http://127.0.0.1:5000/query/' + encodeURIComponent(query));
const responseJSON = await response.json();
return responseJSON
}
load(): void {
super.load()
this.draw();
}
private draw(): void {
const container = this.containerEl.children[1];
const rootEl = document.createElement('div');
const headerDiv = rootEl.createDiv({ cls: 'nav-header' });
const footerDiv = rootEl.createDiv({ cls: 'nav-header' });
let header = headerDiv.createEl('h3');
header.appendText(this.customName);
header.style.textAlign = 'left';
header.style.marginTop = '0px';
header.style.marginBottom = '0px';
header.style.position = 'absolute';
header.style.top = '15px';
let status = headerDiv.createEl('h6');
status.id = 'status';
status.appendText('online');
status.style.textAlign = 'left';
status.style.marginTop = '0px';
status.style.marginBottom = '5px';
status.style.color = 'grey'
let conversationDiv = headerDiv.createDiv({ cls: 'nav-header' });
conversationDiv.id = 'conversationDiv'
conversationDiv.style.padding = '0';
conversationDiv.style.backgroundColor = 'var(--background-secondary-alt)';
conversationDiv.style.position = 'absolute';
conversationDiv.style.left = '0';
conversationDiv.style.width = '100%';
conversationDiv.style.paddingLeft = '10px';
conversationDiv.style.paddingRight = '10px';
conversationDiv.style.overflowY = 'scroll';
conversationDiv.style.height = 'calc(100% - 110px)'
let input = footerDiv.createEl('input');
input.id = 'dual-input-box';
input.type = 'text';
input.style.fontSize = '0.8em'
input.style.paddingInlineStart = '2%'
input.style.paddingInlineEnd = '2%'
input.style.marginTop = '0px';
input.style.marginBottom = '10px';
input.style.maxWidth = '68%';
input.style.minWidth = '68%';
input.style.position = 'absolute';
input.style.bottom = '0';
input.style.left = '5%';
let button = footerDiv.createEl('button');
button.appendText('Send');
button.id = 'send-button';
button.style.alignItems = 'left';
button.style.paddingInlineStart = '2%';
button.style.paddingInlineEnd = '2%';
button.style.marginTop = '0px';
button.style.marginBottom = '10px';
button.style.width = '20%';
button.style.position = 'absolute';
button.style.bottom = '0';
button.style.left = '75%';
this.registerDomEvent(button, 'click', () => this.sendMessage());
this.registerDomEvent(input, 'keydown', (event) => {
if (event.key == 'Enter') {
this.sendMessage();
}
})
container.empty();
container.appendChild(rootEl);
}
private drawMessage(content: string, side: string): void {
let conversationDiv = <HTMLDivElement> document.getElementById('conversationDiv');
let p = conversationDiv.createEl('p');
p.appendText(content);
p.style.userSelect = 'text';
p.style.textAlign = 'left';
p.style.fontSize = '0.8em';
p.style.borderRadius = '5px';
p.style.lineHeight = '18px';
p.style.padding = '5px';
if (side == 'right') {
p.style.backgroundColor = 'var(--background-primary)';
} else {
p.style.backgroundColor = 'var(--background-secondary)';
}
p.style.width = '90%';
p.style.position = 'relative';
if (side == 'right') {
p.style.left = '10%';
}
conversationDiv.scrollBy(0, 1000);
}
private setStatus(content: string): void {
let statusP = <HTMLParagraphElement> document.getElementById('status')
statusP.setText(content);
}
}<file_sep>---
id: 20210829093745
created_date: 29/08/2021
updated_date: 29/08/2021
tags:
- review
- typography
- typography-anki
---
# 20210829093738 - Kerning (typography)
[ ](#anki-card)
## 📝 Notes
- What is kerning ?
## 🔗 Links
- <file_sep>---
id:
created_date: {{date:DD/MM/YYYY}}
type: daily-note
tags:
- daily
---
# {{title}}
## Links
-
## Thoughts
- <file_sep>---
id: 20210829094738
created_date: 29/08/2021
updated_date: 29/08/2021
tags:
- todo
---
# 20210829094555 - Todo term
[ ](#anki-card)
## 📝 Notes
-
## 🔗 Links
- <file_sep>{{date:YYYYMMDDHHmmss}}<file_sep>from markdown import markdown
from bs4 import BeautifulSoup
import frontmatter
import re
def md_to_text(file):
"""Extract text from markdown file which contains front matter."""
content = open(file).read()
content = re.sub(r'^---[\s\S]*---\n*', '', content)
content = re.sub(r'\[\[[^\|]*\|([^\]]*)\]\]', '\g<1>' , content)
content = re.sub(r'\[\[(.*)\]\]', '\g<1>', content)
content = re.sub(r'```([^`])*```\n*', '', content)
content = re.sub(r'\$([^$])*\$*', '', content)
content = markdown(content)
content = BeautifulSoup(content, features='html.parser')
content = content.get_text()
return content<file_sep>#!/bin/bash
python3 update_stats.py
git add .
git commit -a -m "$*"
git push
<file_sep>---
id: {{date:YYYYMMDDHHmmss}}
created_date: {{date:DD/MM/YYYY}}
updated_date: {{date:DD/MM/YYYY}}
author:
tags:
- quote
- review
---
# {{title}}
>
>
> <div class="signature"> - Name </div><file_sep>regex==2020.10.15
click==7.1.2
tqdm==4.50.2
joblib==0.17.0
six==1.15.0
Flask==1.1.2
beautifulsoup4==4.9.3
flask_cors==3.0.10
Markdown==3.3.4
PyInstaller==4.2
python_frontmatter==1.0.0
sentence_transformers==1.0.4
torch==1.8.1
transformers==4.5.0
<file_sep>---
id:
created_date: 29/08/2021
updated_date: 29/08/2021
type: resource
tags:
- resource
- review
---
# 📦 20210829094050 - 20210829094032 - Typography terms
## 🔗 Links
- [[20210829093738 - Kerning (typography)]]
- [[20210829093905 - Typeface (typography)]]
- [[Some new terminology]]<file_sep>---
id: 20210829093913
created_date: 29/08/2021
updated_date: 29/08/2021
tags:
- review
- typography
- typography-anki
---
# 20210829093905 - Typeface (typography)
[ ](#anki-card)
## 📝 Notes
- What is typeface?
## 🔗 Links
- | a624cf61aa0d5d113cd235ec0b8e2df06464422f | [
"Markdown",
"Python",
"Text",
"TypeScript",
"Shell"
] | 30 | Markdown | ctmcisco/obsidian-template | 2faa4c69f60bdcf7ff0ee4fbbc185b2a614191e9 | 69065bc61917b83ba8c351371f08c44bf2c7101e |
refs/heads/main | <repo_name>dado93/PSoC-MechKeyboard<file_sep>/PSoC5LP/Bootloader.cydsn/README.md
## PSoC-MechKeyboard Bootloader Project
This project is required to implement bootloader functionality in the PSoC-MechKeyboard.
In order to be able to upgrade the firmware (if required) when the keyboard is already completely
assembled, the bootloader functionality allows to perform a firmware upgrade via USB.
In normal mode, bootloader passes controls to application code without waiting for any command.
When firmware upgrade is required, bootloader process can be started in two ways:
- by pressing the on-board switch on the CY8CKIT-059, which is connected to pin 2.2 until the keyboard is powered
- by pressing the keyboard switch connected to the configured pins in the project until the keyboard is powered. For this second mode of operation, be sure to configure the pins `Wait_Row` and `Wait_Col` in the Pin Assignment tab inside PSoC Creator Design Wide Resources. These pins must be connected to the switch which is configured to trigger the bootloader operation<file_sep>/README.md
# PSoC-MechKeyboard
The aim of this project is to design a functional firmware for custom mechanical keyoards
running on [Cypress-Infineon PSoC micro-controllers](https://www.cypress.com/products/microcontrollers-mcus).
Two different implementations are currently being developed, targeting two different architectures:
- [PSoC 5LP](https://www.cypress.com/products/32-bit-arm-cortex-m3-psoc-5lp), for single-core USB HID Keyboards
- [PSoC 6](https://www.cypress.com/products/psoc-6-microcontrollers-32-bit-arm-cortex-m4m0), for dual-core BLE HID Keyboards
The kits I'm using for the firmware development are the following ones:
- [CY8CKIT-059](https://www.cypress.com/documentation/development-kitsboards/cy8ckit-059-psoc-5lp-prototyping-kit-onboard-programmer-and) for PSoC 5LP architecture
- [CY8CPROTO-063-BLE](https://www.cypress.com/documentation/development-kitsboards/psoc-6-ble-prototyping-kit-cy8cproto-063-ble) for PSoC6 architecture
## PSoC 5LP Project
### TODO
[x] - Implement Bootloader for USB firmware update
## PSoC 6 Project
<file_sep>/PSoC5LP/Keyboard.cydsn/keycodes.h
/**
* \file keycodes.h
* \brief List of keycodes sent from keyboard to host.
*
* [](https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf)
*/
#ifndef __KEYCODES_H__
#define __KEYCODES_H__
#define IS_ERROR(code) (KC_ROLL_OVER <= (code) && (code) <= KC_UNDEFINED)
#define IS_ANY(code) (KC_A <= (code) && (code) <= 0xFF)
#define IS_KEY(code) (KC_A <= (code) && (code) <= KC_EXSEL)
#define IS_MOD(code) (KC_LCTRL <= (code) && (code) <= KC_RGUI)
#define IS_SPECIAL(code) ((0xA5 <= (code) && (code) <= 0xDF) || (0xE8 <= (code) && (code) <= 0xFF))
#define IS_SYSTEM(code) (KC_PWR <= (code) && (code) <= KC_WAKE)
#define IS_CONSUMER(code) (KC_MUTE <= (code) && (code) <= KC_BRID)
#define IS_FN(code) (KC_FN0 <= (code) && (code) <= KC_FN31)
#define IS_MOUSEKEY(code) (KC_MS_UP <= (code) && (code) <= KC_MS_ACCEL2)
#define IS_MOUSEKEY_MOVE(code) (KC_MS_UP <= (code) && (code) <= KC_MS_RIGHT)
#define IS_MOUSEKEY_BUTTON(code) (KC_MS_BTN1 <= (code) && (code) <= KC_MS_BTN5)
#define IS_MOUSEKEY_WHEEL(code) (KC_MS_WH_UP <= (code) && (code) <= KC_MS_WH_RIGHT)
#define IS_MOUSEKEY_ACCEL(code) (KC_MS_ACCEL0 <= (code) && (code) <= KC_MS_ACCEL2)
#define MOD_BIT(code) (1 << MOD_INDEX(code))
#define MOD_INDEX(code) ((code)&0x07)
#define MOD_MASK_CTRL (MOD_BIT(KC_LCTRL) | MOD_BIT(KC_RCTRL))
#define MOD_MASK_SHIFT (MOD_BIT(KC_LSHIFT) | MOD_BIT(KC_RSHIFT))
#define MOD_MASK_ALT (MOD_BIT(KC_LALT) | MOD_BIT(KC_RALT))
#define MOD_MASK_GUI (MOD_BIT(KC_LGUI) | MOD_BIT(KC_RGUI))
#define MOD_MASK_CS (MOD_MASK_CTRL | MOD_MASK_SHIFT)
#define MOD_MASK_CA (MOD_MASK_CTRL | MOD_MASK_ALT)
#define MOD_MASK_CG (MOD_MASK_CTRL | MOD_MASK_GUI)
#define MOD_MASK_SA (MOD_MASK_SHIFT | MOD_MASK_ALT)
#define MOD_MASK_SG (MOD_MASK_SHIFT | MOD_MASK_GUI)
#define MOD_MASK_AG (MOD_MASK_ALT | MOD_MASK_GUI)
#define MOD_MASK_CSA (MOD_MASK_CTRL | MOD_MASK_SHIFT | MOD_MASK_ALT)
#define MOD_MASK_CSG (MOD_MASK_CTRL | MOD_MASK_SHIFT | MOD_MASK_GUI)
#define MOD_MASK_CAG (MOD_MASK_CTRL | MOD_MASK_ALT | MOD_MASK_GUI)
#define MOD_MASK_SAG (MOD_MASK_SHIFT | MOD_MASK_ALT | MOD_MASK_GUI)
#define MOD_MASK_CSAG (MOD_MASK_CTRL | MOD_MASK_SHIFT | MOD_MASK_ALT | MOD_MASK_GUI)
#define FN_BIT(code) (1 << FN_INDEX(code))
#define FN_INDEX(code) ((code)-KC_FN0)
#define FN_MIN KC_FN0
#define FN_MAX KC_FN31
enum hid_keyboard_keypad_usage {
KC_NO,
KC_ROLL_OVER,
KC_POST_FAIL,
KC_UNDEFINED,
KC_A,
KC_B,
KC_C,
KC_D,
KC_E,
KC_F,
KC_G,
KC_H,
KC_I,
KC_J,
KC_K,
KC_L,
KC_M, // 0x10
KC_N,
KC_O,
KC_P,
KC_Q,
KC_R,
KC_S,
KC_T,
KC_U,
KC_V,
KC_W,
KC_X,
KC_Y,
KC_Z,
KC_1,
KC_2,
KC_3, // 0x20
KC_4,
KC_5,
KC_6,
KC_7,
KC_8,
KC_9,
KC_0,
KC_ENTER,
KC_ESCAPE,
KC_BSPACE,
KC_TAB,
KC_SPACE,
KC_MINUS,
KC_EQUAL,
KC_LBRACKET,
KC_RBRACKET, // 0x30
KC_BSLASH,
KC_NONUS_SLASH,
KC_SCOLON,
KC_QUOTE,
KC_GRAVE,
KC_COMMA,
KC_DOT,
KC_FSLASH,
KC_CAPSLOCK,
KC_F1,
KC_F2,
KC_F3,
KC_F4,
KC_F5,
KC_F6,
KC_F7, // 0x40
KC_F8,
KC_F9,
KC_F10,
KC_F11,
KC_F12,
KC_PSCREEN,
KC_SCROLLLOCK,
KC_PAUSE,
KC_INSERT,
KC_HOME,
KC_PGUP,
KC_DELETE,
KC_END,
KC_PGDOWN,
KC_RIGHT,
KC_LEFT, // 0x50
KC_UP,
KC_DOWN,
KC_NUMLOCK,
KC_KP_SLASH,
KC_KP_ASTERISK,
KC_KP_MINUS,
KC_KP_PLUS,
KC_KP_ENTER,
KC_KP_1,
KC_KP_2,
KC_KP_3,
KC_KP_4,
KC_KP_5,
KC_KP_6,
KC_KP_7,
KC_KP_8, // 0x60
KC_KP_9,
KC_KP_0,
KC_KP_DOT,
KC_NONUS_BSLASH,
KC_APP,
KC_POWER,
KC_KP_EQUAL,
KC_F13,
KC_F14,
KC_F15,
KC_F16,
KC_F17,
KC_F18,
KC_F19,
KC_F20,
KC_F21, // 0x70
KC_F22,
KC_F23,
KC_F24,
KC_EXECUTE,
KC_HELP,
KC_MENU,
KC_SELECT,
KC_STOP,
KC_AGAIN,
KC_UNDO,
KC_CUT,
KC_COPY,
KC_PASTE,
KC_FIND,
KC_MUTE,
KC_VOLUP, // 0x80
KC_VOLDOWN,
KC_LOCKING_CAPS,
KC_LOCKING_NUM,
KC_LOCKING_SCROLL,
KC_KP_COMMA,
KC_KP_EQUAL_AS400,
KC_INT1,
KC_INT2,
KC_INT3,
KC_INT4,
KC_INT5,
KC_INT6,
KC_INT7,
KC_INT8,
KC_INT9,
KC_LANG1, // 0x90
KC_LANG2,
KC_LANG3,
KC_LANG4,
KC_LANG5,
KC_LANG6,
KC_LANG7,
KC_LANG8,
KC_LANG9,
KC_ALT_ERASE,
KC_SYSREQ,
KC_CANCEL,
KC_CLEAR,
KC_PRIOR,
KC_RETURN,
KC_SEPARATOR,
KC_OUT,
KC_OPER,
KC_CLEAR_AGAIN,
KC_CRSEL,
KC_EXSEL,
#if 0
// ***************************************************************
// These keycodes are present in the HID spec, but are *
// nonfunctional on modern OSes. QMK uses this range (0xA5-0xDF) *
// for the media and function keys instead - see below. *
// ***************************************************************
KC_KP_00 = 0xB0,
KC_KP_000,
KC_THOUSANDS_SEPARATOR,
KC_DECIMAL_SEPARATOR,
KC_CURRENCY_UNIT,
KC_CURRENCY_SUB_UNIT,
KC_KP_LPAREN,
KC_KP_RPAREN,
KC_KP_LCBRACKET,
KC_KP_RCBRACKET,
KC_KP_TAB,
KC_KP_BSPACE,
KC_KP_A,
KC_KP_B,
KC_KP_C,
KC_KP_D,
KC_KP_E, //0xC0
KC_KP_F,
KC_KP_XOR,
KC_KP_HAT,
KC_KP_PERC,
KC_KP_LT,
KC_KP_GT,
KC_KP_AND,
KC_KP_LAZYAND,
KC_KP_OR,
KC_KP_LAZYOR,
KC_KP_COLON,
KC_KP_HASH,
KC_KP_SPACE,
KC_KP_ATMARK,
KC_KP_EXCLAMATION,
KC_KP_MEM_STORE, //0xD0
KC_KP_MEM_RECALL,
KC_KP_MEM_CLEAR,
KC_KP_MEM_ADD,
KC_KP_MEM_SUB,
KC_KP_MEM_MUL,
KC_KP_MEM_DIV,
KC_KP_PLUS_MINUS,
KC_KP_CLEAR,
KC_KP_CLEAR_ENTRY,
KC_KP_BINARY,
KC_KP_OCTAL,
KC_KP_DECIMAL,
KC_KP_HEXADECIMAL,
#endif
/* Modifiers */
KC_LCTRL = 0xE0,
KC_LSHIFT,
KC_LALT,
KC_LGUI,
KC_RCTRL,
KC_RSHIFT,
KC_RALT,
KC_RGUI
// **********************************************
// * 0xF0-0xFF are unallocated in the HID spec. *
// * QMK uses these for Mouse Keys - see below. *
// **********************************************
};
/* Media and Function keys */
enum internal_special_keycodes {
/* Generic Desktop Page (0x01) */
KC_SYSTEM_POWER = 0xA5,
KC_SYSTEM_SLEEP,
KC_SYSTEM_WAKE,
/* Consumer Page (0x0C) */
KC_AUDIO_MUTE,
KC_AUDIO_VOL_UP,
KC_AUDIO_VOL_DOWN,
KC_MEDIA_NEXT_TRACK,
KC_MEDIA_PREV_TRACK,
KC_MEDIA_STOP,
KC_MEDIA_PLAY_PAUSE,
KC_MEDIA_SELECT,
KC_MEDIA_EJECT, // 0xB0
KC_MAIL,
KC_CALCULATOR,
KC_MY_COMPUTER,
KC_WWW_SEARCH,
KC_WWW_HOME,
KC_WWW_BACK,
KC_WWW_FORWARD,
KC_WWW_STOP,
KC_WWW_REFRESH,
KC_WWW_FAVORITES,
KC_MEDIA_FAST_FORWARD,
KC_MEDIA_REWIND,
KC_BRIGHTNESS_UP,
KC_BRIGHTNESS_DOWN,
/* Fn keys */
KC_FN0 = 0xC0,
KC_FN1,
KC_FN2,
KC_FN3,
KC_FN4,
KC_FN5,
KC_FN6,
KC_FN7,
KC_FN8,
KC_FN9,
KC_FN10,
KC_FN11,
KC_FN12,
KC_FN13,
KC_FN14,
KC_FN15,
KC_FN16, // 0xD0
KC_FN17,
KC_FN18,
KC_FN19,
KC_FN20,
KC_FN21,
KC_FN22,
KC_FN23,
KC_FN24,
KC_FN25,
KC_FN26,
KC_FN27,
KC_FN28,
KC_FN29,
KC_FN30,
KC_FN31
};
enum mouse_keys {
/* Mouse Buttons */
KC_MS_UP = 0xF0,
KC_MS_DOWN,
KC_MS_LEFT,
KC_MS_RIGHT,
KC_MS_BTN1,
KC_MS_BTN2,
KC_MS_BTN3,
KC_MS_BTN4,
KC_MS_BTN5,
/* Mouse Wheel */
KC_MS_WH_UP,
KC_MS_WH_DOWN,
KC_MS_WH_LEFT,
KC_MS_WH_RIGHT,
/* Acceleration */
KC_MS_ACCEL0,
KC_MS_ACCEL1,
KC_MS_ACCEL2
};
#endif<file_sep>/PSoC5LP/Bootloader.cydsn/main.c
/**
* Main file for USB Bootloader.
*
* This program is executed when the board is powered. If the switch connected to
* the column and row configured in the Pins tab is pressed when the board is
* powered, or if the on-board switch (connected to pin 2.2) is pressed,
* then bootloader operation starts and firmware upgrade can be performed.
* Otherwise, control is passed to application program.
*/
#include "project.h"
int main(void)
{
CyGlobalIntEnable; /* Enable global interrupts. */
/* Place your initialization/startup code here (e.g. MyInst_Start()) */
Bootloader_LED_Write(1);
Wait_Column_Write(1);
if ( (Wait_Row_Read() == 1) || ( BL_Switch_Read() == 0) )
{
Bootloader_SET_RUN_TYPE(Bootloader_START_BTLDR);
}
Wait_Column_Write(0);
Bootloader_Start();
for(;;)
{
/* Place your application code here. */
}
return 0;
}
/* [] END OF FILE */
<file_sep>/PSoC6/Keyboard.cydsn/main_cm4.c
/**
* \brief Main source file for PSoC6 BLE Keyboard
*
* \author <NAME>
*/
#include "debug_interface.h"
#include "project.h"
int main(void)
{
__enable_irq(); /* Enable global interrupts. */
// Initialize debug serial port
UART_START();
setvbuf(stdin, NULL, _IONBF, 0);
DBG_PRINTF("\f");
DBG_PRINTF("BLE HID Keyboard Example\r\n");
for(;;)
{
/* Place your application code here. */
}
}
/* [] END OF FILE */
<file_sep>/PSoC6/Keyboard.cydsn/main_cm0p.c
/**
* \brief Main source file for CM0 core.
*
* This is the main source code for th CM0 code in the
* PSoC6 BLE HID Keyboard project.
*
* \author <NAME>
*/
#include "project.h"
int main(void)
{
__enable_irq(); /* Enable global interrupts. */
/* Unfreeze IO after Hibernate */
if(Cy_SysPm_GetIoFreezeStatus())
{
Cy_SysPm_IoUnfreeze();
}
/* Enable CM4. CY_CORTEX_M4_APPL_ADDR must be updated if CM4 memory layout is changed. */
Cy_SysEnableCM4(CY_CORTEX_M4_APPL_ADDR);
/* Place your initialization/startup code here (e.g. MyInst_Start()) */
for(;;)
{
/* Place your application code here. */
}
}
/* [] END OF FILE */
<file_sep>/PSoC6/Keyboard.cydsn/debug_interface.h
/**
* \file debug.h
* \brief Header file for debug interface.
*
* The debug interface allows to monitor the
* program through a standard serial port.
* In production, make sure to disable the debug
* module by setting the #DEBUG_UART_ENABLED to
* #DISABLED.
*/
#ifndef __DEBUG__
#define __DEBUG__
#include "config.h"
#include <project.h>
#include <stdio.h>
/***************************************
* UART Macros / prototypes
***************************************/
#if (DEBUG_UART_ENABLED == ENABLED)
#define DBG_PRINTF(...) (printf(__VA_ARGS__))
#define UART_PUT_CHAR(...) while(1UL != UART_Put(__VA_ARGS__))
#define UART_GET_CHAR(...) (UART_Get())
#define UART_IS_TX_COMPLETE(...) (UART_IsTxComplete())
#define UART_WAIT_TX_COMPLETE(...) while(UART_DEB_IS_TX_COMPLETE() == 0) ;
#define UART_SCB_CLEAR_RX_FIFO(...) (Cy_SCB_ClearRxFifo(UART_SCB__HW))
#define UART_START(...) (UART_Start(__VA_ARGS__))
#else
#define DBG_PRINTF(...)
#define UART_DEB_PUT_CHAR(...)
#define UART_DEB_GET_CHAR(...) (0u)
#define UART_DEB_IS_TX_COMPLETE(...) (1u)
#define UART_DEB_WAIT_TX_COMPLETE(...) (0u)
#define UART_DEB_SCB_CLEAR_RX_FIFO(...) (0u)
#define UART_START(...)
#endif /* (DEBUG_UART_ENABLED == ENABLED) */
#endif
/* [] END OF FILE */
<file_sep>/PSoC6/Keyboard.cydsn/config.h
/* ========================================
*
* Copyright YOUR COMPANY, THE YEAR
* All Rights Reserved
* UNPUBLISHED, LICENSED SOFTWARE.
*
* CONFIDENTIAL AND PROPRIETARY INFORMATION
* WHICH IS THE PROPERTY OF your company.
*
* ========================================
*/
#ifndef __CONFIG_H__
#define __CONFIG_H__
/***************************************
* Conditional Compilation Parameters
***************************************/
#define ENABLED (1u)
#define DISABLED (0u)
/**
* \brief Enable Debug serial port.
*/
#define DEBUG_UART_ENABLED ENABLED
#endif
/* [] END OF FILE */
| 10c6b93da263583422c01eba56a442081dc8af38 | [
"Markdown",
"C"
] | 8 | Markdown | dado93/PSoC-MechKeyboard | d5cbc8f6a4bdfe3efbe30421c7739191b6872819 | 7cb1bc3d4647882983e0d939487ba3d80b979698 |
refs/heads/master | <repo_name>judearasu/website<file_sep>/src/pages/about.js
import React from "react"
import Layout from "../components/layout"
import SEO from "../components/seo"
const AboutPage = () => (
<Layout>
<SEO title="About me" />
<h1>About</h1>
<p>
Hi there, I'm Thillai. I'm a software engineer currently working at a
payroll company. I'm particulary interested in Golang, Data structures and
Machine learning. I enjoy drawing UX paper prototypes for both my personal
and professional projects.
</p>
<p>
Apart from computes, I really enjoy playing PUBG Mobile, traveling, hiking
and watching NBA matches (LAKERS are my favaourites)
</p>
<p>
If you have any questions or just want to chat, you can reach out to me on
{" "}<a href="http://twitter.com/judearasu">Twitter</a> or shoot me an {" "}
<a href="mailto:<EMAIL>"><EMAIL></a>
</p>
</Layout>
)
export default AboutPage
<file_sep>/src/pages/index.js
import React from 'react'
import Layout from '../components/layout'
import SEO from '../components/seo'
const IndexPage = () => (
<Layout>
<SEO title="Home" />
<h1>🥨 <NAME> 🥨</h1>
<p>I love programming, design, explain with words and code.</p>
<div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
{/* <Image /> */}
</div>
<div className="social">
<div className="twitter badge">
<a href="https://twitter.com/judearasu/" target="_blank" rel="noopener" title="Twitter">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z"></path></svg></a>
</div>
<div className="twitter badge"><a href="https://github.com/judearasu/" target="_blank" rel="noopener" title="Github"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"></path></svg></a>
</div>
<div className="linkedin badge">
<a href="https://www.linkedin.com/in/tharas/" target="_blank" rel="noopener" title="Linkedin">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"></path><rect x="2" y="9" width="4" height="12"></rect><circle cx="4" cy="4" r="2"></circle></svg></a>
</div>
<div className="insta badge">
<a href="https://www.instagram.com/judearas/" target="_blank" rel="noopener" title="Instagram"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path><line x1="17.5" y1="6.5" x2="17.5" y2="6.5"></line></svg></a>
</div>
</div>
</Layout>
)
export default IndexPage
<file_sep>/node-apis/create-schema.js
exports.createSchemaCustomization = ({ actions, schema }) => {
const { createTypes } = actions
createTypes(`interface BlogPost @nodeInterface {
id: ID!
title: String!
body: String!
slug: String!
date: Date! @dateformat
tags: [String]!
keywords: [String]!
excerpt: String!
}`)
createTypes(
schema.buildObjectType({
name: `MdxBlogPost`,
fields: {
id: { type: `ID!` },
title: {
type: `String!`,
},
slug: {
type: `String!`,
},
date: { type: `Date!`, extensions: { dateformat: {} } },
tags: { type: `[String]!` },
keywords: { type: `[String]!` },
excerpt: {
type: `String!`,
args: {
pruneLength: {
type: `Int`,
defaultValue: 140,
},
},
resolve: mdxResolverPassthrough(`excerpt`),
},
body: {
type: `String!`,
resolve: mdxResolverPassthrough(`body`),
},
},
interfaces: [`Node`, `BlogPost`],
})
)
}<file_sep>/_posts/lessons-learnt.md
---
title: Lessons learnt as a youtube streamer
date: '2021-02-17'
spoiler: A personal work reflection.
category: personal
author: <NAME>
tags:
- work, youtube
---
Last year March i have started publishing videos my youtube channel [JunkCast7](https://www.youtube.com/channel/UCAYJrtmppEfIzhoL0_I1BNg). At the initial start i believed posting videos on youtube is pretty simple.On March 2020 i prepared my first video about javascript challenges. With my macbook Pro 2017 and defult built-in screen recorders the video came well. It was not upto high standard in terms of quality but still it's compromising.
### Doing isn’t enough, you need to know how to market your work
This was my most hard-hitting realization in the social networking career. In my start of my job, i used to technical writings about ruby, html and publish it on my blog. And via **seo**, i got quite a few audiences. But on youtube the reality is totally different. We have more competitors and more videos on the same content. I am a person works hard for the stuff to get done and not to interest on marketting the stuffs. It took a while to realize that's not enough. Knowing how to present your work to your audience or right people is key on the current world. It's applicable to all fields and i am not restricting to specific field.
### Topics do matter
My intial videos are about coding challenges on Javascript and material design styles. But the vidoes doesn't reach out well and the reason might be more related content is already available on Youtube. Then i published a video about a real time work/problem and to my surprise i had more views. Thereby i conclue real time topics only will have more reach than normal ones.
### Tools i came to know
Screen recorder, OBS, Canvaa, Adobe spark are the tools which i used for my youtube videos.
### Thoughts
Learning is an art and i find the streaming videos helps me to learn and know about the new technologies and challenges.
<file_sep>/_posts/confessions.md
---
title: Confessions of a Developer
date: '2021-02-02'
spoiler: A personal reflection.
category: personal
author: <NAME>
tags:
- life, personal, ethics
---
It's been quite a while since I've forgotten to learn, think and practice for an year.
- At the beginnig of the year **2020** i planned for few things that i would target on that year. But due to pandemic started working from home. At the start of pandemic it looks good as day's prolong i was not comfortable and had lot of tension and stress.
- In mid of the year i started my javascript library **COBB** on behalf of the place where i stayed.And to the surprise i started a youtube channel named **JunkCast7**.
- From the work perspective i was totally occupied. Due to the situation and peer pressure worked around the clock. Voice and thoughts was not recognized instead the 90's ideas are getting implanted.
- I purchased UX tools and started paper prototyping for few of my works.
- Started writing a CSS framework named yellow later i skipped.
- So far 2020 is not great for me
<file_sep>/src/config/theme-options.js
const themeOptions = {
basePath: "/blog",
contentPath: "_posts",
assetPath: "_assets",
}
<file_sep>/src/utils/helpers.js
const sanitizeHTML = require(`sanitize-html`)
const _ = require(`lodash`)
export function formatReadingTime(minutes) {
let cups = Math.round(minutes / 5)
// let bowls = 0
if (cups > 5) {
return `${new Array(Math.round(cups / Math.E))
.fill("🍱")
.join("")} ${minutes} min read`
} else {
return `${new Array(cups || 1).fill("☕️").join("")} ${minutes} min read`
}
}
export function countText(rawText) {
let timeToRead = 0
const pureText = sanitizeHTML(rawText, { allowTags: [] })
const avgWPM = 265
const wordCount =
_.words(pureText).length +
_.words(pureText, /[\p{sc=Katakana}\p{sc=Hiragana}\p{sc=Han}]/gu).length
timeToRead = Math.round(wordCount / avgWPM)
if (timeToRead === 0) {
timeToRead = 1
}
return timeToRead
}
<file_sep>/node-apis/onCreateNode.js
const { createFilePath } = require("gatsby-source-filesystem")
exports.onCreateNode = async (
{ node, actions, getNode, createNodeId },
themeOptions
) => {
const { createNode, createParentChildLink } = actions
const { contentPath, basePath } = withDefaults(themeOptions)
// Make sure it's an MDX node
if (node.internal.type !== `Mdx`) {
return
}
// Create source field (according to contentPath)
const fileNode = getNode(node.parent)
const source = fileNode.sourceInstanceName
if (node.internal.type === `Mdx` && source === contentPath) {
let slug
if (node.frontmatter.slug) {
if (path.isAbsolute(node.frontmatter.slug)) {
// absolute paths take precedence
slug = node.frontmatter.slug
} else {
// otherwise a relative slug gets turned into a sub path
slug = urlResolve(basePath, node.frontmatter.slug)
}
} else {
// otherwise use the filepath function from gatsby-source-filesystem
const filePath = createFilePath({
node: fileNode,
getNode,
basePath: contentPath,
})
slug = urlResolve(basePath, filePath)
}
// normalize use of trailing slash
slug = slug.replace(/\/*$/, `/`)
const fieldData = {
title: node.frontmatter.title,
tags: node.frontmatter.tags || [],
slug,
date: node.frontmatter.date,
keywords: node.frontmatter.keywords || [],
}
const mdxBlogPostId = createNodeId(`${node.id} >>> MdxBlogPost`)
await createNode({
...fieldData,
// Required fields.
id: mdxBlogPostId,
parent: node.id,
children: [],
internal: {
type: `MdxBlogPost`,
contentDigest: createContentDigest(fieldData),
content: JSON.stringify(fieldData),
description: `Mdx implementation of the BlogPost interface`,
},
})
createParentChildLink({ parent: node, child: getNode(mdxBlogPostId) })
}
}
<file_sep>/src/templates/post-query.js
import React from 'react'
import { graphql, Link } from 'gatsby';
import Layout from '../components/layout';
import SEO from '../components/seo';
import { MDXRenderer } from 'gatsby-plugin-mdx';
import { formatReadingTime, countText } from '../utils/helpers';
import { Disqus } from 'gatsby-plugin-disqus'
class PostPage extends React.Component {
render() {
const post = this.props.data.blogPost
const previous = this.props.data.previous
const next = this.props.data.next
let disqusConfig = {
url: `${this.props.data.site.siteMetadata.siteUrl}`,
identifier: post.id,
title: post.title,
}
console.log(disqusConfig);
// let { previous, next, slug } = this.props.pageContext
return (
<Layout>
<SEO title={post.title} slug={post.slug} />
<main>
<h1>{post.title}</h1>
<p className='caption caption--sm'>
{/* By <Link
to="/"
style={{
boxShadow: `none`,
textDecoration: `none`
}}>
<span className='caption caption--sm'>{post.author}</span></Link> on */}
{post.date} {` • ${formatReadingTime(countText(post.body))}`}</p>
<MDXRenderer>{post.body}</MDXRenderer>
</main>
<nav>
<ul
style={{
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-between',
listStyle: 'none',
padding: 0,
}}
>
<li>
{previous && (
<Link
to={previous.slug}
rel="prev"
style={{ marginRight: 20 }}
>
← {previous.title}
</Link>
)}
</li>
<li>
{next && (
<Link to={next.slug} rel="next">
{next.title} →
</Link>
)}
</li>
</ul>
</nav>
<Disqus config={disqusConfig} />
</Layout>
)
}
}
export default PostPage
export const query = graphql`
query PostPageQuery($id: String!, $previousId: String, $nextId: String) {
site {
siteMetadata {
title
siteUrl
social {
name
url
}
}
}
blogPost(id: { eq: $id }) {
id
excerpt
body
slug
title
tags
keywords
date(formatString: "MMMM DD, YYYY")
author
}
previous: blogPost(id: { eq: $previousId }) {
id
excerpt
slug
title
date(formatString: "MMMM DD, YYYY")
}
next: blogPost(id: { eq: $nextId }) {
id
excerpt
slug
title
date(formatString: "MMMM DD, YYYY")
}
}
`
<file_sep>/node-apis/create-pages.js
const fs = require(`fs`)
const path = require(`path`)
const mkdirp = require(`mkdirp`)
const Debug = require(`debug`)
const { createFilePath } = require(`gatsby-source-filesystem`)
const { urlResolve, createContentDigest } = require(`gatsby-core-utils`)
const PostTemplate = require.resolve(`./../src/templates/post-query`)
const PostsTemplate = require.resolve(`./../src/templates/posts-query`)
exports.createPages = async ({ graphql, actions, reporter }, themeOptions) => {
const { createPage } = actions
const { basePath } = withDefaults(themeOptions)
const result = await graphql(`
{
allBlogPost(sort: { fields: [date, title], order: DESC }, limit: 1000) {
edges {
node {
id
slug
}
}
}
}
`)
if (result.errors) {
reporter.panic(result.errors)
}
// Create Posts and Post pages.
const { allBlogPost } = result.data
const posts = allBlogPost.edges
// Create a page for each Post
posts.forEach(({ node: post }, index) => {
const previous = index === posts.length - 1 ? null : posts[index + 1]
const next = index === 0 ? null : posts[index - 1]
const { slug } = post
createPage({
path: slug,
component: PostTemplate,
context: {
id: post.id,
previousId: previous ? previous.node.id : undefined,
nextId: next ? next.node.id : undefined,
},
})
})
// // Create the Posts page
createPage({
path: basePath,
component: PostsTemplate,
context: {},
})
}
<file_sep>/_posts/2020.md
---
title: My Decade in Review
date: '2020-01-19'
spoiler: A personal reflection.
category: personal,
author: <NAME>,
tags:
- life, personal
---
This was my second official blog, prior to this one i was active for a long on my first blog [genlinux.org](#http://www.genlinux.org/). I tried to write my writings on medium and found quite boring as i dont have the flexibility to change my theme.
Things i did at the mid of 2019
1. Started writing javascript utility library Cobb
2. kickstarted my thoughts on my long term review project
3. Learned how to contribute on open source projects
4. About product UX design.
# December 2019
I cloned gatsby project and started working on customizing the gatsby to develop my blog on Gatsby.I found
the gatsby blog ([overreacted.io] #https://overreacted.io/ and [hswolf] #https://hswolff.com/ ) are very helpful including the gatsby-blog-core.
# Jan-
<file_sep>/gatsby-config.js
const themeDefaults = require("./src/utils/default-options")
const themeOptions = require("./src/utils/default-options")
const siteOptions = themeDefaults(themeOptions)
module.exports = {
siteMetadata: {
title: `Root 🐎`,
description: `Personal blog by <NAME>. I love programming, design, explain with words and code.`,
siteUrl: "https://root.genlinux.org/",
author: `<NAME>`,
options: themeOptions,
navigation: [
{
name: `About`,
url: `/about`,
},
{
name: `Blog`,
url: `/blog`,
},
],
social: [
{
name: `Twitter`,
url: `https://twitter.com/judearasu`,
},
{
name: `GitHub`,
url: `https://github.com/judearasu`,
},
],
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/ride.jpg`, // This path is relative to the root of the site.
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `pages`,
path: `${__dirname}/src/pages/`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
path: siteOptions.contentPath,
name: siteOptions.contentPath,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
path: siteOptions.assetPath,
name: siteOptions.assetPath,
},
},
{
resolve: `gatsby-plugin-mdx`,
options: {
extensions: [`.mdx`, `.md`],
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: siteOptions.basePath,
path: siteOptions.contentPath,
},
},
{
resolve: `gatsby-plugin-disqus`,
options: {
shortname: `https-root-genlinux-org`
}
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
| 2a1b0f1e93bb5949e9f86be40e3127c990a13d36 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | judearasu/website | f934e64ea9592991150f0a1ae96941c2e5656730 | b3c1071c6c67b7a45ab2588e5ccd213f5223f3bd |
refs/heads/master | <repo_name>hiep294/phonegap-basic<file_sep>/platforms/browser/www/js/loadPage/funcs/record/index.js
// HANDLE EVENT FOR EACH LISTVIEW ITEM
function onDeleteApartment(_id) {
if (!confirm('Are you sure to delete this apartment?')) {
return
}
// delete in db
Apartment.deleteRecord(_id)
// delete in state
records = records.filter(item => item._id !== _id)
// delete in ui
$(`li#id${_id}`).remove();
}
function onSaveNotes(_id) {
const chosenRecord = records.find(record => record._id === _id);
const newNotes = $(`#id${_id} textarea`).val();
const apartmentWillBeUpdated = {
_id: chosenRecord._id,
propertyType: chosenRecord.property_type,
bedroomType: chosenRecord.bedroom_type,
datetimeLocal: chosenRecord.datetime_local,
price: chosenRecord.price,
furnitureType: chosenRecord.furniture_type,
notes: newNotes,
reporterName: chosenRecord.reporter_name,
image: chosenRecord.image
}
Apartment.checkEdittingDuplication(apartmentWillBeUpdated, callbackOfChecking);
function callbackOfChecking(isDuplicated) {
if(isDuplicated) {
alert('Duplicated!')
return
}
// change in web sql
Apartment.updateNotes(_id, newNotes)
// change state
chosenRecord.notes = newNotes;
// change ui
hideBtnsControlNotes(_id)
}
}
function onCancelChangeNotes(_id) {
// find record
const record = records.find(item => item._id === _id)
// revert ui
$(`#id${_id} textarea`).val(record.notes)
hideBtnsControlNotes(_id)
}<file_sep>/platforms/browser/www/js/models/apartment.js
const Apartment = {
createRecord: function(propertyType, bedroomType, datetimeLocal, price, furnitureType, notes, reporterName, image) {
db.transaction(
function(tx) {
tx.executeSql(
"INSERT INTO apartments(property_type, bedroom_type, datetime_local, price, furniture_type, notes, reporter_name, image) values(?, ?, ?, ?, ?, ?, ?, ?)",
[propertyType, bedroomType, datetimeLocal, price, furnitureType, notes, reporterName, image],
function(tx, results){},
function(tx, error) {
console.log("add product error: " + error.message);
}
);
},
function(error) {},
function() {}
)
},
checkDuplication: function({propertyType, bedroomType, datetimeLocal, price, furnitureType, notes, reporterName, image}, callbackOfChecking) {
db.transaction(
function(tx) {
tx.executeSql(
'SELECT * FROM apartments WHERE property_type = ? AND bedroom_type = ? AND datetime_local = ? AND price = ? AND furniture_type = ? AND notes = ? AND reporter_name = ?',
[propertyType, bedroomType, datetimeLocal, price, furnitureType, notes, reporterName],
function(tx, results){
const isDuplicated = results.rows.length > 0
callbackOfChecking(isDuplicated);
},
function(tx, error) {
console.log("add product error: " + error.message);
}
);
},
function(error) {},
function() {}
)
},
checkEdittingDuplication: function({_id, propertyType, bedroomType, datetimeLocal, price, furnitureType, notes, reporterName, image}, callbackOfChecking) {
db.transaction(
function(tx) {
tx.executeSql(
'SELECT * FROM apartments WHERE _id <> ? AND property_type = ? AND bedroom_type = ? AND datetime_local = ? AND price = ? AND furniture_type = ? AND notes = ? AND reporter_name = ?',
[_id, propertyType, bedroomType, datetimeLocal, price, furnitureType, notes, reporterName],
function(tx, results){
const isDuplicated = results.rows.length > 0
console.log(results.rows.length)
callbackOfChecking(isDuplicated);
},
function(tx, error) {
console.log("add product error: " + error.message);
}
);
},
function(error) {},
function() {}
)
},
loadRecords: function(setRecordsInClient) {
db.readTransaction(
function(tx) {
tx.executeSql(
"SELECT * FROM apartments",
[],
function(tx, results) {
setRecordsInClient(results);
}
)
}
)
},
deleteRecord: function(_id) {
db.transaction(function(tx) {
tx.executeSql('DELETE FROM apartments WHERE _id = ?', [_id])
}
)
},
deleteAllRecords: function() {
db.transaction(function(tx) {
tx.executeSql('DELETE FROM apartments')
}
)
},
updateNotes: function(_id, notes) {
db.transaction((tx) => {
tx.executeSql('UPDATE apartments SET notes = ? WHERE _id = ?', [notes, _id])
})
},
update: function({_id, propertyType, bedroomType, datetimeLocal, price, furnitureType, notes, reporterName, image}) {
db.transaction((tx) => {
tx.executeSql('UPDATE apartments SET property_type = ?, bedroom_type = ?, datetime_local = ?, price = ?, furniture_type = ?, notes = ?, reporter_name = ?, image = ? WHERE _id = ?', [propertyType, bedroomType, datetimeLocal, price, furnitureType, notes, reporterName, image, _id]);
})
}
}
<file_sep>/platforms/browser/www/js/loadPage/funcs/filter/ui.js
const inputSearchAllUI = `
<div class="form-group mb-1">
<input onkeyup="onChangeOptionalKeyword()" id="txtOptionalKeyword" name="txtOptionalKeyword" type="text" class="form-control" placeholder="Keyword" aria-label="Username" aria-describedby="basic-addon1">
</div>
`
const selectSearchPropertyTypeUI = `
<div class="form-group mb-1">
<select onchange="onChangeKeyword()" class="form-control" name="txtKeyword" id="txtKeyword">
<option selected disabled="disabled">Choose...</option>
<option value="Flat">Flat</option>
<option value="House">House</option>
<option value="Bungalow">Bungalow</option>
</select>
</div>
`
const selectSearchBedroomTypeUI = `
<div class="form-group mb-1">
<select onchange="onChangeKeyword()" class="form-control" name="txtKeyword" id="txtKeyword">
<option selected disabled="disabled">Choose...</option>
<option value="Studio">Studio</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
</div>
`
const inputSearchReporterNameUI = `
<div class="form-group mb-1">
<input onkeyup="onChangeKeyword()" id="txtKeyword" name="txtKeyword" type="text" class="form-control" placeholder="Keyword" aria-label="Username" aria-describedby="basic-addon1">
</div>
`
const inputSearchNotesUI = `
<div class="form-group mb-1">
<textarea onkeyup="onChangeOptionalKeyword()" class="form-control" id="txtOptionalKeyword" name="txtOptionalKeyword" placeholder="Keyword"></textarea>
</div>
`
const selectSearchFurnitureTypeUI = `
<div class="form-group mb-1">
<select onchange="onChangeOptionalKeyword()" class="form-control" name="txtOptionalKeyword" id="txtOptionalKeyword">
<option selected disabled="disabled">Choose...</option>
<option value="">None</option>
<option value="Furnished">Furnished</option>
<option value="Unfurnished">Unfurnished</option>
<option value="Part Furnished">Part Furnished</option>
</select>
</div>
`
const inputSearchDatetimeRangeUI = `
<div class="ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset ui-input-has-clear">
<input type="datetime-local" id="txtDatetime1" onchange="onChangeDatetime1()" data-clear-btn="true" name="datetime1" max="9999-12-31T23:59">
<a href="#" tabindex="-1" aria-hidden="true"
onclick="onClearDatetime1()"
class="ui-input-clear ui-btn ui-icon-delete ui-btn-icon-notext ui-corner-all ui-input-clear-hidden"
title="Clear text">Clear text</a>
</div>
<div class="ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset ui-input-has-clear">
<input type="datetime-local" id="txtDatetime2" onchange="onChangeDatetime2()" data-clear-btn="true" name="datetime2" max="9999-12-31T23:59">
<a href="#" tabindex="-1" aria-hidden="true"
onclick="onClearDatetime2()"
class="ui-input-clear ui-btn ui-icon-delete ui-btn-icon-notext ui-corner-all ui-input-clear-hidden"
title="Clear text">Clear text</a>
</div>
`
const inputSearchPriceRangeUI = `
<div class="form-group mb-2">
<input
onchange="onChangePrice1()"
id="txtPrice1" name="txtPrice1"
type="number" class="form-control"
placeholder="Price 1" aria-label="Username" aria-describedby="basic-addon1">
</div>
<div class="form-group mb-1">
<input
onchange="onChangePrice2()"
id="txtPrice2" name="txtPrice2"
type="number" class="form-control"
placeholder="Price 2" aria-label="Username" aria-describedby="basic-addon1">
</div>
`
function setInputSearchType(UISetting) {
$('#inputSearchType').empty()
$('#inputSearchType').append(UISetting)
}
$(document).on("pagecreate", () => {
// intial search type for all
setInputSearchType(inputSearchAllUI);
})
$('select#searchType').on('change', () => {
// set search type
searchType = $('#searchType').val()
// reset keyword
resetSearchInput()
// change ui
switch (searchType) {
case 'all':
setInputSearchType(inputSearchAllUI);
break;
case 'property_type':
setInputSearchType(selectSearchPropertyTypeUI);
break;
case 'bedroom_type':
setInputSearchType(selectSearchBedroomTypeUI)
break;
case 'datetime_local':
setInputSearchType(inputSearchDatetimeRangeUI)
break;
case 'price':
setInputSearchType(inputSearchPriceRangeUI)
break;
case 'furniture_type':
setInputSearchType(selectSearchFurnitureTypeUI)
break;
case 'notes':
setInputSearchType(inputSearchNotesUI)
break;
case 'reporter_name':
setInputSearchType(inputSearchReporterNameUI);
break;
default:
break;
}
})
<file_sep>/platforms/browser/www/js/editPage/state.js
let editedApartment = {
bedroom_type: "One",
datetime_local: "2222-02-22T14:22",
furniture_type: "Furnished",
image: "",
notes: "222www",
price: 222,
property_type: "House",
reporter_name: "2131hiep",
_id: 2
}
// let editedId;
// let editedPropertyType = $('#editedPropertyType');
// let editedBedroomType ;
// let editedDatetimeLocal;
// let editedPrice;
// let editedFurnitureType;
// let editedNotes;
// let editedDescription;
// let editedReporterName;
// let editedImage = "";
// property_type, bedroom_type, datetime_local,
// price, furniture_type, notes, reporter_name, image, description
function onEditApartment(_id) {
editedApartment = records.find(item => item._id === _id);
}
$(document).on("pagebeforeshow", "#editPage", () => {
setInitial();
})
function resetFields() {
setInitial();
alert('Fields are reseted.');
}
function setInitial() {
// this run after onEditApartment()
$('#editedPropertyType').val(editedApartment.property_type);
$('#editedPropertyType-button span').text(editedApartment.property_type);
//
$('#editedBedroomType').val(editedApartment.bedroom_type);
$('#editedBedroomType-button span').text(editedApartment.bedroom_type);
//
$('#editedDatetimeLocal').val(editedApartment.datetime_local);
$('#editedPrice').val(editedApartment.price);
//
$('#editedFurnitureType').val(editedApartment.furniture_type);
$('#editedFurnitureType-button span').text(editedApartment.furniture_type || "None");
//
$('#editedNotes').val(editedApartment.notes);
$('#editedReporterName').val(editedApartment.reporter_name);
$('#myEditedImage').attr('src', editedApartment.image);
}
<file_sep>/platforms/browser/www/js/apartmentDetailPage/funcs.js
function showApartmentDetail(_id) {
const record = records.find(item => item._id === _id);
apartment = record;
// $('#apartmentDetail').popup('open');
// window.open("/#apartmentDetail");
$("#propertyTypeDetail").text(record.property_type);
$('#bedroomTypeDetail').text(record.bedroom_type);
$('#datetimeLocalDetail').text(moment(record.datetime_local).format('MMM Do YYYY, h:mm a'));
$('#priceDetail').text(record.price);
$('#furnitureTypeDetail').text(record.furniture_type);
$('#notesDetail').text(record.notes);
$('#reporterNameDetail').text(record.reporter_name);
$('#myImageDetail').attr("src", record.image);
}<file_sep>/www/js/exercise1.js
function ringABell() {
navigator.notification.beep(1);
}
function vibrate() {
navigator.vibrate(2000);
}
<file_sep>/platforms/browser/www/js/clickOutsideMenu.js
// https://codepen.io/alexgill/pen/EWWojp
$(document).mouseup(e => {
for (var i = 0; i < records.length; i++) {
$menu = $(`li#id${records[i]._id} p#btnsControlApartment`);
if (!$menu.is(e.target) // if the target of the click isn't the container...
&& $menu.has(e.target).length === 0) // ... nor a descendant of the container
{
$menu.children().not(':first-child').remove();
}
}
});
<file_sep>/platforms/browser/www/js/loadPage/funcs/filter/index.js
$('form#search-form').validate({
rules: {
datetime1: {
required: true
},
datetime2: {
required: true
},
txtKeyword: {
required: true
},
txtPrice1: {
required: true
},
txtPrice2: {
required: true
}
},
messages: {
txtPrice1: {
required: "Please input a price."
},
txtPrice2: {
required: "Please input a price."
}
},
errorPlacement: function (error, element) {
error.prependTo(element.parent());
},
// submit form
submitHandler: function (form) {
switch (searchType) {
case 'all':
filterForAllFields();
break;
case 'property_type':
filterForPropertyType();
break;
case 'bedroom_type':
filterForPropertyType();
break;
case 'datetime_local':
filterForDatetimeLocal();
break;
case 'price':
filterForPrice();
break;
case 'furniture_type':
filterForFurnitureType();
break;
case 'reporter_name':
filterForReporterName();
break;
case 'notes':
filterForNotes();
break;
default:
break;
}
displayApartments(searchedRecords)
return false;
}
});
function filterForAllFields() {
if (!keyword) {
searchedRecords = records;
return;
}
searchedRecords = records.filter(item => {
for (let key in item) {
str = JSON.stringify(item[key])
if (doesIncludeKeyword(str)) return true
}
return false
})
}
function filterForPropertyType() {
searchedRecords = records.filter(item => item[searchType] === keyword)
}
function filterForFurnitureType() {
if (keyword) {
filterForPropertyType();
return
}
searchedRecords = records.filter(item => !item[searchType] ? true : false)
}
function filterForDatetimeLocal() {
searchedRecords = records.filter(item => moment(item[searchType]).isBetween(datetime1, datetime2, null, '[]'))
}
function filterForPrice() {
searchedRecords = records.filter(item => {
if (item[searchType] <= price1 && item[searchType] >= price2) return true;
if (item[searchType] >= price1 && item[searchType] <= price2) return true;
return false;
})
}
function filterForReporterName() {
searchedRecords = records.filter(item => doesIncludeKeyword(item[searchType]))
}
function filterForNotes() {
if (keyword) {
filterForReporterName(); // has the same effect
return
}
searchedRecords = records.filter(item => !item[searchType] ? true : false)
}
function doesIncludeKeyword(str) {
strLow = str.toLowerCase()
keywordLow = keyword.toLowerCase()
return strLow.includes(keywordLow)
}
<file_sep>/www/js/loadPage/funcs/record/ui.js
function getApartmentUI(record) {
return `
<li id="id${record._id}">
<a href="#apartmentDetail" class="ui-btn property-type-listviewitem-header" style="padding-left: 0px; padding-right: 0px" onclick="showApartmentDetail(${record._id})">
<center class="property-type">${record.property_type}</center>
</a>
${record.image ? `
<a href="#apartmentDetail" class="ui-btn property-type-listviewitem-header" style="padding: 0px; border-top: 0px;">
<center>
<img onclick="showApartmentDetail(${record._id})" src="${record.image}" alt="" class="apartment-image">
</center>
</a>
` : ''}
<a class="ui-btn property-type-listviewitem-details" style="border-top: 0px; background-color: #f6f6f6; cursor: default">
<p id="btnsControlApartment">
<img id="btnMenu" class="apartment-control" src="img/menu.png" alt="" onclick="onToggleMenu(${record._id})">
</p>
<p>Bedroom Type: ${record.bedroom_type}</p>
<p>Created At: ${moment(record.datetime_local).format('MMM Do YYYY, h:mm a')}</p>
<p>Monthly Rent Price: $${record.price}</p>
<p>Furniture Type: ${record.furniture_type}</p>
<p>Reporter Name: ${record.reporter_name}</p>
<p>Notes:</p>
<textarea onkeyup="showBtnsControlNotes(${record._id})" cols="40" rows="8" name="textarea" id="textarea" class="ui-input-text ui-shadow-inset ui-body-inherit ui-corner-all ui-textinput-autogrow" style="height: 42px; font-size: 0.8rem;">${record.notes}</textarea>
<p id="btnsControlNotes">
<span id="saveNotes" onclick="onSaveNotes(${record._id})">Save</span>
<span> </span>
<span id="cancelChangeNotes" onclick="onCancelChangeNotes(${record._id})">Cancel</span>
</p>
</a>
</li>
`
}
const menufunctions = (_id) => `
<a href="#" onclick="onDeleteApartment(${_id})">
<img src="img/delete.png" class="apartment-control" alt="">
</a>
<a href="#editPage" onclick="onEditApartment(${_id})">
<img src="img/edit.png" class="apartment-control" alt="">
</a>
`
function onToggleMenu(_id) {
const parent = $(`li#id${_id} p#btnsControlApartment`);
const check = parent.children().length;
if (check === 1) {
parent.append(menufunctions(_id))
return
}
parent.children().not(':first-child').remove();
}
function showBtnsControlNotes(_id) {
$(`#id${_id} #btnsControlNotes`).css('display', 'block')
}
function hideBtnsControlNotes(_id) {
$(`#id${_id} #btnsControlNotes`).css('display', 'none')
}<file_sep>/README.md
# Toturial refs
* https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-dialogs/index.html
* https://stackoverflow.com/questions/5995628/adding-attribute-in-jquery
https://www.w3schools.com/jquery/jquery_css.asp
* https://stackoverflow.com/questions/21190632/is-there-a-way-to-handle-clear-event-on-text-input-in-jquery-mobile
# UI maintain docs (if it is hard to maintain)
* to add one more property type, should modify in index.html#addPage, loadPage.js > selectSearchPropertyTypeUI.
* to add one more field, should modify in index.html#addPage, index.html#loadPage > #search-form
# Little Errors
When change database, or table structure, should clear existed database or table
<file_sep>/platforms/browser/www/js/loadPage/funcs/records.js
// LOAD RECORDS
$(document).on("pagebeforeshow", "#loadpage", () => {
clearRecordsState();
Apartment.loadRecords(setRecordsInClient);
})
function setRecordsInClient({ rows }) {
for (var i = 0; i < rows.length; i++) {
records.push(rows.item(i))
}
displayApartments(records);
}
function displayApartments(list) {
// // delete in ui
$('#apartments').empty();
// display
for (var i = 0; i < list.length; i++) {
const apartmentUI = getApartmentUI(list[i]);
$('#apartments').append(apartmentUI);
}
}
//
function onDeleteAllApartments() {
const check = confirm('Are you sure to delete all records?');
if (check) {
// delete in db
Apartment.deleteAllRecords();
// clear state
clearRecordsState();
// render again
displayApartments(records);
}
}<file_sep>/www/js/models/database.js
console.log("database handler");
const db = window.openDatabase(
"rentalZ2.db",
"1.0",
"Rental apartments database",
5*1024*1024
);
db.transaction(
function(tx){
//
tx.executeSql(
"create table if not exists apartments(_id integer primary key, property_type text, bedroom_type text, datetime_local text, price real, furniture_type text, notes text, reporter_name text, image text)",
[],
function(tx, results) {},
function(tx, error) {
console.log("Error while creating the table: " + error.message)
}
)
},
function(error) {
console.log("Transaction error: " + error.message);
},
function() {
console.log("Create DB transaction completed successfully");
}
)
| 24510f2bd3fe988e76e0f12a49ce4fe5dfde4899 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | hiep294/phonegap-basic | dea8f5b9cd939d0536beaf1a43abf6af71415dee | 2eb97ca8d578a975388b09850a70053811bea743 |
refs/heads/master | <repo_name>Antoinebr/Puppeteer-Service<file_sep>/__tests__/thirdparty.test.js
//routes.test.js
const request = require('supertest');
const app = require('../app');
process.env.PORT = 4300
/**
* beforeAll
*
* Runs before running all the tests
*/
beforeAll(() => {
const listener = app.listen(process.env.PORT, () => console.log('Your app is listening on port ' + listener.address().port))
// setting up test specific route :
app.get('/controllHomePage', (req, res) => res.sendFile(__dirname + '/assets/thirdparty/home.html'));
app.get('/controllHomePageSlowedDown', (req, res) => setTimeout( () => res.sendFile(__dirname + '/assets/thirdparty/home.html'), 34000) );
});
/**
* afterAll
*
* Runs after running all the tests
*/
afterAll(() => {
console.log('server closed!');
});
describe('Test the third party endpoint', () => {
beforeEach(() => {
jest.setTimeout(200000);
});
it('should return a 4xx when the url patameter is missing', async () => {
const response = await request(app).get('/get3p');
expect(response.status).toEqual(400);
});
it('should send an error with a 500 status', async () => {
const response = await request(app).get('/get3p?url=google.fr');
expect(response.status).toEqual(500);
expect(response.text).toEqual("Error: Protocol error (Page.navigate): Cannot navigate to invalid URL");
});
it('should return a 200 HTTP code on the asset page', async () => {
const response = await request(app).get('/controllHomePage');
expect(response.status).toEqual(200);
});
it('should detect third party on the controll page', async () => {
const response = await request(app).get(`/get3p?url=http://localhost:${process.env.PORT }/controllHomePage`);
expect(response.status).toEqual(200);
expect(response.text).toEqual('{\"shouldBeBlocked\":[\"zopim.com\",\"google-analytics.com\",\"facebook.net\"],\"shouldntBeBlocked\":[]}');
});
it('shouldn\'t return a timeout', async() => {
const response = await request(app).get(`/get3p?url=http://localhost:${process.env.PORT }/controllHomePageSlowedDown`);
expect(response.status).toEqual(200);
expect(response.text).toEqual('{\"shouldBeBlocked\":[\"zopim.com\",\"google-analytics.com\",\"facebook.net\"],\"shouldntBeBlocked\":[]}');
});
});<file_sep>/controllers/thirdpartyCtrl.js
const list = require('../thirdparty-list/list');
const puppeteer = require('puppeteer');
const URL = require('url');
const {
dumpError
} = require('../utils/error');
exports.get3p = async (request, response) => {
const url = request.query.url;
if (!url) return response.status(400).send('Please provide a URL. Example: ?url=https://example.com');
const browser = await puppeteer.launch({
dumpio: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'], // , '--disable-dev-shm-usage']
});
if (request.query.mocked) {
return response.json({
"shouldBeBlocked": [
"netmng.com",
"googleadservices.com",
"google-analytics.com",
"googletagmanager.com",
"facebook.net",
"youtube.com"
],
"shouldntBeBlocked": [
"sc-static.net",
"ytimg.com",
"yimg.com",
"googleapis.com",
"cdn-jaguarlandrover.com"
]
});
}
try {
const page = await browser.newPage();
await page.goto(url, {
waitUntil: 'load',
timeout : 90000
});
if (process.env.DEBUG) {
console.log(`[Pupeeteer] Opened dd ${url}`);
}
await page.waitFor(2000);
const thirdPartyScripts = await page.evaluate(() => {
const domainList = new Set();
[...document.querySelectorAll('script')]
.filter(e => !e.src.includes(document.location.hostname) && e.src !== "")
.map(e => domainList.add(e.src));
return [...domainList];
});
const thirdPartyHosts = thirdPartyScripts.map(e => URL.parse(e).host);
if (process.env.DEBUG) {
console.log(thirdPartyHosts);
console.log(`[Pupeeteer] Finished ${url}`);
}
const thirdPartyScriptsClassified = list.classifyThirdParties(thirdPartyHosts);
response.json(thirdPartyScriptsClassified);
} catch (err) {
if (process.env.DEBUG) {
console.log(dumpError(err))
}
response.status(500).send(err.toString());
}
await browser.close();
};<file_sep>/thirdparty-list/list.js
const fs = require('fs');
const parseDomain = require('parse-domain');
// read the list from the file
const known3pHostname = fs.readFileSync(__dirname + '/3plist.txt');
// put the elements in an object to garantee a O(1) access
//
// @example : {googleAnalytics : googleAnalytics, gtm : gtm }
//
const listof3P = {};
known3pHostname.toString().split('\n').forEach(domain => listof3P[domain] = domain);
/**
* isAThirdPaty
* test if a given element is in the object
* @param {string} hostname
* @returns {bool}
*/
const isAThirdPaty = hostname => listof3P[hostname] ? true : false;
/**
* isThirdPartyURL
* test if a given URL is a thrid party
* @param {string} hostname
* @returns {bool}
*/
exports.isThirdPartyURL = url => {
const {
domain,
tld
} = parseDomain(url);
hostname = `${domain}.${tld}`;
return isAThirdPaty(hostname);
}
/**
* classifyThirdParties
*
* @param {array} hostnameList an array of hostnames
* @returns {object} with 2 keys shouldBeBlocked (array) shouldntBeBlock (array)
*/
exports.classifyThirdParties = hostnameList => {
let shouldBeBlocked = new Set();
let shouldntBeBlocked = new Set();
for (let hostname of hostnameList) {
const {
domain,
tld
} = parseDomain(hostname);
hostname = `${domain}.${tld}`;
isAThirdPaty(hostname) ? shouldBeBlocked.add(hostname) : shouldntBeBlocked.add(hostname);
}
return {
shouldBeBlocked: [...shouldBeBlocked],
shouldntBeBlocked: [...shouldntBeBlocked]
}
}<file_sep>/Makefile
build:
docker build -t antoine/docker-puppeteer . --force-rm;
run:
docker run -d -p 3001:8080 -it antoine/docker-puppeteer<file_sep>/controllers/coverageCtrl.js
const puppeteer = require('puppeteer');
const list = require('../thirdparty-list/list');
const URL = require('url');
class coverageRunner {
constructor(
url,
EVENTS = [
'domcontentloaded',
'load',
]) {
this.url = url;
this.stats = new Map();
this.EVENTS = EVENTS;
}
/**
* addUsage
*
* @param {!Object} coverage
* @param {string} type Either "css" or "js" to indicate which type of coverage.
* @param {string} eventType The page event when the coverage was captured.
*/
addUsage(coverage, type, eventType) {
for (const entry of coverage) {
if (!this.stats.has(entry.url)) {
this.stats.set(entry.url, []);
}
const urlStats = this.stats.get(entry.url);
let eventStats = urlStats.find(item => item.eventType === eventType);
if (!eventStats) {
eventStats = {
cssUsed: 0,
jsUsed: 0,
get usedBytes() {
return this.cssUsed + this.jsUsed;
},
totalBytes: 0,
get percentUsed() {
return this.totalBytes ? Math.round(this.usedBytes / this.totalBytes * 100) : 0;
},
eventType,
url: entry.url,
};
urlStats.push(eventStats);
}
eventStats.totalBytes += entry.text.length;
for (const range of entry.ranges) {
eventStats[`${type}Used`] += range.end - range.start - 1;
}
}
}
/**
* collectCoverage
*
* @param {string} URL
*/
async collectCoverage(URL) {
const browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'], // , '--disable-dev-shm-usage']
headless: true
});
console.log("[codeCoverage] pupetteer started...");
// Do separate load for each event. See
// https://github.com/GoogleChrome/puppeteer/issues/1887
const collectPromises = this.EVENTS.map(async event => {
const page = await browser.newPage();
await Promise.all([
page.coverage.startJSCoverage(),
page.coverage.startCSSCoverage()
]);
await page.goto(URL, {
waitUntil: event
});
await page.waitFor(5000);
// await page.waitForNavigation({waitUntil: event});
const [jsCoverage, cssCoverage] = await Promise.all([
page.coverage.stopJSCoverage(),
page.coverage.stopCSSCoverage()
]);
this.addUsage(cssCoverage, 'css', event);
this.addUsage(jsCoverage, 'js', event);
await page.close();
});
await Promise.all(collectPromises);
return browser.close();
}
/**
*
*
* @param {string} URL
*/
async collectCoverageFromPupetter(URL = this.url) {
return new Promise(async (resolve, reject) => {
try {
let data = {
summary: {},
urls: []
};
await this.collectCoverage(URL);
for (const [url, vals] of this.stats) {
this.EVENTS.forEach(event => {
const usageForEvent = vals.filter(val => val.eventType === event);
if (usageForEvent.length) {
for (const stats of usageForEvent) {
const formatter = new UsageFormatter(stats);
formatter.stats.summary = formatter.summary();
data.urls.push(formatter.stats);
}
}
});
}
// Print total usage for each event.
this.EVENTS.forEach(event => {
let totalBytes = 0;
let totalUsedBytes = 0;
const metrics = Array.from(this.stats.values());
const statsForEvent = metrics.map(eventStatsForUrl => {
const statsForEvent = eventStatsForUrl.filter(stat => stat.eventType === event)[0];
// TODO: need to sum max totalBytes. Currently ignores stats if event didn't
// have an entry. IOW, all total numerators should be max totalBytes seen for that event.
if (statsForEvent) {
totalBytes += statsForEvent.totalBytes;
totalUsedBytes += statsForEvent.usedBytes;
}
});
const percentUsed = Math.round(totalUsedBytes / totalBytes * 100);
// create summary
data.summary[event] = {}
data.summary[event].percentUsed = percentUsed;
data.summary[event].totalUsedBytes = formatBytesToKB(totalUsedBytes);
data.summary[event].totalBytes = formatBytesToKB(totalBytes);
});
return resolve(data);
} catch (error) {
return reject(`Something went wrong ${error}`);
}
});
}
}
function formatBytesToKB(bytes) {
if (bytes > 1024) {
const formattedNum = new Intl.NumberFormat('en-US', {
maximumFractionDigits: 1
}).format(bytes / 1024);
return `${formattedNum}KB`;
}
return `${bytes} bytes`;
}
/**
* UsageFormatter
*
* Format the data
*/
class UsageFormatter {
constructor(stats) {
this.stats = stats;
}
summary(used = this.stats.usedBytes, total = this.stats.totalBytes) {
const percent = Math.round((used / total) * 100);
return `${formatBytesToKB(used)}/${formatBytesToKB(total)} (${percent}%)`;
}
shortSummary(used, total = this.stats.totalBytes) {
const percent = Math.round((used / total) * 100);
return used ? `${formatBytesToKB(used)} (${percent}%)` : 0;
}
}
/**
*
* @param {object} coverage
* @param {string} mainURL
*/
const identifyThirdParty = (coverage, mainURL) => {
const mainHost = URL.parse(mainURL).host;
coverage.urls = coverage.urls.map(c => {
const host = URL.parse(c.url).host;
c.isExternal = (host === mainHost) ? false : true;
c.isThirdParty = list.isThirdPartyURL(host);
return c;
});
return coverage;
}
/**
* readTheCoverage
*
* @param {object} coverage
* @param {string} event
* @param {string} type
* @param {boolean} filter3P
*/
const readTheCoverage = (coverage, event, type = "js", filter3P = false) => {
let final = coverage.urls.filter(c => c.eventType === event);
// for JavaScript
if (type === "js") {
final = final.filter(c => c.jsUsed > 0 && c.cssUsed === 0);
if (filter3P) final = final.filter(c => !c.isThirdParty);
}
// for CSS
if (type === "css") final = final.filter(c => c.cssUsed > 0 && c.jsUsed === 0);
let urlTotalBytes = final.reduce((initial, url) => initial + url.totalBytes, initial = 0);
let urlUsedBytes = final.reduce((initial, url) => initial + url.usedBytes, initial = 0);
return {
event,
filter3P,
percentageUsed: Math.round(urlUsedBytes / urlTotalBytes * 100),
percentageUnused: 100 - Math.round(urlUsedBytes / urlTotalBytes * 100),
totalBytes: urlTotalBytes
}
}
exports.sendCoverage = async (req, res) => {
console.log(`[codeCoverage] Request... ${req.query.url}`)
const coverageData = new coverageRunner(req.query.url);
let coverage = await coverageData.collectCoverageFromPupetter()
.catch(e => res.status(500).send(`Something went wrong ${e}`));
coverage = identifyThirdParty(coverage, req.query.url);
res.json({
js: readTheCoverage(coverage, 'load', 'js', req.query.filter3p),
css: readTheCoverage(coverage, 'load', 'css'),
coverage
});
};<file_sep>/README.md
# Puppeteer Service
A service to get different informations from a given website thanks to Puppeteer
More endpoints and features to come
## How to start
```make build && make run```
## API
### Get the third party for a given domain
```bash
curl -X GET 'http://localhost:3001/get3p?url=https://www.renault.fr/' \
-H 'Content-Type: application/json'
```
Returns :
```shouldntBeBlocked``` is equal to everything but marketing tags, so you find CDN...
```JSON
{
"shouldBeBlocked": [
"netmng.com",
"googleadservices.com",
"google-analytics.com",
"googletagmanager.com",
"facebook.net",
"youtube.com"
],
"shouldntBeBlocked": [
"sc-static.net",
"ytimg.com",
"yimg.com",
"googleapis.com",
]
}
```
### Get the code coverage of a given url
```bash
curl -X GET 'http://localhost:3001/coverage?url=https://www.renault.fr/' \
-H 'Content-Type: application/json'
```
Retuns :
(The response example is truncated )
```JSON
{
"summary": {
"domcontentloaded": {
"percentUsed": 17,
"totalUsedBytes": "796KB",
"totalBytes": "4,659.5KB"
},
"load": {
"percentUsed": 39,
"totalUsedBytes": "2,711.4KB",
"totalBytes": "6,967.8KB"
},
"networkidle0": {
"percentUsed": 39,
"totalUsedBytes": "2,764.1KB",
"totalBytes": "7,038KB"
}
},
"urls": [
{
"cssUsed": 0,
"jsUsed": 0,
"usedBytes": 0,
"totalBytes": 4186,
"percentUsed": 0,
"eventType": "domcontentloaded",
"url": "https://libs.cdn.renault.com/etc/designs/renault_v2/18.13.1.RENAULT-7/common-assets/css/fonts/fonts-latin-basic.min.css",
"summary": "0 bytes/4.1KB (0%)"
},
{
"cssUsed": 0,
"jsUsed": 12727,
"usedBytes": 12727,
"totalBytes": 41338,
"percentUsed": 31,
"eventType": "networkidle0",
"url": "https://c.la1-c1-lon.salesforceliveagent.com/content/g/js/35.0/deployment.js?_=1543409239150",
"summary": "12.4KB/40.4KB (31%)"
}
]
}
```
### Get a mobile screenshot
```bash
curl -X GET 'http://localhost:3001/screenshot?url=https://www.renault.fr/'
```
Returns : the image
## Deploy this image ?
### You can use Google Cloud Run
Deploy the image :
```
gcloud builds submit --tag gcr.io/<nameOfYourGCPProject>/puppeteer-service
```
Deploy the image :
```
gcloud beta run deploy --image gcr.io/<nameOfYourGCPProject>/puppeteer-service --memory=1Gi
```<file_sep>/app.js
const express = require('express');
const cors = require('cors');
const thirdpartyCtrl = require('./controllers/thirdpartyCtrl');
const coverageCtrl = require('./controllers/coverageCtrl');
const screenshotCtrl = require('./controllers/screenshotCtrl')
const app = express();
app.use(cors());
// router
app.get('/', (req, res) => res.json({availableRoutes: [`${req.protocol}://${req.headers.host}/get3p/?url=https://renault.fr`, `${req.protocol}://${req.headers.host}/coverage/?url=https://renault.fr`, `${req.protocol}://${req.headers.host}/screenshot/?url=https://renault.fr`]}));
app.get('/get3p', thirdpartyCtrl.get3p);
app.get('/coverage', coverageCtrl.sendCoverage);
app.get('/screenshot', screenshotCtrl.takeScreenshot);
module.exports = app;<file_sep>/utils/error.js
const chalk = require('chalk');
exports.dumpError = (err) => {
if (typeof err === 'object') {
if (err.message) {
console.log(chalk.red('\nMessage: ' + err.message));
}
if (err.stack) {
console.log(chalk.blue('\nStacktrace:\n===================='));
console.log(chalk.yellow(err.stack));
console.log(chalk.blue('===================='));
}
} else {
console.log('dumpError :: argument is not an object');
}
};<file_sep>/controllers/screenshotCtrl.js
const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const phone = devices['Nexus 5X'];
exports.takeScreenshot = async (request,response) => {
const url = request.query.url;
if (!url) {
return response.status(400).send(
'Please provide a URL. Example: ?url=https://example.com');
}
// Default to a reasonably large viewport for full page screenshots.
const viewport = {
width: 1280,
height: 1024,
deviceScaleFactor: 2
};
let fullPage = true;
const size = request.query.size;
if (size) {
const [width, height] = size.split(',').map(item => Number(item));
if (!(isFinite(width) && isFinite(height))) {
return response.status(400).send(
'Malformed size parameter. Example: ?size=800,600');
}
viewport.width = width;
viewport.height = height;
fullPage = false;
}
const browser = await puppeteer.launch({
dumpio: true,
// headless: false,
// executablePath: 'google-chrome',
args: ['--no-sandbox', '--disable-setuid-sandbox'], // , '--disable-dev-shm-usage']
});
try {
const page = await browser.newPage();
await page.setViewport(viewport);
await page.emulate(phone);
await page.goto(url, {
waitUntil: 'networkidle0'
});
const opts = {
fullPage,
// omitBackground: true
type:"jpeg", quality: 60
};
if (!fullPage) {
opts.clip = {
x: 0,
y: 0,
width: viewport.width,
height: viewport.height
};
}
let buffer;
const element = request.query.element;
if (element) {
const elementHandle = await page.$(element);
if (!elementHandle) {
return response.status(404).send(
`Element ${element} not found`);
}
buffer = await elementHandle.screenshot();
} else {
buffer = await page.screenshot(opts);
}
response.type('image/png').send(buffer);
} catch (err) {
response.status(500).send(err.toString());
}
await browser.close();
} | cd53ba3b537c5aa3d4498fec400dd6c45728ecc0 | [
"JavaScript",
"Makefile",
"Markdown"
] | 9 | JavaScript | Antoinebr/Puppeteer-Service | 82016a26c2e1430b41af140a6a5985a80eb110b0 | 9c5cc0718e0d1d66e8b45aa3c0ef475bc498a752 |
refs/heads/master | <repo_name>NuNote/NuNote-app<file_sep>/php/ForgotPassword.php
<?php
// User Forgot Password
// This Will Be Changed If We Have Time
// This Is Going Off The Idea That We
// Have A Page Accessible When Logining In
// It Will Ask For Their UserName
?><file_sep>/php/UploadGroup.php
<?php
// Upload Group Page
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
//$json = '{"uploadGroup":1, "username":"test"}';
//$arr = json_decode($json, true);
//$uploadGroup = $arr['uploadGroup'];
//$username = $arr['username'];
$uploadGroup = $_GET['uploadGroupID'];
$typed = array();
$scanned = array();
$picture = array();
$info = array();
$documents = array();
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
// Query For Typed Documents
$sql = "SELECT Documents.ID, Documents.Rating, Documents.RatingCount, Documents.OriginalFileName
FROM Documents
WHERE Documents.UploadGroup = '$uploadGroup' AND Documents.DocType = 'Typed' LIMIT 3;";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($doc = mysqli_fetch_assoc($res))
{
array_push($typed, [
'documentid' => $doc['ID'],
'documentRating' => $doc['Rating'],
'documentRatingCount' => $doc['RatingCount'],
'documentFileName' => $doc['OriginalFileName']
]);
}
$info = array("Typed"=>"true");
}
else
{
$info = array("Typed"=>"false");
}
// Query For Picture Documents
$sql = "SELECT Documents.ID, Documents.Rating, Documents.RatingCount, Documents.OriginalFileName
FROM Documents
WHERE Documents.UploadGroup = '$uploadGroup' AND Documents.DocType = 'Picture' LIMIT 3;";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($doc = mysqli_fetch_assoc($res))
{
array_push($picture, [
'documentid' => $doc['ID'],
'documentRating' => $doc['Rating'],
'documentRatingCount' => $doc['RatingCount'],
'documentFileName' => $doc['OriginalFileName']
]);
}
$info['picture'] = "true";
}
else
{
$info['picture'] = "false";
}
// Query For Scanned Documents
$sql = "SELECT Documents.ID, Documents.Rating, Documents.RatingCount, Documents.OriginalFileName
FROM Documents
WHERE Documents.UploadGroup = '$uploadGroup' AND Documents.DocType = 'Scanned' LIMIT 3;";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($doc = mysqli_fetch_assoc($res))
{
array_push($scanned, [
'documentid' => $doc['ID'],
'documentRating' => $doc['Rating'],
'documentRatingCount' => $doc['RatingCount'],
'documentFileName' => $doc['OriginalFileName']
]);
}
$info['scanned'] = "true";
}
else
{
$info['scanned'] = "false";
}
$documents = array($info,$typed, $scanned, $picture);
echo json_encode($documents, JSON_NUMERIC_CHECK);
}
$conn->close();
?><file_sep>/php/NoteListing.php
<?php
// Note Listing Page
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
//$json = '{"uploadGroup":1, "docType":"typed"}';
//$arr = json_decode($json, true);
$uploadGroup = $_GET['uploadGroup'];
$docType = $_GET['docType'];
$documents = array();
$error = array();
$pageInfo = array();
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
// Query For Typed Documents
$sql = "SELECT Documents.ID, Documents.Rating, Documents.RatingCount, Documents.OriginalFileName
FROM Documents
WHERE Documents.UploadGroup = '$uploadGroup' AND Documents.DocType = '$docType'";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($doc = mysqli_fetch_assoc($res))
{
array_push($documents, [
'documentid' => $doc['ID'],
'documentRating' => $doc['Rating'],
'documentRatingCount' => $doc['RatingCount'],
'documentFileName' => $doc['OriginalFileName']
]);
}
$error = array("error"=>"False");
}
else
{
$error = array("error"=>"True");
}
$pageInfo = array($error, $documents);
echo json_encode($pageInfo, JSON_NUMERIC_CHECK);
}
$conn->close();
?><file_sep>/Register:Verify User/Readme.txt
*****************************************
README RegisterUser/UserLogin
*****************************************
This is to explain the two php documents
RegisterUser.php and UserLogin.php and
the corresponding screenshots to show
they are working properly.
We first start with RegisterUser.php and
a blank Users table as shown in screenshot
"Empty". Then shown in screenshot
"TestUTestP" we are inserting the username
"test" and the password "<PASSWORD>" into the
Users Table. When the code is ran, we can
see from screenshot "UpdateTest" that the
info was added successfully to the Users
table.
If we run RegisterUser.php again we can
see that it does not enter duplicate
usernames into the table, so all usernames
need to be uniqe. This is shown in screenshot
"UserNameTaken".
We then move to UserLogin.php and, as shown
in screenshot "LoginTest", we are attempting
to login user "test" using the password
"<PASSWORD>". We can see from screenshot
"InvalidPassword" that the user "test" was
found in the database, but the password
does not match.
If we then change the password to the
correct password that is "<PASSWORD>". We can
see from screenshot "LoginSuccessful" that
password matches what is hashed in the
table and user is allowed to login
A concern would be does the hash function
unique for each password as this will protect
from rainbow tables. The answer is yes and is
demonstrated
We first move back to RegisterUser.php and
update the username to "test2", but the password
stays the same as shown is screenshot
"Test2SamePassword". Once RegisterUser.php is
ran we can see from screenshot
"2UsersSamePassDifferentHash" that the hashed
password is unique for each user even though
the two users happen to have the same password
Next we can verify that user "test2" can still
login with UserLogin.php as shown in screenshots
"Test2Login" and "Test2LoginSuccess" we can
see that user "test2" logins succesfully with
password "<PASSWORD>"
Also UserLogin.php check to make sure username
entered is in the database before checking
for password. We can see from screenshot
"UserNameNotFound" that the username is
not in the Users table and we know that
because we only have two usernames in the table
as shown before, those being "test" and "test2"
These are all the scenarios that I could think
of that involbed Registering and Logging in a
User. Please let me know what else needs to
be added. All code and screenshots mentioned
are in this zip file. <file_sep>/php/UploadFile.php
<?php
// This Works With testUpload.html, But
// It Currently Does Not Work With
// The DropZone Thing That Was Added
// We Might Need To Change How
// Documents Are Uploaded On FrontEnd
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
$testUser = 1;
$testUploadGroup = 1;
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully";
echo '<br />';
}
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$tmpName = $_FILES["fileToUpload"]["tmp_name"];
$fileName = $_FILES["fileToUpload"]["name"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$newFileName = tempnam('uploads/', '');
unlink($newFileName);
$newFileName = $newFileName.".".$imageFileType;
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newFileName))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
//$sql = "INSERT INTO Documents (FileName, Uploader, UploadGroup, FilePath, Rating, Status, OriginalFileName, DocType) VALUES('$tmpName', '$testUser', '$testUploadGroup', '$target_dir', 5, 'Good', '$fileName', 'Typed')";
$sql = "INSERT INTO Documents (FileName, Uploader, UploadGroup, FilePath, Rating, Status, OriginalFileName, DocType)
VALUES('$newFileName', '$testUser', '$testUploadGroup', '$target_dir', 5, 'Good', '$fileName', 'Typed')";
if ($conn->query($sql) === TRUE)
{
echo "Document Uploaded Successfully";
echo '<br />';
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
echo '<br />';
}
$conn->close();
}
else {
echo "Sorry, there was an error uploading your file.";
}
}
?><file_sep>/js/register.js
$(document).ready(function() {
console.log("ready");
sessionStorage.removeItem("findClassResults");
initStates();
});
$(function() {
$('select').change(function() {
console.log("it got called");
if ($(this).val() != "default") {
console.log($('select').index(this));
console.log($('select').index(this) + 1);
resetDropdowns($('select').index(this) + 1);
console.log($(this).attr("id"));
var nextIndex = $('select').index(this) + 1;
var nextSelectID = $('select').eq(nextIndex).attr("id");
console.log("next index: " + nextIndex);
console.log("next select id: " + nextSelectID);
if (nextSelectID == "city-select") {
$.ajax({
type: "GET",
data: {
"function": "city",
"state": $(this).val()
},
url: "php/general.php",
dataType: "json",
success: function(data) {
//return data;
console.log(data);
var cities = data;
fillDropDown("city-select", cities);
},
error: function() {
alert("Ahh fug");
}
});
} else if (nextSelectID == "school-select") {
$.ajax({
type: "GET",
data: {
"function": "school",
"state": $("#state-select").val(),
"city": $(this).val()
},
url: "php/general.php",
dataType: "json",
success: function(data) {
//return data;
//console.log(data);
console.log(data);
var schools = data;
fillDropDown("school-select", schools);
},
error: function() {
alert("Ahh fug");
}
});
}
}
});
});
function resetDropdowns(currentSelection) {
// Make sure next box is enabled and reset
$('select').eq(currentSelection).val("default");
$('select').eq(currentSelection).attr("disabled", false);
// disable and reset all other boxes
for (i = currentSelection + 1; i < 5; i++) {
$('select').eq(i).val("default");
$('select').eq(i).attr("disabled", true);
}
}
function fillDropDown(divID, optionsArray) {
$("#" + divID).empty();
//$("#" + divID).append("<option value=\"default\">Select State</option>");
$("#" + divID).append("<option value=\"default\">Select Option</option>");
$.each(optionsArray, function(i, p) {
//console.log(p);
$("#" + divID).append($('<option>' + p + '</option>'));
})
}
function initStates() {
$.ajax({
type: "GET",
data: {
"function": "state"
},
url: "php/general.php",
dataType: "json",
success: function(data) {
console.log(data);
var states = data;
fillDropDown("state-select", states);
},
error: function() {
alert("Ahh fug");
}
});
}<file_sep>/php/ReportComment.php
<?php
// Report Comment
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
// Type Of Report (Spam, Rule Break, Possible Trump)
// For Comments Reports Can Only Be Spam Or Rule Break
$type = 'Spam';
$comment_id = 1;
$explanation = 'This is me complaining';
$votes = 0;
$user = 1;
$timestamp = date("Y-m-d H:i:s");
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully";
echo '<br />';
$sql = "INSERT INTO CommentReport (CommentID, Type, Explanation, Votes, UserID, ReportDate)
VALUES('$comment_id', '$type', '$explanation', '$votes', '$user', '$timestamp')";
if ($conn->query($sql) === TRUE)
{
echo "Comment Reported Successfully";
echo '<br />';
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
echo '<br />';
}
$conn->close();
}
?><file_sep>/php/CreateUploadGroup.php
<?php
// Create Upload Group
// Have to use "127.0.0.1"
// instead of localhost
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
/*
$classID = $_GET['classID'];
$name = $_GET['name'];
*/
$classID = 1;
$name = "Newer UploadGroup";
$error = array();
$conn = new mysqli($servername, $myname, $mypass, $dbname);
if ($conn->connect_error)
{
//die("Connection failed: " . $conn->connect_error);
$error["error"] = "True";
$error["reason"] = "Connection error";
}
else
{
$sql = "SELECT Name From Upload_Groups WHERE ClassID='$classID' AND Name='$name'";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
$error["error"] = "True";
$error["reason"] = "Name taken";
}
else
{
$sql = "INSERT INTO Upload_Groups (Name, ClassID)
VALUES ('$name', '$classID')";
if ($conn->query($sql) === TRUE)
{
$error["error"] = "False";
}
else
{
$error["error"] = "True";
$error["reason"] = "Connection error";
}
}
}
echo json_encode($error);
$conn->close();
?><file_sep>/php/ClassPage.php
<?php
// Class Page
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
$json = '{"classid":1, "username":"test"}';
$arr = json_decode($json, true);
//$classid = $arr['classid'];
$classid = $_POST['classid'];
//$username = $arr['username'];
$username = $_POST['username'];
$class = array();
$info = array();
$uploadGroup = array();
$pageInfo = array();
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
// Query For Upload Groups For This Class
$sql = "SELECT * From Upload_Groups Where ClassID = '$classid';";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($tmp = mysqli_fetch_assoc($res))
{
array_push($uploadGroup, [
'groupID' => $tmp['ID'],
'groupName' => $tmp['Name']
]);
}
$info = array("uploadGroup"=>"True");
}
else
{
$info = array("uploadGroup"=>"False");
}
// Query For Class Professor Info
$sql = "SELECT Classes.ID, Classes.ProfessorID, Professors.FirstName, Professors.LastName
FROM (Classes
INNER JOIN Professors ON Classes.ProfessorID = Professors.ID)
WHERE Classes.ID = '$classid';";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($tmp = mysqli_fetch_assoc($res))
{
array_push($class, [
'fName' => $tmp['FirstName'],
'lName' => $tmp['LastName']
]);
}
$info['error'] = "False";
}
else
{
$info['error'] = "True";
}
$pageInfo = array($info,$uploadGroup, $class);
echo json_encode($pageInfo, JSON_NUMERIC_CHECK);
}
//echo json_encode($username);
?><file_sep>/php/UploadDocument.php
<?php
// UPLOAD DOCUMENT
// DOES NOT WORK YET
if(!empty($_FILES))
{
// Have to use "127.0.0.1"
// instead of localhost
$servername = "127.0.0.1";
$myname = "root";
$mypass = "<PASSWORD>";
$dbname = "SchoolThing";
$testUser = 1;
$testUploadGroup = 1;
// Create Connection
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully";
echo '<br />';
}
$targetDirectory = "/upload-target";
$fileName = $_FILES['file']['name'];
//$tmpName = $_FILES['file']['tmp_name'];
// $fileType = $_FILES['file']['type'];
//$ext = pathinfo($fileName, PATHINFO_EXTENSION);
//if ($ext === 'png') || ($ext === 'jpeg')
//{
// $fileType = 'Picture';
//}
//elseif ($ext === 'pdf')
//{
// $fileType = 'Scanned';
//}
//else
//{
// $fileType = 'Typed';
//}
$targetFile = $targetDirectory.$tmpName;
//$targetFile = $targetDirectory.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile))
{
$sql = "INSERT INTO Documents (FileName, Uploader, UploadGroup, FilePath, Rating, Status, OrginalFileName, DocType) VALUES('$tmpName', '$testUser', '$testUploadGroup', '$targetDirectory', 500, 'Good', '$fileName', 'Typed')";
$conn->query($sql);
insert file information into db table
if ($conn->query($sql) === TRUE)
{
echo "Document Uploaded Successfully";
echo '<br />';
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
echo '<br />';
}
$conn->close();
}
}
?><file_sep>/js/doc_select.js
var numOfDocs = 0;
var numOfDocs2 = 0;
var numOfDocs3 = 0;
var docTitle = "some title.doc";
var docRating;
var numOfDocsPerRow = 4;
var numOfDocsPerRow2 = 4;
var numOfDocsPerRow3 = 4;
var colSize = 3;
var rVal, gVal;
// remember, ratings on scale from 0 to 5
var currentClassInfo = JSON.parse(sessionStorage.getItem("currClassInfo"));
$(document).ready(function() {
$(".class-name-header").text(currentClassInfo.className + ", " + sessionStorage.getItem("currDocGroupName"));
$(".doc-type-header").text(sessionStorage.getItem("currDocType") + " Documents");
getDocsAJAX();
});
$(function() {
// Need to make number of docs per row scale with screen width
//$('div').click(function() { // WHY DO YOU WORK AND THE OTHER ONE DOESN'T
// if (event.target.id == "inner-div") {
// alert("she clicc me");
// }
//})
$('#add-stuff-btn').click(function() {
appendDocuments('.main-div-1');
});
$('#add-stuff-btn-2').click(function() {
if (numOfDocs2 % numOfDocsPerRow2 === 0) {
$('#current2').attr("id", "full");
$('.other-div-1').append("<div id=\"current2\"; class=\"row\"<div>");
}
docRating = (Math.random() * 5).toFixed(1);
// Not a huge fan of the green color :T
if (docRating <= 2.5) {
rVal = 255;
gVal = docRating * 40;
} else {
rVal = (5 - docRating) * 40;
gVal = 255;
}
$('#current2').append(
"<div class=\"col-md-" + colSize + "\">" +
"<h4 style=\"text-align: center;\">" +
"<div id=\"inner-div\">" +
"<p class=\"doc-title\">" + docTitle + "</p>" +
"<div class=\"circle\" style=\"background-color: rgb(" + rVal + "%, " + gVal + "%, 0%)\">" + docRating + "</div>" +
"</div>" +
"</h4>" +
"</div>");
numOfDocs2++;
});
$('#add-stuff-btn-3').click(function() {
if (numOfDocs3 % numOfDocsPerRow3 === 0) {
$('#current3').attr("id", "full");
$('.third-div-1').append("<div id=\"current3\"; class=\"row\"<div>");
}
docRating = (Math.random() * 5).toFixed(1);
// Not a huge fan of the green color :T
if (docRating <= 2.5) {
rVal = 255;
gVal = docRating * 40;
} else {
rVal = (5 - docRating) * 40;
gVal = 255;
}
$('#current3').append(
"<div class=\"col-md-" + colSize + "\">" +
"<h4 style=\"text-align: center;\">" +
"<div id=\"inner-div\">" +
"<p class=\"doc-title\">" + docTitle + "</p>" +
"<div class=\"circle\" style=\"background-color: rgb(" + rVal + "%, " + gVal + "%, 0%)\">" + docRating + "</div>" +
"</div>" +
"</h4>" +
"</div>");
numOfDocs3++;
});
//$('#inner-div').click(function() { // WHY DON'T YOU WORK
// console.log("she clicc?");
// alert("she clicc me");
//});
});
/*
function appendDocuments(divID) {
if (numOfDocs % numOfDocsPerRow === 0) {
$('#current').attr("id", "full");
$(divID).append("<div id=\"current\"; class=\"row\"<div>");
}
docRating = (Math.random() * 5).toFixed(1);
// Not a huge fan of the green color :T
if (docRating <= 2.5) {
rVal = 255;
gVal = docRating * 40;
} else {
rVal = (5 - docRating) * 40;
gVal = 255;
}
$('#current').append(
"<div class=\"col-md-" + colSize + "\">" +
"<h4 style=\"text-align: center;\">" +
"<div id=\"inner-div\" class=\"document-div\">" +
"<p class=\"doc-title\">" + docTitle + "</p>" +
"<div class=\"circle\" style=\"background-color: rgb(" + rVal + "%, " + gVal + "%, 0%)\">" + docRating + "</div>" +
"</div>" +
"</h4>" +
"</div>");
numOfDocs++;
}*/
function appendDocument(divID, docTitle, docRating, docID) {
if (numOfDocs % numOfDocsPerRow === 0) {
$('#current').attr("id", "full");
$("#" + divID).append("<div id=\"current\"; class=\"row\"<div>");
}
//docRating = (Math.random() * 5).toFixed(1);
// Not a huge fan of the green color :T
if (docRating <= 2.5) {
rVal = 255;
gVal = docRating * 40;
} else {
rVal = (5 - docRating) * 40;
gVal = 255;
}
$('#current').append(
"<div class=\"col-md-" + colSize + "\">" +
"<h4 style=\"text-align: center;\">" +
"<div class=\"inner-div document-div\" id=\"" + docID + "\">" +
"<p class=\"doc-title\">" + docTitle + "</p>" +
"<div class=\"circle\" style=\"background-color: rgb(" + rVal + "%, " + gVal + "%, 0%)\">" + docRating + "</div>" +
"</div>" +
"</h4>" +
"</div>");
numOfDocs++;
}
function getDocsAJAX() {
$.ajax({
type: "GET",
data: {"uploadGroup" : sessionStorage.getItem("currDocGroupID"), "docType" : sessionStorage.getItem("currDocType")},
url: "php/NoteListing.php",
dataType: "json",
complete: function(data) { //eventually change to success
console.log("yay!");
console.log(data);
},
error: function() {
alert("Ahh fug");
}
});
}<file_sep>/php/RegisterUser.php
<?php
//REGISTER USER
//*******************************
// THIS IS A PROOF OF CONCEPT
//*******************************
// IT CURRENTY DOES NOT PREVENT
// SQL INJECTION; HOWEVER, I
// HAVE A PROPER WAY TO DO IT
// BUT THAT IS AN EXTRA FEATURE
// THAT WILL BE WORRIED ABOUT LATER
//
// WILL REQUIRE POST TO RECEIVE
// VARIABLES FROM FORM AS
// SHOWN ON THE 2 LINES BELOW
// $username=$_POST['user'];
// $password=$_POST['pass'];
//*******************************
session_start();
// Have to use "127.0.0.1"
// instead of localhost
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
/*
$testname = "Bryan";
$testlast = "Janes";
$testU = "test";
$testpass = "<PASSWORD>";
$testemail = "email";
$testrep = 500;
$testflagged = "Yes";
$testschool = 1;
*/
$testname = $_GET["reg-fname"];
$testlast = $_GET["reg-lname"];
$testU = $_GET["reg-uname"];
$testpass = $_GET["reg-pass"];
$testemail = $_GET["reg-email"];
$testrep = 500;
$testflagged = "No";
//$testschool = 1;
//$_GET["school-select"]
$city = $_GET["city-select"];
$state = $_GET["state-select"];
$school = $_GET["school-select"];
$hash = crypt($testpass);
$success;
$errorMessage;
//echo $hash;
//echo '<br />';
// Create Connection
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
$success = false;
die("Connection failed: " . $conn->connect_error);
}
else
{
$sql = "SELECT ID FROM Schools WHERE State = '$state' AND City = '$city' AND Name = '$school'";
$res = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($res);
$testschool = $row['ID'];
// Check If Username Is Taken
$sql = "SELECT * FROM Users where UserName= '$testU'";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
//echo 'UserName Is Taken';
//echo '<br />';
$success = false;
$errorMessage = "UserName Is Taken";
}
else
{
// If Not Taken Put User Info Into Database
$sql = "INSERT INTO Users (FirstName, LastName, UserName, Password, EmailAddr, Reputation, flagged, SchoolID)
VALUES ('$testname', '$testlast', '$testU', '$hash', '$testemail', '$testrep', '$testflagged', '$testschool')";
if ($conn->query($sql) === TRUE)
{
//echo "New record created successfully";
//echo '<br />';
// Create Session For Username Which Can Be Used Elsewhere
$_SESSION["username"] = $testU;
$success = true;
$errorMessage = "";
}
else
{
//echo "Error: " . $sql . "<br>" . $conn->error;
//echo '<br />';
$success = false;
$errorMessage = $conn->error; // is this right?
}
}
}
$reply = array($success, $errorMessage);
echo json_encode($reply);
$conn->close();
?><file_sep>/php/create_class.php
<!DOCTYPE html>
<html>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = '<PASSWORD>';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$json = '{"classname":"test", "professorid":1, "schoolid":1, "subjectid":1, "classnumber":5000, "classcode":"CSCE"}';
$arr = json_decode($json, true);
$classname = $arr['classname'];
$professorid = $arr['professorid'];
$schoolid = $arr['schoolid'];
$subjectid = $arr['subjectid'];
$classnumber = $arr['classnumber'];
$classcode = $arr['classcode'];
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = "INSERT INTO Classes (Name, ProfessorID, SchoolID, SubjectID, ClassNumber, ClassCode)
VALUES ($classname, $professorid, $schoolid, $subjectid, $classnumber, $classcode);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// close connection
mysql_close($conn);
?>
</body>
</html>
<file_sep>/php/general.php
<?php
$function = $_GET['function'];
if ($function == 'state')
{
getStates();
} elseif ($function == 'city')
{
$state = $_GET['state'];
getCities($state);
} elseif ($function == 'school')
{
$state = $_GET['state'];
$city = $_GET['city'];
getSchool($state, $city);
} elseif ($function == 'general')
{
getGeneralSubject();
} elseif ($function == 'specific')
{
$general = $_GET['general'];
getSpecificSubject($general);
}
function getStates(){
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$data = array();
$sql = "SELECT DISTINCT State FROM Schools ORDER BY State";
$res = mysqli_query($conn,$sql);
while ($row=mysqli_fetch_array($res))
{
$data[] = $row['State'];
}
echo json_encode($data);
}
}
function getCities($state){
$servername = "127.0.0.1";
$myname = "root";
$mypass = "";
$dbname = "nunote";
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$data = array();
$sql = "SELECT DISTINCT City FROM Schools WHERE State='$state' ORDER BY City";
$res = mysqli_query($conn,$sql);
while ($row=mysqli_fetch_array($res))
{
$data[] = $row['City'];
}
echo json_encode($data);
}
}
function getSchool($state, $city){
$servername = "127.0.0.1";
$myname = "root";
$mypass = "";
$dbname = "nunote";
$conn = new mysqli($servername, $myname, $mypass, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$data = array();
$sql = "SELECT Name FROM Schools WHERE State='$state' and City='$city' ORDER BY Name";
$res = mysqli_query($conn, $sql);
while ($row=mysqli_fetch_array($res))
{
$data[] = $row['Name'];
}
echo json_encode($data);
}
}
function getGeneralSubject(){
$servername = "127.0.0.1";
$myname = "root";
$mypass = "";
$dbname = "nunote";
$conn = new mysqli($servername, $myname, $mypass, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$data = array();
$sql = "SELECT Name FROM General_Subjects ORDER BY Name";
$res = mysqli_query($conn, $sql);
while ($row=mysqli_fetch_array($res))
{
$data[] = $row['Name'];
}
echo json_encode($data);
}
}
function getSpecificSubject($general)
{
$servername = "127.0.0.1";
$myname = "root";
$mypass = "";
$dbname = "nunote";
$conn = new mysqli($servername, $myname, $mypass, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$data = array();
$sql = "Select GS_Subjects.GeneralName, Specific_Subjects.Name
FROM ((Specific_Subjects
INNER JOIN GS_Subjects ON Specific_Subjects.ID = GS_Subjects.SpecificID)
INNER JOIN General_Subjects ON GS_Subjects.GeneralName = General_Subjects.Name)
WHERE General_Subjects.Name = '$general' ORDER BY Name";
$res = mysqli_query($conn, $sql);
while ($row=mysqli_fetch_array($res))
{
$data[] = $row['Name'];
}
echo json_encode($data);
}
}
?>
<file_sep>/js/global/nav.js
/*$(document).ready(function() {
});
/*$(window).bind("resize", setMaxWidth);
function setMaxWidth() {
$('body').css("maxWidth", $(window).width() + "px");
}
});*/
var barMoving = false;
$(document).ready(function() {
//alert("nav UserName is: " + sessionStorage.getItem("username"));
$("#username-link").text(sessionStorage.getItem("username"));
//alert($('.karma-rank').find('a').text());
$('.karma-rank').find('a').text("KARMA: " + sessionStorage.getItem("karma"));
});
$(function() {
$("#logout-link").click(function() {
$('.fade-in-mask').fadeIn(150);
$('.spinner-div-container').show();
$(".sub-navbar").animate({
'top': "-=150px"
}, 350, function() {
window.location.href = "index.html";
});
$('.navbar').animate({
'top': "-=75px"
}, 350, function() {
window.location.href = "index.html";
});
});
$(".profile-dropdown").click(function() {
console.log($(".sub-navbar").position().top);
if ($(".sub-navbar").position().top >= 70) {
moveSubNav("down");
} else {
moveSubNav("up");
}
});
$("#find-class-btn").click(function() {
moveSubNav("down");
loadContent("find_class");
});
$('#user-page-btn').click(function() {
moveSubNav("down");
loadContent("user_page");
});
$('html').click(function(e) {
if (e.target != $('.navbar-static-top')[0] && !$.contains($('.navbar-static-top')[0], e.target)) {
if ($(".sub-navbar").position().top >= 70) {
moveSubNav("down");
}
}
});
});
function moveUp() {
$('.navbar').animate({
'top': "-=75px"
}, 450, function() {
window.location.href = "index.html";
});
}
function moveSubNav(direction) {
if (!barMoving) {
barMoving = true;
if (direction == "up") {
$('.sub-navbar').animate({
'top': "+=80px"
}, 280, function() {
barMoving = false;
});
} else {
$('.sub-navbar').animate({
'top': "-=80px"
}, 280, function() {
barMoving = false;
});
}
}
}
/*
function setSelectID(id) {
selectID = id;
}
// Use to load content based on previous page selections
function getSelectID() {
return selectID;
}
function loadContent(content) {
$('.fade-in-mask').fadeIn(150);
$('.spinner-div-container').show();
var toLoad = content + ".html";
//alert(toLoad);
$(".main-body").load(toLoad, function() {
$('.spinner-div-container').hide();
$('.fade-in-mask').fadeOut(150);
});
}*/<file_sep>/php/ReportDocument.php
<?php
// Report Document
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
// Type Of Report (Spam, Rule Break, Possible Trump)
// For Documents Reports Can Be All 3
$type = 'Rule Break';
$document_id = 1;
$explanation = 'This is me complaining';
$votes = 0;
$user = 1;
$timestamp = date("Y-m-d H:i:s");
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully";
echo '<br />';
$sql = "INSERT INTO DocumentReport (DocumentID, Type, Explanation, Votes, UserID, ReportDate)
VALUES('$document_id', '$type', '$explanation', '$votes', '$user', '$timestamp')";
if ($conn->query($sql) === TRUE)
{
echo "Document Reported Successfully";
echo '<br />';
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
echo '<br />';
}
$conn->close();
}
?><file_sep>/php/AddClass.php
<?php
//Add Class
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
$json = '{"classid":1, "username":"test"}';
$arr = json_decode($json, true);
$classid = $arr['classid'];
$username = $arr['username'];
$error = array();
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
$error = array("error"=>"False");
}
else
{
$sql = "SELECT ID FROM Users WHERE UserName = '$username'";
$res = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($res);
$userid = $row['ID'];
$sql = "INSERT INTO Users_Classes (UserID, ClassID)
VALUES ('$userid', '$classid')";
if ($conn->query($sql) === TRUE)
{
$error = array("error"=>"False");
}
else
{
$error = array("error"=>"True");
}
}
echo json_encode($error);
$conn->close();
?><file_sep>/php/AddDocComment.php
<?php
// This Works With testAddComment.html
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
$comment = $_POST['comment'];
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully";
echo '<br />';
}
$status = 'Good';
$testUser = 1;
$testDoc = 1;
$sql = "INSERT INTO Comments (DocumentID, Comment, UserID, Status)
VALUES('$testDoc', '$comment', '$testUser', '$status')";
if ($conn->query($sql) === TRUE)
{
echo "Comment Uploaded Successfully";
echo '<br />';
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
echo '<br />';
}
$conn->close();
?><file_sep>/js/login_page.js
$(document).ready(function() {
sessionStorage.clear();
$(".spinner-div-container").hide();
$('.fade-in-mask').fadeOut(350);
$('#main-body').animate({
'margin-top': "+=2vw"
}, 500);
});
$(function() {
$('html').click(function(e) {
if (e.target.id == 'login-btn' && !$('#popup-window').hasClass('show')) {
$('#popup-window').toggleClass('show');
$('.dark-mask').fadeIn(200);
popupLoadContent("login-popup");
//popupLoadContent("register_user");
popupVisible = true;
} else if (e.target.id == 'login-window-button') {
if ($("#user").val() === "" || $("#pass").val() === "") {
alert("Please make sure you enter both a name and a password!");
return;
}
loginAJAX();
if (false) { // validate credentials when backend is linked
alert("Invalid username or password");
return;
}
return;
} else if (e.target.id == 'find-class-btn') {
$('.fade-in-mask').fadeIn(350);
$('#main-body').animate({
'margin-top': "-=2vw"
}, 500, function() {
sessionStorage.setItem("isGuest", true);
goToHomePage();
});
return;
} else if (e.target.id == 'register-btn') {
//alert("link to register page");
popupLoadContent("register_user");
initStates();
} else if (e.target.id == 'forgotPass') {
alert("Maybe add \"enter user id or email\" thing or something to reset password");
} else if (e.target.id == 'register-window-btn') {
//alert("send registry info to backend");
if (areAllRegBoxesFilled()) {
registerAJAX();
}
} else if (e.target.id == 'back-btn') {
popupLoadContent("login-popup");
} else if (e.target != $('#popup-window')[0] && !$.contains($('#popup-window')[0], e.target)) {
if ($('#popup-window').hasClass('show')) {
$('#popup-window').toggleClass('show');
$('.dark-mask').fadeOut(200);
}
}
});
});
function parseResponse(data) {
sessionStorage.setItem("karma", data[2][0].karma);
sessionStorage.setItem("school", data[2][0].school);
sessionStorage.setItem("schoolID", data[2][0].schoolID);
sessionStorage.setItem("username", data[2][0].username);
sessionStorage.setItem("docUploadsInfo", JSON.stringify(data[3]));
console.log(data[4]);
for (var i in data[4]) {
console.log(data[4][i]);
}
sessionStorage.setItem("classesInfo", JSON.stringify(data[4]));
var classesInfo = JSON.parse(sessionStorage.getItem("classesInfo"));
console.log(classesInfo[0]);
}
function goToHomePage() {
if (JSON.parse(sessionStorage.getItem("isGuest"))) {
sessionStorage.setItem("username", "guest");
sessionStorage.setItem("karma", "N/A");
} else {
$('#popup-window').toggleClass('show');
$('.dark-mask').fadeOut(200);
}
$('.fade-in-mask').fadeIn(350);
$('#main-body').animate({
'margin-top': "-=2vw"
}, 500, function() {
$('.spinner-div-container').show();
window.location.href = "home_page.html";
});
}
function registerAJAX() {
$.ajax({
type: "GET",
data: $("#reg-form").serialize(),
url: "php/RegisterUser.php",
dataType: "json",
success: function(data) { //eventually change to complete
console.log("yay!");
//if (da)
console.log(data);
//console.log(data.responseText);
//console.log(data.responseText[0]);
//console.log(data.responseText[1]);
console.log($.parseJSON(data[0]));
if (!$.parseJSON(data[0])) {
console.log("uh oh");
alert(data[1]);
} else {
alert("Success!");
popupLoadContent("login-popup");
}
},
error: function() {
alert("Ahh fug");
}
});
}
function areAllRegBoxesFilled() {
fieldIDs = ["reg-fname", "reg-lname", "reg-uname", "reg-pass", "reg-email"];
for (var i = 0; i < fieldIDs.length; i++) {
if ($("#" + fieldIDs[i]).val() === "") {
alert("Please make sure you've entered all of your info!");
return false;
}
}
if ($("#school-select").val() === "default") {
alert("Please make sure you've entered all of your info!");
return false;
}
return true;
}
function loginAJAX() {
$.ajax({
type: "GET",
data: $("#login-form").serialize(),
url: "php/UserLogin.php",
dataType: "json",
success: function(data) { //eventually change to complete
//console.log(data[0]);
if ($.parseJSON(data[0])) {
//alert("it exists!");
//alert(sessionStorage.getItem("username"));
// check if second thing had error
console.log(data);
parseResponse(data);
sessionStorage.setItem("isGuest", false);
goToHomePage();
} else {
alert("das wrong, mayne");
// inject "wrong" message to login page
}
},
error: function() {
alert("Ahh fug");
}
});
}<file_sep>/php/UserClass.php
<?php
// User's Classes
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
//$testU = "blah";
$json = '{"id":1,"firstname":"Bryan","username":"test"}';
$arr = json_decode($json, true);
//echo $arr['id'];
$id = $arr['id'];
//$id = 2;
$firstname = $arr['firstname'];
$username = $arr['username'];
//echo $id;
//echo '<br />';
//echo $firstname;
//echo '<br />';
//echo $username;
//echo '<br />';
// Create Connection
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully";
echo '<br />';
}
// SELECT STATMENT WITH MULTIPLE JOINS
// WE MIGHT NEED TO CHANGE THIS TO NOT SHOW AS
// MUCH DATA
$sql = "SELECT Users_Classes.*, Classes.*, Professors.*
FROM ((Users_Classes
INNER JOIN Classes ON Users_Classes.ClassID = Classes.ID )
INNER JOIN Professors ON Classes.ProfessorID = Professors.ID)
WHERE Users_Classes.UserID = '$id'";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
$classes = array();
$num = mysqli_num_rows($res);
while($result = mysqli_fetch_assoc($res))
{
array_push($classes, [
'id' => $id,
'firstname' => $firstname,
'username' => $username,
'numOfClasses' => $num,
'className' => $result['Name'],
'classNum' => $result['ClassNumber'],
'firstProf' => $result['FirstName'],
'lastProf' => $result['LastName']
]);
}
$class = json_encode($classes, JSON_NUMERIC_CHECK);
echo $class;
}
else
{
echo "No Classes Listed In Table";
echo '<br />';
$rows = array("id"=>$id, "firstname"=>$firstname, "username"=>$username, "className"=>"Error - No Classes");
echo json_encode($rows,JSON_NUMERIC_CHECK);
}
//$sql = "SELECT * FROM Users where UserName= '$testU'";
//$res = mysqli_query($conn,$sql);
// JSON IS WORKING ON THIS
// FINALLY FIGURED IT OUT :)
/*
********************************************************
$result = mysqli_query($conn, "SELECT * FROM Users");
$rows = array();
while($r = mysqli_fetch_assoc($result))
{
//$rows['object_name'][] = $r;
//$rows[] = $r;
array_push($rows, [
'id' => $r['ID'],
'firstname' => $r['FirstName'],
'lastname' => $r['LastName'],
'username' => $r['UserName'],
'reputation' => $r['Reputation'],
'schoolid' => $r['SchoolID']
]);
}
$blah = json_encode($rows, JSON_NUMERIC_CHECK);
//print json_encode($rows);
echo $blah;
echo '<br />';
$arr = json_decode($blah, true);
echo $arr[0]['id'];
echo '<br />';
echo $arr[1]['id'];
echo '<br />';
echo $arr[0]['firstname'];
********************************************************
*/
?><file_sep>/php/NotePage.php
<?php
// Note Page
//*************************
// THIS SHOULD NOT BE USED
//*************************
// NOT FINISHED
// FIGURING OUT HOW TO PULL
// SUBCOMMENTS CORRECTLY
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
$json = '{"documentid":1, "username":"test"}';
$arr = json_decode($json, true);
$classid = $arr['documentid'];
$username = $arr['username'];
$conn = new mysqli($servername, $myname, $mypass, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
}
?><file_sep>/php/UserLogin.php
<?php
// USER LOGIN
//*******************************
// THIS IS A PROOF OF CONCEPT
//*******************************
// IT CURRENTY DOES NOT PREVENT
// SQL INJECTION; HOWEVER, I
// HAVE A PROPER WAY TO DO IT
// BUT THAT IS AN EXTRA FEATURE
// THAT WILL BE WORRIED ABOUT LATER
//
// WILL REQUIRE POST TO RECEIVE
// VARIABLES FROM FORM AS
// SHOWN ON THE 2 LINES BELOW
// $username=$_POST['user'];
// $password=$_POST['pass'];
//*******************************
session_start();
// Have to use "127.0.0.1"
// instead of localhost
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
//$testU = "test";
//$testpass = "<PASSWORD>";
$testU = $_GET['user'];
$testpass = $_GET['pass'];
$userInfo = array();
$userClass = array();
$userUploads = array();
$pageInfo = array();
$error = array();
$loginSucc;
// Create Connection
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
// Check If UserName Is In Table
$sql = "SELECT * FROM Users where UserName= '$testU'";
$res = mysqli_query($conn,$sql);
$loginSucc;
if(mysqli_num_rows($res)>0)
{
//echo 'UserName '.$testU.' Is In Table';
//echo '<br />';
// Check If Password Matches
$sql = "SELECT ID, Password From Users Where UserName = '$testU'";
$res = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($res);
$var = $row['Password'];
$id = $row['ID'];
if(crypt($testpass, $var) == $var)
{
//echo 'Password Matches - Successful Login';
$loginSucc = 'true';
$sql = "SELECT Users.UserName, Users.Reputation, Schools.*
FROM (Users
INNER JOIN Schools ON Users.SchoolID = Schools.ID)
WHERE Users.ID = '$id'";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($tmp = mysqli_fetch_assoc($res))
{
array_push($userInfo, [
'username' => $testU,
'karma' => $tmp['Reputation'],
'school' => $tmp['Name'],
'schoolID' => $tmp['ID']
]);
}
$error['error'] = "False";
}
else
{
$error['error'] = "True";
}
$sql = "SELECT ID, OriginalFileName FROM Documents Where Uploader = '$id' ORDER BY Upload_Date ASC LIMIT 3";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($tmp = mysqli_fetch_assoc($res))
{
array_push($userUploads, [
'documentID' => $tmp['ID'],
'fileName' => $tmp['OriginalFileName']
]);
}
$error['error'] = "False";
}
else
{
$error['error'] = "True";
}
$sql = "SELECT Users.UserName, Users_Classes.*, Classes.*
FROM ((Classes
INNER JOIN Users_Classes ON Classes.ID = Users_Classes.ClassID)
INNER JOIN Users ON Users_Classes.UserID = Users.ID)
WHERE Users.ID = '$id'";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($tmp = mysqli_fetch_assoc($res))
{
array_push($userClass, [
'classID' => $tmp['ID'],
'className' => $tmp['Name']
]);
}
$error['error'] = "False";
}
else
{
$error['error'] = "True";
}
}
else
{
//echo 'Invalid Password For UserName '.$testU;
$loginSucc = 'false';
}
}
else
{
//echo 'UserName '.$testU.' Not Found';
$loginSucc = 'false';
}
$pageInfo = array($loginSucc, $error, $userInfo, $userUploads, $userClass);
echo json_encode($pageInfo, JSON_NUMERIC_CHECK);
}
$conn->close();
// session_destroy();
?><file_sep>/js/user_page.js
var userID = "userName";
var userUploadsInfo = JSON.parse(sessionStorage.getItem("docUploadsInfo"));
var userClassesInfo = JSON.parse(sessionStorage.getItem("classesInfo"));
$(document).ready(function() {
// get user's school
$("#school-div").append("<h4><a href=\"#1\">" + sessionStorage.getItem("school") + "</a></h4>");
//console.log(userUploadsInfo);
// get user's classes
if (userClassesInfo.length > 0) {
showClasses();
} else {
$('#classes-div').append("<p>No Classes. :(</p>");
}
// get user's uploads (limit to 4 or so, limit on backend?)
if (userUploadsInfo.length > 0) {
showUploads();
} else {
$('#uploads-div').append("<p>No Uploads. :(</p>");
}
});
$(function() {
$(".class-link").click(function(e) {
var currClassName = $(this).text();
var currentClassInfo = $.grep(userClassesInfo, function(obj) {
return (obj.className == currClassName);
});
sessionStorage.setItem("currClassInfo", JSON.stringify(currentClassInfo[0]));
console.log(currentClassInfo[0].classID);
$.ajax({
type: "POST",
data: {"classid" : currentClassInfo[0].classID, 'username' : userID},
url: "php/ClassPage.php",
dataType: "json",
complete: function(data) { //eventually change to complete
console.log(data);
var docGroups = JSON.parse(data.responseText)[1];
var teacherNames = JSON.parse(data.responseText)[2][0];
console.log("doc groups:");
console.log(docGroups);
//console.log(teacherNames);
sessionStorage.setItem("currClassGroups", JSON.stringify(docGroups));
sessionStorage.setItem("currClassProfName", JSON.stringify(teacherNames));
loadContent("class_page");
},
error: function() {
alert("Ahh fug");
}
});
});
});
function showClasses() {
for (var i in userClassesInfo) {
$('#classes-div').append("<h4><a class=\"class-link\" href=\"#\">" + userClassesInfo[i].className + "</a></h4>");
}
}
function showUploads() {
for (var i in userUploadsInfo) {
$('#uploads-div').append("<h4><a href=\"#\">" + userUploadsInfo[i].fileName + "</a></h4>");
}
}<file_sep>/js/document_folder.js
var numOfDocs = 0;
var numOfDocsPerRow = 4;
var colSize = 3;
var rVal, gVal;
var currentClassInfo = JSON.parse(sessionStorage.getItem("currClassInfo"));
var docs;
// remember, ratings on scale from 0 to 5
$(document).ready(function() {
// append documents from backend here
$(".class-name-header").text(currentClassInfo.className + ", " + sessionStorage.getItem("currDocGroupName"));
docs = null;
$.ajax({
type: "GET",
data: {
"uploadGroupID": sessionStorage.getItem("currDocGroupID"),
"username": sessionStorage.getItem("username")
},
url: "php/UploadGroup.php",
dataType: "json",
complete: function(data) { //eventually change to complete
console.log(data);
docs = JSON.parse(data.responseText);
console.log(docs);
fillDivs();
},
error: function() {
alert("Ahh fug");
}
});
});
$(function() {
$('#add-stuff-btn').click(function() {
// change to do on doc load for each type div
// have loop through array, not numOfDocsPerRow
// if docs exist for type file
var test = true;
if (test) {
for (i = 0; i < numOfDocsPerRow - 1; i++) {
appendDocument('#typed-docs-div');
}
appendViewMoreDoc('#typed-docs-div', "typed");
} else {
$('#typed-docs-div').append("<p id=\"no-docs-par\">No Documents Here. :(</p>");
}
});
$(document).on('click', '.view-more-btn', function(event) {
//alert(event.target.id);
/*var parentTypeId = $(event.target).closest(".doc-type-div").attr("id");
var idSplit = parentTypeId.split("-");
sessionStorage.setItem("currDocType", idSplit[0]);*/
sessionStorage.removeItem("currDocType");
sessionStorage.setItem("currDocType", event.target.id);
//alert(sessionStorage.getItem("currDocType"));
loadContent("doc_select");
});
$(document).on('click', '.document-div', function(event) {
//alert(event.target.id);
var currDocType;
sessionStorage.removeItem("currDocID");
sessionStorage.setItem("currDocID", event.target.id);
loadContent("document_page");
// load content based on id
});
});
function appendDocGroup(groupName) {
}
function appendDocument(divID, docTitle, docRating, docID) {
if (numOfDocs % numOfDocsPerRow === 0) {
$('#current').attr("id", "full");
$("#" + divID).append("<div id=\"current\"; class=\"row\"<div>");
}
//docRating = (Math.random() * 5).toFixed(1);
// Not a huge fan of the green color :T
if (docRating <= 2.5) {
rVal = 255;
gVal = docRating * 40;
} else {
rVal = (5 - docRating) * 40;
gVal = 255;
}
$('#current').append(
"<div class=\"col-md-" + colSize + "\">" +
"<h4 style=\"text-align: center;\">" +
"<div class=\"inner-div document-div\" id=\"" + docID + "\">" +
"<p class=\"doc-title\">" + docTitle + "</p>" +
"<div class=\"circle\" style=\"background-color: rgb(" + rVal + "%, " + gVal + "%, 0%)\">" + docRating + "</div>" +
"</div>" +
"</h4>" +
"</div>");
numOfDocs++;
}
function appendViewMoreDoc(divID, uploadType) {
$("#current").append(
"<div class=\"col-md-3\">" +
"<h4 style=\"text-align: center;\">" +
"<div class=\"view-more-btn inner-div\" id=\" " + uploadType + "\">" +
"<p class=\"button-title\">VIEW MORE</p>" +
"</div>" +
"</h4>" +
"</a>" +
"</div>"
)
}
function fillDivs() {
// [1] is typed, [2] is scanned, [3] is [picture]
if (JSON.parse(docs[0].Typed)) {
for (var i = 0; i < docs[1].length; i++) {
console.log("there's typed");
console.log(docs[1][i]);
appendDocument("typed-docs-div", docs[1][i].documentFileName, docs[1][i].documentRating, docs[1][i].documentid);
}
appendViewMoreDoc("typed-docs-div", "typed"); // need to get group id or something
} else {
$("#typed-docs-div").append("<p>No Documents :(</p>");
}
console.log("\ndone\n");
numOfDocs = 0;
if (JSON.parse(docs[0].scanned)) {
console.log("there's scanned");
for (var j = 0; j < docs[2].length; j++) {
console.log(docs[2][j]);
appendDocument("scanned-docs-div", docs[2][j].documentFileName, docs[2][j].documentRating, docs[2][j].documentid);
}
appendViewMoreDoc("scanned-docs-div", "scanned"); // need to get group id or something
} else {
console.log("no scanned")
$("#scanned-docs-div").append("<p>No Documents :(</p>");
}
console.log("\ndone\n");
numOfDocs = 0;
console.log(JSON.parse(docs[0].picture));
if (JSON.parse(docs[0].picture)) {
console.log("there's pictures");
for (var k = 0; k < docs[3].length; k++) {
console.log(docs[3][k]);
appendDocument("photo-docs-div", docs[3][k].documentFileName, docs[3][k].documentRating, docs[3][k].documentid);
}
appendViewMoreDoc("photo-docs-div", "photos"); // need to get group id or something
} else {
console.log("I should run...");
$("#photo-docs-div").append("<p>No Documents :(</p>");
}
}<file_sep>/php/findclassTest.php
<!DOCTYPE html>
<html>
<?php
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
// Create Connection
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully";
echo '<br />';
}
?>
<head>
<style>
form {
margin: 0 auto;
width:155px;
text-align: center;
}
h1 {
text-align: center;
}
</style>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Find Class</h1>
<br>
<br>
<div class="container">
<form>
<div class="form-group">
<label for="sel1">Select State:</label>
<select class="form-control" id="sel1">
<option value="x">Select State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
<br>
<label for="sel2">Select State (list from database):</label>
<select class="form-control" id="sel2">
<option value="x">Select City</option>
<?php
$sql = mysqli_query($conn, "SELECT DISTINCT State FROM Schools ORDER BY State");
while ($row = $sql->fetch_assoc()){
?>
<option value="state"><?php echo $row['State']; ?></option>
<?php
// close while loop
}
?>
</select>
<input type="submit">
</div>
</form>
</div>
</body>
</html>
<?php
// close connection
mysql_close($conn);
?>
<file_sep>/python/convert.py
import sys, re, os, subprocess
from PIL import Image
from fpdf import FPDF
import pypandoc
# Documentation says this is all PyFPDF supports
validImageTypes = ["png", "jpeg", "jpg", "gif"]
# A LOT of these in the documentation
validDocTypes = ["doc", "docx", "txt", "rtf", "odt"]
# In case of multiple images
imageList = []
# Get file names from CLI arguments (testing)
for index in range(1, len(sys.argv) - 1):
imageList.append(sys.argv[index])
print "one file is: " + sys.argv[index]
# Converted PDF file name without directory
convertedFileName = re.search('^[^.]*', sys.argv[-1].rsplit('/', 1)[-1]).group(0) + ".pdf"
print "convertedFileName: " + convertedFileName
# Original file name with directory
fullFileName = sys.argv[1]
print "FULL file name: " + fullFileName
# Extract file extension
fileType = re.search('[^.]+$', fullFileName).group(0).lower()
print "file type: " + fileType
# Filter out directory portions if they exist
fileNameNoLocation = fullFileName.rsplit('/', 1)[-1]
print "File Name without directories: " + fileNameNoLocation
# Extract file name without extension
fileName = re.search('^[^.]*', fileNameNoLocation).group(0)
print "file NAME is: " + fileName
if fileType in validImageTypes:
print "\n\"" + fileType + "\" is a supported file type!"
pdf = FPDF()
pdf.set_auto_page_break(False)
pdf.set_display_mode("fullpage", "single")
for fullImageName in imageList:
pdf.add_page()
pdf.image(fullImageName, x = None, y = None, w = 0, h = 0, type = '', link = '')
pdf.output("OUTPUT/" + convertedFileName, 'F')
print convertedFileName + " written to OUTPUT directory"
elif fileType in validDocTypes:
print "\n\"" + fileType + "\" is a supported file type!"
convertedFileName = "OUTPUT/" + fileName + '.pdf'
if fileType in ["txt", "rtf"]:
output = pypandoc.convert(fullFileName, 'pdf', outputfile=convertedFileName, format='md')
elif fileType in ["odt", "docx"]:
output = pypandoc.convert(fullFileName, 'pdf', outputfile=convertedFileName, extra_args=['--latex-engine=xelatex'])
elif fileType == "doc":
subprocess.call( ['soffice',
'--headless',
'--convert-to',
'pdf',
fullFileName ] )
else:
output = pypandoc.convert(fullFileName, 'pdf', outputfile=convertedFileName)
else:
print "\n\"" + fileType + "\" is not supported"<file_sep>/php/repUser.php
<!DOCTYPE html>
<?php
$servername = "127.0.0.1";
$myname = "root";
$mypass = "<PASSWORD>";
$dbname = "nunote";
$json = '{"username":"test"}';
$arr = json_decode($json, true);
$username = $arr['username'];
// Create Connection
$conn = new mysqli($servername, $myname, $mypass, $dbname);
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully";
echo '<br />';
}
$sql = "UPDATE Users SET Reputation=Reputation + 1 WHERE UserName='$username'";
// close connection
mysql_close($conn);
?>
<file_sep>/php/DocView.php
<?php
// Note Page
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
$json = '{"documentid":1, "username":"test"}';
$arr = json_decode($json, true);
$documentid = $arr['documentid'];
$username = $arr['username'];
$docInfo = array();
$commInfo = array();
$error = array();
$pageInfo = array();
$conn = new mysqli($servername, $myname, $mypass, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
// Query For Document Info
$sql = "SELECT Documents.ID, Documents.Upload_Date, Users.ID, Users.UserName, Users.Reputation
FROM (Documents
INNER JOIN Users On Documents.Uploader = Users.ID)
WHERE Documents.ID = '$documentid'";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($doc = mysqli_fetch_assoc($res))
{
array_push($docInfo, [
'documentDate' => $doc['Upload_Date'],
'uploader' => $doc['UserName'],
'karma' => $doc['Reputation']
]);
}
$error = array("error"=>"False");
}
else
{
$error = array("error"=>"True");
}
// Query For Comment Info
$sql = "SELECT Comments.ID, Comments.Comment, Comments.UserID, Comments.Status, Comments.CommentDate, Users.UserName, Users.Reputation
FROM (Comments INNER JOIN Users ON Comments.UserID = Users.ID)
WHERE Comments.DocumentID = '$documentid'
ORDER BY Comments.CommentDate";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($comm = mysqli_fetch_assoc($res))
{
array_push($commInfo, [
'commentID' => $comm['ID'],
'message' => $comm['Comment'],
'commentStatus' => $comm['Status'],
'commentDate' => $comm['CommentDate'],
'username' => $comm['UserName'],
'karma' => $comm['Reputation']
]);
}
$error["comments"] = "True";
}
else
{
$error = array_push($error, ["comments"=>"False"]);
}
$pageInfo = array($error, $docInfo, $commInfo);
echo json_encode($pageInfo, JSON_NUMERIC_CHECK);
}
$conn->close();
?><file_sep>/php/FindClassResults.php
<?php
// FIND CLASS RESULTS
// Have to use "127.0.0.1"
// instead of localhost
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
/*
$state ="Alabama";
$city ="Fayetteville";
$school = "University of Arkansas";
$general = "Engineering";
$specific = "Computer Science/Computer Engineering";
*/
$state = $_GET['state'];
$city = $_GET['city'];
$school = $_GET['school'];
$general = $_GET['general'];
$specific = $_GET['specific'];
$pageInfo = array();
$class = array();
$error = array();
$conn = new mysqli($servername, $myname, $mypass, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$sql = "SELECT Classes.*
FROM ((Classes
INNER JOIN Schools ON Classes.SchoolID = Schools.ID)
INNER JOIN Specific_Subjects ON Classes.SubjectID = Specific_Subjects.ID)
WHERE Schools.Name = '$school' AND
Schools.City = '$city' AND
Schools.State = '$state' AND
Specific_Subjects.Name='$specific'";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res)>0)
{
while($tmp = mysqli_fetch_assoc($res))
{
array_push($class, [
'classID' => $tmp['ID'],
'className' => $tmp['Name']
]);
}
$error['error'] = "false";
}
else
{
$error['error'] = "true";
}
$pageInfo = array($error, $class);
echo json_encode($pageInfo, JSON_NUMERIC_CHECK);
}
//echo json_encode($sql);
$conn->close();
?><file_sep>/php/RateDocument.php
<?php
// Rate Document
// Have to use "127.0.0.1"
// instead of localhost
$servername = "127.0.0.1";
$myname = "root";
//$mypass = "";
$mypass = "<PASSWORD>";
$dbname = "nunote";
/*
$docID = $_GET['docID'];
$rating = $_GET['rating'];
*/
$docID = 1;
$rating = 3;
$error = array();
$conn = new mysqli($servername, $myname, $mypass, $dbname);
if ($conn->connect_error)
{
//die("Connection failed: " . $conn->connect_error);
$error = "True";
}
else
{
$error = "False";
if ($rating == 1)
{
$sql = "SELECT Rating, RatingCount, OneRating, TwoRating, ThreeRating, FourRating, FiveRating
FROM Documents where ID= '$docID'";
$res = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($res);
$oldRating = $row['Rating'];
$ratingCount = $row['RatingCount'];
$oneRating = $row['OneRating'];
$twoRating = $row['TwoRating'];
$threeRating = $row['ThreeRating'];
$fourRating = $row['FourRating'];
$fiveRating = $row['FiveRating'];
$oneRating = $oneRating + 1;
/*
echo $oneRating;
echo '<br />';
echo $twoRating;
echo '<br />';
echo $threeRating;
echo '<br />';
echo $fourRating;
echo '<br />';
echo $fiveRating;
echo '<br />';
echo $ratingCount;
echo '<br />';
echo $oldRating;
echo '<br />';
*/
$ratingCount = $oneRating + $twoRating + $threeRating + $fourRating + $fiveRating;
$newRating = (($oneRating * 1) + ($twoRating * 2) + ($threeRating * 3) + ($fourRating * 4) + ($fiveRating * 5)) / $ratingCount;
/*
echo $oneRating;
echo '<br />';
echo $twoRating;
echo '<br />';
echo $threeRating;
echo '<br />';
echo $fourRating;
echo '<br />';
echo $fiveRating;
echo '<br />';
echo $ratingCount;
echo '<br />';
echo $newRating;
echo '<br />';
*/
$sql = "Update Documents Set Rating='$newRating', RatingCount='$ratingCount',
OneRating='$oneRating', TwoRating='$twoRating', ThreeRating='$threeRating',
FourRating='$fourRating', FiveRating='$fiveRating' WHERE ID='$docID'";
//$res = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE)
{
echo "Update Sucessfully";
}
else
{
$error = "True";
}
}
elseif ($rating == 2)
{
$sql = "SELECT Rating, RatingCount, OneRating, TwoRating, ThreeRating, FourRating, FiveRating
FROM Documents where ID= '$docID'";
$res = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($res);
$oldRating = $row['Rating'];
$ratingCount = $row['RatingCount'];
$oneRating = $row['OneRating'];
$twoRating = $row['TwoRating'];
$threeRating = $row['ThreeRating'];
$fourRating = $row['FourRating'];
$fiveRating = $row['FiveRating'];
$twoRating = $twoRating + 1;
$ratingCount = $oneRating + $twoRating + $threeRating + $fourRating + $fiveRating;
$newRating = (($oneRating * 1) + ($twoRating * 2) + ($threeRating * 3) + ($fourRating * 4) + ($fiveRating * 5)) / $ratingCount;
$sql = "Update Documents Set Rating='$newRating', RatingCount='$ratingCount',
OneRating='$oneRating', TwoRating='$twoRating', ThreeRating='$threeRating',
FourRating='$fourRating', FiveRating='$fiveRating' WHERE ID='$docID'";
//$res = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE)
{
$error = "False";
}
else
{
$error = "True";
}
}
elseif ($rating == 3)
{
$sql = "SELECT Rating, RatingCount, OneRating, TwoRating, ThreeRating, FourRating, FiveRating
FROM Documents where ID= '$docID'";
$res = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($res);
$oldRating = $row['Rating'];
$ratingCount = $row['RatingCount'];
$oneRating = $row['OneRating'];
$twoRating = $row['TwoRating'];
$threeRating = $row['ThreeRating'];
$fourRating = $row['FourRating'];
$fiveRating = $row['FiveRating'];
$threeRating = $threeRating + 1;
$ratingCount = $oneRating + $twoRating + $threeRating + $fourRating + $fiveRating;
$newRating = (($oneRating * 1) + ($twoRating * 2) + ($threeRating * 3) + ($fourRating * 4) + ($fiveRating * 5)) / $ratingCount;
$sql = "Update Documents Set Rating='$newRating', RatingCount='$ratingCount',
OneRating='$oneRating', TwoRating='$twoRating', ThreeRating='$threeRating',
FourRating='$fourRating', FiveRating='$fiveRating' WHERE ID='$docID'";
//$res = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE)
{
$error = "False";
}
else
{
$error = "True";
}
}
elseif ($rating == 4)
{
$sql = "SELECT Rating, RatingCount, OneRating, TwoRating, ThreeRating, FourRating, FiveRating
FROM Documents where ID= '$docID'";
$res = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($res);
$oldRating = $row['Rating'];
$ratingCount = $row['RatingCount'];
$oneRating = $row['OneRating'];
$twoRating = $row['TwoRating'];
$threeRating = $row['ThreeRating'];
$fourRating = $row['FourRating'];
$fiveRating = $row['FiveRating'];
$fourRating = $fourRating + 1;
$ratingCount = $oneRating + $twoRating + $threeRating + $fourRating + $fiveRating;
$newRating = (($oneRating * 1) + ($twoRating * 2) + ($threeRating * 3) + ($fourRating * 4) + ($fiveRating * 5)) / $ratingCount;
$sql = "Update Documents Set Rating='$newRating', RatingCount='$ratingCount',
OneRating='$oneRating', TwoRating='$twoRating', ThreeRating='$threeRating',
FourRating='$fourRating', FiveRating='$fiveRating' WHERE ID='$docID'";
//$res = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE)
{
$error = "False";
}
else
{
$error = "True";
}
}
elseif ($rating == 5)
{
$sql = "SELECT Rating, RatingCount, OneRating, TwoRating, ThreeRating, FourRating, FiveRating
FROM Documents where ID= '$docID'";
$res = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($res);
$oldRating = $row['Rating'];
$ratingCount = $row['RatingCount'];
$oneRating = $row['OneRating'];
$twoRating = $row['TwoRating'];
$threeRating = $row['ThreeRating'];
$fourRating = $row['FourRating'];
$fiveRating = $row['FiveRating'];
$fiveRating = $fiveRating + 1;
$ratingCount = $oneRating + $twoRating + $threeRating + $fourRating + $fiveRating;
$newRating = (($oneRating * 1) + ($twoRating * 2) + ($threeRating * 3) + ($fourRating * 4) + ($fiveRating * 5)) / $ratingCount;
$sql = "Update Documents Set Rating='$newRating', RatingCount='$ratingCount',
OneRating='$oneRating', TwoRating='$twoRating', ThreeRating='$threeRating',
FourRating='$fourRating', FiveRating='$fiveRating' WHERE ID='$docID'";
//$res = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE)
{
$error = "False";
}
else
{
$error = "True";
}
}
else
{
$error = "True";
}
}
echo json_encode($error);
$conn->close();
?> | 1cb34bf60f8d5148649f0050956124ffcc70720b | [
"JavaScript",
"Python",
"Text",
"PHP"
] | 30 | PHP | NuNote/NuNote-app | c4411e4c4b587ba4faca184cd078c1d77cb5ec45 | 2acc397ddef89e8c47ff6e7173aceb5df59aeacc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.