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/main
<file_sep>import { IUser } from './user.interface'; export class User implements IUser { userName: string; email: string; phone: number; public constructor(un?: string, em?: string, ph?: number) { this.userName = un ? un : ''; this.email = em ? em : ''; this.phone = ph ? ph : 0; } } <file_sep>import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { FormValidationMonitorModule } from 'form-validation-monitor'; import { AppComponent } from './app.component'; import { FirstCapitalCharCustomValidator } from './first-capital-char-custom.validator'; @NgModule({ declarations: [ AppComponent, FirstCapitalCharCustomValidator ], imports: [ BrowserModule, FormsModule, CommonModule, NgbModule, FormValidationMonitorModule ], providers: [FirstCapitalCharCustomValidator], bootstrap: [AppComponent] }) export class AppModule { } <file_sep># lk-lib lk's npm library for Angular <file_sep># Form Validation Monitor This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 11.1.2. ## Description of the form-validation-monitor This npm contains an Angular form validation monitor tool. (lk-form-validation-monitor) The purpose of the Angular form validation monitor tool is, to show in realtime the angular validation result (status, valid, invalid) and validation signals (pristine, dirty, touched, untouched) with the _FormControl_, _FormGroup_, _FormArray_ value eg. of the three fundamental building blocks (_FormControl, FormGroup, FormArray_) of Angular forms. If the main form contains a complex building block eg. _FormGroup_ or _FormArray_, the user if click on it, can recursively traverse the complex building block content. Prerequisities is standard Template-Driven or Reactive (with former name model-driven) Angular forms. ## Usage of the Form Validation Monitor selector: _lk-form-validation-monitor_ _<lk-form-validation-monitor-v4 [mainFormGroup]="dataEntryForm" [topGap]="5" [fontSize]="1"></lk-form-validation-monitor-v4>_ Where the - mainFormGroup is the reference in the templae of the main form, - topGap is the height of the gap in rem, between the UI of the Form Validation Monitor and other UI elements above - fontSize is the numeric value the size of font in rem _<form (ngSubmit)="onSubmit(dataEntryForm)" #dataEntryForm="ngForm" novalidate autocomplete="off">_ what we captured with ViewChild, eg. _@ViewChild('dataEntryForm', {static: true} ) dataEntryForm: NgForm | undefined;_ Do not forget to import the _FormValidationMonitorModule_ into that module which contains the main form. ## Build Run `ng build form-validation-monitor` to build the project. The build artifacts will be stored in the `dist/` directory. ## Publishing After building your library with `ng build form-validation-monitor`, go to the dist folder `cd dist/form-validation-monitor` and run `npm publish`. ## Sources [Demo app source of the lk-form-validation-monitor](https://github.com/lkovari/lk-lib/tree/main/projects/form-validation-monitor-example) [Library source of the lk-form-validation-monitor](https://github.com/lkovari/lk-lib/tree/main/projects/form-validation-monitor) ## Example UI. and the real life usage ![Example UI](https://github.com/lkovari/KLHome/blob/master/src/assets/images/Example-Of-the-lk-form-validation-monitor.png) [The real life usage on the followin webpage](https://lkovari.github.io/KLHome/#/angular-page/angular-page-content7) <file_sep>import { Component, ViewChild } from '@angular/core'; import { NgForm } from '@angular/forms'; import { IUser } from './user.interface'; import { User } from './user.model'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'form-validation-monitor-example'; user: IUser = new User(); userNameMinLength = 4; userNameMaxLength = 20; // originated from : https://www.sitepoint.com/community/t/phone-number-regular-expression-validation/2204 usPhoneNumberPattern = '^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$'; submittedFormData: any; @ViewChild('dataEntryForm', {static: true} ) dataEntryForm: NgForm | undefined; constructor() { } ngOnInit() { } setValues() { this.dataEntryForm?.resetForm(); this.submittedFormData = undefined; this.user.userName = 'jdoe'; this.user.email = '<EMAIL>'; this.user.phone = 18001234567; const fc = this.dataEntryForm?.controls['userName']; fc?.markAsDirty(); console.log('setValues Click event fired'); } clearValues() { this.dataEntryForm?.form.setValue( { userName: null, email: null, phone: null } ); this.dataEntryForm?.resetForm(); this.submittedFormData = undefined; console.log('clearValues click event fired'); } getDataEntryForm(): NgForm | undefined { return this.dataEntryForm; } onSubmit(userForm: NgForm) { this.submittedFormData = userForm.value; console.log(this.dataEntryForm); } } <file_sep>/* * Public API Surface of form-validation-monitor */ export * from './lib/form-validation-monitor.service'; export * from './lib/form-validation-monitor.component'; export * from './lib/form-validation-monitor.module'; <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { FormControl, FormGroup, FormArray, AbstractControl, NgForm, NgModelGroup } from '@angular/forms'; import { Meta } from '@angular/platform-browser'; @Component({ selector: 'lk-form-validation-monitor', templateUrl: './form-validation-monitor.component.html', styleUrls: ['./form-validation-monitor.component.scss'] }) export class FormValidationMonitorComponent implements OnInit { private readonly PROPERY_TYPE = 'type'; private readonly PROPERY_STATUS = 'status'; private readonly PROPERY_VALID = 'valid'; private readonly PROPERY_INVALID = 'invalid'; private readonly PROPERY_PENDING = 'pending'; private readonly PROPERY_PRISTINE = 'pristine'; private readonly PROPERY_DIRTY = 'dirty'; private readonly PROPERY_TOUCHED = 'touched'; private readonly PROPERY_UNTOUCHED = 'untouched'; private readonly PROPERY_VALUE = 'value'; formControlStatusKeys = [this.PROPERY_TYPE, this.PROPERY_STATUS, this.PROPERY_VALID, this.PROPERY_INVALID, this.PROPERY_PENDING, this.PROPERY_PRISTINE, this.PROPERY_DIRTY, this.PROPERY_TOUCHED, this.PROPERY_UNTOUCHED, this.PROPERY_VALUE]; private _mainFormGroup: FormGroup | undefined; private _topGap = '2'; controlList = new Array<FormControl>(); formGroupStack = new Array<FormGroup>(); @Input() set mainFormGroup(v: any) { if (v instanceof NgForm) { this._mainFormGroup = <FormGroup>v.form; } else { this._mainFormGroup = <FormGroup>v; } } get mainFormGroup(): any { return this._mainFormGroup; } @Input() set topGap(v: string) { this._topGap = v; } get topGap(): string { return this._topGap; } @Input() fontSize = 1; /* * DEVELOPER NOTE: almost all function which called from the template probably should replace with pure pipe, to optimize performance. */ constructor(private meta: Meta) { } ngOnInit() { this.meta.addTag({ name: 'viewport', content: 'width=device-width, initial-scale=1' }); } extractFormGroupPropertyValueByKey(key: string): string { return this.mainFormGroup ? this.mainFormGroup[key] : null; } isComplexControl(ctrl: AbstractControl): boolean { return (ctrl instanceof FormGroup) || (ctrl instanceof FormArray) || (ctrl instanceof NgModelGroup); } extractFormControls(): Array<FormControl> { this.controlList = []; Object.keys( this.mainFormGroup.controls).forEach(key => { this.controlList.push(<FormControl>this.mainFormGroup.controls[key]); }); return this.controlList; } extractFormControlKeys(): string[] { let formControlKey = new Array<string>(); if (this.mainFormGroup && this.mainFormGroup.controls) { formControlKey = Object.keys(this.mainFormGroup.controls); } return formControlKey; } composeObjectName(ctrlKey: string, v: any): string { return ctrlKey + ' : ' + v; } extractFormElementByKey(ctrlKey?: string): FormControl | FormGroup | FormArray | NgModelGroup { // when the ctrlKey is undefined then the mainFormGroup is an NgModelGroup let control; if (ctrlKey) { control = this.mainFormGroup.controls[ctrlKey]; if (control instanceof FormControl) { control = <FormControl>control; } else if (control instanceof FormGroup) { control = <FormGroup>control; } else if (control instanceof FormArray) { control = <FormArray>control; } } else { if (this.mainFormGroup instanceof NgModelGroup) { control = this.mainFormGroup.control; } else { control = this.mainFormGroup; } } return <FormControl | FormGroup | FormArray | NgModelGroup>control; } extractFormGroupElementByKey(ctrlKey?: string): FormGroup { // when the ctrlKey is undefined then the mainFormGroup is an NgModelGroup let control = ctrlKey ? this.mainFormGroup.controls[ctrlKey] : this.mainFormGroup.control; return control = <FormGroup>control; } extractFormControlValueByKey(ctrl: any, key: string): any { return ctrl[key]; } extractType(control: AbstractControl | NgModelGroup): string { let typeName = ''; if (control instanceof FormControl) { typeName = 'FormControl'; } else if (control instanceof FormGroup) { typeName = 'FormGroup'; } else if (control instanceof FormArray) { typeName = 'FormArray'; } return typeName; } getStyleColor(k: string, v: any): string { let color = 'black'; if ((k === this.PROPERY_STATUS && v === this.PROPERY_VALID) || (k === this.PROPERY_VALID && v) || (k === this.PROPERY_INVALID && !v)) { color = 'green'; } else if ((k === this.PROPERY_STATUS && v === this.PROPERY_INVALID) || (k === this.PROPERY_VALID && !v) || (k === this.PROPERY_INVALID && v)) { color = 'red'; } else if (k === 'errors' && v !== null) { color = 'red'; } else if (v instanceof Object) { color = 'blue'; } return color; } isObjectType(v: any): boolean { return v ? v instanceof Object : false; } onClickValue(ctrlKey?: any) { // if has ctrlKey then get the property value else get the FormGroup value const value = ctrlKey ? this.mainFormGroup.controls[ctrlKey].value : this.mainFormGroup.value; window.alert(JSON.stringify(value)); } extractFormName(control: AbstractControl): string | null { let group: FormGroup; let name = ''; if (!(control instanceof FormGroup)) { return null; } else { group = <FormGroup>control; } Object.keys(group.controls).forEach(key => { const childControl = group.get(key); if (childControl !== control) { return; } name = key; }); return name; } /** * * @param control: AbstractControl * @return boolean - if true the passedControl is a complex control, else not */ isItComplexControl(control: AbstractControl | NgModelGroup): boolean { return control instanceof FormGroup || control instanceof FormArray; } onComplexControlClicked(control: FormGroup) { if (this._mainFormGroup) { this.formGroupStack.push(this._mainFormGroup); this._mainFormGroup = control; } } enableBackButton(): boolean { return this.formGroupStack.length > 0; } onBackClicked(event: MouseEvent) { this._mainFormGroup = this.formGroupStack.pop()!; console.log('onBackClicked click event fired ' + event); } }
f1e637c46edae2c6287607671ed8da2b362e8961
[ "Markdown", "TypeScript" ]
7
TypeScript
lkovari/lk-lib
3ee367c5db2214c88cb7031fb31ff40122f2f559
2d749abb21330bad98496b4ee4d68f8fe3800d1c
refs/heads/master
<repo_name>Cupritix/AskingNameAdvanced<file_sep>/README.md # AskingNameAdvanced class work <file_sep>/helloevenmoreadvanced.py #School project print("What is your full name?") wholeName = input() print("How long is your first name?") firstNameLength = int(input()) print("First Last: " + wholeName) print("Last, First: " + wholeName[firstNameLength:] + ", " + wholeName[:firstNameLength]) print("First Name Last Initial: " + wholeName[:firstNameLength] + " "+ wholeName[firstNameLength+1:firstNameLength+2]) print("Last Name, First Initial: " + wholeName[firstNameLength+1:] + ", " + wholeName[:1])
0a728ca28cb4b5ad6b0aa468b3fb211188420735
[ "Markdown", "Python" ]
2
Markdown
Cupritix/AskingNameAdvanced
4c9ddbe0fb8b37ac380132f9de9f727fd2310368
0c2b243cdab8ef8c9ec4956256e1fa37df0f30c6
refs/heads/master
<file_sep>import createSchema from 'part:@sanity/base/schema-creator' import schemaTypes from 'all:part:@sanity/base/schema-type' import blockContent from './blockContent' import category from './category' import collection from './collection' import item from './item' import productVariant from './productVariant' export default createSchema({ name: 'default', types: schemaTypes.concat( [ blockContent, item, category, collection, productVariant, ] ) })
faf9f43b98a3377a72c4046606cd1f5d1c83c236
[ "JavaScript" ]
1
JavaScript
danjonesdev/rendah-mag-store-sanity-cli
d7f115c54d23bac29c68b9eac1a32f5a193ffa44
6cb258abe8fd88806c1556d3d51181e25fe84daf
refs/heads/master
<file_sep># Highly Available NAT Gateway for GKE Nodes This example creates three NAT Gateway instances in different zones and Compute Engine Network Routes to route outbound traffic from an existing GKE cluster. **Figure 1.** *diagram of Google Cloud resources* ![architecture diagram](https://raw.githubusercontent.com/GoogleCloudPlatform/terraform-google-nat-gateway/master/examples/gke-ha-nat-gateway/diagram.png) ## Setup Environment ``` gcloud auth application-default login export GOOGLE_PROJECT=$(gcloud config get-value project) ``` This example assumes you have an existing Kubernetes Engine cluster. ### Get Master IP and Node Tags Record the target cluster name, region, zone, and network: ``` CLUSTER_NAME=dev REGION=us-central1 ZONE_1=us-central1-a ZONE_2=us-central1-b ZONE_3=us-central1-c NETWORK=default SUBNETWORK=default ``` Create a `terraform.tfvars` file with the the region, zone, master IP, and the node pool nework tag name to the tfvars file: ``` NODE_TAG=$(gcloud compute instance-templates describe $(gcloud compute instance-templates list --filter=name~gke-${CLUSTER_NAME:0:20} --limit=1 --uri) --format='get(properties.tags.items[0])') MASTER_IP=$(gcloud compute firewall-rules describe ${NODE_TAG/-node/-ssh} --format='value(sourceRanges)') cat > terraform.tfvars <<EOF region = "${REGION}" zone1 = "${ZONE_1}" zone2 = "${ZONE_2}" zone3 = "${ZONE_3}" gke_master_ip = "${MASTER_IP}" gke_node_tag = "${NODE_TAG}" network = "${NETWORK}" subnetwork = "${SUBNETWORK}" EOF ``` ## Run Terraform ``` terraform init terraform plan -out terraform.tfplan terraform apply terraform.tfplan ``` ## Verify NAT Gateway Routing Create pod and port forward to run test from: ``` kubectl run squid --port 3128 --image datadog/squid && \ kubectl wait deploy/squid --for condition=available kubectl port-forward deploy/squid 3128:3128 & ``` Show the external IP address that the cluster node is using by running a Kubernetes pod that uses curl: ``` curl --proxy localhost:3128 -s http://ipinfo.io/ip ``` Run the above command several more times to see it cycle between the ip addresses of each NAT gateway instance. Run the below command to see all external IPs of the NAT gateways. ``` terraform output ``` Stop the port-forward when finished: ``` killall kubectl ``` ## Caveats 1. The web console SSH will no longer work, you have to jump through the NAT gateway machine to SSH into a GKE node. 2. You can use the `gcloud-ssh` helper script to jump through an arbitrary bastion host: ``` git clone https://github.com/danisla/gcloudfunc.git echo "source ${PWD}/gcloudfunc/gcloudfunc.bash" >> ${HOME}/.bash_profile source ${HOME}/.bash_profile gcloud-ssh ``` ## Cleanup Remove all resources created by terraform: ``` terraform destroy ```<file_sep>#!/bin/bash ws_input=$1 RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m' function red() { printf "${RED}$1${NC}\n" } function green() { printf "${GREEN}$1${NC}\n" } [[ -z "${GOOGLE_PROJECT}" ]] && export GOOGLE_PROJECT=$(gcloud config get-value project) CURR_DIR=$(basename "$PWD") PARENT_DIR=$(basename "$(dirname "$PWD")") cat > backend.tf <<EOF terraform { backend "gcs" { bucket = "concourse-terraform-remote-backend" prefix = "terraform-google-nat-gateway" } } EOF terraform init -get-plugins=true >/dev/null function isStateEmpty() { terraform workspace select -no-color $1 >/dev/null terraform state pull >/dev/null [[ "$(terraform state list | wc -l)" -le 1 ]] } function cleanWorkspace() { local ws=$1 echo "INFO: Checking workspace: $ws" if isStateEmpty $ws; then green "INFO: $ws is clean" else red "WARN: $ws is not clean, destroying resources" terraform destroy -auto-approve fi } for ws in $(terraform workspace list | sed 's/[ *]//g'); do [[ -n "${ws_input}" && "$ws" != "${ws_input}" ]] && continue [[ "$ws" == "default" ]] && continue [[ "$ws" =~ -infra && "${PARENT_DIR}" != "infra" ]] && continue [[ ! "$ws" =~ -infra && "${PARENT_DIR}" != "examples" ]] && continue if [[ "${PARENT_DIR}" == "infra" && "$ws" =~ -infra ]]; then ### Infra cleanup ### case $ws in tf-ci-nat-gke-ha*-infra) [[ "${CURR_DIR}" =~ example-gke-ha-nat ]] && cleanWorkspace $ws continue ;; tf-ci-nat-gke*-infra) [[ "${CURR_DIR}" =~ example-gke-nat && "$ws" =~ ${CURR_DIR##*-} ]] && cleanWorkspace $ws continue ;; esac fi if [[ "${PARENT_DIR}" == "examples" && ! "$ws" =~ -infra ]]; then ### Example cleanup ### case $ws in tf-ci-nat-gke-ha-*) [[ "${CURR_DIR}" == "gke-ha-nat-gateway" ]] && cleanWorkspace $ws continue ;; tf-ci-nat-gke-*) if [[ "${CURR_DIR}" == "gke-nat-gateway" ]]; then export TF_VAR_gke_master_ip=0.0.0.0 export TF_VAR_gke_node_tag=foo cleanWorkspace $ws fi continue ;; tf-ci-nat-ha*) [[ "${CURR_DIR}" == "ha-nat-gateway" ]] && cleanWorkspace $ws continue ;; tf-ci-nat-lb*) [[ "${CURR_DIR}" == "lb-http-nat-gateway" ]] && cleanWorkspace $ws continue ;; tf-ci-nat-module-disable*) [[ "${CURR_DIR}" == "module-disable" ]] && cleanWorkspace $ws continue ;; tf-ci-nat-multi-env*) [[ "${CURR_DIR}" == "multiple-nat-environments" ]] && cleanWorkspace $ws continue ;; tf-ci-nat-squid*) [[ "${CURR_DIR}" == "squid-proxy" ]] && cleanWorkspace $ws continue ;; esac fi done <file_sep># NAT Gateway Module Disable Example This example creates a NAT gateway and demonstrates how to disable it using the input variable. ## Setup Environment ``` gcloud auth application-default login export GOOGLE_PROJECT=$(gcloud config get-value project) ``` ## Run Terraform ``` terraform init terraform plan terraform apply ``` Verify egress traffic is routed through NAT gateway: ``` ./test.sh nat ``` ## Disable the module ``` cat > terraform.tfvars <<EOF module_enabled = false EOF ``` Run Terraform: ``` terraform apply ``` Verify egress traffic is passed directly from the VM: ``` ./test.sh direct ``` ## Cleanup Remove all resources created by terraform: ``` terraform destroy ``` <file_sep># Highly Available NAT Gateway Example This example creates a NAT gateway in 3 Compute Engine zones within the same region. Traffic is balanced between the instances using equal cost based routing with equal route priorities to the same instance tag. **Figure 1.** *diagram of Google Cloud resources* ![architecture diagram](https://raw.githubusercontent.com/GoogleCloudPlatform/terraform-google-nat-gateway/master/examples/ha-nat-gateway/diagram.png) ## Setup Environment ``` gcloud auth application-default login export GOOGLE_PROJECT=$(gcloud config get-value project) ``` ## Run Terraform ``` terraform init terraform plan terraform apply ``` SSH into the instance by hopping through one of the NAT gateway instances, first make sure that SSH agent is running and your private SSH key is added to the authentication agent. ``` gcloud compute config-ssh eval `ssh-agent $SHELL` ssh-add ~/.ssh/google_compute_engine BASTION=$(terraform output -module nat-zone-1 -json | jq -r '.instance.value[0]') REMOTE_HOST=$(terraform output -module mig1 -json | jq -r '.instances.value[0][0]') SSH_USER=$(gcloud config get-value account) gcloud compute ssh ${SSH_USER//@*}@${BASTION} --ssh-flag="-A" -- ssh ${REMOTE_HOST//*instances\//} -o StrictHostKeyChecking=no ``` Check the external IP of the instance: ``` curl http://ipinfo.io/ip ``` Repeat the command above a few times and notice that it cycles between the external IP of the NAT gateway instances. ## Cleanup Remove all resources created by terraform: ``` terraform destroy ``` <file_sep>#!/usr/bin/env bash set -x set -e function cleanup() { set +e killall -9 kubectl kubectl delete deploy proxy } trap cleanup EXIT declare -a EXTERNAL_IPS EXTERNAL_IPS[0]=${EXTERNAL_IP_1:-$(terraform output ip-nat-zone-1)} EXTERNAL_IPS[1]=${EXTERNAL_IP_2:-$(terraform output ip-nat-zone-2)} EXTERNAL_IPS[2]=${EXTERNAL_IP_3:-$(terraform output ip-nat-zone-3)} # Create squid pod to tunnel through kubectl run proxy --port 1080 --image xkuma/socks5 kubectl wait deploy/proxy --for condition=available kubectl port-forward deploy/proxy 1080:1080 & echo "INFO: Verifying all NAT IPs: ${EXTERNAL_IPS[*]}" count=0 while [[ $count -lt 1200 && ${#EXTERNAL_IPS[@]} -gt 0 ]]; do IP=$(curl -m 5 -s --socks5-hostname localhost:1080 http://ipinfo.io/ip || true) if [[ "${IP}" == ${EXTERNAL_IPS[0]} ]]; then echo "INFO: Found NAT IP: ${IP}" EXTERNAL_IPS=("${EXTERNAL_IPS[@]:1}") fi ((count=count+1)) sleep 0.7 done test $count -lt 1200 echo "PASS: All NAT IPs found" <file_sep>#!/usr/bin/env bash set -x set -e NAT_IP=${NAT_IP:-$(terraform output ip-nat-gateway)} LB_IP=${LB_IP:-$(terraform output ip-lb)} count=0 IP="" while [[ $count -lt 600 && "${IP}" != "${NAT_IP}" ]]; do echo "INFO: Waiting for NAT IP to match ${NAT_IP}..." IP=$(curl -sf ${LB_IP}/ip.php || true) ((count=count+1)) sleep 10 done test $count -lt 600 echo "PASS" <file_sep>#!/bin/bash READLINK=readlink [[ $(uname -s) =~ Darwin ]] && READLINK=greadlink SCRIPT_DIR="$(dirname "$(${READLINK} -f $0)")" # Cleanup local terraform artifacts find "${SCRIPT_DIR}/../" -type d -name ".terraform" -exec rm -rf "{}" \; 2>/dev/null find "${SCRIPT_DIR}/../" -type f -name "terraform.tfstate*" -exec rm -f "{}" \; 2>/dev/null find "${SCRIPT_DIR}/../" -type f -name "terraform.tfvars*" -exec rm -f "{}" \; 2>/dev/null export GOOGLE_PROJECT=$(gcloud config get-value project) OLDIFS=${IFS} function exitClean() { IFS=$OLDIFS } trap exitClean EXIT IFS=$'\n' # Cleanup examples for d in $(find "${SCRIPT_DIR}/../examples" -mindepth 1 -maxdepth 1 -type d | sort); do (cd "$d" && "../../tests/cleanup.sh") done # Cleanup infra for d in $(find "${SCRIPT_DIR}/infra/" -mindepth 1 -maxdepth 1 -type d | sort); do (cd "$d" && "../../cleanup.sh") done<file_sep>#!/bin/bash -e # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific lan cat > terraform.tfvars <<EOF region = "${REGION?Is not set}" zone = "${ZONE?Is not set}" network = "${NETWORK?Is not set}" subnetwork = "${SUBNETWORK?Is not set}" gke_master_ip = "${MASTER_IP?Is not set}" gke_node_tag = "${NODE_TAG?Is not set}" EOF<file_sep>#!/usr/bin/env bash set -x set -e function cleanup() { set +e rm -f ssh_config killall -9 autossh killall -9 ssh kill $SSH_AGENT_PID } trap cleanup EXIT declare -a EXTERNAL_IPS EXTERNAL_IPS[0]=${EXTERNAL_IP_1:-$(terraform output ip-nat-zone-1)} EXTERNAL_IPS[1]=${EXTERNAL_IP_2:-$(terraform output ip-nat-zone-2)} EXTERNAL_IPS[2]=${EXTERNAL_IP_3:-$(terraform output ip-nat-zone-3)} NAT_HOST=${NAT_HOST:-$(terraform output nat-host)} REMOTE_HOST_URI=${REMOTE_HOST_URI:-$(terraform output remote-host-uri)} REMOTE_HOST=${REMOTE_HOST_URI//*instances\//} REMOTE_ZONE=$(echo ${REMOTE_HOST_URI} | cut -d/ -f9) # Configure SSH SSH_USER_EMAIL=$(gcloud config get-value account) SSH_USER=${SSH_USER_EMAIL//@*} cat > ssh_config << EOF Host * User ${SSH_USER} StrictHostKeyChecking no UserKnownHostsFile /dev/null Host remote HostName ${EXTERNAL_IPS[0]} ProxyCommand gcloud compute ssh ${SSH_USER}@${NAT_HOST} --ssh-flag="-A -W ${REMOTE_HOST}:22" DynamicForward 1080 EOF if [[ ! -f ${HOME}/.ssh/google_compute_engine ]]; then mkdir -p ${HOME}/.ssh && chmod 0700 ${HOME}/.ssh && \ ssh-keygen -b 2048 -t rsa -f ${HOME}/.ssh/google_compute_engine -q -N "" -C ${SSH_USER_EMAIL} fi eval `ssh-agent` ssh-add ${HOME}/.ssh/google_compute_engine gcloud compute config-ssh export AUTOSSH_LOGFILE=/dev/stderr autossh -M 20000 -f -N -F ${PWD}/ssh_config remote echo "INFO: Verifying all NAT IPs: ${EXTERNAL_IPS[*]}" count=0 while [[ $count -lt 180 && ${#EXTERNAL_IPS[@]} -gt 0 ]]; do IP=$(curl -m 5 -s --socks5 localhost:1080 http://ipinfo.io/ip || true) if [[ "${IP}" == ${EXTERNAL_IPS[0]} ]]; then echo "INFO: Found NAT IP: ${IP}" EXTERNAL_IPS=("${EXTERNAL_IPS[@]:1}") fi ((count=count+1)) sleep 1 done test $count -lt 180 echo "PASS: All NAT IPs found" <file_sep># NAT Gateway for GKE Nodes [![button](//gstatic.com/cloudssh/images/open-btn.svg)](https://console.cloud.google.com/cloudshell/open?cloudshell_git_repo=https://github.com/GoogleCloudPlatform/terraform-google-nat-gateway&cloudshell_image=gcr.io/graphite-cloud-shell-images/terraform:latest&open_in_editor=examples/gke-nat-gateway/main.tf&cloudshell_tutorial=./examples/gke-nat-gateway/README.md) This example creates a NAT Gateway and Compute Engine Network Routes to route outbound traffic from an existing GKE cluster through the NAT Gateway instance. **Figure 1.** *diagram of Google Cloud resources* ![architecture diagram](https://raw.githubusercontent.com/GoogleCloudPlatform/terraform-google-nat-gateway/master/examples/gke-nat-gateway/diagram.png) > Note: This example only deploys a single-node NAT gateway instance and is not intended for production use. See the [ha-natgateway](../ha-nat-gateway) example for a highly available option. ## Set up the Environment 1. Set the project, replace YOUR_PROJECT with your project ID: ```bash PROJECT=YOUR_PROJECT ``` ```bash gcloud config set project ${PROJECT}; ``` 2. Configure the environment for Terraform: ```bash ([[ $CLOUD_SHELL ]] || gcloud auth application-default login); export GOOGLE_PROJECT=$(gcloud config get-value project); ``` 3. This example assumes you have an existing Container Engine cluster. If not, create a cluster: ```bash gcloud container clusters create dev-nat --zone=us-central1-b; ``` ## Change to the example directory ```bash [[ $(basename $PWD) == gke-nat-gateway ]] || cd examples/gke-nat-gateway; ``` ### Get Master IP and Node Tags Record the target cluster name, region and zone: ```bash export CLUSTER_NAME=dev-nat; export REGION=us-central1; export ZONE=us-central1-b; export NETWORK=default; export SUBNETWORK=default; ``` Create a `terraform.tfvars` file with the the region, zone, master IP, and the node pool nework tag name to the tfvars file: ```bash export NODE_TAG=$(gcloud compute instance-templates describe $(gcloud compute instance-templates list --filter=name~gke-${CLUSTER_NAME:0:20} --limit=1 --uri) --format='get(properties.tags.items[0])'); export MASTER_IP=$(gcloud compute firewall-rules describe ${NODE_TAG/-node/-ssh} --format='value(sourceRanges)'); ./make_vars.sh; cat terraform.tfvars; ``` ## Run Terraform ```bash terraform init && terraform apply ``` ## Verify NAT Gateway Routing Show the external IP address that the cluster node is using by running a Kubernetes pod that uses curl: ```bash kubectl run example -i -t --rm --restart=Never --image centos:7 -- curl -s http://ipinfo.io/ip ``` The IP address shown in the pod output should match the value of the NAT Gateway `external_ip`. Get the external IP of the NAT Gateway by running the command below: ```bash terraform output ``` ## Caveats 1. The web console SSH will no longer work, you have to jump through the NAT gateway machine to SSH into a GKE node: ```bash eval ssh-agent $SHELL; ``` ```bash gcloud compute config-ssh ``` ```bash ssh-add ~/.ssh/google_compute_engine; CLUSTER_NAME=dev-nat; REGION=us-central1; gcloud compute ssh $(gcloud compute instances list --filter=name~nat-gateway-${REGION} --uri) --ssh-flag="-A" -- ssh $(gcloud compute instances list --filter=name~gke-${CLUSTER_NAME}- --limit=1 --format='value(name)') -o StrictHostKeyChecking=no; ``` ## Cleanup 1. Remove all resources created by terraform: ```bash terraform destroy ``` 2. Delete Kubernetes Engine cluster: ```bash gcloud container clusters delete dev-nat --zone us-central1-b ```<file_sep>#!/usr/bin/env bash fly -t tf set-pipeline -p tf-nat-gw-regression -c tests/pipelines/tf-nat-gw-regression.yaml -l tests/pipelines/values.yaml fly -t tf set-pipeline -p tf-nat-gw-cleanup -c tests/pipelines/tf-nat-gw-cleanup.yaml -l tests/pipelines/values.yaml fly -t tf set-pipeline -p tf-nat-gw-pull-requests -c tests/pipelines/tf-nat-gw-pull-requests.yaml -l tests/pipelines/values.yaml fly -t tf expose-pipeline -p tf-nat-gw-regression fly -t tf expose-pipeline -p tf-nat-gw-pull-requests<file_sep>#!/usr/bin/env bash set -x set -e function cleanup() { set +e rm -f ssh_config killall -9 autossh killall -9 ssh kill $SSH_AGENT_PID } trap cleanup EXIT NAT_IP=${EXTERNAL_IP:-$(terraform output nat-ip)} NAT_HOST_URI=${NAT_HOST:-$(terraform output nat-host)} NAT_HOST=${NAT_HOST_URI//*instances\//} REMOTE_HOST_URI=${REMOTE_HOST_URI:-$(terraform output vm-host)} REMOTE_HOST=${REMOTE_HOST_URI//*instances\//} REMOTE_ZONE=$(echo ${REMOTE_HOST_URI} | cut -d/ -f9) # Configure SSH SSH_USER_EMAIL=$(gcloud config get-value account) SSH_USER=${SSH_USER_EMAIL//@*} if [[ ! -f ${HOME}/.ssh/google_compute_engine ]]; then mkdir -p ${HOME}/.ssh && chmod 0700 ${HOME}/.ssh && \ ssh-keygen -b 2048 -t rsa -f ${HOME}/.ssh/google_compute_engine -q -N "" -C ${SSH_USER_EMAIL} fi # Create ssh tunnel through NAT gateway. cat > ssh_config << EOF Host * User ${SSH_USER} StrictHostKeyChecking no UserKnownHostsFile /dev/null Host remote HostName ${NAT_IP} ProxyCommand gcloud compute ssh ${SSH_USER}@${NAT_HOST_URI} --ssh-flag="-A -W ${REMOTE_HOST}:22" LocalForward 3128 ${NAT_HOST}:3128 EOF eval `ssh-agent` ssh-add ${HOME}/.ssh/google_compute_engine gcloud compute config-ssh export AUTOSSH_LOGFILE=/dev/stderr autossh -M 20000 -f -N -F ${PWD}/ssh_config remote echo "INFO: Verifying NAT IP through squid proxy: ${NAT_IP}" count=0 while [[ $count -lt 60 ]]; do IP=$(curl -m 5 -s --proxy localhost:3128 http://ipinfo.io/ip || true) if [[ "${IP}" == "${NAT_IP}" ]]; then echo "INFO: Found NAT IP: ${IP}" break fi ((count=count+1)) sleep 10 done test $count -lt 60 echo "PASS: Egress from instance is routed through squid proxy." <file_sep>#!/usr/bin/env bash set -x set -e MODE=$1 [[ "${MODE}" != "nat" && "${MODE}" != "direct" ]] && echo "USAGE: $0 <nat|direct>" && exit 1 function cleanup() { set +e rm -f ssh_config killall -9 autossh killall -9 ssh kill $SSH_AGENT_PID } trap cleanup EXIT NAT_IP=${EXTERNAL_IP:-$(terraform output nat-ip)} NAT_HOST=${NAT_HOST:-$(terraform output nat-host)} REMOTE_HOST_IP=${REMOTE_HOST_IP:-$(terraform output vm-ip)} REMOTE_HOST_URI=${REMOTE_HOST_URI:-$(terraform output vm-host)} REMOTE_HOST=${REMOTE_HOST_URI//*instances\//} REMOTE_ZONE=$(echo ${REMOTE_HOST_URI} | cut -d/ -f9) # Configure SSH SSH_USER_EMAIL=$(gcloud config get-value account) SSH_USER=${SSH_USER_EMAIL//@*} if [[ ! -f ${HOME}/.ssh/google_compute_engine ]]; then mkdir -p ${HOME}/.ssh && chmod 0700 ${HOME}/.ssh && \ ssh-keygen -b 2048 -t rsa -f ${HOME}/.ssh/google_compute_engine -q -N "" -C ${SSH_USER_EMAIL} fi if [[ "${MODE}" == "nat" ]]; then # Create ssh tunnel through NAT gateway. cat > ssh_config << EOF Host * User ${SSH_USER} StrictHostKeyChecking no UserKnownHostsFile /dev/null ConnectTimeout 5 BatchMode yes Host nat HostName ${NAT_IP} ProxyCommand gcloud compute ssh ${SSH_USER}@${NAT_HOST} --ssh-flag="-A -W ${REMOTE_HOST}:22" DynamicForward 1080 EOF eval `ssh-agent` ssh-add ${HOME}/.ssh/google_compute_engine gcloud compute config-ssh export AUTOSSH_LOGFILE=/dev/stderr autossh -M 20000 -f -N -F ${PWD}/ssh_config nat echo "INFO: Verifying NAT IP: ${NAT_IP}" count=0 while [[ $count -lt 60 ]]; do IP=$(curl -m 5 -s --socks5 localhost:1080 http://ipinfo.io/ip || true) if [[ "${IP}" == "${NAT_IP}" ]]; then echo "INFO: Found NAT IP: ${IP}" break fi ((count=count+1)) sleep 10 done test $count -lt 60 echo "PASS: Egress from instance is routed through NAT IP." fi if [[ "${MODE}" == "direct" ]]; then echo "INFO: Verifying external IP is not NAT IP" # Create ssh tunnel with socks proxy to remote instance. cat > ssh_config << EOF Host * User ${SSH_USER} StrictHostKeyChecking no UserKnownHostsFile /dev/null ConnectTimeout 5 BatchMode yes Host remote HostName ${REMOTE_HOST_IP} DynamicForward 1081 EOF eval `ssh-agent` ssh-add ${HOME}/.ssh/google_compute_engine export AUTOSSH_LOGFILE=/dev/stderr autossh -M 20001 -f -N -F ${PWD}/ssh_config remote count=0 while [[ $count -lt 60 ]]; do IP=$(curl -m 5 -s --socks5 localhost:1081 http://ipinfo.io/ip || true) if [[ -n "${IP}" && "${IP}" == "${REMOTE_HOST_IP}" ]]; then echo "INFO: IP check passed: ${IP}" break fi ((count=count+1)) sleep 10 done test $count -lt 60 echo "PASS: Egress from instance is routed directly to internet." fi <file_sep>#!/usr/bin/env bash set -e PIPELINE="tf-nat-gw-regression" JOBS="check-nat-region-map run-example-gke-zonal run-example-gke-private run-example-gke-regional run-example-ha-nat-gateway run-example-lb-nat-gateway run-example-multi-env" for j in $JOBS; do fly -t solutions trigger-job -j ${PIPELINE}/${j} done <file_sep>#!/usr/bin/env bash set -x set -e declare -a EXTERNAL_IPS EXTERNAL_IPS[0]=${EXTERNAL_IP_1:-$(terraform output ip-nat-production)} EXTERNAL_IPS[1]=${EXTERNAL_IP_2:-$(terraform output ip-nat-staging)} LB_IP=${LB_IP:-$(terraform output ip-lb)} echo "INFO: Verifying all NAT IPs: ${EXTERNAL_IPS[*]}" count=0 while [[ $count -lt 600 && ${#EXTERNAL_IPS[@]} -gt 0 ]]; do IP=$(curl -sf http://${LB_IP}/ip.php || true) if [[ "${IP}" == ${EXTERNAL_IPS[0]} ]]; then echo "INFO: Found NAT IP: ${IP}" EXTERNAL_IPS=("${EXTERNAL_IPS[@]:1}") fi ((count=count+1)) sleep 10 done test $count -lt 600 echo "PASS: All NAT IPs found" <file_sep># NAT Gateway to Cloud NAT Migration Guide This guide explains how to migrate from an instance-based NAT gateway to the managed [Cloud NAT](https://cloud.google.com/nat/docs/overview) resource. For more information see the following [documentation](https://cloud.google.com/vpc/docs/special-configurations#migrate-nat). ## Configure a Cloud NAT In the same region your instance-based NAT gateway is located, configure a Cloud NAT resource. ### Using Console or API Use [these instructions](https://cloud.google.com/nat/docs/using-nat) to configure a Cloud NAT in the same region as your instance-based NAT gateway. ### Using [Cloud NAT Terraform Module](https://github.com/terraform-google-modules/terraform-google-cloud-nat) _The instructions below are intended for Terraform 0.12. We recommend [upgrading your resources](https://www.terraform.io/upgrade-guides/0-12.html) to Terraform 0.12, but if you need a Terraform 0.11.x-compatible version of Cloud NAT, use version [0.1.0](https://registry.terraform.io/modules/terraform-google-modules/cloud-nat/google/0.1.0) of [terraform-google-cloud-nat](https://github.com/terraform-google-modules/terraform-google-cloud-nat)._ Create a Cloud NAT resource in your region. If you do not have a Cloud Router, create one using the `google_compute_router` resource. ```hcl resource "google_compute_router" "router" { name = "load-balancer-module-router" region = var.region network = var.network } module "cloud_nat" { source = "terraform-google-modules/cloud-nat/google" version = "~> 1.0.0" project_id = var.project_id region = var.region name = "load-balancer-module-nat" router = google_compute_router.router.name } ``` ## Remove static routes Delete the [static routes](https://cloud.google.com/vpc/docs/using-routes#deletingaroute) that are sending traffic to the instanced-based NAT gateway. * If created via NAT gateway module, routes will be named `[prefix]nat-[zone]` * If created via console or API, routes [may be called](https://cloud.google.com/vpc/docs/special-configurations#natgateway): `no-ip-internet-route`, `natroute1`, `natroute2`, `natroute3` Once removed, confirm that traffic is flowing through Cloud NAT from an instance in your network. ## Remove NAT gateway Delete your NAT gateway instance(s). * If created via NAT gateway module, remove the instance of the module from Terraform and re-apply * If created via console or API, delete your instance-based NAT gateways ## Note for users of squid proxy functionality in NAT gateway Cloud NAT does not support squid or network proxy functionality. To use a squid proxy, see the following [documentation](https://cloud.google.com/vpc/docs/special-configurations#proxyvm).
218281a0a1d039cbf3a253c212969e2061d7ff7c
[ "Markdown", "Shell" ]
16
Markdown
stone-payments/terraform-google-nat-gateway
8d285a49eba4e2fbe710db893b9943713b3b69d4
b7006679ba4b5a71d62e2d033ace30067563e901
refs/heads/master
<file_sep>ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 } younger_ages = ages.reject{|key,value| value >= 100} p younger_ages ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 } puts ages.values.min flintstones = %w(<NAME> Wilma Betty BamBam Pebbles Bernie) index = 0 flintstones.each_with_index do |name, idx| if name[0,2] == "Be" index = idx break end end puts index <file_sep>arr = [{a: 1}, {b: 2, c: 3}, {d: 4, e: 5, f: 6}] # without modifying the original array, use the map method to return a new array # identical in structure to the original but where the value of each integer is # incremented by 1 new_arr = arr.map do |hash| hash_arr = hash.map do |k,v| v += 1 [k,v] end hash_arr.to_h end p new_arr # use a combination of methods, including either the select or reject method, # to return a new array identical in structure to the original but containing # only the integers that are multiples of 3 arr2 = [[2], [3, 5, 7], [9], [11, 13, 15]] new_arr2 = arr2.map do |sub_arr| multiples_of_3_arr = sub_arr.select do |int| int % 3 == 0 end end p new_arr2<file_sep># return a new array containing the same sub-arrays as the original but ordered # logically by only taking into consideration the odd numbers they contain arr = [[1, 6, 7], [1, 4, 9], [1, 8, 3]] # [[1, 8, 3], [1, 6, 7], [1, 4, 9]] new_arr = arr.sort_by do |sub_arr| sub_arr.select{|x| x.odd?} end p new_arr <file_sep># Turn this array into a hash where the names are the keys and the values are # the positions in the array. flintstones = ["Fred", "Barney", "Wilma", "Betty", "Pebbles", "BamBam"] flintstones_hash = {} flintstones.each_with_index{|name, idx| flintstones_hash[name] = idx} p flintstones_hash counter = -1 flintstones_hash_2 = flintstones.map do |name| counter += 1 [name, counter] end p flintstones_hash_2.to_h ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 } p ages.values.sum<file_sep># print out the name, age and gender of each family member: # (Name) is a (age)-year-old (male or female). munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" }, "Marilyn" => { "age" => 23, "gender" => "female"} } munsters.each do |k,v| puts "#{k} is a #{v['age']}-year-old #{v['gender']}." end a = 2 b = [5, 8] arr = [a, b] # [2,[5,8]] arr[0] += 2 #modifies array but not a since integers are immutable, so a = 2, arr = [4,[5,8]] (assigns new value to array) arr[1][0] -= a #still modified, so b = [3,8], arr = [4,[3,8]] p a p b p arr<file_sep>-use underscore for unused block parameters <file_sep># Each UUID consists of 32 hexadecimal characters, and is typically broken into # 5 sections like this 8-4-4-4-12 and represented as a string. # f65c57f6-a6aa-17a8-faa1-a67f2dc9fa91 HEXADECIMAL = %w(1 2 3 4 5 6 7 8 9 a b c d e f) def get_uuid string = "" 32.times do string << HEXADECIMAL.sample end string.insert(8, '-') string.insert(13, '-') string.insert(18, '-') string.insert(23, '-') string end id_1 = get_uuid puts id_1 <file_sep>str = "abcde" array = [] last_index = str.length - 1 str.each_char do |x| array[last_index] = x last_index -= 1 end p array str2 = array.join p str2<file_sep>flintstones = %w(<NAME> Wilma <NAME>) flintstones.map!{|x| x[0,3]} p flintstones # Create a hash that expresses the frequency with which each letter occurs in # this string: statement = "The Flintstones Rock" hash = {} statement = statement.delete(' ') statement = statement.split('') statement.each do |c| hash[c] = statement.count(c) end p hash<file_sep>def integer?(input) input.to_i.to_s == input end def integer?(input) /^\d+$/.match(input) end def integer?(input) Integer(input) rescue false end def float?(input) input.to_f.to_s == input end <file_sep># methods def prompt(message) puts "=> #{message}" end def positive_float?(input) input.to_f.to_s == input && input.to_f > 0 end # initiate variables loan_amount = 0.0 # getting user input loop do prompt "Enter the loan amount: (format: 0.0, be sure to include the decimal point!" loan_amount = gets.chomp break if !loan_amount.empty? && positive_float?(loan_amount) prompt "Please enter a valid, positive float." end prompt "Enter the Annual Percentage Rate (APR): " apr = gets.chomp.to_f prompt "Enter the loan duration: (in months)" months = gets.chomp.to_i # converting APR to monthly monthly_interest_rate = apr / 12 # calculating monthly payment monthly_payment = (loan_amount * (monthly_interest_rate / (1 - (1 + monthly_interest_rate)**(-months)))).round(2) # output puts "You will need to pay #{monthly_payment} per month over a duration of #{months} months." <file_sep> SYMBOLS = %w(X O) def prompt(message) puts "=> #{message}" end def display(array) array.each do |y| print "|" y.each do |x| x = x.center(5, ' ') print " #{x} |" end print "\n" end end def display_win(winner) puts "#{winner} won!" end def clear() [['(0,0)', '(0,1)', '(0,2)'], ['(1,0)', '(1,1)', '(1,2)'], ['(2,0)', '(2,1)', '(2,2)']] end def update(x, y, array, symbol = 'X') array[x][y] = symbol if empty?(x, y, array) end def computer_update(array) loop do x = rand(0..2) y = rand(0..2) break if empty?(x, y, array) && update(x, y, array, 'O') end end # takes coordinates # returns true if it is empty def empty?(x, y, array) !(SYMBOLS.include?(array[x][y])) end # checks if board is full def board_full?(array) array.each_with_index do |sub_array,y| sub_array.each_with_index do |_, x| return false if empty?(x, y, array) end end end def won?(array) vertical_check(array) || diagonal_check(array) || horizontal_check(array) end def horizontal_check(array) array.each_with_index do |sub_array, x| first_symbol = array[x][0] return true if sub_array.all? do |symbol| symbol == first_symbol end end false end def vertical_check(array) y = 0 while y < 3 first_symbol = array[0][y] x = 1 col_same = true while x < 3 if first_symbol != array[x][y] col_same = false end x += 1 end if col_same == true return true end y += 1 end false end def diagonal_check(array) symbol = array[1][1] if array[0][0] == symbol && array[2][2] == symbol return true elsif array[2][0] == symbol && array[0][2] == symbol return true else false end end prompt("Welcome to Tic-tac-toe!") prompt("First player to win 5 rounds wins!") board = [['(0,0)', '(0,1)', '(0,2)'], ['(1,0)', '(1,1)', '(1,2)'], ['(2,0)', '(2,1)', '(2,2)']] loop do # outer loop round_number = 0 player_score = 0 computer_score = 0 loop do # score keeping loop prompt("It is round #{round_number}.") board = clear() loop do # main game loop loop do # checking for valid coordinates display(board) prompt("Enter your coordinates: ") input = gets.chomp input_x = input[0].to_i input_y = input[2].to_i break if update(input_x, input_y, board) prompt("Invalid coordinates! Please try again. ") end if won?(board) display_win("Human") display(board) player_score += 1 break end if board_full?(board) prompt("It's a tie!") break end computer_update(board) if won?(board) display_win("Computer") display(board) computer_score += 1 break end end #main game loop end if player_score >= 5 prompt "Player won 5 : #{computer_score}!" break elsif computer_score >= 5 prompt "Computer won 5 : #{player_score}!" break else prompt "The current score is #{player_score} : #{computer_score}" round_number += 1 end # if statement end end #score keeping loop end prompt "Would you like to play again? (y/n)" answer = gets.chomp if answer != 'y' prompt "Thanks for playing!" break end end # outer loop end <file_sep>def dot_separated_ip_address?(input_string) dot_separated_words = input_string.split(".") return false if(dot_separated_words.size != 4) dot_separated_words.each{|x| return false if !(x.is_an_ip_number)} return true end # Problems: # not returning false condition # not handling the case that there are more or fewer than 4 components to the # IP address (e.g. "4.5.5" or "1.2.3.4.5" should be invalid)<file_sep>hsh = {first: ['the', 'quick'], second: ['brown', 'fox'], third: ['jumped'], fourth: ['over', 'the', 'lazy', 'dog']} # Using the each method, write some code to output all of the vowels from the strings. VOWELS = %w(a e i o u) hsh.each_value do |v| v.each do |str| str.each_char do |char| print char if VOWELS.include?(char) end end end print "\n" arr = [['b', 'c', 'a'], [2, 1, 3], ['blue', 'black', 'green']] # return a new array of the same structure but with the sub arrays being ordered # (alphabetically or numerically as appropriate) in descending order new_arr = arr.map do |x| x.sort{|a, b| b <=> a} end p new_arr<file_sep># sort by descending order arr = ['10', '11', '9', '7', '8'] sorted_arr = arr.sort do |a,b| a = a.to_i b = b.to_i b <=> a end p sorted_arr # order this array of hashes based on the year of publication of each book, # from the earliest to the latest books = [ {title: 'One Hundred Years of Solitude', author: '<NAME>', published: '1967'}, {title: 'The Great Gatsby', author: '<NAME>', published: '1925'}, {title: 'War and Peace', author: '<NAME>', published: '1869'}, {title: 'Ulysses', author: '<NAME>', published: '1922'} ] sorted_books = books.sort_by do |x| x[:published].to_i end p sorted_books #reference the letter g arr1 = ['a', 'b', ['c', ['d', 'e', 'f', 'g']]] puts "arr1: #{arr1[2][1][3]}" arr2 = [{first: ['a', 'b', 'c'], second: ['d', 'e', 'f']}, {third: ['g', 'h', 'i']}] puts "arr2: #{arr2[1][:third][0]}" arr3 = [['abc'], ['def'], {third: ['ghi']}] puts "arr3: #{arr3[2][:third][0][0]}" hsh1 = {'a' => ['d', 'e'], 'b' => ['f', 'g'], 'c' => ['h', 'i']} puts "hsh1: #{hsh1['b'][1]}" hsh2 = {first: {'d' => 3}, second: {'e' => 2, 'f' => 1}, third: {'g' => 0}} puts "hsh2: #{hsh2[:third].key(0)}"<file_sep>def display_board(array) puts "_____________" array.each do |y| print "|" y.each do |x| print " #{x} |" end print "\n" end puts "_____________" end board = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']] display_board(board) <file_sep>def display_board(array) array.each do |y| print "|" y.each do |x| x = x.center(5, padstr=' ') print " #{x} |" end print "\n" end end board = [['x','(0,1)','(0,2)'], ['(1,0)','(1,1)','(1,2)'], ['(2,0)','(2,1)','(2,2)']] display_board(board)<file_sep># For each of these collection objects where the value 3 occurs, # demonstrate how you would change this to 4 arr1 = [1, [2, 3], 4] arr1[1][1] = 4 p arr1 arr2 = [{a: 1}, {b: 2, c: [7, 6, 5], d: 4}, 3] arr2[2] = 4 p arr2 hsh1 = {first: [1, 2, [3]]} hsh1[:first][2][0] = 4 p hsh1 hsh2 = {['a'] => {a: ['1', :two, 3], b: 4}, 'b' => 5} hsh2[['a']][:a][2] = 4 p hsh2 munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" }, "Marilyn" => { "age" => 23, "gender" => "female"} } sum = 0 munsters.each_value do |v| if v['gender'] == 'male' sum += v['age'] end end puts sum <file_sep># a method that takes in two arguments:starting number and ending number # print numbers between the two numbers (inclusive) # if divisible by 3, print fizz # if by 5, buzz # if by both, fizzbuzz # return nil (presumably) def fizzbuzz(first_num, end_num) first_num..end_num.times do |num| if (num % 3 == 0) && (num % 5 == 0) puts "fizzbuzz" elsif (num % 3 == 0) puts "fizz" elsif (num % 5 == 0) puts "buzz" else puts num end end end fizzbuzz(0, 23)<file_sep>#self implementation Kernel.puts("Enter the first number: ") num_1 = Kernel.gets().chomp().to_i() Kernel.puts("Enter the second number: ") num_2 = Kernel.gets().chomp().to_i() Kernel.puts("Enter type of operation: ") operation = Kernel.gets().chomp() case operation when 'add' then puts num_1 + num_2 when 'subtract' then puts num_1 - num_2 when 'multiply' then puts num_1 * num_2 when 'divide' then puts num_1 / num_2 end <file_sep>hsh = { 'grape' => {type: 'fruit', colors: ['red', 'green'], size: 'small'}, 'carrot' => {type: 'vegetable', colors: ['orange'], size: 'medium'}, 'apple' => {type: 'fruit', colors: ['red', 'green'], size: 'medium'}, 'apricot' => {type: 'fruit', colors: ['orange'], size: 'medium'}, 'marrow' => {type: 'vegetable', colors: ['green'], size: 'large'}, } # return an array containing the colors of the fruits and the sizes of the # vegetables. The sizes should be uppercase and the colors should be capitalized # [["Red", "Green"], "MEDIUM", ["Red", "Green"], ["Orange"], "LARGE"] new_arr = [] hsh.each_value do |v| new_arr << v[:colors].map{|x| x.capitalize} << v[:size].upcase end p new_arr
1ce9bfd6c02a5d6538651f479b4b2f4f9ddbcdcd
[ "Text", "Ruby" ]
21
Ruby
12lisalan/ls-ruby-lessons
67ce117b754f8130c1fb90f6962d346727ac00c4
ceb30157d2c882d8b9d037df6b1286abef9e2e01
refs/heads/master
<file_sep>// const logger = require("./logger") // logger.log("ALOK"); // const path = require("path"); // var pathObj = path.parse(__filename); // console.log(pathObj); // const os = require("os"); // var mem = os.totalmem(); // var freemem = os.freemem(); // console.log(mem); // console.log(`freemem: ${freemem}`); const fs = require("fs"); // const files = fs.readdirSync("./"); // console.log(files) fs.readdir("./", function(err, filesAsyn){ if(err) console.log(err); else console.log(filesAsyn); })<file_sep>#include<bits/stdc++.h> using namespace std; int steps(vector<int> &a, vector<int> &b){ if(a.size()<=1 || b.size()<=1 || a.size()!=b.size()) return 0; int res=0, dx,dy; for(int i=0;i<a.size()-1;i++){ dx=abs(a[i+1]-a[i]); dy=abs(b[i+1]-b[i]); while(dx!=0 && dy!=0){ dx--; dy--; res++; } if(dx==0) res+=dy; else res+=dx; } return res; } int main{ vector<int> a,b; int n,m; cin>>n>>m; for(int i=0;i<n;i++) cin>>a[i]; for(int i=0;i<m;i++) cin>>b[i]; int res = steps(a, b); cout<<res; }
2a4296d8d580fb622ff68c2df3fe8dc0735b3490
[ "JavaScript", "C++" ]
2
JavaScript
alok328/Test111
114d88fc76545b5959c9b21d4d9beca30908c32a
577a8f6852edeebf68b5537689660cea11dac8e6
refs/heads/master
<repo_name>MLbyML/pytorch-bioimage-io<file_sep>/pybio/torch/training/__init__.py from pybio.torch.training.simple import simple_training <file_sep>/tests/test_packages/test_UNet2DNucleiBroad_model.py import requests from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional from zipfile import ZipFile import pytest from pybio.spec.utils import get_instance MODEL_EXTENSIONS = (".model.yaml", ".model.yml") UNET_2D_NUCLEI_BROAD_PACKAGE_URL = ( "https://github.com/bioimage-io/pytorch-bioimage-io/releases/download/v0.1.1/UNet2DNucleiBroad.model.zip" ) def guess_model_path(file_names: List[str]) -> Optional[str]: for file_name in file_names: if file_name.endswith(MODEL_EXTENSIONS): return file_name return None def eval_model_zip(model_zip: ZipFile, cache_path: Path): with TemporaryDirectory() as tempdir: temp_path = Path(tempdir) if cache_path is None: cache_path = temp_path / "cache" model_zip.extractall(temp_path) spec_file_str = guess_model_path([str(file_name) for file_name in temp_path.glob("*")]) pybio_model = load_model_config(spec_file_str, root_path=temp_path, cache_path=cache_path) return get_instance(pybio_model) <file_sep>/pybio/torch/training/simple.py import torch from pathlib import Path from torch.utils.data import DataLoader from typing import Union, IO from pybio.spec.utils import get_instance try: from tqdm import trange except ImportError: import warnings warnings.warn("tqdm dependency is missing") trange = range from pybio.spec.nodes import ModelWithKwargs from pybio.torch.transformations import apply_transformations def simple_training( pybio_model: ModelWithKwargs, n_iterations: int, batch_size: int, num_workers: int, out_file: Union[str, Path, IO[bytes]] ) -> torch.nn.Module: """ Simplified training loop. """ if isinstance(out_file, str) or isinstance(out_file, Path): out_file = Path(out_file) out_file.parent.mkdir(exist_ok=True) model = get_instance(pybio_model) # instantiate all training parameters from the training config setup = pybio_model.spec.training.setup sampler = get_instance(setup.sampler) preprocess = [get_instance(prep) for prep in setup.preprocess] postprocess = [get_instance(post) for post in setup.postprocess] losses = [get_instance(loss_prep) for loss_prep in setup.losses] optimizer = get_instance(setup.optimizer, params=model.parameters()) # build the data-loader from our sampler loader = DataLoader(sampler, shuffle=True, num_workers=num_workers, batch_size=batch_size) # run the training loop for ii in trange(n_iterations): x, y = next(iter(loader)) optimizer.zero_grad() x, y = apply_transformations(preprocess, x, y) out = model(x) out, y = apply_transformations(postprocess, out, y) losses = apply_transformations(losses, out, y) ll = sum(losses) ll.backward() optimizer.step() # save model weights torch.save(model.state_dict(), out_file) return model <file_sep>/tests/test_manifest.py from pathlib import Path import pytest import yaml from pybio.spec import utils, load_and_resolve_spec MANIFEST_PATH = Path(__file__).parent.parent / "manifest.yaml" def pytest_generate_tests(metafunc): if "category" in metafunc.fixturenames and "spec_path" in metafunc.fixturenames: with MANIFEST_PATH.open() as f: manifest = yaml.safe_load(f) categories_and_spec_paths = [ (category, spec_path) for category, spec_paths in manifest.items() for spec_path in spec_paths ] metafunc.parametrize("category,spec_path", categories_and_spec_paths) def test_load_specs_from_manifest(cache_path, category, spec_path): spec_path = MANIFEST_PATH.parent / spec_path assert spec_path.exists() loaded_spec = load_and_resolve_spec(spec_path) instance = utils.get_instance(loaded_spec) assert instance
fe2b536f0842d50820367f2b554070d2637282df
[ "Python" ]
4
Python
MLbyML/pytorch-bioimage-io
113e6d01989e39cd955cb2ead311086548d95026
549a1f23c14c37889e8f7a46b938f659b09f7f9c
refs/heads/master
<repo_name>at1as/project_euler<file_sep>/problem_14.rb # The following iterative sequence is defined for the set of positive integers: # # n → n/2 (n is even) # n → 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 # # It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. # # Which starting number, under one million, produces the longest chain? # # NOTE: Once the chain starts the terms are allowed to go above one million. # def collatz(input_number, iterations = 0) return iterations if input_number < 2 if input_number.odd? next_number = (3 * input_number) + 1 else next_number = input_number / 2 end if next_number == 1 return iterations + 1 else return collatz(next_number, iterations + 1) end end values = Hash.new(0) (0..1_000_000).each do |num| values[num] = collatz(num) end puts values.sort_by { |x, y| y }.reverse.first[0] # => 837799 <file_sep>/problem_25.rb # Problem 25: 1000-digit Fibonacci number # # The Fibonacci sequence is defined by the recurrence relation: # # Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. # # Hence the first 12 terms will be: # # F1 = 1 # F2 = 1 # F3 = 2 # F4 = 3 # F5 = 5 # F6 = 8 # F7 = 13 # F8 = 21 # F9 = 34 # F10 = 55 # F11 = 89 # F12 = 144 # # The 12th term, F12, is the first term to contain three digits. # # What is the index of the first term in the Fibonacci sequence to contain 1000 digits? def next_fib(fib_sequence) if fib_sequence.empty? [1] elsif fib_sequence == [1] [1, 1] else fib_sequence + [fib_sequence.last + fib_sequence[-2]] end end def fib_of_length(target_length) fib_sequence = [] idx = 0 while fib_sequence.last.to_s.length != target_length idx += 1 fib_sequence = next_fib(fib_sequence) end idx end puts fib_of_length(1000) <file_sep>/problem_21.rb # Problem 21 – Amicable Numbers # # Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). # If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. # # For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. # # Evaluate the sum of all the amicable numbers under 10000. # def divisors(n) (n-1).downto(1).select do |x| n % x == 0 end end divisor_sums = {} (1..10_000).each do |num| divisor_sums[num] = divisors(num).reduce(&:+) end sum = divisor_sums.to_a.select { |x| divisor_sums.to_a.count(x.reverse) > 0 }.uniq.reject { |x| x[0] == x[1] }.flatten.uniq.reduce(&:+) puts sum # => 31626 <file_sep>/problem_42.rb # Problem 42: Coded Triangle Numbers # # The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: # # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # # By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. # # Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? def triangle(n) (1.to_f/2) * n * (n + 1) end f = File.read("p042_words.txt").split(",").map(&:strip).map {|x| x.delete('"') } triangular_words = 0 f.each do |word| word_value = word.split("").map { |c| ('A'..'Z').zip((1..26)).to_h[c.upcase] }.reduce(:+) triangular_words += 1 if (1..100).map { |x| triangle(x) }.any? {|x| x == word_value } end puts triangular_words # => 162 <file_sep>/problem_32.rb # Problem 32: Pandigital Products # # We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. # # The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. # # Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. # HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. products = (0..10_000).to_a.product((0..100).to_a) product_results = products.map { |x| [x[0], x[1], x[0]*x[1]] } pandigital_products = product_results.select do |x| next if x.reduce(0) { |acc, num| acc + num.to_s.length } != 9 ("1".."9").zip([x[0], x[1], x[2]].flatten.inject("") {|acc, s| "#{acc}#{s}" }.split("").sort).all? { |y| y[0] == y[1] } end puts pandigital_products.map { |x| x[2] }.sort.uniq.flatten.reduce(:+) # => 45228 <file_sep>/problem_6.rb # # # The sum of the squares of the first ten natural numbers is, # 1^2 + 2^2 + ... + 10^2 = 385 # # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)^2 = 55^2 = 3025 # # Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. # # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. # def sum_of_squares (1..100).map { |x| x*x }.sum end def square_of_sums (1..100).reduce(&:+) ** 2 end puts square_of_sums - sum_of_squares # => 25164150 <file_sep>/problem_41.rb # Problem 41: Pandigital Prime # # We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. # # What is the largest n-digit pandigital prime that exists? class Integer def prime? return false if self < 2 return true if self == 2 sqrt = Math.sqrt(self).floor (2..sqrt).to_a.reverse.all? { |x| self % x != 0 } end def pandigital? digits = self.to_s.split("").uniq digits.length == self.to_s.length && (1..self.to_s.length).all? { |x| self.to_s.include? x.to_s } end end pandigitals = (1..10_000_000).select do |x| x.pandigital? && x.prime? end # TODO: still a bit slow, start search in reverse and return immediately upon first found value puts "#{pandigitals.max}" # => 7652413 <file_sep>/problem_12.rb # Problem 12 # Highly divisible triangular number # # The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: # # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # # Let us list the factors of the first seven triangle numbers: # # 1: 1 # 3: 1,3 # 6: 1,2,3,6 # 10: 1,2,5,10 # 15: 1,3,5,15 # 21: 1,3,7,21 # 28: 1,2,4,7,14,28 # # We can see that 28 is the first triangle number to have over five divisors. # # What is the value of the first triangle number to have over five hundred divisors? def factors(number) # TODO: can optimise by only going up to the square of the number (1..number).select { |x| number % x == 0 }.count end def triangular_nums(factor_count, limit) sum = 0 (0..limit).each do |x| sum += x return sum if factors(sum) >= factor_count end end puts triangular_nums(500, 1_000_000_000) # TODO: Very slow!! # => 76576500 <file_sep>/problem_28.rb # Problem 28 - Number spiral diagonals # Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: # # 21 22 23 24 25 # 20 7 8 9 10 # 19 6 1 2 11 # 18 5 4 3 12 # 17 16 15 14 13 # # It can be verified that the sum of the numbers on the diagonals is 101. # # What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? SIZE = 1001 matrix = Array.new(SIZE) { Array.new(SIZE) } spiral_size = 1 x = SIZE / 2 y = SIZE / 2 num = 1 total = [] matrix[x][y] = 1 loop do begin # +x (RIGHT) direction (1..spiral_size).each do |offset| num += 1 matrix[y][x + offset] = num if x + offset < SIZE end x += spiral_size total << matrix[y][x - 1] # +y (DOWN) direction (1..spiral_size).each do |offset| num +=1 matrix[y + offset][x] = num if y + offset < SIZE end y += spiral_size total << matrix[y][x] spiral_size += 1 # -x (LEFT) direction (1..spiral_size).each do |offset| num += 1 matrix[y][x - offset] = num if x - offset > -1 end x -= spiral_size total << matrix[y][x] # -y (UP) direction (1..spiral_size).each do |offset| num += 1 matrix[y - offset][x] = num if y - offset > -1 end y -= spiral_size total << matrix[y][x] spiral_size += 1 rescue NoMethodError => e # this will always throw once the matrix has been populated # when the +y (DOWN) direction tries to create a cell in an out of bounds rows puts total.reduce(:+) break end end # => 669171001 <file_sep>/problem_17.rb # If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? # DO NOT COUNT Spaces, or hypens ONES = { 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine", 0 => "" } TEENS = { 0 => "ten", 1 => "eleven", 2 => "twelve", 3 => "thirteen", 4 => "fourteen", 5 => "fifteen", 6 => "sixteen", 7 => "seventeen", 8 => "eighteen", 9 => "nineteen" } TENS = { 2 => "twenty", 3 => "thirty", 4 => "forty", 5 => "fifty", 6 => "sixty", 7 => "seventy", 8 => "eighty", 9 => "ninety" } res = (1..1000).map do |num| digits = num.to_s.reverse.split("").map(&:to_i) words = [] # Count the 'ones' digit, unless between 11 and 19 if digits.length > 0 && !(digits.length > 1 && digits[1] == 1) words << ONES[digits[0]] end # Count the 'tens' digit. Handle case for 11 - 19 and standard case if digits.length > 1 if digits[1] == 1 words << TEENS[digits[0]] else words << TENS[digits[1]] end end # Count the 'hundreds' digit. Add 'and' to hundred unless number is divisible by 100 if digits.length > 2 if digits[2] != 0 if digits[0..1] != [0, 0] words << (ONES[digits[2]] + "hundred and") else words << (ONES[digits[2]] + "hundred") end end end # Cound the 'thousands' digit. We stop here, so this is only built for the base '1000' case if digits.length == 4 words << (ONES[digits[3]] + "Thousand") end words.reject(&:nil?).map { |w| w.gsub(' ', '').length }.reduce(&:+) end puts "#{res.reduce(&:+)}" # => 21124 <file_sep>/problem_19.rb # Problem 19 # You are given the following information, but you may prefer to do some research for yourself. # # 1 Jan 1900 was a Monday. # Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # Which has twenty-eight, rain or shine. # And on leap years, twenty-nine. # A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. # # How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? DAYS_OF_THE_WEEK = %w(monday tuesday wednesday thursday friday saturday sunday) def leap_year?(year) (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) end def get_months(year) days_of_the_year = [ 31, # JANUARY 28, # FEBRUARY 31, # MARCH 30, # APRIL 31, # MAY 30, # JUNE 31, # JULY 31, # AUGUST 30, # SEPTEMBER 31, # OCTOBER 30, # NOVEMBER 31 # DECEMBER ] if leap_year?(year) # 29 days in february days_of_the_year.tap { |m| m[1] = m[1] + 1 } else days_of_the_year end end def get_days_per_year_range(start, finish) (start..finish).map do |year| get_months(year).map { |m| (1..m).to_a } end end # 1900 is included in range to acquire the correct date of the week taht 1901 starts on # The number of sundays in 1901 are subtracted from the total afterwards sundays_in_century = get_days_per_year_range(1900, 2000).flatten.zip(DAYS_OF_THE_WEEK.cycle).select { |x| x == [1, "sunday"] }.count sundays_in_1900 = get_days_per_year_range(1900, 1900).flatten.zip(DAYS_OF_THE_WEEK.cycle).select { |x| x == [1, "sunday"] }.count puts sundays_in_century - sundays_in_1900 <file_sep>/problem_48.rb # Problem 48: # # The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. # # Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. puts (1..1000).inject(0) { |acc, n| acc + (n ** n) } # => 9110846700 <file_sep>/problem_29.rb # Problem 29 # How many distinct terms are in the sequence generated by a^b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100? class Numeric def normalize(exp) # # 2.normalize(3) # => [2, 3] => [2^3, 1] => [8, 1] # sqrt = Math.sqrt(exp).floor (sqrt..self).each do |i| next if i == 1 r = self ** (1.to_f / i) return [r, (exp * i).to_f] if r == r.to_i end [self.to_f, exp.to_f] end end SIZE = 100 a = (2..SIZE) b = (2..SIZE) combinations = a.to_a.product(b.to_a).uniq # Normalize entries to their smallest exponentials [4,2] -> [2,4], so repeat values can be removed # n.b. This optimization is probably worse than simply skipping this step unique_combinations = combinations.map { |x| x[0].normalize(x[1]) }.uniq # Calculate value of remaining values so that different exponentials with same result will # not be counted multiple times puts "#{ unique_combinations.map {|x| x[0] ** x[1] }.uniq.size }" # => 9183 <file_sep>/problem_4.rb # https://projecteuler.net/problem=4 # # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # # Find the largest palindrome made from the product of two 3-digit numbers. # def get_products combos = (100..999).map do |num1| (100..999).map do |num2| num1 * num2 end end combos.flatten.uniq end class Integer def palindromic? self.to_s == self.to_s.reverse end end puts get_products.select(&:palindromic?).max # => 906609 <file_sep>/problem_37.rb # Problem 27 : Truncatable Primes # # The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. # # Find the sum of the only eleven primes that are both truncatable from left to right and right to left. # # NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. class Integer def prime? return false if self < 2 sqrt = Math.sqrt(self).floor # TODO: Using all? here would be faster since computation of the rest of the sequence would stop upon violation (1..sqrt).select { |x| self % x == 0 }.length == 1 end end def number_combos(number) # "1234" => ["1234" , "234", "34", "4"] number.to_s.split("").each_index.map { |i| number.to_s[i..number.to_s.length-1] } end truncatable_primes = (10...1_000_000).select do |num| number_combos(num).all? { |x| x.to_i.prime? } && number_combos(num.to_s.reverse).map(&:reverse).all? { |x| x.to_i.prime? } && !num.to_s.include?("0") end puts "#{truncatable_primes.reduce(:+)}" # => 748317 <file_sep>/problem_2.rb # Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: # # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. # def fib(values, limit) if values.empty? fib([0, 1], limit) elsif (next_val = values.last + values[-2]) < limit fib(values << next_val, limit) else values end end fib_values = fib([], 4_000_000) puts fib_values.select(&:even?).sum # => 4613732 <file_sep>/problem_40.rb # Problem 40: Champernowne's constant # # An irrational decimal fraction is created by concatenating the positive integers: # # 0.123456789101112131415161718192021... # # It can be seen that the 12th digit of the fractional part is 1. # # If dn represents the nth digit of the fractional part, find the value of the following expression. # # d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 x = (1..200_000).map(&:to_s).join puts x[1_000_000-1], x[100_000-1], x[10_000-1], x[1_000-1], x[100-1], x[10-1], x[1-1]].map(&:to_i).inject(1) { |x, acc| x * acc } # => 210 <file_sep>/problem_49.rb # Problem 49: Prime Permutations # # The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. # # There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. # # What 12-digit number do you form by concatenating the three terms in this sequence? # class Integer def prime? return true if [2, 3].include?(self) return false if self.even? || self == 1 sqrt_n = Math.sqrt(self).floor !(2..sqrt_n).detect { |num| self % num == 0 } end end primes = (1488..9999).select { |n| n.prime? }.sort.uniq match = primes.detect do |n| permutation_primes = n.to_s.split("").permutation(4).map(&:join).sort.uniq.select { |x| primes.include? x.to_i }.map(&:to_i) next unless permutation_primes.length >= 3 permutation_primes.any? { |x| ([x, x + 3330, x + (2*3330)] - permutation_primes).empty? } end puts "#{match}#{match + 3330}#{match + 2*3330}" # => 269960299359 <file_sep>/problem_30.rb # Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: # # 1634 = 1^4 + 6^4 + 3^4 + 4^4 # 8208 = 8^4 + 2^4 + 0^4 + 8^4 # 9474 = 9^4 + 4^4 + 7^4 + 4^4 # # As 1 = 1^4 is not a sum it is not included. # # The sum of these numbers is 1634 + 8208 + 9474 = 19316. # # Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. # Limit should be higher than 99_999 since some 6, 7, or higher digit numbers # may still satisfy the rule. Arbitrarily choosing this value, but it may need # to be increased LIMIT = 999_999 numbers = (10..LIMIT).select do |x| x.to_s.split("").map { |digit| digit.to_i ** 5 }.reduce(:+).to_s == x.to_s end puts numbers.reduce(:+) # => 443839 <file_sep>/problem_36.rb # Problem 36: Double-Base Palindromes # # The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. # # Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. # # (Please note that the palindromic number, in either base, may not include leading zeros.) def palondromic?(number) number.to_s == number.to_s.reverse end numbers = (1..999_999).select do |x| palondromic?(x) && palondromic?(x.to_s(2)) end puts numbers.reduce(:+) # => 872187 <file_sep>/_status_report.rb require 'net/http' require 'nokogiri' text = Net::HTTP.get(URI("https://github.com/at1as/project_euler")) html = Nokogiri::HTML(text) labels = html.xpath('//a[contains(text(), "problem_")]') puts "\nMissing from the first 50 problems:\n" remaining_problems = (1..50).to_a - labels.map { |x| x.inner_html }.map { |x| x.match(/problem_([0-9]*).rb/).captures.first }.map(&:to_i) puts remaining_problems.map {|x| " #{x}"} puts "\n#{remaining_problems.length}/50 problems left" __END__ Output from last run: Missing from the first 50 problems: 15 22 23 26 27 31 35 39 43 44 45 46 47 49 50 15/50 problems left <file_sep>/README.md # Project Euler Problems Solutions to [Project Euler](https://projecteuler.net/archives) problems <file_sep>/problem_3.rb # # The prime factors of 13195 are 5, 7, 13 and 29. # # What is the largest prime factor of the number 600851475143 ? # def is_prime(number) return false if number < 3 || number.even? square = Math.sqrt(number).to_i !(3..square).any? { |x| number % x == 0 } end def get_prime_list(limit) prime_range = (0..Math.sqrt(limit).to_i).select(&:odd?).select { |x| limit % x == 0 }.reverse prime_range.each do |x| return x if is_prime(x) end end puts get_prime_list(600_851_475_143) # => 6857 <file_sep>/problem_38.rb # Problem 38: Pandigital Multiples # # Take the number 192 and multiply it by each of 1, 2, and 3: # # 192 × 1 = 192 # 192 × 2 = 384 # 192 × 3 = 576 # # By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) # # The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). # # What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? class Integer def pandigital? self.to_s.split("").sort.reject { |x| x == "0" }.uniq.length == 9 end end pandigital_products = (10..10_000).map do |x| products = [] (1..100).each do |multiplier| products << x * multiplier break if products.map(&:to_s).join.length >= 9 end if products.map(&:to_s).join.to_s.to_i.pandigital? if products.map(&:to_s).join.length == 9 products.map(&:to_s).join.to_i else nil end else nil end end puts "#{pandigital_products.reject(&:nil?).max }" # => 932718654 <file_sep>/problem_7.rb # 10001st prime # https://projecteuler.net/problem=7 # # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # # What is the 10,001st prime number? def prime?(number) return false if number <= 1 sqrt = Math.sqrt(number).to_i (1..sqrt).select { |x| number % x == 0 }.count < 2 end def nth_prime(target_idx, limit) nth_prime = 0 (0..limit).each do |num| nth_prime += 1 if prime?(num) return num if nth_prime == target_idx end end puts nth_prime(10_001, 1_000_000_000) # => 104743 <file_sep>/problem_34.rb # 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. # # Find the sum of all numbers which are equal to the sum of the factorial of their digits. # # Note: as 1! = 1 and 2! = 2 are not sums they are not included. def factorial(n) return 1 if n < 2 n * factorial(n-1) end valid = (3..500_000).to_a.select do |x| x.to_s.split("").map { |x| factorial(x.to_i) }.reduce(:+) == x end puts valid.reduce(:+) <file_sep>/problem_10.rb # Problem 10: Summation of Primes # # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # # Find the sum of all the primes below two million. def prime?(n) return true if [2,3].include? n return false if n.even? || n == 1 # factors will never exceed the root of the number sqrt_n = Math.sqrt(n).floor factors = !(2..sqrt_n).detect do |num| n % num == 0 end end def primes(limit) (0..limit).select do |n| prime?(n) end end puts primes(2_000_000).reduce(&:+) <file_sep>/problem_18.rb # By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. # # 3 # 7 4 # 2 4 6 # 8 5 9 3 # # That is, 3 + 7 + 4 + 9 = 23. # # Find the maximum total from top to bottom of the triangle below: triangle = <<EOS 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 EOS rows = triangle.each_line.map { |row| row.strip.split(" ").map(&:to_i) } def get_paths(triangle_rows, path, col_number = 0) if triangle_rows.length == 1 return triangle_rows.last.to_a[col_number..col_number+1].map { |x| path + [x] } end return triangle_rows.first.each_with_index.to_a[col_number..col_number+1].map { |x,i| get_paths(triangle_rows[1..-1], path + [x], i) }.flatten(1) end puts "#{get_paths(rows, []).sort_by(&:sum).last.sum}" # => 1074 <file_sep>/problem_9.rb # Special Pythagorean triplet # # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 # # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. # def pythagorean_triplet(target) (1..1000).to_a.each do |a| (a..1000).to_a.each do |b| (b..1000).to_a.each do |c| if a + b + c == target && a**2 + b**2 == c**2 return a * b * c end end end end nil end puts pythagorean_triplet(1000) # => 31875000 <file_sep>/problem_33.rb # Problem 33: Digit Cancelling Fractions # # The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. # # We shall consider fractions like, 30/50 = 3/5, to be trivial examples. # # There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator. # # If the product of these four fractions is given in its lowest common terms, find the value of the denominator. digits = (10..99).to_a # Remove fractions greater than one, trivial fractions, and fractions that contain no mutual numbers in numerator and denominator fractions = digits.product(digits).select { |x| x[0] < x[1] } fractions = fractions.reject { |x| x[0] % 10 == 0 && x[1] % 10 == 0 } fractions = fractions.reject { |x| x.any? { |num| num.to_s.split("").uniq.length == 1 } } fractions = fractions.select { |x| (x[0].to_s.split("") & x[1].to_s.split("")).length > 0 } digit_cancelling = fractions.select do |x| fraction_nums = [x[0], x[1]].flatten.map(&:to_s).map { |x| x.split("") }.flatten repeat_values = fraction_nums.select { |x| fraction_nums.count(x) > 1 }.uniq reduced_fractions = repeat_values.map do |r| x.map { |n| n.to_s.delete(r).to_i } end reduced_fractions.reject { |n| n.any? {|num| num == 0} }.any? do |f| (f[0].to_f / f[1].to_f) == (x[0].to_f / x[1].to_f) end end # Multiply Fractions fraction_result = digit_cancelling.inject([1, 1]) { |acc, fraction| [acc[0] * fraction[1] , acc[1] * fraction[0]] } puts fraction_result[0] / fraction_result[1].gcd(fraction_result[0]) # => 100 <file_sep>/problem_5.rb # # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? # def hello(limit) (1..limit).each do |num| return num if (2..20).to_a.reverse.all? { |x| num % x == 0 } end end # Slow, slow, slow. But it works # TODO: Speed up puts hello(1_000_000_000) # => 232792560
0002cc9161ccbb76cfe37bdea1b7eaa1b8dc5d2d
[ "Markdown", "Ruby" ]
31
Ruby
at1as/project_euler
ff62cf1534a37964d2d4babeffa84dc54afa14e3
5107a6b0a80968020bb6a62a08ea06c9e6784b99
refs/heads/master
<repo_name>kashmira1010/angular4_lists<file_sep>/src/app/auth/auth.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http' import { Router} from '@angular/router'; import { CookieService } from 'ngx-cookie-service'; import { Subject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthService { $authObservable : Subject<any> = new Subject; constructor(private _http : HttpClient, private _router : Router, private _cookie : CookieService) { } login(data : any) { return this._http.post('http://localhost:3000/login',data); // this._http.post('http://localhost:3000/login',data).subscribe((data : any)=>{ // if(data.isloggedIn) // { // this.$authObservable.next(data.token); // this._cookie.set('token', data.token); // this._router.navigate(['/home']); // } // else // { // // console.log("fail"); // } // }); // console.log(data); } checkUserStatus() { return this._cookie.get('token'); } logout() { this._cookie.delete('token'); this.$authObservable.next(false); this._router.navigate(['/login']); } registration(value : any) { // console.log(value); return this._http.post('http://localhost:3000/registration',value); } } <file_sep>/src/app/auth/login/login.component.ts import { Component, OnInit } from '@angular/core'; import { Subject } from 'rxjs'; import { CookieService } from 'ngx-cookie-service'; import { AuthService } from '../auth.service'; import { Router} from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { // loginForm : any = {}; isloggedIn : boolean = false; $authObservable : Subject<any> = new Subject; constructor(private _authService : AuthService, private _cookie : CookieService, private _router : Router) { } ngOnInit() { } login(loginDetail:any) { this._authService.login(loginDetail).subscribe((data : any)=>{ // console.log(data); if(data.isloggedIn) { this.$authObservable.next(data.token); this._cookie.set('token', data.token); this._router.navigate(['/home']); } else { this.isloggedIn = true; } }); } } <file_sep>/src/app/products/detail/detail.component.ts import { Component, OnInit,Input } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { ProductService} from '../product.service'; import {AuthService} from 'src/app/auth/auth.service' // import { HttpClient} from '../product.service'; @Component({ selector: 'app-detail', templateUrl: './detail.component.html', styleUrls: ['./detail.component.css'] }) export class DetailComponent implements OnInit { detailValue : any = {} ; arrStarRating : any = [] ; constructor(private _authService :AuthService, private _activatedRouter : ActivatedRoute, private _route : Router, private _productService : ProductService ) { } ngOnInit() { this._activatedRouter.params.subscribe((data)=>{ // console.log('triggered') this._productService.productDetail(data).subscribe((res)=>{ this.arrStarRating = Array(Math.round(res["starRating"])).fill(Math.round(res["starRating"])); // console.log(this.starRating); this.detailValue = res; }); }); } backToList() { this._route.navigate(['/product']); } } <file_sep>/src/app/products/product.service.ts import { Injectable } from '@angular/core'; import{ HttpClient, HttpHeaders} from '@angular/common/http'; import { AuthService } from 'src/app/auth/auth.service'; @Injectable({ providedIn: 'root' }) export class ProductService { constructor(private _httpRequest : HttpClient, private _authService : AuthService) { } getProducts() { return this._httpRequest.get('http://localhost:3000/getProduct'); } createProducts(product:any) { return this._httpRequest.post('http://localhost:3000/createProduct',product); } productDetail(productCode:any) { return this._httpRequest.post('http://localhost:3000/productDetail',productCode); } } <file_sep>/src/app/products/create/create.component.ts import { Component, OnInit } from '@angular/core'; import { ProductService } from '../product.service'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-create', templateUrl: './create.component.html', styleUrls: ['./create.component.css'] }) export class CreateComponent implements OnInit { product : any = {}; showMessage : String ; isSuccessOrFail : Boolean; productForm : FormGroup; constructor(private _productService : ProductService , private _formBuilder : FormBuilder) { } ngOnInit() { this.productForm = this._formBuilder.group({ productId : ["",[Validators.required,Validators.pattern("^(0|[1-9][0-9]*)$")]], productName : ["",[Validators.required]], productCode : ["",[Validators.required]], releaseDate : ["",[Validators.required,Validators.pattern("(?:(?:0[1-9]|1[0-2])[\/\\-. ]?(?:0[1-9]|[12][0-9])|(?:(?:0[13-9]|1[0-2])[\/\\-. ]?30)|(?:(?:0[13578]|1[02])[\/\\-. ]?31))[\/\\-. ]?(?:19|20)[0-9]{2}")]], description : ["",[Validators.required]], price : ["",[Validators.required,Validators.pattern("^(([1-9]*)|(([1-9]*)\.([0-9]*)))$")]], imageUrl : ["",[Validators.required,Validators.pattern("https?://.+")]] }); } submitProductForm() { // console.log(this.productForm.value); this._productService.createProducts(this.productForm.value).subscribe((data)=>{ if(data) { this.showMessage = "Product add successfully"; this.isSuccessOrFail = !this.isSuccessOrFail ; this.productForm.reset(); } else { this.showMessage = "Product id already available"; this.isSuccessOrFail = !this.isSuccessOrFail ; } }); } } <file_sep>/src/app/auth/register/register.component.ts import { Component, OnInit } from '@angular/core'; import { AuthService } from '../auth.service'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.css'] }) export class RegisterComponent implements OnInit { // registration : any = {}; showMessage : string ; isSuccessOrFail : boolean = false; registerForm : FormGroup; constructor(private _authService : AuthService, private _FormBuilder : FormBuilder) { } ngOnInit() { this.registerForm = this._FormBuilder.group({ firstname : ["", [Validators.required, Validators.minLength(5)]], lastname : ["", [Validators.required, Validators.minLength(5)]], email : ["", [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')]], password : ["", [Validators.required, Validators.minLength(5)]], phonenumber : ["", [Validators.required, Validators.minLength(10)]] }); } submitForm(){ // console.log(this.registerForm.value); this._authService.registration(this.registerForm.value).subscribe((data:any)=>{ if(data) { this.isSuccessOrFail = true; this.showMessage = "Register sucessfull"; this.registerForm.reset(); } else { // console.log(this.isSuccessOrFail); this.isSuccessOrFail = true; this.showMessage = "This email id already register"; } }); } } <file_sep>/README.md # angular4_lists working MEAN stack <file_sep>/src/app/products/product/product.component.ts import { Component, OnInit } from '@angular/core'; import { ProductService } from '../product.service'; import { AuthService } from 'src/app/auth/auth.service'; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.css'], providers : [ProductService] }) export class ProductComponent implements OnInit { pageTitle : string = "Welcome product page"; products : any = []; filterBy :string; showAndHide : boolean = true; constructor(private _productService : ProductService, private _authService : AuthService) { } ngOnInit() { //User is logged in this._productService.getProducts().subscribe((data)=>{ // console.log(data); this.products = data; }); } isHideAndShow() { this.showAndHide = !this.showAndHide; } ratingFnParent(data:string) { this.pageTitle = data; // console.log(data); } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { RouterModule } from '@angular/router'; import { CookieService } from 'ngx-cookie-service'; import { AuthGuard } from './auth/auth.guard'; import { AuthinterceptorService } from './auth/authinterceptor.service'; import { AppComponent } from './app.component'; import { HomeComponent } from './auth/home/home.component'; import { NavigationComponent } from './auth/navigation/navigation.component'; import { LoginComponent } from './auth/login/login.component'; import { AuthService } from './auth/auth.service'; import { RegisterComponent } from './auth/register/register.component'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, HomeComponent, NavigationComponent, LoginComponent, RegisterComponent, ], imports: [ BrowserModule, FormsModule, HttpClientModule, ReactiveFormsModule, RouterModule.forRoot([ // {path :"product", component:ProductComponent, canActivate :[AuthGuard], // children :[ { path:"create", component:CreateComponent}, // ]}, {path : "product", loadChildren : "../app/products/product/product.module#ProductModule"}, {path :"home", component:HomeComponent, canActivate : [AuthGuard]}, {path :"login", component:LoginComponent}, {path :"register", component:RegisterComponent}, {path :"", redirectTo:"home", pathMatch:"full"}, {path :"**", redirectTo : "home"} ]) ], providers: [AuthService,CookieService,AuthGuard, { provide : HTTP_INTERCEPTORS, useClass : AuthinterceptorService, multi : true }], bootstrap: [AppComponent] }) export class AppModule { }
e022cc5795547aa32e17f75cd5ce12a7cf812080
[ "Markdown", "TypeScript" ]
9
TypeScript
kashmira1010/angular4_lists
09aef4762c92e94e32e596825e729d47c25d5def
72642b3874a36715441222c4a8d88c952f68cbc2
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; const API_URL = 'http://api.openweathermap.org/data/2.5/weather'; const API_KEY = '0e16df06b6e5088ff909d8e67c46bf5f'; @Injectable({ providedIn: 'root' }) export class WeatherServiceService { constructor(private httpClient: HttpClient) { } getCityWeather = (city) => { const getUrl = API_URL + '?q=' + city + '&APPID=' + API_KEY; return this.httpClient.get(getUrl); } } <file_sep>import { Component } from '@angular/core'; import { WeatherServiceService } from './services/weather-service.service'; import { FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'ANGULAR-API'; cityName = ''; weatherData = { name: '', temp: '', imageUrl: '', weatherStatus: '' }; today = new Date(); constructor( private weatherService: WeatherServiceService, private formBuilder: FormBuilder ) { } getWeather() { this.weatherService .getCityWeather(this.cityName).subscribe( res => { this.weatherData.name = res['name'] + ',' + res['sys']['country']; this.weatherData.temp = res['main'].temp; this.weatherData.imageUrl = 'http://openweathermap.org/img/wn/' + res['weather'][0]['icon ']+ '@2x.png'; this.weatherData.weatherStatus = res['weather'][0]['description']; }, err => console.log('error', err) ); } }
fa6a9aa864e5ac5a8aed358b38c0fee432899427
[ "TypeScript" ]
2
TypeScript
AhmedDjallelEddineSetererrahmane/PlaneryGmbH_angular_test
38993ab4928cadf2482d159c08132b8443ec62f5
17d00ede3601e19167852d98a11adf4eea866ef6
refs/heads/master
<repo_name>fukit0/ImageRecognition-PCA<file_sep>/src/main/java/ytu/ml/pca/PCAUtil.java package ytu.ml.pca; import java.awt.Robot; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import javax.xml.crypto.Data; import org.apache.commons.math3.linear.EigenDecomposition; import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.descriptive.summary.Sum; import org.apache.commons.math3.util.MathUtils; import org.omg.CORBA.TRANSACTION_MODE; import Jama.EigenvalueDecomposition; import Jama.Matrix; /** * Class responsible for all the calcualtion needed for PCA * @author furkan * */ public class PCAUtil { public static Logger logger = Logger.getGlobal(); /** * calculates the mean vector of each train sample set * * i.e, 5 sample line for classifier '0' * @param trainSamples * @return */ public static double[] calculateMeanVector(double[][] trainSamples) { double[] returnMap = new double[64]; // for every pixel index for(int x = 0 ; x < 64 ; x++){ double total = 0.0; // iterates the train samples for each classifier for(int trainRow = 0; trainRow < trainSamples.length ; trainRow++){ double value = trainSamples[trainRow][x]; total += value; } double mean = total / 50; returnMap[x] = mean; } return returnMap; } /** * subtract mean vector values from every train values * @param trainSamples * @param meanVector * @return */ public static double[][] calculateMeanCenteredTrainMatrix(double[][] trainSamples, double[] meanVector){ double[][] meanCenteredTrainMatrix = new double[Constants.NUMBER_OF_TRAIN_VECTORS][Constants.NUMBER_OF_PIXEL_VALUES]; // Iterates the sample set for each classifier for(int row = 0;row < trainSamples.length ; row++){ double[] subtractedValue = getSubtractedVector(trainSamples[row], meanVector); meanCenteredTrainMatrix[row] = subtractedValue; } return meanCenteredTrainMatrix; } /** * creates covariance matrix of matrix which is formed by mean centered vectors * @param returnMatrix * @return */ public static double[][] findCovarianceMatrix(double[][] meanCenteredVectors){ // yazdir(meanCenteredVectors); RealMatrix mx = MatrixUtils.createRealMatrix(meanCenteredVectors); RealMatrix covarianceMatrix = new Covariance(mx).getCovarianceMatrix(); return covarianceMatrix.getData(); } private static void yazdir(double[][] meanCenteredVectors) { for(int x = 0; x< meanCenteredVectors.length ; x++){ for(int y=0 ; y < meanCenteredVectors[x].length; y++){ System.out.print(meanCenteredVectors[x][y]+","); } System.out.print("\n"); } } public static double[][] createTrainEigenSpace(DataTable dataTable) { RealMatrix covarianceMatrix = MatrixUtils.createRealMatrix(dataTable.getCovarianceMatrix()); EigenDecomposition eigen = new EigenDecomposition(covarianceMatrix); dataTable.setEigen(eigen); double d = eigen.getRealEigenvalue(0); double[] eigenValues = eigen.getRealEigenvalues();// it gives the eigenvalues sorted double sumOfEigenValues = sumOfValues(eigenValues); double total = 0.0; int i = 0; // last index of the eligible eigen value while(total/sumOfEigenValues < dataTable.getThreshold()){ total = total + eigenValues[i]; i++; } dataTable.setNumberOfNewFeatures(i-1); // creating eigenspace by forming eigenvectors as matrix // rows as feature, columns as value logger.info(""); double[][] eigenvectorMatrix = getEigenVectorMatrix(dataTable); RealMatrix eigenspaceVectorMatrix = MatrixUtils.createRealMatrix(eigenvectorMatrix); // eigen vector matrix - feature sayısı X eigen value sayısı (64) RealMatrix meanCenteredTrainMatrix = MatrixUtils.createRealMatrix(dataTable.getMeanCenteredTrainMatrix()); // mean centered train matrix - pixel value X train data sayısı RealMatrix trainEigenSpace = eigenspaceVectorMatrix.multiply(meanCenteredTrainMatrix.transpose()); //satırları özellik dizisi yapmak için transpoze aldık return trainEigenSpace.transpose().getData(); } private static double[][] getEigenVectorMatrix(DataTable dataTable) { EigenDecomposition eigen = dataTable.getEigen(); int eigenVectorLength = eigen.getRealEigenvalues().length; double[][] eigenvectorMatrix = new double[dataTable.getNumberOfNewFeatures()][eigenVectorLength]; for(int featureCounter = 0 ; featureCounter < dataTable.getNumberOfNewFeatures() ; featureCounter++){ RealVector vector = eigen.getEigenvector(featureCounter); for (int columnCounter = 0; columnCounter < eigenVectorLength; columnCounter++) { eigenvectorMatrix[featureCounter][columnCounter] = vector.getEntry(columnCounter); } } return eigenvectorMatrix; } public static double[][] createTestEigenSpace(DataTable dataTable) { // feature sayısı X eigen value sayısı double[][] eigenvectorMatrix = getEigenVectorMatrix(dataTable); // test data sayısı X pixel sayısı double[][] meanCenteredTestMatrix = new double[Constants.NUMBER_OF_TEST_VECTORS][Constants.NUMBER_OF_PIXEL_VALUES]; int testSampleCounter = 0; for (double[] validationSample : dataTable.getTestSamples()) { meanCenteredTestMatrix[testSampleCounter] = getSubtractedVector(validationSample, dataTable.getTrainMeanVector()); } RealMatrix eigenSpaceVectorMatrix = MatrixUtils.createRealMatrix(eigenvectorMatrix); // feat RealMatrix meanCenteredMatrix = MatrixUtils.createRealMatrix(meanCenteredTestMatrix); // meanCenteredTestMatrix RealMatrix testEigenSpace = eigenSpaceVectorMatrix.multiply(meanCenteredMatrix.transpose()); //satırları özellik dizisi yapmak için transpoze aldıks return testEigenSpace.transpose().getData(); } private static double[] getSubtractedVector(double[] vector, double[] meanVector) { double[] subtractedVector = new double[vector.length]; for (int valueCounter = 0; valueCounter < vector.length; valueCounter++) { subtractedVector[valueCounter] = vector[valueCounter] - meanVector[valueCounter]; } return subtractedVector; } private static double sumOfValues(double[] eigenValues) { double result = 0; for (double value:eigenValues) result += value; return result; } public static void test(double[][] trainSpaceMatrix, List<Integer> trainImageValue, double[][] testEigenMatrix, List<Integer> testImageValue) { // test datasını iterate ediyoruz, her özellik için traindeki 50 veriye ait 3 özellik ile distance alıorz int numberOfTrueRecognition = 0; int numberOfFalseRecognition = 0; for(int testDataCounter = 0; testDataCounter<testEigenMatrix.length; testDataCounter++){ double minDistance = 999999; int minDistanceIndex = -1; for(int trainDataCounter = 0; trainDataCounter < trainSpaceMatrix.length ; trainDataCounter++){ double distance = getDistance(testEigenMatrix[testDataCounter],trainSpaceMatrix[trainDataCounter]); if(distance < minDistance){ minDistance = distance; minDistanceIndex = trainDataCounter; } } // Compare wheter its true or false if(trainImageValue.get(minDistanceIndex).intValue() == testImageValue.get(testDataCounter).intValue()){ numberOfTrueRecognition++; }else{ numberOfFalseRecognition++; } } double accuracy = ((double)numberOfTrueRecognition / (numberOfTrueRecognition + numberOfFalseRecognition)) * 100; System.out.printf("\nAccuracy of the tree is: %.3f\n",accuracy); } /** * Euclidean Distance * @param testVector * @param trainVector * @return */ private static double getDistance(double[] testVector, double[] trainVector) { double diff_square_sum = 0.0; for (int i = 0; i < testVector.length; i++) { diff_square_sum += (trainVector[i] - testVector[i]) * (trainVector[i] - testVector[i]); } return Math.sqrt(diff_square_sum); } }
943ed700b6231e13716d53f05e8e55d8f42b0949
[ "Java" ]
1
Java
fukit0/ImageRecognition-PCA
d83ed43f533dd2ca7ce3c8324cc8bff1da044e97
0301d6ddccc07de1f0a5780fe5c231599ffc2bb2
refs/heads/main
<repo_name>gasperjw1/Nothing<file_sep>/Topic_Model_Seinfeld.py ####### Code written by <NAME> ####### Creates a Topic Model that analyzes the show Seinfeld given a set of topics defined by a given corpus ############################################################## ############################################################## # Initial set of imports for the following code ############################################################## ############################################################## from nltk.corpus.reader.wordnet import Lemma from nltk.tokenize import word_tokenize from nltk.tag import pos_tag import spacy spacy.load("en_core_web_sm") from spacy.lang.en import English parser = English() import pandas as pd import csv from csv import DictReader import sys ############################################################## ############################################################## ############################################################## ############################################################## # Part 1 ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## # Creates a list of first names to be used later when removing # unneccesary information ############################################################## ############################################################## names = [] with open('./initialInformation/fn_boys.csv') as allNames: name_dict = DictReader(allNames) for row in name_dict: names.append(row['FirstForename'].lower()) print(len(names)) print('Done with names') with open('./initialInformation/fn_girls.csv') as allNames: name_dict = DictReader(allNames) for row in name_dict: names.append(row['FirstForename'].lower()) print(len(names)) print('Done with names') ############################################################## ############################################################## # Tokenizes a given script ############################################################## ############################################################## def tokenize(script): listOfTokens = parser(script) ldaT = [] for tk in listOfTokens: if tk.orth_.isspace(): continue elif tk.like_url: ldaT.append('URL') elif tk.orth_.startswith('@'): ldaT.append('SCREEN_NAME') else: ldaT.append(tk.lower_) return ldaT ############################################################## ############################################################## # Lemmatizes a given word ############################################################## ############################################################## import nltk nltk.download('wordnet') from nltk.corpus import wordnet as wn def getLemma(word): lem = wn.morphy(word) if lem is None: return word else: return lem from nltk.stem.wordnet import WordNetLemmatizer def getLemma2(word): return WordNetLemmatizer().lemmatize(word) ############################################################## ############################################################## # Makes a list of stop words to be used for cleaning a given # script ############################################################## ############################################################## nltk.download('stopwords') stopWords = set(nltk.corpus.stopwords.words('english')) ############################################################## ############################################################## ############################################################## ############################################################## # Part 2 ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## # This function sets up the script to be analyzed by the LDA # model ############################################################## ############################################################## from nltk import word_tokenize, pos_tag nltk.download('averaged_perceptron_tagger') def setUp(script): is_noun_adj = lambda pos: pos[:2] == 'NN' or pos[:2] == 'JJ' tokens = tokenize(script) tokens = [tk for tk in tokens if len(tk) > 4] tokens = [tk for tk in tokens if tk not in stopWords] tokens = [tk for tk in tokens if tk not in names and tk != 'fuckin'] tokens = [tk for (tk, pos) in pos_tag(tokens) if is_noun_adj(pos)] tokens = [getLemma2(tk) for tk in tokens] return tokens ############################################################## ############################################################## # Reads the seinfeld scripts and does an initial clean of each # episode then calls setUp to set up the script for analyzing. # We then create a csv file storing each episode and it's # now cleaned script. ############################################################## ############################################################## counter = 0 episodeNumList = [] scriptList = [] scriptInfo = [] csv.field_size_limit(100000000) with open('./initialInformation/seinfeld_scripts.csv', 'r') as read_obj: csv_dict_reader = DictReader(read_obj) for row in csv_dict_reader: stop = False script2 = "" script3 = "" script4 = "" cleanedScript = "" for word in row['text'].split(' '): if "<" not in word: script2 = script2 + ' ' + word for word in script2.split(' '): if '(' in word: stop = True if not stop: script3 = script3 + " " + word if ')' in word: stop = False stop = False for word in script3.split(' '): if len(word) > 0: script4 = script4 + " " + word for word in script4.split(' '): tempWord = "" for letter in word: if letter == "." or letter == "!" or letter == "?": tempWord = tempWord + " " else: tempWord = tempWord + letter cleanedScript = cleanedScript + " " + tempWord counter += 1 episodeNumList.append(counter) scriptList.append(cleanedScript) t = setUp(cleanedScript) scriptInfo.append(t) print('Done with Seinfeld Scripts') df = pd.DataFrame({ 'Episode Number': episodeNumList, 'Script': scriptList}) df.to_csv('results/cleanedSeinfeldScripts.csv', index=False) ############################################################## ############################################################## ############################################################## ############################################################## # Part 3 ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## # Creates a corpus and a dictionary using a self-made # Bag-of-Words. Then we use this to create our LDA Model. ############################################################## ############################################################## comedy = ['hilarious', 'enjoy', 'fun', 'crazy','absurd', 'ironic', 'laugh', 'funny', 'ridiculous'] romance = ['relationship', 'marriage', 'like', 'admire', 'passion', 'love', 'connection', 'communication', 'divorce'] drama = ['intense', 'serious', 'sad', 'conflict', 'life', 'death', 'pain', 'mad', 'cry'] childrens = ['cartoon', 'fantasy', 'adventure', 'corny', 'light', 'educational', 'family', 'school', 'friendship'] family = ['brother', 'sister', 'father', 'mother', 'relationship', 'love', 'friend', 'family'] mystery = ['clue', 'murder', 'detective', 'weapon', 'doubt', 'investigation', 'alibi', 'motive', 'victim'] bagOfWords = [comedy,romance,drama,childrens,family,mystery] AMT_OF_TOPICS = 6 AMT_OF_WORDS = 9 from gensim import corpora dict = corpora.Dictionary( bagOfWords ) corp = [dict.doc2bow(genre) for genre in bagOfWords] import pickle pickle.dump(corp, open('corpus.pkl', 'wb')) dict.save('dictionary.gensim') import gensim ldamodel = gensim.models.ldamodel.LdaModel(corp, num_topics = AMT_OF_TOPICS, id2word = dict, passes = 10) mod = 'model' + str(AMT_OF_TOPICS) + '.gensim' ldamodel.save(mod) ############################################################## ############################################################## # Here we take the Seinfeld scripts and analyze them using the # LDA Model we created, finding the percentage of relevance # between each script and the topics deduced from the corpus. # We then use this information to create an overall topic # model for the entire show. ############################################################## ############################################################## topics = ldamodel.print_topics(num_words = AMT_OF_WORDS) for topic in topics: print(topic) epNum = 0 ### To keep track of the amount of episodes mostRelTopic = 0 ### Middle-man type variable relTopicPerc = 0.0 ### Middle-man type vairable totalPercTopics = [] ### To store the average relevance of each topic in comparison to the entire show percPerEpisode = [] ### To store the average relevance of each topic in comparison to the each episode mostRelTopicList = [] ### To store the most relevant topic for each episode # Range is total number of topics. We initializing both arrays. for i in range(AMT_OF_TOPICS): totalPercTopics.append(0.0) percPerEpisode.append([]) for seinScript in scriptInfo: # Runs the LDA Model on the given episode seinScript_bow = dict.doc2bow(seinScript) listOfRelTopics = ldamodel.get_document_topics(seinScript_bow) epNum += 1 checkbox = 0 # Updates the lists with the information from the given episode # after running it through the LDA Model for i in range(AMT_OF_TOPICS): if len(listOfRelTopics) > checkbox: temp = listOfRelTopics[checkbox] if temp[0] == i: totalPercTopics[i] += temp[1] percPerEpisode[i].append(temp[1]) if temp[1] > relTopicPerc: mostRelTopic = i relTopicPerc = temp[1] checkbox += 1 else: percPerEpisode[i].append(0.002) else: percPerEpisode[i].append(0.002) totalPercTopics[i] += 0.002 mostRelTopicList.append((mostRelTopic + 1)) mostRelTopic = 0 relTopicPerc = 0.0 for i in range(AMT_OF_TOPICS): totalPercTopics[i] /= epNum ############################################################## ############################################################## ############################################################## ############################################################## # Part 4 ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## # Makes a csv file to store the information of each episode # and the overall statistics of the show. ############################################################## ############################################################## print('The average topic relation: ') print(totalPercTopics) df = pd.DataFrame({ 'Episode Number': episodeNumList, 'Main Topic': mostRelTopicList }) topicNum = 0 for top in percPerEpisode: columnName = 'Topic ' + str(topicNum + 1) + ' Relevance' df[columnName] = top topicNum += 1 df.to_csv('results/SeinfeldTopicModel.csv', index=False) df2 = pd.DataFrame({ 'Topics': topics, 'Average Relevance': totalPercTopics}) df2.to_csv('results/SeinfeldTopicAverage.csv', index=False)<file_sep>/README.md # Nothing We use an LDA topic model approach to analyze the show _Seinfeld_ and whether or not it is a "show about nothing." ## Contributors - [<NAME>](https://github.com/gasperjw1) - [<NAME>]() - [<NAME>]() ## Build To run the program, run the Python program `Topic_Model_Seinfeld.py`. The program has already been ran, but can be ran again for testing purposes. If ran, all the other files will be overwritten with updated information due to running the program. ## Notes Packages required to successfully run this program are: - spacy - nltk - gensim - pickle All the necessary information to run the program is located in the folder named `initialInformation`. All the csv files created as a result of running the program will be located in the folder named `results`. Both these folders currently contain files due to the program being ran already. In terms of reading the results, if any given set of words (that defines a certain topic) does not encompass at least 50% of the entire show, then we deem that topic (generated from our corpus) as not a definition of the show. <file_sep>/TXT2CSV.py import os import csv #'path_of_directory' dirpath = './initialInformation/Comedy' output = './initialInformation/comedyScripts.csv' with open(output, 'w') as outfile: csvout = csv.writer(outfile) csvout.writerow(['Name', 'Content']) files = os.listdir(dirpath) for filename in files: with open(dirpath + '/' + filename) as afile: endOfTitle = filename.find('_') csvout.writerow([filename[0:endOfTitle], afile.read()]) afile.close() outfile.close() # #'path_of_directory' # dirpath = './initialInformation' # output = './initialInformation/namesFL.csv' # with open(output, 'w') as outfile: # csvout = csv.writer(outfile) # csvout.writerow(['Name']) # files = os.listdir(dirpath) # for filename in files: # with open(dirpath + '/' + filename) as afile: # for line in (afile.read()).split('\n'): # if len(line) > 1 and not line.isspace() and len(line) <= 10: # csvout.writerow([line]) # afile.close() # outfile.close()
51aadaeb802ee5604399372d086b00a53b1f142a
[ "Markdown", "Python" ]
3
Python
gasperjw1/Nothing
d978575635c37f2efda797fc142db178a3fe127f
ab22787719c87c1f36ad4b04d66f10fa7dd36fad
refs/heads/master
<file_sep>import random def dungeon_root(): return ["obstacle", "treasure"] dungeon = dungeon_root() branches = [] def generate_obstacle(): return random.choice([ ["key", "obstacle", "lock", "obstacle"], ["monster", "obstacle"], ["room"], ["branch", "lock"], ]) # TODO: probably limit the depth of these (or not, for arbitrary complexity) def generate_branch(): return random.choice([ #cycle ["root", "obstacle", "key", "obstacle", "root"], #branch ["root", "obstacle", "key"], ]) def recurse_dungeon(dungeon): while "obstacle" in dungeon: dungeon = process_dungeon(dungeon) return dungeon def fill_branches(dungeon, branches=[], depth=0): for i, node in enumerate(dungeon): if node != "branch": continue elif depth > 2: # hard fix dungeon[i] = "key" continue num = len(branches) dungeon[i] = "branch-{}".format(num) new_branch = recurse_dungeon(generate_branch()) branches.append([]) # placeholder for injection (inner_dungeon, branches) = fill_branches(new_branch, branches, depth=depth+1) branches[num] = inner_dungeon return (dungeon, branches) def process_dungeon(dungeon): new_dungeon = [] for i, node in enumerate(dungeon): if node == "obstacle": generated_obstacle = generate_obstacle() for element in generated_obstacle: new_dungeon += [element] else: new_dungeon += [dungeon[i]] return new_dungeon dungeon = recurse_dungeon(dungeon) (dungeon, branches) = fill_branches(dungeon) print "--------" print "Dungeon:" print dungeon print "--------" if len(branches): print "--------" print "Branches:" for i, branch in enumerate(branches): print "{}:".format(i), branch print "--------" #for i in range(1000): # results[random.randint(1,5)-1] += 1 #print results <file_sep>from Tkinter import * master = Tk() canvas_width = 1200 canvas_height = 900 w = Canvas(master, width=canvas_width, height=canvas_height) w.pack() # Draw Isometric grid # Draw NW-SE lines for i in range(20): w.create_line(0, i*50, canvas_width, i*50 + 100, fill="grey") y = int(canvas_height / 2) w.create_line(0, y, canvas_width, y, fill="#476042") mainloop()
0d5f61b54024064aa5407d3993e3ffde5ec95efb
[ "Python" ]
2
Python
FelixMcFelix/PGMaps
ef829ac065929539df59e3d57e2810c24125699e
9190514cb0158b978cec7105a40f2a1ed272077b
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from "@angular/router"; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor(private router: Router) { } ngOnInit() { } onLoadServers() { this.router.navigate(['servers']); // We can also add { relativeTo... } if we wish to upload relative // links inside this route // // this.router.navigate(['servers'], { relativeTo : this.route}); // } } <file_sep>import { Component } from '@angular/core'; // Add the service imprt import { LoggingService } from '../logging.service'; import { AccountsService } from '../accounts.service'; @Component({ selector: 'app-new-account', templateUrl: './new-account.component.html', styleUrls: ['./new-account.component.css'], // Add the required service as provider attribute of the Componenet providers: [LoggingService] }) export class NewAccountComponent { // Add the Constructor with the Service injection // Make sure to specify the required type // Since we dont add the AccountsService to the provider list it will be inherited from the // top component and will be injected here. This way we can share the service and have a // single instance for the entire application constructor( private logger: LoggingService, private accountsService: AccountsService) { } onCreateAccount(accountName: string, accountStatus: string) { // Use the accounts service to add account this.accountsService.addAcount(accountName, accountStatus); // Use the Service to log messages this.logger.logStatusChange('New status: ' + accountStatus); } } <file_sep> /** * Service is just a simple js class. * Our service will simply log our messages to the console * * - No decorator is required. * - The service will be injected into the componenets and or directives */ export class LoggingService { // class method logStatusChange(message: string) { console.log(`[Service] - ${message}`); } } <file_sep>import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; // This code below is the main code which is being executed if (environment.production) { enableProdMode(); } // DONT be confused with the bootstrap css framework // The app module is imported above in following the import chain. // // The 'AppModule' is loading the 'AppComponent' // which contains the 'app-root' selector as explaind in the module file. platformBrowserDynamic() .bootstrapModule(AppModule) .catch(err => console.log(err)); <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from "@angular/router"; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'] }) export class UserComponent implements OnInit { user: { id: number, name: string }; // Add the current router to the CTOR constructor(private route: ActivatedRoute) { } ngOnInit() { // Get the data from the router. // Fetch the data from the route this.user = { id: this.route.snapshot.params['user_id'], name: this.route.snapshot.params['user_name'], } } } <file_sep><!-- header start --> <a href="https://stackoverflow.com/users/1755598/codewizard"><img src="https://stackoverflow.com/users/flair/1755598.png" width="208" height="58" alt="profile for CodeWizard at Stack Overflow, Q&amp;A for professional and enthusiast programmers" title="profile for CodeWizard at Stack Overflow, Q&amp;A for professional and enthusiast programmers"></a>&emsp;![Visitor Badge](https://visitor-badge.laobi.icu/badge?page_id=nirgeier)&emsp;[![Linkedin Badge](https://img.shields.io/badge/-nirgeier-blue?style=flat&logo=Linkedin&logoColor=white&link=https://www.linkedin.com/in/nirgeier/)](https://www.linkedin.com/in/nirgeier/)&emsp;[![Gmail Badge](https://img.shields.io/badge/-<EMAIL>-fcc624?style=flat&logo=Gmail&logoColor=red&link=mailto:<EMAIL>)](mailto:<EMAIL>)&emsp;[![Outlook Badge](https://img.shields.io/badge/-<EMAIL>-fcc624?style=flat&logo=microsoftoutlook&logoColor=blue&link=mailto:<EMAIL>)](mailto:<EMAIL>) ## <!-- header end --> # Angular Tutorial This repository will walk step by step to teach you the basics of angular. Each step is committed in its own commit so you can perform diff/pull request To see what was changed between each steps. ### Kickstart The following code was executed to create this angular project - Install all the requirements `npm install -g @angular/cli` - Create the project skelton `ng new angularTutorial` `cd angularTutorial` - Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/` The app will automatically reload if you change any of the source files. ### Step 01 - Basics Lets navigate through the different project files to get idea what is going on - Make sure `ng serve` is running and open the browser on `http://localhost:4200/` - Change the application title inside the `app.component.ts` - Change the `app/component.html` to display the title ### Step 02 - Create manual components We are going to create new component - Create new folder named `server` under the `app` folder. - Inside the folder create the following new files - `server.component.css` - `server.component.html` - `server.component.ts` - Define the component in the `server.component.ts` View the code to see whats is required. - Register the component inside `app.module.ts` ### Step 03 - Create components using the CLI Instead of creating manual components we will create one using the CLI commands. - In your terminal type `ng generate component servers` or short way: `ng g c servers` - Update the html code to the `servers.component.html` ### Step 04 - Adding bootstrap CSS - install bootstrap `npm i bootstrap` - Add the bootstrap css path to the `.angular-cli.json` - Add html code to verify that the css is loaded ### Step 05 - Data Binding Data binding allow us to add dynamic content to the application. There are several forms of Binding. Lets start with the simple one - Edit the `ServerComponent` inside the `server.component.ts` and add the variables and the method as appear in the source code - Edit the template `server.component.html` and add the binding code to display the content ### Step 06 - Property Binding At this step we update property using timer and the changes will be reflated in the code. We will add and update button state. - Edit `servers.component.ts` and add the required code - The syntax for property binding is `[<html properly>]=<angular property>` - To bind attribute like dataset use the `[attr.<attribute name>]` => `[attr.data-allow]="allowNewServer"` ### Step 07 - Event Binding - The syntax for adding an event binding is using `(<event name>)="<event handler>"` - Edit `servers.component.ts` and add the required variables and methods - Update the component html and add the required code. In this step we demonstrated the previous bindings as well. ### Step 08 - 2 way binding In the previous step we have demonstrated 2 way binding. Lets dive into it now. - 2Way binding allow us to display literal values of the property for example - The syntax is combination of `[] && ()` => `[(ngModel)]` - Add the import `FormsModule` inside the `app.module.ts` (import declaration & inside the imports array). **!NOte: `FormsModule` should be in `imports` not in `declarations`** - Declare the `ngModel` inside our `servers.component.html` ### Step 09 - Directives - Directives are html extensions (DOM) which are being created from templates (usually not always). - Directives are usually attributes - The syntax is `*` for example : `*ngIf=...` #### ngIf (Structural directive) - `ngIf` is used to conditionals display content. - The simple way is to use it as attribute - We can also us it with `local reference` for `if else` syntax #### ngStyle / ngClass - `ngStyle` is used to conditionally add style to an element. - `ngClass` is used to conditionally add css class to an element. - Add the required css code - Replace the `[attr.data-allow]="allowNewServer"` with ngClass code from the source ### Step 10 - Multiple components Create multiple components and add communication between them - For this step we will need to get familiar with `ngFor` Directive, so read about it before starting this step. - You can simply checkout this step and copy the content. This steps will be used as placeholder for the content. If you wish to do it your self follow the steps below. - Create the first component without testing specs `ng g c cockpit --spec false` - Create the second component without testing specs `ng g c server-element --spec false` - Copy the initial html code from the `cockpit.component.html` to your component - Copy the content of the `server-element.component.html` into your component - Copy the content of the `app.component.ts` - Copy the content of the `app.component.html` #### At this point the project should be broken and you will see the following message `Property 'serverElements' does not exist on type 'CockpitComponent'.` - To fix it for now we will comment out the code so we can continue. ### Step 11 - Binding custom properties - Add the required code inside the `server-element.component.ts`. This code define our custom element - Inside the `app.component.ts` define the `serverElements`, again copy it from the initial code. - Add the `[element]` property to the `app.component.html`. At this point we should see error (_in the browser console_) since the property can be accessed only from within `server-element` component and we are adding it to the app component - In order to "expose" it to parent component we need to add `decorator` **`@Input()`** to the element. Don't forget to add the required import as well ### Step 12 - Binding custom events - In this step we want to notify the parent component that inner component was updated - Update the `app.component.ts` with the event handlers code - Update the `app.component.html` to support the new event we created - Add the 2 custom event data in `cockpit.component.ts`. Make sure to expose them with `EventEmitter` & `@Output()` Don't forget to add the required import as well - Inside `cockpit.component.ts` fire (emit) the events # Directives --- ### 13 - Attribute directives - First lets start with attribute directives - Create a new folder `src/app/directives/highlight` - Create the directive file `src/app/directives/highlight/highlight.directive.ts` ```js import { Directive, ElementRef, OnInit } from '@angular/core'; @Directive({ selector: '[appBasicHighlight]' }) export class BasicHighlightDirective implements OnInit { constructor(private elementRef: ElementRef) { } ngOnInit() { this.elementRef.nativeElement.style.backgroundColor = 'green'; } } ``` - Register the directive in the app module - Add the attribute directive to the app template ```html <div class="container"> ... <p appHighlight>This is our appHighlight directive</p> ... </div> ``` ### step14 - Directive Render - Lets create a new directive and this time with the CLI command ``` $ ng g d directives/text-highlight --spec false # We should now see the following output create src/app/directives/text-highlight.directive.ts update src/app/app.module.ts ``` - Add the required code to the `directives/text-highlight.directive.ts` - Add the directive to the template and verify that its working ### step15 - Directive Events - In this step we will interact with the directive - In order to do it we need to add `HostListener` - which will be used for our mouse events - Add the `HostListener` to the directive from previous step ```js @HostListener( <event_name>) <function_name> (<Event data>) ``` ### step16 - Directive Properies (HostBinding) - In this step we will be changing one of the nodes property like style, class etc. - First of all add `HostBinding` to the directive - Add the property we wish to bind to ```js # In our case we wish to bind the style.backgroundColor property @HostBinding('style.backgroundColor') bgColor: string; ``` - Update the code in the `HostListener` ```js @HostListener('mouseleave') mouseleave(event: Event) { this.bgColor = 'transparent'; this.color = 'black'; } ``` ### step17 - Directive Properties (readProperty) - Instead of having the colors hard code we wish to read them from the element - First add the `Input` decorator ```js // Add the input fields @Input() defaultBgColor: string; @Input() hoverBgColor: string; // Initialize values ``` - Add the required attribute colors in `ngOninit` ```js ngOnInit() { // Set the defaults ... this.bgColor = this.defaultBgColor; this.color = this.defaultColor; ... ``` ### step18 - Structural Directives - In the previous steps we used attribute directives, now we will add structural directives - Lets create a new directive using the CLI which wil be opposite to the ng-if ``` ng g d unless --spec false ``` - We need to get the condition as input from the element so we need to add the `@Input` - Since we also need to listen to changes we will add the `set` keyword to the `@Input` **The name of the property must be the same as the directive name** ```js @Input() set appUnless(condition: boolean) {} ``` - Add the contractor properties (template & view) ```js constructor( private templateRef: TemplateRef<any>, private vcRef: ViewContainerRef ) { } ``` - Now update the unless `@Input()` logic ```js @Input() set appUnless(condition: boolean) { if (!condition) { this.vcRef.createEmbeddedView(this.templateRef); } else { this.vcRef.clear(); } } ``` - Add the required code to the `app.component.html` ```html <div *appUnless="true">This is the content when *appUnless="true"</div> <div *appUnless="false">This is the content when *appUnless="false"</div> ``` - Practice: - Add property to the app component to control if the unless is visible or not # Routing --- ### step 19 - Routing - Extract the attached zip to new folder - This will be our sample application for this part - We have multiple components loaded in the app component. - We have navigation menu in the app which will be used to upload and display different part of the app ```html <ul class="nav nav-tabs"> <li role="presentation" class="active"><a href="#">Home</a></li> <li role="presentation"><a href="#">Servers</a></li> <li role="presentation"><a href="#">Users</a></li> </ul> ``` - Add the routes to the app module. The routs is a specific structure. `{ path : ... }` ```js import { Routes } from '@angular/router'; ... const appRoutes: Routes = [ { path: '<path to this route >', component: <Component for this route> } ]; // In our sample application it will look like: const appRoutes: Routes = [ { path: '', component: HomeComponent }, { path: 'users', component: UsersComponent }, { path: 'servers', component: ServersComponent } ]; ... ``` - Register the routes. Registering routes is done via the `RouteModules` - Add new import - Use the `forRoot` which add the routes to the angular application ```js import { Routes, RouterModule } from '@angular/router'; ... imports: [ ... RouterModule.forRoot(appRoutes) ... ], ``` ### step 20 - router-outlet - In this step we will set up the routing to display the content - Edit the `./src/app/app.component.html` and replace the components with the `<router-outlet></router-outlet>` directive. - This tells angular where to display the content of the route ```html <div class="row"> <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2"> <router-outlet></router-outlet> </div> </div> ``` - Open the browser and add the check to see if the routes are working as expected - http://localhost:4200/users - http://localhost:4200/servers - Adding navigation - Use the nav links - Remove the `href="#"` from the nav items - Add the `router-link` directive with the appropriate link (The link is on the `<a>`) - Set the `routerLinkActive / routerLinkActiveOptions"` the current tab to mark it as active (`<li>`) ```html <li ... routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }"> <a routerLink="/">Home</a> </li> ``` ### step 21 - Routing from TypeScript - Add some button to `./src/app/home/home.component.html` ```html <button class="btn btn-primary" (click)="onLoadServers()">Load Servers</button> ``` - Add the following: - import - constructor declaration - required code (click handler = `onLoadServers` ) in the `./src/app/home/home.component.ts` ```js export class HomeComponent implements OnInit { // Add the required router variable constructor(private router: Router) { } // The click handler onLoadServers() { this.router.navigate(['servers']); } } ``` #### Routing with parameters - Add parameter to the url in the `./src/app/app.module.ts` using the `<route>:<param>` - This will cause the `/users` to return error ```js const appRoutes: Routes = [ ... { path: 'users/:user_id', component: UsersComponent }, ... ]; ``` - Add the required imports and code and `ActiveRoute` to the `./src/app/users/user/user.component.ts` - Read the parameters from the router using the `this.route.snapshot.params['<param>']` ```js export class UserComponent implements OnInit { user: { id: number, name: string }; constructor(private route: ActivatedRoute) { } ngOnInit() { this.user = { id: this.route.snapshot.params['user_id'], name: this.route.snapshot.params['user_name'], } } } ``` - Update the template `./src/app/users/user/user.component.html` to display the route values ```js <p>User with ID <b>{{ user.id }}</b> loaded.</p> <p>User name is <b>{{ user.name }}</b> </p> ``` - Add new link which will pass parameters to the desired router - Edit the `./src/app/users/user/user.component.html` - Add the following syntax - (Directive) -> `[routerLink]="[ <params> ]"` ```html <a [routerLink]="['/users','1','Moshe !!!!']">Load user</a> ``` # Services & Injections --- - Services are usually a shared classes (code) which is used across the whole application. - For example, service can be used for translation, Date formatting or any other utils or filtering. - Good tutorial can be found here: <a href="https://code.tutsplus.com/tutorials/beginners-guide-to-angular-4-services--cms-29675"> beginners-guide-to-angular-4-services</a> - Services are used with <a href="https://angular.io/guide/dependency-injection">Angular Dependency Injection</a> ### step 22 - Services - Checkout the <a href="services-start.zip">attached zip<a/> and extract it to a new folder - Initialize and execute the application ```sh cd <app folder> npm i ng serve ``` - Run the application - View the code and try to figure out what the app does - How data is passed between the different components - Check the `console` for the output #### Services - Lets write our first service - Our service will be a simple logger which will replace the `console.log` across the application - Create a new class `services-start/src/app/logging.service.ts` - Service is a just a regular JS class ```js /** * Service is just a simple js class. * Our service will simply log our messages to the console * * - No decorator is required. * - The service will be injected into the components and or directives */ export class LoggingService { // class method logStatusChange(status: string) { console.log(`[Service] - New status: ${status}`); } } ``` - Inject the service to the required modules - The injection is done by adding the service we need into the constructor - Add the required import (the `LoggingService`) - Add the service provider. Provider tells Angular which service we will need - In the constructor we **must** declare the specific type ```js // services-start/src/app/new-account/new-account.component ... import { LoggingService } from '../logging.service'; ... @Component({ ... // Add the required service as provider attribute of the Component providers: [LoggingService] }) ... export class NewAccountComponent { ... // Add the Constructor with the Service injection // Make sure to specify the required type constructor( private logger: LoggingService){} ... } ``` - Search for all `console.log` in other components and convert them to the `LoggingService` - Tip: In Visual studio code you can simply add the provider list and the import will be added automatically ```js ... export class NewAccountComponent { ... onCreateAccount(accountName: string, accountStatus: string) { ... // Use the Service to log messages this.logger.logStatusChange('New status: ' + accountStatus); } } ``` - Verify that the code is working and that the `console.log` is printed out from the service. ### step 23 - Data Services - Data services are used to store data - Lets create service for storing the AccountData - Create new service file `services-start/src/app/accounts.service.ts` - Move the code from the `AppComponent` to the new service file ```js /** * This service will store our accounts data */ export class AccountsService { // Remove the code from the app components and paste it here accounts = [ { name: "Master Account", status: "active" }, { name: "Test Account", status: "inactive" }, { name: "Hidden Account", status: "unknown" }, ]; addAccount(name: string, status: string) { this.accounts.push({ name: name, status: status }); } updateStatus(id: number, newStatus: string) { this.accounts[id].status = newStatus; } } ``` - Since we have an accounts in the `services-start/src/app/app.component.html` we need to read them from the service ```html <app-account *ngFor="let acc of accounts; let i = index" [account]="acc" [id]="i" (statusChanged)="onStatusChanged($event)" ></app-account> ``` - Add the service to the `services-start/src/app/app.component.ts` - Import - Provider - Constructor - Initialization should be done inside the `OnInit` ```js // app.component.ts import { AccountsService } from './accounts.service'; ... @Component({ ... providers: [AccountsService] }) export class AppComponent implements OnInit { // Add the accounts array. The content will be loaded from the service accounts: { name: string, status: string }[] = []; // Inject the service constructor(private accountsService: AccountsService) { } // initialize the accounts data ngOnInit() { // Get the accounts from the service this.accounts = this.accountsService.accounts; } } ``` - Update the `NewAccountComponent` - Remove the `EventEmitter` since its now part of the service - Add imports & update the code ```js // Add the service imprt import { LoggingService } from '../logging.service'; import { AccountsService } from '../accounts.service'; export class NewAccountComponent { constructor( private logger: LoggingService, private accountsService: AccountsService) { } onCreateAccount(accountName: string, accountStatus: string) { this.accountsService.addAccount(accountName, accountStatus); this.logger.logStatusChange('New status: ' + accountStatus); } } ``` - Update the `AccountComponent` as well and remove the unused code ```js import { LoggingService } from '../logging.service'; import { AccountsService } from '../accounts.service'; export class AccountComponent { @Input() account: { name: string, status: string }; @Input() id: number; // Add the Constructor with the Service injection // Make sure to specify the required type constructor( private logger: LoggingService, private accountsService: AccountsService ) { } onSetTo(status: string) { this.accountsService.updateStatus(this.id, status); this.logger.logStatusChange('New status: ' + status); } } ```
83218c609aae13ae987f399e12972cf27faa6754
[ "Markdown", "TypeScript" ]
6
TypeScript
nirgeier/AngularTutorial
f3576a0abae921921baf88b59896be42da8c0f98
0d4a9c68f28eb4ac83b95664e19ff253d6c571d9
refs/heads/master
<file_sep>package com.example.akash.orientationproject; import android.media.Image; import android.widget.ImageView; import java.io.Serializable; /** * Created by Akash on 11/30/2017. */ public class SuperHero implements Serializable { String name; String alias; String power; String weak; String bio; int pic; public SuperHero(String name, String alias, String power, String weak, int pic, String bio){ this.name = name; this.alias = alias; this.power = power; this.weak = weak; this.bio=bio; this.pic = pic; } public String getName(){ return name; } public String getAlias(){ return alias; } public String getPower(){ return power; } public String getWeak() { return weak; } public String getBio() { return bio; } public Integer getPic() { return pic; } }
9a305a7a4f703c2754087de39c98099a2ea65d0b
[ "Java" ]
1
Java
akashpathuri/SuperheroCentral
893e4aa69653dee2fc04540e4b35310e9e7ac55a
cb63315c2ef8201631341897cd3153072c3614ab
refs/heads/master
<repo_name>betterchalk-tunde/form<file_sep>/public/app.js "use strict"; const userDetails = []; const form = document.querySelector('.needs-validation'); const firstName = document.querySelector('#firstName'); const lastName = document.querySelector('#lastName'); const email = document.querySelector('#email'); const username = document.querySelector('#username'); const address = document.querySelector('#address'); const address2 = document.querySelector('#address'); form.addEventListener('submit', (e) => { e.preventDefault(); const top = document.querySelector('.top'); const alert_container = document.createElement('div'); alert_container.classList.add("py-3", "border", "rounded", "my-3"); let text_node; let message = ''; let alert_type = ''; if (firstName.value === '' || lastName.value === '' || email.value === '' || username.value === '' || address.value === '') { alert_type = "alert-danger"; message = 'Please fill all fields'; } else { const user = { firstName: firstName.value, lastName: lastName.value, email: email.value, username: username.value, address: address.value }; userDetails.push(user); alert_type = "alert-success"; message = `Congratulations ${user.firstName}, your order has been created`; } alert_container.classList.add(alert_type); text_node = document.createTextNode(message); alert_container.appendChild(text_node); top.appendChild(alert_container); function hide_element() { alert_container.style.display = 'none'; } setTimeout(hide_element, 2000); }); <file_sep>/README.md #This is an app to create a user and validate the user input and display a message whether the validation is successful or not using TypeScript .The index.html file is outside the src folder cause I wanted to use a package called lite-server which automatically refreshes the page after saving a file .Use npm install to install all dependencies and npm start to start the lite server<file_sep>/src/app.ts interface User { firstName: string; lastName: string; email: string; username: string; address: string; } const userDetails: User[] = [] const form = document.querySelector('.needs-validation') as HTMLFormElement const firstName = document.querySelector('#firstName') as HTMLInputElement const lastName = document.querySelector('#lastName') as HTMLInputElement const email = document.querySelector('#email') as HTMLInputElement const username = document.querySelector('#username') as HTMLInputElement const address = document.querySelector('#address') as HTMLInputElement const address2 = document.querySelector('#address') as HTMLInputElement form.addEventListener('submit', (e: Event) => { e.preventDefault() const top = document.querySelector('.top')! const alert_container = document.createElement('div') alert_container.classList.add("py-3", "border", "rounded", "my-3") let text_node: Text let message: string = '' let alert_type: string = '' if (firstName.value === '' || lastName.value === '' || email.value === '' || username.value === '' || address.value === '') { alert_type = "alert-danger" message = 'Please fill all fields' } else { const user: User = { firstName: firstName.value, lastName: lastName.value, email: email.value, username: username.value, address: address.value } userDetails.push(user) alert_type = "alert-success" message = `Congratulations ${user.firstName}, your order has been created` } alert_container.classList.add(alert_type) text_node = document.createTextNode(message) alert_container.appendChild(text_node) top.appendChild(alert_container) function hide_element() { alert_container.style.display = 'none' } setTimeout(hide_element, 2000) })
317963b9d1ff8a569d114f433fda75bcad7a29fa
[ "JavaScript", "TypeScript", "Markdown" ]
3
JavaScript
betterchalk-tunde/form
6cad5e8ad6682042f1e90ad39428ce0369fc7c51
d98fdfd6cf2a7ce54ec63d1d7d48da88a304b865
refs/heads/master
<file_sep>import React from 'react'; import ErrorBoundary from 'components/ErrorBoundary'; const Dashboard = () => { return ( <ErrorBoundary> <h2>Dashboard</h2> </ErrorBoundary> ); }; export default Dashboard; <file_sep>import React, { memo } from 'react'; import { Nav } from 'react-bootstrap'; import { Sidebar as Wrapper, Link } from 'components/Sidebar/style'; import { AppRoutes, DashboardRoutes } from 'routes'; const Sidebar = memo(() => { return ( <Wrapper> <Nav> <Link to={DashboardRoutes.MAIN.path}>Dashboard</Link> <Link to={DashboardRoutes.PROFILE.path}>Profile</Link> <Link to={DashboardRoutes.CHANGE_PASSWORD.path}>Change Password</Link> <Link to={AppRoutes.LOGOUT.path}>Logout</Link> </Nav> </Wrapper> ); }); export default Sidebar; <file_sep>import { AUTH_USER, SIGNOUT } from 'pages/Auth/ducks/action-types'; import { setUserToken } from 'utils/user'; import { authenticateUser, registerUser, updateProfile } from 'api'; export function setAuthUser(payload) { return { type: AUTH_USER, payload }; } export function deleteUserInfo() { return { type: SIGNOUT }; } export const authenticateUserAction = (email, password) => (dispatch) => { return authenticateUser(email, password) .then((resp) => { if (resp) { dispatch(setAuthUser(resp)); setUserToken(resp); return true; } return Promise.reject(resp); }) .catch((e) => { return Promise.reject(e); }); }; export const registerUserAction = (email, password, firstName, lastName) => ( dispatch ) => { return registerUser(email, password, firstName, lastName) .then((resp) => { if (resp) { dispatch(setAuthUser(resp)); setUserToken(resp); return true; } return Promise.reject(resp); }) .catch((e) => { return Promise.reject(e); }); }; export const updateProfileAction = (email, password, firstName, lastName) => ( dispatch ) => { return updateProfile(email, password, firstName, lastName) .then((resp) => { if (resp) { setUserToken(resp); return true; } return Promise.reject(resp); }) .catch((e) => { return Promise.reject(e); }); }; <file_sep>import concat from 'lodash/concat'; import { RESET_TERMS, SET_EMAIL_FILTERS, RESET_FILTERS, LOADING_EMAILS, SET_EMAILS, SET_TERMS, SET_EMAIL_DETAIL, RESET_EMAILS, RESET_EMAIL_DETAIL, } from 'pages/Emails/actions/action-types'; import { showLoading } from 'pages/App/actions'; import API from 'api'; export function setTerms(payload) { return { type: SET_TERMS, payload }; } export function resetTerms() { return { type: RESET_TERMS }; } export function setFilters(payload) { return { type: SET_EMAIL_FILTERS, payload }; } export function resetFilters() { return { type: RESET_FILTERS }; } export function loadingEmails(payload) { return { type: LOADING_EMAILS, payload }; } export function setEmails(payload) { return { type: SET_EMAILS, payload }; } export function resetEmails() { return { type: RESET_EMAILS }; } export function setEmailById(payload) { return { type: SET_EMAIL_DETAIL, payload }; } export function resetEmailDetail() { return { type: RESET_EMAIL_DETAIL }; } export const setFiltersAction = (term, startDate, endDate) => (dispatch) => { dispatch(setFilters({ term, startDate, endDate })); }; export const resetFiltersAction = () => (dispatch) => { dispatch(resetFilters()); }; export const resetEmailsData = () => (dispatch) => { dispatch(resetEmails()); dispatch(resetEmailDetail()); }; export const fetchTerms = (pos = []) => (dispatch) => { const postAction = (payload) => { dispatch(setTerms(payload)); }; return API.getTerms(postAction, pos); }; export const fetchEmailById = (emailId) => (dispatch) => { dispatch(showLoading(true)); dispatch(resetEmailDetail()); const postAction = (payload) => { dispatch(showLoading(false)); dispatch(setEmailById(payload)); }; return API.getEmailById(postAction, emailId); }; export const fetchEmails = (startDate = '', endDate = '', termId = '') => ( dispatch, getState ) => { const { nextPageUrl, emails, isLoading } = getState().analytics; if (((!nextPageUrl && emails.length === 0) || nextPageUrl) && !isLoading) { dispatch(loadingEmails(true)); const postAction = (payload) => { if (emails.length > 0) { payload.results = concat(emails, payload.results); } dispatch(setEmails(payload)); dispatch(loadingEmails(false)); }; return API.getEmails(postAction, nextPageUrl, startDate, endDate, termId); } }; export const resetTermsData = () => (dispatch) => { dispatch(resetTerms()); }; <file_sep>export { default as FilledButton } from 'elements/Button/FilledButton'; export { default as BorderedButton } from 'elements/Button/BorderedButton'; <file_sep>import { SET_PROFILE } from 'pages/Profile/ducks/action-types'; export function setProfile(payload) { return { type: SET_PROFILE, payload }; } <file_sep>import React from 'react'; import { Container, Row, Col } from 'react-bootstrap'; import Header from 'components/Header'; import Sidebar from 'components/Sidebar'; const Dashboard = (Content) => { return (props) => { return ( <> <Header /> <Container fluid> <Row> <Col sm='2' className='pl-0'> <Sidebar /> </Col> <Col sm='10'> <Content {...props} /> </Col> </Row> </Container> </> ); }; }; export default Dashboard; <file_sep>import React, { useEffect } from 'react'; import { AppRoutes } from 'routes'; import { deleteUserToken } from 'utils/user'; const Logout = () => { useEffect(() => { deleteUserToken(); window.location.replace(AppRoutes.LOGIN.path); }, []); return <></>; }; export default Logout; <file_sep>import axios from 'axios'; import getRoute from 'api/routes'; import { AppRoutes } from 'routes'; export const setAuthToken = (token) => { axios.defaults.headers.common['Authorization'] = `Bearer ${token}`; }; const failedResponse = (error) => { if ( error.response && error.response.status && error.response.status === 401 ) { window.location.replace(AppRoutes.LOGOUT.path); } return Promise.reject(error); }; const getRequest = (route) => { if (!route) { return; } return axios .get(route) .then((response) => { return response.data; }) .catch((error) => { return failedResponse(error); }); }; export const postRequest = (route, data = {}) => { return axios .post(route, data) .then((response) => { return response; }) .catch((error) => { return failedResponse(error); }); }; export const putRequest = (route, data = {}) => { return axios .put(route, data) .then((response) => { return response; }) .catch((error) => { return failedResponse(error); }); }; export const registerUser = (email, password, firstName, lastName) => { const data = { email, password, firstName, lastName }; const route = getRoute('registerUser'); return postRequest(route, data); }; export const authenticateUser = (email, password) => { const data = { email, password }; const route = getRoute('login'); return postRequest(route, data); }; export const getUserInfo = (userId) => { const route = getRoute('userProfile', { userId }); return getRequest(route); }; export const updateProfile = (userId, email, password, firstName, lastName) => { const data = { email, password, firstName, lastName }; const route = getRoute('userProfile', { userId }); return putRequest(route, data); }; <file_sep>import { combineReducers } from 'redux'; import { SIGNOUT } from 'pages/Auth/ducks/action-types'; import app from 'pages/App/reducer'; import auth from 'pages/Auth/ducks/reducer'; const combinedReducer = combineReducers({ app, auth, }); const rootReducer = (state, action) => { if (action.type === SIGNOUT) { state = undefined; } return combinedReducer(state, action); }; export default rootReducer; <file_sep>import React, { useState } from 'react'; import { connect } from 'react-redux'; import { Formik, Form } from 'formik'; import * as Yup from 'yup'; import { Card, Alert } from 'react-bootstrap'; import { APP_NAME } from 'config'; import { registerUserAction } from 'pages/Auth/ducks/actions'; import { AppRoutes } from 'routes'; import TextField from 'elements/Form/TextField'; import { FilledButton, BorderedButton } from 'elements/Button'; const initStates = { email: '', password: '', confirmPassword: '', firstName: '', lastName: '', }; const validation = Yup.object({ firstName: Yup.string().min(3).required('First Name should not be empty.'), lastName: Yup.string().min(3).required('Last Name should not be empty.'), email: Yup.string().email().required('Emails should not be empty.'), password: Yup.string().required('Password should not be empty.'), confirmPassword: Yup.string() .oneOf([Yup.ref('password'), null], 'Passwords must match') .required('Confirm Password should not be empty.'), }); const Signup = ({ registerUser, history }) => { const [errorMsg, handleErrorMsg] = useState(''); const [isSubmitting, handleSubmission] = useState(false); const handleSubmit = (values, { setErrors }) => { handleSubmission(true); const { firstName, lastName, email, password } = values; registerUser(email, password, firstName, lastName) .then((resp) => { if (resp) { history.push(AppRoutes.DASHBOARD.path); } handleSubmission(false); }) .catch((error) => { handleSubmission(false); history.push(AppRoutes.DASHBOARD.path); if (error && error.message) { handleErrorMsg(error.message); } const { firstName, lastName, email, password } = error; setErrors({ firstName, lastName, email, password }); }); }; return ( <Card className='px-2 py-4'> <Card.Title className='text-center'>{APP_NAME}</Card.Title> <Card.Body> {errorMsg && <Alert variant='danger'>{errorMsg}</Alert>} <Formik initialValues={initStates} validationSchema={validation} onSubmit={handleSubmit} > <Form> <TextField label='<NAME>' name='firstName' type='text' placeholder='<NAME>' /> <TextField label='<NAME>' name='lastName' type='text' placeholder='<NAME>' /> <TextField label='Email' name='email' type='text' placeholder='Email' /> <TextField label='Password' name='password' type='password' placeholder='<PASSWORD>' /> <TextField label='Confirm Password' name='confirmPassword' type='<PASSWORD>' placeholder='<PASSWORD> Password' /> <FilledButton type='submit' disabled={isSubmitting ? true : false} className='mr-2' > Submit </FilledButton> <BorderedButton type='reset' className='float-right'> Reset </BorderedButton> </Form> </Formik> </Card.Body> </Card> ); }; const mapDispatchToProps = (dispatch) => { return { registerUser: (email, password, firstName, lastName) => dispatch(registerUserAction(email, password, firstName, lastName)), }; }; export default connect(null, mapDispatchToProps)(Signup); <file_sep>import map from 'lodash/map'; import size from 'lodash/size'; import last from 'lodash/last'; import replace from 'lodash/replace'; import { API_BASE_PATH } from 'config'; const ROUTES_OBJ = { login: `${API_BASE_PATH}/login`, registerUser: `${API_BASE_PATH}/register`, userProfile: `${API_BASE_PATH}/register/<userId>`, }; /** * getRoute creates the URL through provided routeName & params arguments * @param {string} routeName any object name of ROUTES_OBJ e.g. login * @param {Object} [params={}] param values replace with strings present <...>. * @return {string} URL * @TODO: implement routing for array based data, if the value is an array then */ const getRoute = (routeName, params = {}) => { let url = ROUTES_OBJ[routeName]; const result = map(params, (val, key) => { val = Array.isArray(val) ? val.join(',') : val; url = replace(url, new RegExp(`<${key}>`, 'g'), val); return url; }); url = size(result) > 0 ? last(result) : url; return url; }; export default getRoute; <file_sep>import styled from 'styled-components'; import { Link as RouterLink } from 'react-router-dom'; export const Sidebar = styled.div` height: calc(100vh - 65px); background-color: #fcfcfc; -moz-box-shadow: 0px 0px 10px #c7c7c7; -webkit-box-shadow: 0px 0px 10px #c7c7c7; box-shadow: 0px 0px 10px #c7c7c7; `; export const Link = styled(RouterLink)` border-bottom: 1px solid #dcdcdc; padding: 20px 10px; display: block; color: #2c2c2c; text-decoration: none; width: 100%; `; <file_sep>`react-starter-kit` is starter boilerplate for a universal web app to give the best the development experience to developer. It encourages the developer to use the best development practices and helps to focus on the development of app requirements instead of spending the time on creating the application architecture. ##### What's Being Used? - [axios](https://www.npmjs.com/package/axios) for making AJAX calls to a server. - [formik](https://www.npmjs.com/package/formik) for the management of form states & validation - [react-fontawesome](https://www.npmjs.com/package/@fortawesome/react-fontawesome) to use the fortawesome icon in app - [history](https://www.npmjs.com/package/history) to use browser's history in react-router-dom - [lodash](https://www.npmjs.com/package/lodash) to use the utilities of Javascript - [node-sass](https://www.npmjs.com/package/node-sass) for sass support - [react](https://www.npmjs.com/package/react) for managing the presentation logic of application. - [react-bootstrap](https://www.npmjs.com/package/react-bootstrap) for frontend template - [react-redux](https://www.npmjs.com/package/react-redux) for generating and managing state model. - [redux](https://www.npmjs.com/package/redux) for store based store management - [redux-thunk](https://www.npmjs.com/package/redux-thunk) for redux middleware - [styled-components](https://www.npmjs.com/package/styled-components) for the implementation of js based styling - [universal-cookie](https://www.npmjs.com/package/universal-cookie) to utilize the browser cookies - [yup](https://www.npmjs.com/package/yup) to manage the form validations ## Getting Started In order to get started developing, you'll need to do a few things first. 1. Install all of the `node_modules` required for the package. Depending on the computer's configuration, you may need to prefix this command with a `sudo`. ``` npm install ``` or ``` sudo npm install ``` `yarn` can be used it is already installed ``` yarn install ``` or ``` sudo yarn install ``` 2. Create `.env` environment file by making a duplicate of the `.env-example` and remove the `-example`. In the `.env` file and update all the credentials of your application. 3) Lastly, run the start command to get the project off the ground. ``` npm start ``` or ``` yarn start ``` 4. Head over to [http://localhost:3000](http://localhost:3000) to see the app live! ## File Structure ### build/ This is where application will be compiled. Assets, like images and fonts, should be placed directly within this folder. Also in this folder is a default `index.html` file for serving up the application. ### src/ The client folder houses the client application for project. This is where client-side Javascript components (and their directly accompanying styles) live. ## Application Structure ### api/ API directory contains the api calls which are triggering through the app. The purpose of api/ directory is to create an abstract layer for api with function with the paramters. The parameters force the developer to use the payload which is required for api call. ### assets/ Assets contains images and css resources of app ### components/ Components contains all the feature of blocks application page. Components should work like feature based widgets and should be rendered through the `pages`. ### config/ Config directory contains all the configurations of the app like app name, api base path, api routes etc. ### elements/ Elements directory contains all the basic UI elements with required styling like form fields, dropdowns, buttons, tables, icons, cards, links, headings etc. ### layouts/ Layouts are the HOCS which contains all the page layouts which are being used in app like layout for admin dashboard, registered users & public site layout. And these layouts wraps the relevant routes though `routes`. ### pages/ Pages contains all the application pages or top level react-router components. Pages should be used to implement the layout/grid of any page. #### pages/ducks/ Each ducks directory in pages directory contains all the resources/code related to parent page like action-types.js, actions.js, reducer.js. actions.js & reducer.js can be replaced with actions/ & reducers/ directory to break the fat files into small well-defined modules. ### routes/ Routes has the configuration of all the react routes which are being used in app. ### store/ Store directory has the redux store configuration and root reducer of app. ### utils/ Utilities that can be used by any part of application. <file_sep>import React, { useState } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { Formik, Form } from 'formik'; import * as Yup from 'yup'; import { Card, Alert } from 'react-bootstrap'; import { APP_NAME } from 'config'; import { authenticateUserAction } from 'pages/Auth/ducks/actions'; import { AppRoutes } from 'routes'; import TextField from 'elements/Form/TextField'; import { FilledButton, BorderedButton } from 'elements/Button'; const initStates = { email: '', password: '', }; const validation = Yup.object({ email: Yup.string().email().required('Emails should not be empty.'), password: Yup.string().required('Password should not be empty.'), }); const Login = ({ authenticateUser, history }) => { const [errorMsg, handleErrorMsg] = useState(''); const [isSubmitting, handleSubmission] = useState(false); const handleSubmit = (values, { setErrors }) => { handleSubmission(true); const { email, password } = values; authenticateUser(email, password) .then((resp) => { if (resp) { history.push(AppRoutes.DASHBOARD.path); } handleSubmission(false); }) .catch((error) => { history.push(AppRoutes.DASHBOARD.path); let fieldError = {}; if (error && error.message) { handleErrorMsg(error.message); } if (error.email) { fieldError = error.email; } if (error.password) { fieldError = error.password; } setErrors(fieldError); handleSubmission(false); }); }; return ( <Card className='px-2 py-4'> <Card.Title className='text-center'>{APP_NAME}</Card.Title> <Card.Body> {errorMsg && <Alert variant='danger'>{errorMsg}</Alert>} <Formik initialValues={initStates} validationSchema={validation} onSubmit={handleSubmit} > <Form> <TextField label='Email' name='email' type='text' placeholder='Email' /> <TextField label='Password' name='password' type='<PASSWORD>' placeholder='<PASSWORD>' /> <FilledButton type='submit' disabled={isSubmitting ? true : false} className='mr-2' > Submit </FilledButton> <BorderedButton type='reset' className='float-right'> Reset </BorderedButton> </Form> </Formik> <div className='text-center pt-4'> <Link to={AppRoutes.SIGNUP.path}> Signup if you don't have an account yet </Link> </div> </Card.Body> </Card> ); }; const mapDispatchToProps = (dispatch) => { return { authenticateUser: (email, password) => dispatch(authenticateUserAction(email, password)), }; }; export default connect(null, mapDispatchToProps)(Login); <file_sep>import styled from 'styled-components'; import { Container as BSContainer } from 'react-bootstrap'; import BGImage from 'assets/img/bg5.jpg'; export const Container = styled(BSContainer)` background: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(${BGImage}); -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; height: 100vh; `; <file_sep>import React, { lazy, Suspense } from 'react'; import map from 'lodash/map'; import { Route, Switch, Redirect } from 'react-router-dom'; import siteLayout from 'layouts/Site'; import dashboardLayout from 'layouts/Dashboard'; import Login from 'pages/Auth/Login'; import Logout from 'pages/Auth/Logout'; const Signup = lazy(() => import('pages/Auth/Signup')); const ChangePassword = lazy(() => import('pages/Auth/ChangePassword')); const Dashboard = lazy(() => import('pages/Dashboard')); const Profile = lazy(() => import('pages/Profile')); export const RoutesHOC = (routes, defaultPath) => { return (props) => ( <Suspense fallback={<div />}> <Switch> {map(routes, (route) => { return ( <Route key={route.name} path={route.path} component={route.component} /> ); })} <Redirect to={defaultPath} /> </Switch> </Suspense> ); }; export const DashboardRoutes = { PROFILE: { path: '/profile', name: 'Profile', component: Profile, }, CHANGE_PASSWORD: { path: '/change-password', name: 'Change Password', component: ChangePassword, }, MAIN: { path: '/', name: 'Dashboard', component: Dashboard, }, }; export const AppRoutes = { SIGNUP: { path: '/signup', name: 'Signup', component: siteLayout(Signup), }, LOGIN: { path: '/login', name: 'Login', component: siteLayout(Login), }, LOGOUT: { path: '/logout', name: 'Logout', component: Logout, }, DASHBOARD: { path: '/', name: 'Dashboard', component: dashboardLayout(RoutesHOC(DashboardRoutes, '/')), }, }; export const DEFAULT_PATH = AppRoutes.LOGIN.path; export const USER_LANDING_PAGE = AppRoutes.DASHBOARD.path; export const AppRouter = RoutesHOC(AppRoutes, '/login'); <file_sep>const { REACT_APP_IS_PRODUCTION, REACT_APP_API_URL, REACT_APP_SENTRY_URL, } = process.env; export const IS_PRODUCTION = REACT_APP_IS_PRODUCTION === 'true'; export const API_BASE_PATH = REACT_APP_API_URL.toString(); export const SENTRY_URL = REACT_APP_SENTRY_URL.toString(); export const APP_NAME = 'React Boilerplate'; export const COOKIE_USER_TOKEN_FIELD = 'authToken'; <file_sep>import { LOADING_EMAILS, SET_EMAIL_FILTERS, RESET_FILTERS, SET_TERMS, SET_EMAILS, RESET_EMAILS, SET_EMAIL_DETAIL, RESET_EMAIL_DETAIL, RESET_TERMS, } from 'pages/Emails/actions/action-types'; const initialState = { isLoading: false, filters: { startDate: '', endDate: '', term: {}, }, terms: { next: '', results: [], }, count: 0, emails: [], emailDetail: {}, nextPageUrl: null, }; function searchReducer(state = initialState, action) { switch (action.type) { case LOADING_EMAILS: state = { ...state, isLoading: action.payload }; break; case SET_EMAIL_FILTERS: state = { ...state, filters: { startDate: action.payload.startDate, endDate: action.payload.endDate, term: action.payload.term, }, }; break; case RESET_FILTERS: state = { ...state, filters: { startDate: initialState.filters.startDate, endDate: initialState.filters.endDate, term: initialState.filters.term, }, }; break; case SET_TERMS: state = { ...state, terms: action.payload }; break; case SET_EMAILS: state = { ...state, count: action.payload.count, emails: action.payload.results, nextPageUrl: action.payload.next, }; break; case RESET_EMAILS: state = { ...state, count: initialState.count, emails: initialState.emails, nextPageUrl: initialState.nextPageUrl, }; break; case SET_EMAIL_DETAIL: state = { ...state, emailDetail: action.payload }; break; case RESET_EMAIL_DETAIL: state = { ...state, emailDetail: initialState.emailDetail }; break; case RESET_TERMS: state = { ...state, terms: { ...state.terms, next: initialState.terms.next, }, }; break; default: } return state; } export default searchReducer; <file_sep>import { SHOW_LOADING } from 'pages/App/actions/action-types'; export function showLoading(payload) { return { type: SHOW_LOADING, payload }; } <file_sep>import React, { useState } from 'react'; import { connect } from 'react-redux'; import { Formik, Form } from 'formik'; import * as Yup from 'yup'; import { Card, Alert } from 'react-bootstrap'; import { updateProfileAction } from 'pages/Auth/ducks/actions'; import TextField from 'elements/Form/TextField'; import { FilledButton, BorderedButton } from 'elements/Button'; const initStates = { email: '', password: '', confirmPassword: '', firstName: '', lastName: '', }; const validation = Yup.object({ firstName: Yup.string().min(3).required('First Name should not be empty.'), lastName: Yup.string().min(3).required('Last Name should not be empty.'), email: Yup.string().email().required('Emails should not be empty.'), password: Yup.string(), confirmPassword: Yup.string().oneOf( [Yup.ref('password'), null], 'Passwords must match' ), }); const successNotification = 'User profile has been successully updated.'; const Profile = ({ updateProfile }) => { const [errorMsg, handleErrorMsg] = useState(''); const [successMsg, handleSuccessMsg] = useState(''); const [isSubmitting, handleSubmission] = useState(false); const handleSubmit = (values, { setErrors }) => { handleSubmission(true); handleSuccessMsg(''); handleErrorMsg(''); const { firstName, lastName, email, password } = values; updateProfile(email, password, firstName, lastName) .then((resp) => { handleSubmission(false); handleSuccessMsg(successNotification); }) .catch((error) => { handleSubmission(false); if (error && error.message) { handleErrorMsg(error.message); } const { firstName, lastName, email, password } = error; setErrors({ firstName, lastName, email, password }); }); }; return ( <Card className='px-2 py-4 mt-4'> <Card.Title className='text-center'>Profile</Card.Title> <Card.Body> {errorMsg && <Alert variant='danger'>{errorMsg}</Alert>} {successMsg && <Alert variant='success'>{successMsg}</Alert>} <Formik initialValues={initStates} validationSchema={validation} onSubmit={handleSubmit} > <Form> <TextField label='<NAME>' name='firstName' type='text' placeholder='<NAME>' /> <TextField label='<NAME>' name='lastName' type='text' placeholder='<NAME>' /> <TextField label='Email' name='email' type='text' placeholder='Email' /> <TextField label='Password' name='password' type='password' placeholder='<PASSWORD>' /> <TextField label='Confirm Password' name='confirmPassword' type='<PASSWORD>' placeholder='<PASSWORD> Password' /> <FilledButton type='submit' disabled={isSubmitting ? true : false} className='mr-2' > Submit </FilledButton> <BorderedButton type='reset' className='float-right'> Reset </BorderedButton> </Form> </Formik> </Card.Body> </Card> ); }; const mapDispatchToProps = (dispatch) => { return { updateProfile: (email, password, firstName, lastName) => dispatch(updateProfileAction(email, password, firstName, lastName)), }; }; export default connect(null, mapDispatchToProps)(Profile);
9bb4a25990e67c1bf038be043b6448643c29e820
[ "JavaScript", "Markdown" ]
21
JavaScript
hussnainwithss/Ubook-improved
df22df32283d6fbf1ad0ed45130ca619260e547a
a7e3220da7168cba6b9d4af30be91d04c165b358
refs/heads/main
<file_sep>## Formação em Elixir Stone Pagamentos | Desafio Técnico ### Requisitos Para executar a aplicação é necessário utilizar o NodeJs: ``` node app.js ``` ### Descrição Trecho Principal (a partir da linha 127): ```javascript const QUANTIDADE_EMAILS = gerarRandomInt(min,max); const QUANTIDADE_ITENS = gerarRandomInt(min,max); let itens = gerarItens(QUANTIDADE_ITENS); let emails = gerarEmails(QUANTIDADE_EMAILS); let mapaFinal = calcula(itens, emails); console.table(mapaFinal); ``` Informe os limites mínimo e máximo na função ``gerarRadomInt()`` para gerar uma quantidade de emails e quantidade de itens de forma aleatória. As funções ``gerarItens()`` e ``gerarEmails()`` retornam listas de itens e emails, respectivamente. A função ``calcula()`` recebe as duas listas, distribui o valor total dos produtos seguindo a regra de negócio definida no desafio, retornando um mapa chave->valor com o Email e Valor que cada pessoa irá pagar. Caso a lista de emails seja vazia, a aplicação informa que a lista não possui pessoas cadastradas. Caso a lista de produtos é vazia, cada pessoa da lista de emails pagará o valor '0'. ### Detalhe A função principal, ``calcula(itens, emails)``, calcula o valor total dos itens, divide o valor total dos itens pela quantidade de emails cadastrados. Como essa divisão naturalmente resultará um número de ponto flutuante, utilizamos a função Piso ``Math.floor(x)`` que retorna o menor número inteiro dentre o número "x". Esse é, então, o valor mínimo que cada pessoa irá pagar. A aplicação então atribui o valor mínimo para todos os emails. Caso haja resto inteiro da divisão, o programa soma 1 centavo para cada pessoa até que não sobre mais resto. **Nota** As linhas 118 até 121 estão comentadas e podem ser utilizadas pelo avaliador técnico para conferir se os resultados estão coincidindo com a saída da aplicação: ```javascript // console.log(`Valor total dos Itens (em centavos de R$): ${valorItens}`); // console.log(`Quantidade de Pessoas: ${emails.length}`); // console.log(`Valor para Mínimo para cada usuário ${valorMinimo}`); // console.log(`Valor restante, após divisão mínima, é ${restante}`); ``` <file_sep>"use strict"; /* Função para gerar inteiros aleatórios dado um range Min e Max; */ function gerarRandomInt(min, max){ min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random()*(max-min)) + min; } /* Gera uma string aleatória, dado tamanho; */ function stringAleatoria(tamanho) { let conjuntoCaracteres = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let stringAleatoria = ''; for (let i = 0; i < tamanho; i++) { let randomPoz = Math.floor(Math.random() * conjuntoCaracteres.length); stringAleatoria += conjuntoCaracteres.substring(randomPoz,randomPoz+1); } return stringAleatoria; } /* Gera uma lista de itens, dado tamanho */ function gerarItens(tamanhoLista){ let conjuntoItens = new Set(); for(let i=0; i<tamanhoLista;i++){ let item = { nome: stringAleatoria(5), quantidade: gerarRandomInt(0,9999), precoUnitario: gerarRandomInt(0,999999) }; conjuntoItens.add(item) } return Array.from(conjuntoItens); } /* Conforme regra de negócio, o email é UNIQUE. Decidi por utilizar o SET, pois o Set permite apenas uma ocorrência para o mesmo valor informado; A função retorna um Array a partir do Set de emails. ------ A função retorna emails com tamanho padrão da RFC5321, ou seja, email de tamanho máximo 255 caracteres, sendo 64 caracteres máximos no nome e 191 caracteres máximos no domínio. A função retorna pelo menos um caractere no nome e pelo menos 1 caractere na parte do domínio. */ function gerarEmails(tamanhoLista){ let qntCharNome; let qntCharDominio; let conjuntoEmails = new Set(); for(let i=0; i<tamanhoLista;i++){ qntCharNome = gerarRandomInt(1,64); qntCharDominio = gerarRandomInt(1,191); conjuntoEmails.add(stringAleatoria(qntCharNome)+"@"+stringAleatoria(qntCharDominio)); } return Array.from(conjuntoEmails); }; /* Recebe um array de Itens e retorna o valor total da lista (preçoUnitário do Item * quantidade) */ function valorTotalItens(itens){ let total = 0; itens.forEach(item => { total = item.quantidade * item.precoUnitario; }); return total; } /* Função para distribuir na lista o resto inteiro da divisão */ function distribuiValorRestante(lista, valorParaDistribuir){ let contador = 0; for(let i=0; i<lista.length; i++){ if(valorParaDistribuir<=0){break;} lista[i].valor = lista[i].valor + 1; valorParaDistribuir--; } return lista; }; function calcula(itens, emails){ let resultado = new Array(); let valorItens = valorTotalItens(itens); let quantidadeEmails = emails.length; let valorMinimo = 0; let restante = 0; if(quantidadeEmails<1){ console.log("A lista de Emails não possui pessoas cadastradas.") }else{ valorMinimo = Math.floor(valorItens/quantidadeEmails); restante = valorItens-(valorMinimo*quantidadeEmails); emails.forEach(email=>{ resultado.push({pessoa : email, valor: valorMinimo}); }); if(restante>0){ resultado = distribuiValorRestante(resultado, restante); } } // console.log(`Valor total dos Itens (em centavos de R$): ${valorItens}`); // console.log(`Quantidade de Pessoas: ${emails.length}`); // console.log(`Valor para Mínimo para cada usuário ${valorMinimo}`); // console.log(`Valor restante, após divisão mínima, é ${restante}`); return resultado; } /*==================== MAIN ========================*/ const QUANTIDADE_EMAILS = gerarRandomInt(0,9999); const QUANTIDADE_ITENS = gerarRandomInt(0,99999); let itens = gerarItens(QUANTIDADE_ITENS); let emails = gerarEmails(QUANTIDADE_EMAILS); let mapaFinal = calcula(itens, emails); console.table(mapaFinal);
9a0aa434cd39bf5f4411e0914b0ea5c316459149
[ "Markdown", "JavaScript" ]
2
Markdown
manoelbjr/Desafio_Stone
2b16b9c139f3a51e0d459f7d1e0dd6728af8aa4d
ffc0677eedbbb40f468647805f2b705872c65e95
refs/heads/master
<file_sep>package edu.washington.accessmap; import android.app.Activity; import android.content.Intent; import android.location.Address; import android.location.Location; import android.os.Bundle; import android.os.Parcelable; import android.provider.ContactsContract; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import com.mapbox.mapboxsdk.geometry.LatLng; import org.json.JSONException; import org.json.JSONObject; import java.util.Locale; public class Routing extends Activity { private static final String FROM_CURRENT_LOCATION = "From: Your Current Location"; private static final Address DUMMY = new Address(Locale.US); private EditText fromText = null; private Address fromAddress = null; private Address fromAddressStart = null; private EditText toText = null; private Address toAddress = null; private RadioGroup radioGroup = null; private String selectedMobility = null; private Button executeRouteButton = null; private Location userLocation = null; private Address toAddressStart = null; private boolean useUserLocation = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_routing); fromText = (EditText) findViewById(R.id.from_address); toText = (EditText) findViewById(R.id.to_address); radioGroup = (RadioGroup) findViewById(R.id.mobility_radio_group); executeRouteButton = (Button) findViewById(R.id.execute_route_search_button); useUserLocation = this.getIntent().getExtras().getBoolean("USER_LOCATION"); if (useUserLocation) { // first time routing fromText.setText(FROM_CURRENT_LOCATION); } else { // reopened_route fromAddressStart = this.getIntent().getExtras().getParcelable("FROM_ADDRESS"); if (fromAddressStart.getMaxAddressLineIndex() != 1 && fromAddressStart.getAddressLine(0).equals(FROM_CURRENT_LOCATION)) { // still use user location useUserLocation = true; fromText.setText(FROM_CURRENT_LOCATION); } else { // use passes in address fromText.setText("From: " + DataHelper.extractAddressText(fromAddressStart)); fromAddress = fromAddressStart; } } toAddressStart = this.getIntent().getExtras().getParcelable("TO_ADDRESS"); if (toAddressStart != null) { toText.setText("To: " + DataHelper.extractAddressText(toAddressStart)); toAddress = toAddressStart; } fromText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent searchAddress = new Intent(Routing.this, SearchAddressActivity.class); searchAddress.putExtra("PREVIOUS_SEARCH", DUMMY); Routing.this.startActivityForResult(searchAddress, 1); } }); toText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent searchAddress = new Intent(Routing.this, SearchAddressActivity.class); searchAddress.putExtra("PREVIOUS_SEARCH", DUMMY); Routing.this.startActivityForResult(searchAddress, 2); } }); executeRouteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent resultIntent = new Intent(); // could all be null!! resultIntent.putExtra("USER_LATLNG", useUserLocation); resultIntent.putExtra("FROM_ADDRESS", fromAddress); resultIntent.putExtra("TO_ADDRESS", toAddress); resultIntent.putExtra("MOBILITY_SELECTION", radioGroup.getCheckedRadioButtonId()); setResult(Activity.RESULT_OK, resultIntent); finish(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { // fromAddress if (resultCode == Activity.RESULT_OK) { fromAddress = data.getExtras().getParcelable("SELECTED_ADDRESS"); fromText.setText("From: " + DataHelper.extractAddressText(fromAddress)); useUserLocation = false; } else if (resultCode == Activity.RESULT_CANCELED) { //Write your code if there's no result } } else if (requestCode == 2) { // to Address if (resultCode == Activity.RESULT_OK) { toAddress = data.getExtras().getParcelable("SELECTED_ADDRESS"); toText.setText("To: " + DataHelper.extractAddressText(toAddress)); } else if (resultCode == Activity.RESULT_CANCELED) { //Write your code if there's no result } } } //onActivityResult } <file_sep>package edu.washington.accessmap; import android.app.ProgressDialog; import android.location.Address; import android.location.Location; import com.mapbox.mapboxsdk.annotations.Marker; import com.mapbox.mapboxsdk.annotations.PolylineOptions; import com.mapbox.mapboxsdk.geometry.LatLng; import java.util.ArrayList; import java.util.List; /** * Created by samuelfelker on 12/4/15. */ public class MapStateTracker { private Marker userLocationMarker = null; private Location userLastLocation = null; private Marker lastSearchedAddressMarker = null; private Address lastSearchedAddress = null; private ArrayList<LatLng> currentRoute = null; private Address currentRouteStart = null; private Address currentRouteEnd = null; private boolean handleAddressOnResume = false; private LatLng lastCenterLocation = null; private double lastZoomLevel = MainActivity.DATA_ZOOM_LEVEL; private boolean isFirstConnection = true; private ProgressDialog routingDialog = null; private LatLng userLatLng = null; public MapStateTracker() {} // GETTERS AND SETTERS BELOW public LatLng getUserLatLng() { return userLatLng; } public void setUserLatLng(LatLng userLatLng) { this.userLatLng = userLatLng; } public ProgressDialog getRoutingDialog() { return routingDialog; } public void setRoutingDialog(ProgressDialog routingDialog) { this.routingDialog = routingDialog; } public Marker getLastSearchedAddressMarker() { return lastSearchedAddressMarker; } public void setLastSearchedAddressMarker(Marker lastSearchedAddressMarker) { this.lastSearchedAddressMarker = lastSearchedAddressMarker; } public Location getUserLastLocation() { return userLastLocation; } public void setUserLastLocation(Location userLastLocation) { this.userLastLocation = userLastLocation; } public Marker getUserLocationMarker() { return userLocationMarker; } public void setUserLocationMarker(Marker userLocationMarker) { this.userLocationMarker = userLocationMarker; } public Address getLastSearchedAddress() { return lastSearchedAddress; } public void setLastSearchedAddress(Address lastSearchedAddress) { this.lastSearchedAddress = lastSearchedAddress; } public ArrayList<LatLng> getCurrentRoute() { return currentRoute; } public void setCurrentRoute(ArrayList<LatLng> currentRoute) { this.currentRoute = currentRoute; } public boolean isHandleAddressOnResume() { return handleAddressOnResume; } public void setHandleAddressOnResume(boolean handleAddressOnResume) { this.handleAddressOnResume = handleAddressOnResume; } public LatLng getLastCenterLocation() { return lastCenterLocation; } public void setLastCenterLocation(LatLng lastCenterLocation) { this.lastCenterLocation = lastCenterLocation; } public double getLastZoomLevel() { return lastZoomLevel; } public void setLastZoomLevel(double lastZoomLevel) { this.lastZoomLevel = lastZoomLevel; } public boolean isFirstConnection() { return isFirstConnection; } public void setIsFirstConnection(boolean isFirstConnection) { this.isFirstConnection = isFirstConnection; } public Address getCurrentRouteEnd() { return currentRouteEnd; } public void setCurrentRouteEnd(Address currentRouteEnd) { this.currentRouteEnd = currentRouteEnd; } public Address getCurrentRouteStart() { return currentRouteStart; } public void setCurrentRouteStart(Address currentRouteStart) { this.currentRouteStart = currentRouteStart; } } <file_sep>package edu.washington.accessmap; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import java.util.HashMap; import java.util.Map; /** * Created by samuelfelker on 11/19/15. */ public class FeatureAdjuster extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); final MapFeature[] mapFeatures = (MapFeature[]) getArguments().getParcelableArray("MAP_FEATURES_STATE"); final Map<String, MapFeature> featureMap = new HashMap<String, MapFeature>(); boolean[] defaultChecked = new boolean[mapFeatures.length]; final String[] listView = new String[mapFeatures.length]; for (int i = 0; i < mapFeatures.length; i++) { featureMap.put(mapFeatures[i].getName(), mapFeatures[i]); listView[i] = mapFeatures[i].getName(); defaultChecked[i] = mapFeatures[i].isVisible(); } builder.setTitle("Select Features") .setMultiChoiceItems(listView, defaultChecked, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { MapFeature checkedFeature = featureMap.get(listView[which]); checkedFeature.setVisibility(isChecked); } }) // Set the action buttons .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { MapFeature[] results = new MapFeature[mapFeatures.length]; for (int i = 0; i < mapFeatures.length; i++) { results[i] = featureMap.get(mapFeatures[i].getName()); } MainActivity.setMapFeatures(results); } }); return builder.create(); } } <file_sep>package edu.washington.accessmap; import android.app.Dialog; import android.app.DialogFragment; import android.app.LoaderManager; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.content.Loader; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Telephony; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.app.Activity; import android.os.Bundle; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.model.Polyline; import com.mapbox.mapboxsdk.annotations.Annotation; import com.mapbox.mapboxsdk.annotations.Marker; import com.mapbox.mapboxsdk.annotations.MarkerOptions; import com.mapbox.mapboxsdk.annotations.PolylineOptions; import com.mapbox.mapboxsdk.constants.Style; import com.mapbox.mapboxsdk.geometry.BoundingBox; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.views.MapView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; public static final int DATA_ZOOM_LEVEL = 16; public static final float CHANGE_DATA_DISTANCE = 200; public static final String TAG = MainActivity.class.getSimpleName(); // map variables public MapView mapView = null; private MapStateTracker mapTracker = null; private static MapFeature[] mapFeatureState = null; // ui elements private EditText addressText = null; private FloatingActionButton closeSearchDisplayButton = null; private ImageButton centerUserLocationButton = null; private ImageButton zoomOutButton = null; private ImageButton zoomInButton = null; private ImageButton adjustFeaturesButton = null; private ImageButton routeButton = null; private ListView routeListView = null; private FloatingActionButton closeRouteView = null; // google services variables private GoogleApiClient mGoogleApiClient = null; private LocationRequest mLocationRequest = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buildGoogleApiClient(); buildLocationRequest(); /** Instanciate MapView and properties */ mapTracker = new MapStateTracker(); mapView = (MapView) findViewById(R.id.mapview); setUpMapProperties(savedInstanceState); // Instanciate Map Feature Tracker Resources res = getResources(); String[] featureResources = res.getStringArray(R.array.feature_array); mapFeatureState = new MapFeature[featureResources.length]; instanciateFeatureTracker(featureResources); // User Interface Listeners buildUserInterfaceListeners(); // Alert User if no Network Connection checkWifi(); } public void setUpMapProperties(Bundle savedInstanceState) { mapView.setStyleUrl(Style.MAPBOX_STREETS); mapTracker.setLastCenterLocation(new LatLng(47.6, -122.3)); mapView.setCenterCoordinate(mapTracker.getLastCenterLocation()); mapView.setZoomLevel(DATA_ZOOM_LEVEL); mapView.setCompassGravity(Gravity.BOTTOM); mapView.setLogoGravity(Gravity.RIGHT); mapView.onCreate(savedInstanceState); } // Pulls feature information from string resources public void instanciateFeatureTracker(String[] featureResources) { for (int i = 0; i < featureResources.length; i++) { System.out.println(featureResources[i]); String[] results = featureResources[i].split("\\|"); System.out.println(results[0] + " " + results[1] + " " + results[2]); mapFeatureState[i] = new MapFeature(results[0], results[1], Boolean.valueOf(results[2])); } } public void buildUserInterfaceListeners() { mapView.addOnMapChangedListener(handleMapChange); addressText = (EditText) findViewById(R.id.address_text_bar); addressText.setOnClickListener(searchAddress); closeSearchDisplayButton = (FloatingActionButton) findViewById(R.id.close_search_display); closeSearchDisplayButton.setOnClickListener(closeSearchDisplayButtonOnCLickListener); centerUserLocationButton = (ImageButton) findViewById(R.id.center_user_location_button); centerUserLocationButton.setOnClickListener(centerOnUserLocationButtonOnClickListener); zoomInButton = (ImageButton) findViewById(R.id.zoom_in_button); zoomInButton.setOnClickListener(zoomInButtonOnClickListener); zoomOutButton = (ImageButton) findViewById(R.id.zoom_out_button); zoomOutButton.setOnClickListener(zoomOutButtonOnClickListener); adjustFeaturesButton = (ImageButton) findViewById(R.id.adjust_features_button); adjustFeaturesButton.setOnClickListener(adjustFeaturesButtonOnClickListener); routeButton = (ImageButton) findViewById(R.id.route_button); routeButton.setOnClickListener(routeButtonOnClickListener); routeListView = (ListView) findViewById(R.id.list_view); routeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent routeSearch = new Intent(MainActivity.this, Routing.class); routeSearch.putExtra("FROM_ADDRESS", mapTracker.getCurrentRouteStart()); routeSearch.putExtra("USER_LOCATION", false); routeSearch.putExtra("TO_ADDRESS", mapTracker.getCurrentRouteEnd()); MainActivity.this.startActivityForResult(routeSearch, 2); } }); closeRouteView = (FloatingActionButton) findViewById(R.id.close_routing_display); closeRouteView.setOnClickListener(closeRouteViewOnCLickListener); } // Detects if new data should be loaded on the map, or if data should be removed MapView.OnMapChangedListener handleMapChange = new MapView.OnMapChangedListener() { @Override public void onMapChanged(int change) { double currentZoom = mapView.getZoomLevel(); LatLng centerCoordinate = mapView.getCenterCoordinate(); float computedDistance = computeDistance(centerCoordinate, mapTracker.getLastCenterLocation()); if (mapTracker.getLastZoomLevel() >= DATA_ZOOM_LEVEL && currentZoom < DATA_ZOOM_LEVEL) { MapArtist.clearMap(mapView, mapTracker); } else if (mapTracker.getLastZoomLevel() < DATA_ZOOM_LEVEL && currentZoom >= DATA_ZOOM_LEVEL) { loadData(); } else if (computedDistance > CHANGE_DATA_DISTANCE && currentZoom >= DATA_ZOOM_LEVEL) { mapTracker.setLastCenterLocation(centerCoordinate); refreshMap(); } mapTracker.setLastZoomLevel(currentZoom); } }; View.OnClickListener searchAddress = new View.OnClickListener() { @Override public void onClick(View arg0) { Intent searchAddress = new Intent(MainActivity.this, SearchAddressActivity.class); searchAddress.putExtra("PREVIOUS_SEARCH", mapTracker.getLastSearchedAddress()); MainActivity.this.startActivityForResult(searchAddress, 1); } }; View.OnClickListener zoomInButtonOnClickListener = new View.OnClickListener() { @Override public void onClick(View arg0) { double currentZoomLevel = mapView.getZoomLevel(); if (currentZoomLevel + 1 < MapView.MAXIMUM_ZOOM_LEVEL) { mapView.setZoomLevel(currentZoomLevel + 1, true); // animated zoom in } else { // cant zoom any further mapView.setZoomLevel(MapView.MAXIMUM_ZOOM_LEVEL, true); } mapTracker.setLastZoomLevel(currentZoomLevel); if (currentZoomLevel >= DATA_ZOOM_LEVEL) { loadData(); } } }; View.OnClickListener zoomOutButtonOnClickListener = new View.OnClickListener() { @Override public void onClick(View arg0) { double currentZoomLevel = mapView.getZoomLevel(); mapView.setZoomLevel(currentZoomLevel - 1, true); // animated zoom out mapTracker.setLastZoomLevel(currentZoomLevel); if (currentZoomLevel < DATA_ZOOM_LEVEL) { MapArtist.clearMap(mapView, mapTracker); } } }; View.OnClickListener adjustFeaturesButtonOnClickListener = new View.OnClickListener(){ @Override public void onClick(View arg0) { DialogFragment featureAdjuster = new FeatureAdjuster() { @Override public void onDismiss(final DialogInterface dialog) { refreshMap(); // makes users preferences load when dialog closes getFragmentManager().beginTransaction().remove(this).commit(); // ensures dialog closes } }; Bundle args = new Bundle(); args.putParcelableArray("MAP_FEATURES_STATE", mapFeatureState); featureAdjuster.setArguments(args); featureAdjuster.show(getFragmentManager(), "adjust_features"); } }; View.OnClickListener routeButtonOnClickListener = new View.OnClickListener(){ @Override public void onClick(View arg0) { closeSearchDisplay(); // could be active here if routing after a search Intent routeSearch = new Intent(MainActivity.this, Routing.class); routeSearch.putExtra("USER_LOCATION", true); // no from address needed if true routeSearch.putExtra("TO_ADDRESS", mapTracker.getLastSearchedAddress()); MainActivity.this.startActivityForResult(routeSearch, 2); } }; View.OnClickListener closeRouteViewOnCLickListener = new View.OnClickListener(){ @Override public void onClick(View arg0) { closeRouteView(); } }; View.OnClickListener closeSearchDisplayButtonOnCLickListener = new View.OnClickListener(){ @Override public void onClick(View arg0) { closeSearchDisplay(); } }; View.OnClickListener centerOnUserLocationButtonOnClickListener = new View.OnClickListener(){ @Override public void onClick(View arg0) { handleNewLocation(mapTracker.getUserLastLocation(), true); } }; // GOOGLE API LOCATION SERVICE METHODS protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } protected synchronized void buildLocationRequest() { mLocationRequest = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(10 * 1000) // 10 seconds, in milliseconds .setFastestInterval(1 * 1000); // 1 second, in milliseconds } @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "Location services connected."); mapTracker.setUserLastLocation(LocationServices.FusedLocationApi.getLastLocation( mGoogleApiClient)); if (mapTracker.getUserLastLocation() == null) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } else if (mapTracker.isFirstConnection()) { mapTracker.setIsFirstConnection(false); handleNewLocation(mapTracker.getUserLastLocation(), true); loadData(); } } @Override public void onLocationChanged(Location mLastLocation) { mapTracker.setUserLastLocation(mLastLocation); handleNewLocation(mapTracker.getUserLastLocation(), false); } // new user location detected private void handleNewLocation(Location mLastLocation, boolean center) { Log.i(TAG, "handling new location"); double currentLatitude = mLastLocation.getLatitude(); double currentLongitude = mLastLocation.getLongitude(); LatLng currentPosition = new LatLng(currentLatitude, currentLongitude); if (mapTracker.getUserLocationMarker() != null) { mapView.removeAnnotation(mapTracker.getUserLocationMarker()); } mapTracker.setUserLocationMarker(mapView.addMarker(new MarkerOptions() .position(currentPosition))); if (center) { mapView.setCenterCoordinate(currentPosition); mapTracker.setLastCenterLocation(currentPosition); if (mapView.getZoomLevel() >= DATA_ZOOM_LEVEL) { refreshMap(); } } } @Override public void onConnectionSuspended(int i) { Log.i(TAG, "Location services suspended. Please reconnect."); } @Override public void onConnectionFailed(ConnectionResult connectionResult) { if (connectionResult.hasResolution()) { try { // Start an Activity that tries to resolve the error connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); } } else { Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode()); int errorCode = connectionResult.getErrorCode(); if (errorCode == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED || errorCode == ConnectionResult.SERVICE_MISSING || errorCode == ConnectionResult.SERVICE_DISABLED) { Dialog dialog = GooglePlayServicesUtil.getErrorDialog(errorCode, this, 1); dialog.show(); // redirects to google play store } } } // ANDROID ACTIVTY FUNCTIONS @Override protected void onStart() { super.onStart(); mapView.onStart(); } @Override protected void onStop() { super.onStop(); mapView.onStop(); } @Override public void onPause() { super.onPause(); mapView.onPause(); if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } @Override public void onResume() { super.onResume(); mapView.onResume(); mGoogleApiClient.connect(); if (mapTracker.isHandleAddressOnResume()) { // search address activity just finished try { if (mapTracker.getLastSearchedAddressMarker() != null) { mapView.removeAnnotation(mapTracker.getLastSearchedAddressMarker()); } Address lastSearchedAddress = mapTracker.getLastSearchedAddress(); LatLng searchedPosition = DataHelper.extractLatLng(lastSearchedAddress); String textAddress = DataHelper.extractAddressText(lastSearchedAddress); addressText.setText(textAddress); mapTracker.setLastSearchedAddressMarker(mapView.addMarker(new MarkerOptions() .position(searchedPosition) .title("Searched Address:") .snippet(textAddress))); enterSearchDisplay(); mapView.setCenterCoordinate(searchedPosition); } catch (IllegalStateException ise) { Toast.makeText(getApplicationContext(), "cannot resolve exact location of searched address", Toast.LENGTH_LONG).show(); } mapTracker.setHandleAddressOnResume(false); } } @Override protected void onDestroy() { super.onDestroy(); mapView.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } // Handles result of other activity execution like address searching @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { // search activity received if (resultCode == Activity.RESULT_OK) { Address selectedAddress = data.getExtras().getParcelable("SELECTED_ADDRESS"); mapTracker.setLastSearchedAddress(selectedAddress); mapTracker.setHandleAddressOnResume(true); // onResume() is about to be called and searched address added to map } else if (resultCode == Activity.RESULT_CANCELED) { //Write code for if there's no result } } else if (requestCode == 2) { // routing activity received if (resultCode == Activity.RESULT_OK) { if (data.getExtras().getBoolean("USER_LATLNG")) { // use user current location double currentLatitude = mapTracker.getUserLastLocation().getLatitude(); double currentLongitude = mapTracker.getUserLastLocation().getLongitude(); Address x = new Address(Locale.US); // build dummy address to use in routing x.setAddressLine(0, "Your Current Location"); x.setLatitude(currentLatitude); x.setLongitude(currentLongitude); mapTracker.setCurrentRouteStart(x); System.out.println(mapTracker.getCurrentRouteStart()); } else { // dont use user location mapTracker.setCurrentRouteStart((Address) data.getExtras().getParcelable("FROM_ADDRESS")); } mapTracker.setCurrentRouteEnd((Address) data.getExtras().getParcelable("TO_ADDRESS")); // TODO: receive mobility type and send it with api call // String mobilitySelection = data.getExtras().getString("MOBILITY_SELECTION"); if (mapTracker.getCurrentRouteStart() == null || mapTracker.getCurrentRouteEnd() == null) { Toast.makeText(getApplicationContext(), "you must select start and end destination for routing", Toast.LENGTH_LONG).show(); } else { String coordinates = DataHelper.getRouteCoordinates(mapTracker); new CallAccessMapAPI().execute(getString(R.string.routing_url), getString(R.string.routing_endpoint), coordinates); mapTracker.setRoutingDialog(ProgressDialog.show(this, "", "Finding Route. Please wait...", true)); enterRouteView(); } } else if (resultCode == Activity.RESULT_CANCELED) { //Write your code if there's no result } } } //onActivityResult public void checkWifi() { ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected()) { Toast.makeText(getApplicationContext(), "Access Map needs Wifi or Mobile Network connection", Toast.LENGTH_LONG).show(); } } // returns -1 on error otherwise meters between coordinates private float computeDistance(LatLng one, LatLng two) { float[] distanceArray = new float[1]; try { Location.distanceBetween(one.getLatitude(), one.getLongitude(), two.getLatitude(), two.getLongitude(), distanceArray); return distanceArray[0]; } catch (IllegalArgumentException iae) { // failure return -1; } } // method called from feature adjuster to save new feature choices public static void setMapFeatures(MapFeature[] newFeatureSelection) { mapFeatureState = newFeatureSelection; } private void enterRouteView() { addressText.setVisibility(View.GONE); routeButton.setVisibility(View.GONE); routeListView.setVisibility(View.VISIBLE); closeRouteView.setVisibility(View.VISIBLE); RelativeLayout.LayoutParams culb = (RelativeLayout.LayoutParams) centerUserLocationButton.getLayoutParams(); culb.addRule(RelativeLayout.BELOW, R.id.list_view); RelativeLayout.LayoutParams zib = (RelativeLayout.LayoutParams) zoomInButton.getLayoutParams(); zib.addRule(RelativeLayout.BELOW, R.id.adjust_features_button); } private void closeRouteView() { addressText.setVisibility(View.VISIBLE); routeButton.setVisibility(View.VISIBLE); routeListView.setVisibility(View.GONE); closeRouteView.setVisibility(View.GONE); RelativeLayout.LayoutParams culb = (RelativeLayout.LayoutParams) centerUserLocationButton.getLayoutParams(); culb.addRule(RelativeLayout.BELOW, R.id.address_text_bar); RelativeLayout.LayoutParams zib = (RelativeLayout.LayoutParams) zoomInButton.getLayoutParams(); zib.addRule(RelativeLayout.BELOW, R.id.route_button); MapArtist.clearRoute(mapView, mapTracker); refreshMap(); } private void enterSearchDisplay() { closeSearchDisplayButton.setVisibility(View.VISIBLE); } private void closeSearchDisplay() { closeSearchDisplayButton.setVisibility(View.GONE); addressText.setText(""); mapTracker.setLastSearchedAddressMarker(null); // to prevent drawing refreshMap(); } // DATA HANDLING FUNCTIONS BELOW public void refreshMap() { MapArtist.clearMap(mapView, mapTracker); loadData(); } // loads data for every checked feature public void loadData() { String bounds = MapArtist.getDataBounds(mapView.getCenterCoordinate()); String api_url = getString(R.string.api_url); for (MapFeature mapFeature : mapFeatureState) { if (mapFeature.isVisible()) { new CallAccessMapAPI().execute(api_url, mapFeature.getUrl(), bounds); } } } private class CallAccessMapAPI extends AsyncTask<String, String, JSONObject> { @Override protected JSONObject doInBackground(String... params) { String urlString = params[0] + params[1]; // URL to call String coordinates = params[2]; // bounds for data or route start and stop JSONObject result = null; // HTTP Get try { String query = ""; if (params[1].equals("route.json")) { query = String.format("waypoints=%s", coordinates); } else { query = String.format("bbox=%s", coordinates); } URL url = new URL(urlString + "?" + query); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader(urlConnection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); result = new JSONObject(response.toString()); result.put("class", params[1]); // track data type in json object } catch (Exception e ) { System.out.println(e.getMessage()); return null; } return result; } protected void onPostExecute(JSONObject result) { if (result == null) { // server or network error mapTracker.getRoutingDialog().cancel(); // closes spinning "finding route" dialog closeRouteView(); Toast.makeText(getApplicationContext(), "A Network error occurred, or no possible route avaliable, please check Network connection", Toast.LENGTH_LONG).show(); } else { try { switch (result.getString("class")) { case "/curbs.geojson": MapArtist.drawCurbs(mapView, result); break; case "/sidewalks.geojson": MapArtist.drawSidewalks(mapView, result); break; case "/permits.geojson": MapArtist.drawPermits(mapView, result); break; case "route.json": mapTracker.setCurrentRoute(MapArtist.extractRoute(result)); // populate route display List<String> routeInfo = new ArrayList<String>(); routeInfo.add("From: " + DataHelper.extractAddressText(mapTracker.getCurrentRouteStart())); routeInfo.add("To: " + DataHelper.extractAddressText(mapTracker.getCurrentRouteEnd())); ArrayAdapter adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.custom_list_element, R.id.list_content, routeInfo); routeListView.setAdapter(adapter); MapArtist.drawRoute(mapView, mapTracker, true); mapTracker.getRoutingDialog().cancel(); break; } } catch (JSONException je) { Log.i(TAG, "JSON ERROR"); } } } } // end CallAccessMapAPI }<file_sep>package edu.washington.accessmap; import android.location.Address; import android.os.AsyncTask; import android.util.Log; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.views.MapView; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Created by samuelfelker on 12/5/15. */ public class DataHelper { public static final String TAG = DataHelper.class.getSimpleName(); public static final int MAX_ADDRESS_LENGTH = 50; public static String extractAddressText(Address address) { String textAddress = ""; if (address.getMaxAddressLineIndex() != -1) { textAddress = address.getAddressLine(0); } for (int i = 1; i <= address.getMaxAddressLineIndex(); i++) { textAddress += ", " + address.getAddressLine(i); } if (textAddress.length() > MAX_ADDRESS_LENGTH) { return textAddress.substring(0, MAX_ADDRESS_LENGTH) + "..."; } else { return textAddress; } } public static LatLng extractLatLng(Address address) { return new LatLng(address.getLatitude(), address.getLongitude()); } public static String getRouteCoordinates(MapStateTracker mapTracker) { String result = "["; Address start = mapTracker.getCurrentRouteStart(); Address end = mapTracker.getCurrentRouteEnd(); result += start.getLatitude(); result += "," + start.getLongitude(); result += "," + end.getLatitude(); result += "," + end.getLongitude() + "]"; return result; } }
de3ac347e06ee44b828acd4608f6a738c94c911a
[ "Java" ]
5
Java
sfelker/access-map-android
16cd025dee60455dd469a16f843bd0d3e25471ab
df5a546d4e5c4fda634347ebd42cd6e3100fbe67
refs/heads/master
<repo_name>a21029delia/r_prg_midterm_04<file_sep>/r_prg_midterm_04.R # Create a function my_sort_asc() my_sort_asc <- function(input_vec){ for(i in 1:(length(input_vec) - 1) ){ for(j in (i + 1):length(input_vec) ){ if(input_vec[i] > input_vec[j]){ temp_i <- input_vec[i] input_vec[i] <- input_vec[j] input_vec[j] <- temp_i } } } return(input_vec) } # Create input set.seed(87) my_seq <- round(runif(10) * 100) # Function all my_sort_asc(my_seq) sort(my_seq) # Create a function my_sd() my_sd <- function(input_vec){ x_bar <-mean(input_vec) n_minus_one <- length(input_vec) - 1 summation <- 0 for(x_i in input_vec){ summation <- summation + (x_i - x_bar)^2 } return(sqrt(summation)) } # Create an input set.seed(87) my_seq <- round(runif(10) * 100) # Function all my_sd(my_seq) sd(my_seq) # Create a function GBMI calculator() bmi_calculator <- function(w,h){ h <- h / 100 return(w / h^2) } #create in put heights <- c(173, 168, 171, 189, 179) weights <- c(65.4, 59.2, 63.6, 88.4, 68.7) heights_and_weights <- data.frame(heights, weights) #Function call bmi_data <- mapply(FUN = bmi_calculator, w = weights, h = heights) bmi_data <- cbind(heights_and_weights,bmi_data) View(bmi_data)
7760411c6be336f557fa0d6de2547b1bbb2f7e0e
[ "R" ]
1
R
a21029delia/r_prg_midterm_04
7c42b3c4cee7af4bd7b5f768f13f065c0cf73105
392924da3995b11b3402e0b7e7b219a383eb07fc
refs/heads/master
<file_sep>const express = require('express'); const router = express.Router(); const conn = require('./../db/db') const svgCaptcha = require('svg-captcha'); //验证码 const sms_util = require('./../util/sms_util'); let md5 = require('blueimp-md5'); const session = require('express-session'); let users = {}; /* GET home page. */ router.get('/', (req, res, next)=> { res.render('index', { title: '狗子' }); }); /** * 获取首页轮播图接口 */ router.get('/api/homecasual', (req, res)=>{ let sqlStr = 'select * from pdd_homecasual'; //查询数据库 conn.query(sqlStr, (err, results) => { if (err) return res.json({code: 1, message: '资料不存在', affextedRows: 0}) res.json({code: 200, data: results,affextedRows: results.affextedRows}) }) /* const data = require('../data/homecasual'); res.json({code: 200, message: data}) */ }); /** * 获取首页导航 */ router.get('/api/homenav', (req, res)=>{ /* let sqlStr = 'select * from homenav'; conn.query(sqlStr, (err, results) => { if (err) return res.json({code: 1, message: '资料不存在', affextedRows: 0}) res.json({code: 200, message: results, affextedRows: results.affextedRows}) }) */ const data = require('../data/homenav'); res.json({code: 200, message: data}); }); /** * 获取首页商品列表 */ router.get('/api/homeshoplist', (req, res)=>{ /* let sqlStr = 'select * from homeshoplist'; conn.query(sqlStr, (err, results) => { if (err) return res.json({code: 1, message: '资料不存在', affextedRows: 0}) res.json({code: 200, message: results, affextedRows: results.affextedRows}) }) */ setTimeout(function () { const data = require('../data/shopList'); res.json({code: 200, message: data}) }, 300); }); /** * 获取推荐商品列表 */ router.get('/api/recommendshoplist', (req, res)=>{ // 1.0 获取参数 let pageNo = req.query.page || 1; let pageSize = req.query.count || 20; console.log(pageNo); console.log(pageSize); // 1.1 数据库查询的语句 let sqlStr = 'SELECT * FROM pdd_recommend LIMIT ' + (pageNo - 1) * pageSize + ',' + pageSize; // console.log(sqlStr); conn.query(sqlStr, (err, results) => { if (err) return res.json({code: 1, message: '资料不存在', affextedRows: 0}) res.json({code: 200, data: results,affextedRows: results.affextedRows}) }) /* setTimeout(function () { const data = require('../data/recommend'); res.json({code: 200, message: data}) }, 10); */ }); /* const recommendArr = require('./../data/recommend').data; router.get('/recommend/api', function (req, res, next) { // 1. 定义临时数组 let temp_arr_all = []; // 2. 遍历 for (let i = 0; i < recommendArr.length; i++) { // 2.1 取出单个数据对象 let oldItem = recommendArr[i]; // 2.2 取出数据表中对应的字段 let temp_arr = []; temp_arr.push(oldItem.goods_id); temp_arr.push(oldItem.goods_name); temp_arr.push(oldItem.short_name); temp_arr.push(oldItem.thumb_url); temp_arr.push(oldItem.hd_thumb_url); temp_arr.push(oldItem.image_url); temp_arr.push(oldItem.price); temp_arr.push(oldItem.normal_price); temp_arr.push(oldItem.market_price); temp_arr.push(oldItem.sales_tip); temp_arr.push(oldItem.hd_url); // 2.3 合并到大的数组 temp_arr_all.push(temp_arr); } // console.log(temp_arr_all); // 3. 批量插入数据库表 // 3.1 数据库查询的语句 let sqlStr = "INSERT INTO pdd_recommend(`goods_id`,`goods_name`,`short_name`, `thumb_url`, `hd_thumb_url`, `image_url`, `price`, `normal_price`, `market_price`, `sales_tip`, `hd_url`) VALUES ?"; // 3.2 执行语句 conn.query(sqlStr, [temp_arr_all], (error, results, fields) => { if (error) { console.log(error); console.log('插入失败'); } else { console.log('插入成功'); } }); }); */ /** * 获取推荐商品列表拼单用户 */ router.get('/api/recommenduser', (req, res)=>{ setTimeout(function () { const data = require('../data/recommend_users'); res.json({code: 200, message: data}) }, 10); }); /** * 获取搜索分类列表 */ router.get('/api/searchgoods', (req, res)=>{ setTimeout(function () { const data = require('../data/search'); res.json({code: 200, message: data}) }, 10); }); /** * 获取商品数据 */ router.get('/api/getqalist', (req, res) => { const course = req.query.course; const limit = req.query.limit || 20; const keyword = req.query.keyword || ''; let sqlStr = 'select * from qa where course= "' + course + '" LIMIT ' + limit; if (keyword !== '') { sqlStr = 'select * from qa where course= "' + course + '" AND qname LIKE "%' + keyword + '%" LIMIT ' + limit; } conn.query(sqlStr, (err, results) => { if (err) return res.json({code: 1, message: '资料不存在', affextedRows: 0}); res.json({code: 200, message: results, affextedRows: results.affextedRows}) }) }); //一次性登录验证码 router.get('/api/captcha', (req, res) => { // 1. 生成随机验证码 let captcha = svgCaptcha.create({ color: true, noise: 2, //干扰线条 ignoreChars: '0o1i', size: 4 //大小 }); //console.log(captcha); // 2. 保存到sessions 转小写 req.session.captcha = captcha.text.toLocaleLowerCase(); console.log(req.session.captcha); // 3. 返回客户端 res.type('svg'); res.send(captcha.data); //res.json({code:200,data:captcha.text.toLocaleLowerCase()}) }); //短信验证码 router.get('/api/phone_code', (req, res) => { //获取手机号 let phone = req.query.phone; console.log(phone) //随机验证码 let code = sms_util.randomCode(6) console.log(code) /* sms_util.sendCode(phone, code, function (success) { if(seccess){ //没钱模拟下真实通道 console.log(success); users[phone] = code; res.json({code: 200, message:'验证码获取成功'}) }else{ res.json({code: 0, message:'验证码获取失败'}) } })*/ setTimeout(()=>{ users[phone] = code; res.json({code: 200, message:code,users}) },1000) //res.json({code: 200, message:'验证码获取成功'}) }) //手机验证码登录 router.post('/api/login_code',(req,res,next)=>{ //获取前台数据 const phone = req.body.phone; const code = req.body.code; console.log(users) //res.json({code:200,message:{phone,code}}) //验证验证码 /* if(users[phone] !== code){ res.json({code:0,message:'验证码错误'}) return } */ if(users[phone] !== code){ res.json({code: 0, message: '验证码不正确!'}); } delete users[phone] //删除已经验证过的session中的号码 let sqlStr = `SELECT * FROM pdd_users WHERE user_phone = ${phone} LIMIT 1`; conn.query(sqlStr, (error, results, fields) => { if (error) { res.json({code: 0, message: '请求数据失败'}); } else { results = JSON.parse(JSON.stringify(results)); if (results[0]) { // 用户已经存在 // console.log(results[0]); req.session.userId = results[0].id; // 返回数据给客户端 res.json({ code: 200, message:results[0] }); } else { // 新用户 const addSql = "INSERT INTO pdd_users (user_name, user_phone) VALUES (?, ?)"; const addSqlParams = [phone, phone]; conn.query(addSql, addSqlParams, (error, results, fields) => { //results = JSON.parse(JSON.stringify(results)); // console.log(results); if(!error){ req.session.userId = results.insertId; let sqlStr = "SELECT * FROM pdd_users WHERE id = '" + results.insertId + "' LIMIT 1"; conn.query(sqlStr, (error, results, fields) => { if (error) { res.json({code: 0, message: '请求数据失败'}); } else { results = JSON.parse(JSON.stringify(results)); // 返回数据给客户端 res.json({ code: 200, message:results[0] }); } }); } }); } } }); }) //用户名密码登录 router.post('/api/login_pwd',(req,res,next)=>{ //获取前台数据 const user_name = req.body.user_name; const password = md5(req.body.pwd); const captcha = req.body.captcha.toLowerCase(); console.log(user_name,password,captcha) //验证图形验证码 //console.log(captcha, req.session.captcha, req.session); /* if(captcha !== req.session.captcha){ res.json({code:1,message:'图形验证码错误'}) } delete req.session.captcha*/ let sqlStr = `SELECT * FROM pdd_users WHERE user_name = '${user_name}' LIMIT 1`; conn.query(sqlStr, (error, results, fields) => { if (error) { res.json({code: 0, message: '用户名错误'}); } else { results = JSON.parse(JSON.stringify(results)); if (results[0]) { // 用户已经存在 //验证密码 console.log(password,results[0].password) if(results[0].password !== <PASSWORD>){ res.json({code: 0, message: '密码错误'}); }else{ req.session.userId = results[0].id; // 返回数据给客户端 res.json({ code: 200, message: {id: results[0].id, user_name: results[0].user_name, user_phone: results[0].user_phone} }); } } else { // 新用户 const addSql = "INSERT INTO pdd_users (user_name,password) VALUES (?, ?)"; const addSqlParams = [user_name, password]; conn.query(addSql, addSqlParams, (error, results, fields) => { //results = JSON.parse(JSON.stringify(results)); // console.log(results); if(!error){ req.session.userId = results.insertId; let sqlStr = "SELECT * FROM pdd_users WHERE id = '" + results.insertId + "' LIMIT 1"; conn.query(sqlStr, (error, results, fields) => { if (error) { res.json({code: 0, message: '请求数据失败'}); } else { results = JSON.parse(JSON.stringify(results)); // 返回数据给客户端 res.json({ code: 200, message: {id: results[0].id, user_name: results[0].user_name, user_phone: results[0].user_phone} }); } }); } }); } } }); }) /* * 根据session中的用户id获取用户信息 * */ router.get('/api/user_info', (req, res) => { // 1.0 获取参数 let userId = req.session.userId; // 1.1 数据库查询的语句 console.log(userId) let sqlStr = "SELECT * FROM pdd_users WHERE id = '" + userId + "' LIMIT 1"; conn.query(sqlStr, (error, results, fields) => { if (error) { res.json({err_code: 0, message: '请求数据失败'}); } else { results = JSON.parse(JSON.stringify(results)); if(!results[0]){ delete req.session.userId; res.json({error_code: 1, message: '请先登录'}); }else { // 返回数据给客户端 res.json({ success_code: 200, message: {id: results[0].id, user_name: results[0].user_name, user_phone: results[0].user_phone} }); } } }); }); //修改用户信息接口 router.post('/api/change_user', (req, res) => { // 1. 获取数据 const id = req.body.user_id; const user_name = req.body.user_name || ''; const user_sex = req.body.user_sex || ''; const user_address = req.body.user_address || ''; const user_birthday = req.body.user_birthday || ''; const user_sign = req.body.user_sign || ''; console.log(id,user_name) // 2. 验证 if (!id) { res.json({err_code: 0, message: '修改用户信息失败!'}); } // 3. 更新数据 let sqlStr = "UPDATE pdd_users SET user_name = ? , user_sex = ?, user_address = ?, user_birthday = ?, user_sign = ? WHERE id = " + id; let strParams = [user_name, user_sex, user_address, user_birthday, user_sign]; conn.query(sqlStr, strParams, (error, results, fields) => { if (error) { res.json({err_code: 0, message: '修改用户信息失败!'}); } else { res.json({success_code: 200, message: '修改用户信息成功!'}); } }); }) router.post('/api/add_shop_cart', (req, res) => { // 1. 验证用户 /* let user_id = req.body.user_id; if(!user_id || user_id !== req.session.userId){ res.json({err_code:0, message:'非法用户'}); return; } */ // 2. 获取客户端传过来的商品信息 let goods_id = req.body.goods_id; let goods_name = req.body.goods_name; let thumb_url = req.body.thumb_url; let price = req.body.price; let buy_count = 1; let is_pay = 0; // 0 未购买 1购买 // 3. 查询数据 let sql_str = "SELECT * FROM pdd_cart WHERE goods_id = '" + goods_id + "' LIMIT 1"; conn.query(sql_str, (error, results, fields) => { if (error) { res.json({err_code: 0, message: '服务器内部错误!'}); } else { results = JSON.parse(JSON.stringify(results)); // console.log(results); if (results[0]) { // 3.1 商品已经存在 //console.log(results[0]); let buy_count = results[0].buy_count + 1; let sql_str = "UPDATE pdd_cart SET buy_count = " + buy_count + " WHERE goods_id = '" + goods_id + "'"; conn.query(sql_str, (error, results, fields) => { if (error) { res.json({err_code: 0, message: '加入购物车失败!'}); } else { res.json({success_code: 200, message: '加入购物车成功!'}); } }); } else { // 3.2 商品不存在 let add_sql = "INSERT INTO pdd_cart(goods_id, goods_name, thumb_url, price, buy_count, is_pay) VALUES (?, ?, ?, ?, ?, ?)"; let sql_params = [goods_id, goods_name, thumb_url, price, buy_count, is_pay]; conn.query(add_sql, sql_params, (error, results, fields) => { if (error) { res.json({err_code: 0, message: '加入购物车失败!'}); } else { res.json({success_code: 200, message: '加入购物车成功!'}); } }); } } }); }); /** * 查询购物车的商品 */ router.get('/api/cart_goods', (req, res) => { // 1.0 获取参数 /* if(!req.session.userId){ res.json({err_code: 0, message: '请先登录!'}); return; } */ // 1.1 数据库查询的语句 let sqlStr = "SELECT * FROM pdd_cart"; conn.query(sqlStr, (error, results, fields) => { if (error) { res.json({err_code: 0, message: '请求数据失败'}); } else { // 返回数据给客户端 res.json({success_code: 200, message: results}); } }); }); module.exports = router;
c3e4d62d927a16ae55be07abcd20b5be6b1055b4
[ "JavaScript" ]
1
JavaScript
jf0508/pddServer
d7b52cc043cc5a60c876dfed467b6ebfbe8cdb9d
5f006f54e85582247e22cff48b0d89ef82ef2ddf
refs/heads/master
<repo_name>zxteloiv/problem-reservoir<file_sep>/prs/views/templates/header.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?><!DOCTYPE html> <html lang="zh_CN"> <head> <meta charset="utf-8"> <title><?php echo $title; ?></title> <link rel="stylesheet" href="assets/css/bootstrap.min.css" media="all"> <link rel="stylesheet" href="assets/css/bootstrap-theme.min.css" media="all"> <style> .vcenter { display: inline-block; vertical-align: middle; float: none; } .cover-container { margin-right: auto; margin-left: auto; } .inner { padding: 30px; } .cover { padding: 0 20px; } .cover .btn-lg { padding: 10px 20px; font-weight: bold; } </style> </head> <body> <nav class="navbar navbar-default navbar-static-top"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="/prs">首页</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li <?php if ($active_title == 'query') echo 'class="active"'; ?>><a href="query">查询题目</a></li> <li <?php if ($active_title == 'add') echo 'class="active"'; ?>><a href="add">增加题目</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <file_sep>/prs/models/problemOp.php <?php class ProblemOp extends CI_Model { const DELETE_PID_NOT_FOUND = 5001; const DELETION_FAILED = 5002; const EMPTY_PROBLEM_PARAM = 5003; const INSERTION_FAILED = 5004; const EMPTY_UPDATE_ID = 5005; const CONTENT_JSON_INVALID = 5006; const PAGE_PROBLEM_SIZE = 10; function __construct() { parent::__construct(); $this->db = $this->load->database('prs', true); $this->load->helper('utils'); date_default_timezone_set('Asia/Shanghai'); } function getProblemByID($pid) { $sql = 'select * from problems where '. 'problem_id = '. $this->db->escape($pid); $results = $this->db->query($sql); // nothing in the database if ($results === false || $results->num_rows() < 1) { return array(); } $problems = array(); foreach ($results->result_array() as $problem) { //$problems[$problem['problem_id']] = $problem; $problem['pid'] = $problem['problem_id']; unset($problem['problem_id']); $problem['content'] = json_decode($problem['content']); $problems[] = $problem; } return $problems; } function doCreation($param) { if (empty($param['content'])) { echo outputError(self::EMPTY_PROBLEM_PARAM, 'problem content is empty'); return; } $this->set_val_if_not_empty($param, 'content'); $this->set_val_if_not_empty($param, 'course'); $this->set_val_if_not_empty($param, 'chapter'); $this->set_val_if_not_empty($param, 'difficulty'); $this->set_val_if_not_empty($param, 'description'); $this->set_val_if_not_empty($param, 'points'); $this->set_val_if_not_empty($param, 'keypoints'); $this->db->set('create_time', date('Y-m-d H:i:s')); $this->db->set('modify_time', date('Y-m-d H:i:s')); $rtn = $this->db->insert('problems'); if ($rtn) { $pid = $this->db->insert_id(); echo json_encode(array('errno' => 0, 'errmsg' => 'create success', 'pid' => $pid)); } else { echo outputError(self::INSERTION_FAILED, 'failed to create'); } return; } function doUpdating($param) { if (empty($param['pid'])) { echo outputError(self::EMPTY_UPDATE_ID, 'problem id is empty'); return; } $this->set_val_if_not_empty($param, 'content'); $this->set_val_if_not_empty($param, 'course'); $this->set_val_if_not_empty($param, 'chapter'); $this->set_val_if_not_empty($param, 'difficulty'); $this->set_val_if_not_empty($param, 'description'); $this->set_val_if_not_empty($param, 'points'); $this->set_val_if_not_empty($param, 'keypoints'); $this->db->set('modify_time', date('Y-m-d H:i:s')); $this->db->where('problem_id', $param['pid'], true); $rtn = $this->db->update('problems'); if ($rtn) { echo json_encode(array('errno' => 0, 'errmsg' => 'update success', 'affected_rows' => $this->db->affected_rows() )); } else { echo outputError(self::UPDATE_FAILED, 'failed to update'); } return; } function set_val_if_not_empty($param, $key) { if (!empty($param[$key])) { $this->db->set($key, $param[$key], true); } } function doQuery($param) { if (!empty($param['course'])) { $this->db->where('course', $param['course'], true); } if (!empty($param['chapter'])) { $this->db->where('chapter', $param['chapter'], true); } if (!empty($param['keypoints'])) { $this->db->where('keypoints', $param['keypoints'], true); } if (!empty($param['difficulty'])) { $this->db->where('difficulty', $param['difficulty'], true); } if (!empty($param['points'])) { $this->db->where('points', $param['points'], true); } if (!empty($param['description'])) { $this->db->like('description', $param['description'], 'both', true); } $num = $this->db->count_all_results('problems', false); $pagenum = intval($num / self::PAGE_PROBLEM_SIZE) + 1; // page num starts from 1 $page = intval(empty($param['page']) ? 1 : $param['page']); $offset = ($page - 1) * self::PAGE_PROBLEM_SIZE; if ($offset < 0) $offset = 0; $this->db->select('*'); $query = $this->db->get(null, self::PAGE_PROBLEM_SIZE, $offset); $data = array(); foreach ($query->result() as $row) { $content = json_decode($row->content, true); if ($content === null) { echo outputError(self::CONTENT_JSON_INVALID, 'content has illegal json'); return; } $data[] = array( 'pid' => $row->problem_id, 'points' => $row->points, 'course' => $row->course, 'chapter' => $row->chapter, 'keypoints' => $row->keypoints, 'difficulty' => $row->difficulty, 'description' => $row->description, 'content' => $content, 'create_time' => $row->create_time, 'modify_time' => $row->modify_time ); } $rtn = array( 'errno' => 0, 'errmsg' => 'success', 'data' => $data, 'pagenum' => $pagenum, 'pageid' => $page ); echo json_encode($rtn); } function doDeletion($param) { if (!isset($param['pid'])) { echo outputError(self::DELETE_PID_NOT_FOUND, 'unknown key to delete'); return; } $pid = $param['pid']; $this->db->where('problem_id', $pid, true); $rtn = $this->db->delete('problems'); // it may be wiser to delete attachments later on in maintaining process if ($rtn && $this->db->affected_rows() > 0) { echo json_encode(array( 'errno' => 0, 'errmsg' => 'delete success')); } else { echo outputError(self::DELETION_FAILED, 'failed to execute deletion'); } return; } } <file_sep>/prs/views/query.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <div class="container"> <div class="page-header"> <p class="lead">题目筛选查询</p> </div> <div class="panel panel-primary"> <div class="panel-heading">筛选条件(留空或为0时不用作筛选)</div> <div class="panel-body " id="filters"> <div class="row"> <div class="col-md-3"> <label for="course">科目:</label> <select class="form-control" id="course"> <option value="自动控制原理" selected>自动控制原理</option> <option value="智能控制系统">智能控制系统</option> </select> </div> <div class="col-md-3"> <label for="chapter">章节:</label> <input type="text" value="" id="chapter" class="form-control"/> </div> <div class="col-md-3"> <label for="keypoints">知识点:</label> <input type="text" value="" id="keypoints" class="form-control"/> </div> <div class="col-md-3"> <label for="description">备注含有</label> <input type="text" id="description" class="form-control"/> </div> </div> <div class="row"> <div class="col-md-3 vcenter"> <label for="points">分值:</label> <input type="number" value="0" id="points" class="form-control"/> </div><!-- the comment is to prevent any blocks to appear --><div class="col-md-3 vcenter"> <label for="difficulty">难度:</label> <select id="difficulty" class="form-control"> <option value="0" selected ></option> <option value="10" >容易</option> <option value="30" >普通</option> <option value="50" >较难</option> <option value="70" >很难</option> </select> </div><!-- --><div class="col-md-3 vcenter"> <label for="pid" >题目ID:</label> <input id="pid" value="" type="text" class="form-control" /> </div><!-- --><div class="col-md-3 vcenter"> <button class="btn btn-default" id="reset">清空</button> <button class="btn btn-success" id="search">查询</button> </div> </div> </div> </div> <div id="result_container" class="hidden"> <table class="table table-striped table-bordered" id="query_result"> <caption>查询结果</caption> <thead> <tr> <td class="col-md-1 text-center">#</td> <td class="col-md-3 text-center">属性</td> <td class="col-md-6 text-center">内容</td> <td class="col-md-2 text-center">操作</td> </tr> </thead> <tbody> </tbody> </table> <nav> <ul class="pagination" id="pagination"> <li> <a href='#'> <span>&laquo;</span> </a> </li> <li><a href="#">1</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </nav> <input type="hidden" value="" id="querypage" /> </div> <div class="panel panel-info"> <div class="panel-heading">所选题目 </div> <p id="summary" class="hidden">summary:<span id="summary_points"></span></p> <div class="panel-body" id="select_problems_content"> </div> </div> </div> <script src="assets/js/jquery-1.11.3.min.js"></script> <script src="assets/js/query-page.js"></script> <file_sep>/docs/database.sql -- phpMyAdmin SQL Dump -- version 4.5.0.2 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: 2015-12-01 13:08:27 -- 服务器版本: 10.0.17-MariaDB -- PHP Version: 5.6.14 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `prs` -- CREATE DATABASE IF NOT EXISTS `prs` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE `prs`; -- -------------------------------------------------------- -- -- 表的结构 `img_attachment` -- CREATE TABLE `img_attachment` ( `img_id` int(10) UNSIGNED NOT NULL COMMENT '图片id', `img_name` varchar(50) NOT NULL DEFAULT '''''' COMMENT '图片名', `img_type` varchar(25) NOT NULL DEFAULT '''''' COMMENT '图片类型(MIME)', `img_size` varchar(20) NOT NULL DEFAULT '''''' COMMENT '图片大小', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '文件提交时间', `img` mediumblob NOT NULL COMMENT '图片内容' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- 表的结构 `problems` -- CREATE TABLE `problems` ( `problem_id` int(10) UNSIGNED NOT NULL, `course` varchar(50) NOT NULL DEFAULT '''''' COMMENT '所属课程', `chapter` varchar(50) NOT NULL DEFAULT '''''' COMMENT '所属章节', `points` smallint(5) UNSIGNED NOT NULL DEFAULT '0' COMMENT '分值,单位为0.1分', `difficulty` tinyint(3) UNSIGNED NOT NULL DEFAULT '0' COMMENT '题目难度', `description` varchar(255) NOT NULL DEFAULT '''''' COMMENT '其它描述', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间', `modify_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间', `content` longtext NOT NULL COMMENT '内容,json串,list of primitives', `keypoints` varchar(255) NOT NULL DEFAULT '''''' COMMENT '知识点', `states` tinyint(3) UNSIGNED NOT NULL DEFAULT '0' COMMENT '问题状态, 0:正常, 1:图片附件失效, etc.', `years` varchar(50) NOT NULL DEFAULT '' COMMENT '考试年份', `backup1` varchar(200) NOT NULL DEFAULT '' COMMENT '补充1', `backup2` varchar(200) NOT NULL DEFAULT '' COMMENT '补充2' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='题库表'; -- -- Indexes for dumped tables -- -- -- Indexes for table `img_attachment` -- ALTER TABLE `img_attachment` ADD PRIMARY KEY (`img_id`); -- -- Indexes for table `problems` -- ALTER TABLE `problems` ADD PRIMARY KEY (`problem_id`), ADD KEY `modify_time` (`modify_time`), ADD KEY `course` (`course`), ADD KEY `chapter` (`chapter`), ADD KEY `keypoints` (`keypoints`), ADD KEY `course_2` (`course`,`chapter`,`points`), ADD KEY `course_3` (`course`,`chapter`,`difficulty`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `img_attachment` -- ALTER TABLE `img_attachment` MODIFY `img_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '图片id'; -- -- AUTO_INCREMENT for table `problems` -- ALTER TABLE `problems` MODIFY `problem_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/prs/helpers/utils_helper.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); if (!function_exists('outputError')) { function outputError($errno, $errmsg) { $rtn = array( 'errno' => $errno, 'errmsg' => $errmsg ); return json_encode($rtn); } } <file_sep>/prs/assets/js/query-page.js /*! * Script for the Add Page. */ if (typeof jQuery === 'undefined') { throw new Error('jQuery must be included before.') } // Bind function to reset button: // Reset all control value +function($) { $('#reset').click(function(evt){ $('#chapter').val(''); $('#keypoints').val(''); $('#description').val(''); $('#points').val(0); $('#difficulty option:eq(0)').prop('selected', true); $('#pid').val(''); }); $('#filters').change(function(){ $('#querypage').val(''); }); }(jQuery); // Bind function to search button: // Build a query parameter and send it to API using ajax. var handleSearchClick = function(evt) { doSearch(); }; var doSearch = function() { var raw_params = { course: $('#course').val(), chapter: $('#chapter').val(), keypoints: $('#keypoints').val(), difficulty: parseInt($('#difficulty').val()), description: $('#description').val(), points: parseInt($('#points').val()), page: parseInt($('#querypage').val()) }; var params = {}; for (var k in raw_params) { if (!raw_params[k]) { continue; }; params[k] = raw_params[k]; } var pid = $('#pid').val(); if (pid && !jQuery.isEmptyObject(params)) { alert('其他条件与题目ID同时使用时将视为无效'); params = {pid: pid}; } jQuery.ajax('problem/search', { method: "POST", dataType: "json", data: params, success: onSearchAjaxSuccess, error: onSearchAjaxError }); }; var onSearchAjaxError = function(jqXHR, state, err) { alert(state + ":" + err); }; var onSearchAjaxSuccess = function(data, state, jqXHR) { if (!data || ['errno', 'errmsg', 'pageid', 'pagenum', 'data'].map(function(val){ return !(val in data); }).reduce(function(prevVal, curVal){ return (prevVal || curVal); })) { alert('服务器返回错误结果'); return; } if (data['errno'] > 0) { alert(data['errno'] + ":" + data['errmsg']); return; } initQueryResult(data['data']); initPagination(data['pageid'], data['pagenum']); }; var initQueryResult = function(data) { var dataTable = $('#query_result').find('tbody'); dataTable.html('').removeClass('hidden'); for (var i in data) { var problem = data[i]; var row = $('<tr>'); var id = $('<td>').addClass('col-md-1').text(problem['pid']); var prop = $('<td>').addClass('col-md-3'); var content = $('<td>').addClass('col-md-6').css('max-width', '100%'); var op = $('<td>').addClass('col-md-2'); initProblemProperties(problem, prop); initProblemContent(problem, content); initOperationButton(problem, op); row.append(id); row.append(prop); row.append(content); row.append(op); dataTable.append(row); }; }; var initOperationButton = function(problem, op) { var pid = problem['pid']; var points = problem['points']; var del_btn = $('<button>') .addClass('btn btn-danger') .attr('del_pid', pid) .append($('<span>').addClass('glyphicon glyphicon-remove').text('删除')) .click(handleDelBtnClick) ; var select_btn = $('<button>') .addClass('btn btn-success') .attr('select_pid', pid) .attr('points', points) .append($('<span>').addClass('glyphicon glyphicon-ok').text('选中')) .click(handleSelectBtnClick) ; var group = $('<div>') .addClass('btn-group') .attr('role', 'group') .append(del_btn).append(select_btn) ; op.append(group); }; var handleDelBtnClick = function(evt) { var del_btn = $(this); if (!confirm('确定从题库中删除此题吗?')) { return; } var row = del_btn.closest('tr'); var pid = del_btn.attr('del_pid'); $.ajax('problem/del', { method: 'POST', dataType: 'json', data: {pid: pid}, success: function(data, state, jqXHR) { if (!data || !('errno' in data) || !('errmsg' in data)) { alert('服务器连接失败'); return; } if (data['errno'] > 0) { alert(data['errno'] + ":" + data['errmsg']); return; } row.remove(); }, error: function(jqXHR, state, err) { alert(state + ":" + err); return; } }); }; var handleSelectBtnClick = function(evt) { var select_btn = $(this); var pid = select_btn.attr('select_pid'); var problem_points = parseInt(select_btn.attr('points')); var row = select_btn.closest('tr'); var new_row = $('<div>').addClass('row') .attr('pid', pid).attr('points', problem_points); var summary = $('#summary').removeClass('hidden'); var points = parseInt($('#summary_points').text()); if (!points) { points = 0; } if (!problem_points) { problem_points = 0; } points += problem_points; $('#summary_points').text(points); var contents = row.find('img'); contents.detach().after($('<br/>')); new_row.append(contents); $('#select_problems_content').append(new_row).append($('<hr/>')); row.remove(); }; var initProblemContent = function(problem, content) { if (!('content' in problem) || !problem['content']) { return; } for (var i in problem['content']) { var primitive = problem['content'][i]; if (!('type' in primitive) || !primitive['type']) { continue; } if (primitive['type'] == 'image') { if (!('img_id' in primitive) || !primitive['img_id']) { continue; } img_id = primitive['img_id']; if (content.children().length > 0) {content.append($('<br/>'));} content.append($('<img>').addClass('img-responsive') .css('max-width', '500px') .attr('src', 'img/loadImg/' + img_id)); } } }; var initProblemProperties = function(problem, prop) { if ('course' in problem && problem['course'] && problem['course'] != "") { if (prop.children().length > 0) prop.append($('<br/>')); prop.append($('<span>').text(problem['course'])) } if ('chapter' in problem && problem['chapter'] && problem['chapter'] != "") { if (prop.children().length > 0) prop.append($('<br/>')); prop.append($('<span>').text(problem['chapter'])) } if ('keypoints' in problem && problem['keypoints'] && problem['keypoints'] != "") { if (prop.children().length > 0) prop.append($('<br/>')); prop.append($('<span>').text(problem['keypoints'])) } if ('difficulty' in problem && problem['difficulty'] && problem['difficulty'] != "") { if (prop.children().length > 0) prop.append($('<br/>')); prop.append($('<span>').text('难度:' + problem['difficulty'])); } if ('points' in problem && problem['points'] && problem['points'] != "") { if (prop.children().length > 0) prop.append($('<br/>')); prop.append($('<span>').text('分值:' + problem['points'])); } }; var initPagination = function(pageid, pagenum) { var pagination = $('#pagination').html(''); if (pageid <= 0 || pagenum <= 0 || pageid > pagenum) { $('result_container').addClass('hidden'); return; } pageid = parseInt(pageid); pagenum = parseInt(pagenum); if (pageid > 1) { var previous = $('<li>').append($('<a>').attr('pageid', pageid - 1).append( $('<span>').addClass('glyphicon-backward glyphicon') )); previous.click(getHandlerOnPageClick(pageid - 1)); pagination.append(previous); } var candidate = [pageid - 4, pageid - 3, pageid - 2, pageid - 1, pageid, pageid + 1, pageid + 2, pageid + 3, pageid + 4]; for (var val in candidate) { if (val < 1 || pagenum < val) { continue; } var page = $('<li>').append($('<a>').attr('pageid', val).text(val)); page.click(getHandlerOnPageClick(val)); if (pageid == val) { page.addClass('active'); } pagination.append(page); }; if (pageid < pagenum) { var next = $('<li>').append( $('<a>').attr('pageid', pageid + 1).append( $('<span>').addClass('glyphicon-forward glyphicon') )); next.click(getHandlerOnPageClick(pageid + 1)); pagination.append(next); } $('#result_container').removeClass('hidden'); }; var getHandlerOnPageClick = function(desired_page) { return function(evt) { var page = $(this); $('#querypage').val(desired_page); doSearch(); }; }; +function($) { $('#search').click(handleSearchClick); }(jQuery); <file_sep>/prs/views/debug.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <div> <?php echo $msg; ?> </div> <br/> <file_sep>/prs/controllers/problem.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Problem extends CI_Controller { function __construct() { parent::__construct(); $this->get = $this->input->get(); $this->post = $this->input->post(); $this->load->model('ProblemOp'); } public function index() { return; } public function search() { if (isset($this->post['pid'])) { $this->byID($this->post['pid']); return; } $this->ProblemOp->doQuery($this->post); } public function byID($pid) { $data = $this->ProblemOp->getProblemByID($pid); if (empty($data)) { echo json_encode(array('errno' => 0, 'errmsg' => 'success', 'data' => array(), 'pageid' => 0, 'pagenum' => 0)); return; } echo json_encode(array('errno' => 0, 'errmsg' => 'success', 'data' => $data, 'pageid' => 1, 'pagenum' => 1 )); } public function byIDs($list) { echo json_encode(array('errno' => 233, 'errmsg' => 'not implemented')); } public function create() { $this->ProblemOp->doCreation($this->post); } public function update() { $this->ProblemOp->doUpdating($this->post); } public function del() { $this->ProblemOp->doDeletion($this->post); } } <file_sep>/README.md # problem-reservoir A CRUD system designed to help teachers compile a test. ## How to Use This system needs PHP and CodeIgniter. It is deployed using Nginx but it will run under any PHP server theoretically. The CodeIgniter version 3.0.2 code is also distributed here. You must copy prs and system folders to your own web root. Further configuration can be modified in the `prs/index.php` file, which may allow you to put these two folders somewhere else. Access the home page by something like `http://localhost/prs/`. ## Others Here're some Chinese intro notes to my advisor. > 这个题库系统初版支持题目录入和按需查询功能。包括服务端和客户端两个部分。 > 服务端系统以 API 为核心,以 PHP 和 Nginx 实现了类似 RESTful 风格的 HTTP 接口,用于与客户端交互。 > 服务端使用了流行的 MVC 架构,代码之间实现了低耦合,便于扩充新的功能。后台存储使用 MySQL 关系数据库,保存了题库的各项属性和题目内容,必要时部分内容可改用更高效的 KV 系统。 > 客户端使用了 HTML5 和 JavaScript 做用户交互,方便跨平台使用。由于均为静态内容,可以使用 CDN 加速访问,或与服务端独立部署。 > <file_sep>/prs/models/image.php <?php class Image extends CI_Model { function __construct() { parent::__construct(); $this->db = $this->load->database('prs', true); } function getImageByID($img_id){ $results = $this->db->query('select * from img_attachment where '. 'img_id = "'. $this->db->escape($img_id) . '"' ); // nothing in the database if ($results === false || $results->num_rows() < 1) { return array(); } $images = array(); foreach ($results->result_array() as $image) { $images[$image['problem_id']] = $image; } return $problems; } function getImgAttrByID($img_id) { $results = $this->db->query( 'select img_id, img_name, img_type, img_size, create_time' . 'from img_attachment where ' . 'img_id = "'. $this->db->escape($img_id) . '"' ); if ($results == false || $results->num_rows() != 1) { return array(); } return $results->row_array(); } function getRawImageByID($img_id) { $sql = 'select img from img_attachment where img_id = '. $this->db->escape($img_id); $results = $this->db->query($sql); if ($results == false || $results->num_rows() != 1) { return null; } return $results->row()->img; } } <file_sep>/prs/views/welcome_message.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <div class="cover-container"> <div class="inner cover"> <h1 class="cover-heading">欢迎使用题库系统.</h1> <p class="lead">通过录入题目和题目的不同属性,来实现试题的便捷管理。使用不同的筛选条件,使得组卷变得更加容易。</p> <p class="lead"> <a class="btn btn-lg btn-default" href="query">查询题目</a> </p> </div> <div class="mastfoot"> <div class="inner"> <p>Made by <a href="http://getbootstrap.com/">Bootstrap</a> Copyright 2015 </p> </div> </div> </div> <file_sep>/prs/views/add.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <div class="container"> <div class="page-header"> <p class="lead">录入新的题目</p> </div> <div class="panel panel-primary"> <div class="panel-heading">题目属性</div> <div class="panel-body"> <div class="row"> <div class="col-md-4"> <label for="course">科目:</label> <select class="form-control" id="course"> <option value="1">自动控制原理</option> <option value="2">智能控制系统</option> </select> </div> <div class="col-md-4"> <label for="chapter">章节:</label> <input type="text" value="" id="chapter" class="form-control"/> </div> <div class="col-md-4"> <label for="keypoints">知识点:</label> <input type="text" value="" id="keypoints" class="form-control"/> </div> </div> <div class="row"> <div class="col-md-4"> <label for="points">分值:</span> <input type="number" value="5" id="points" class="form-control"/> </div> <div class="col-md-4"> <label for="difficulty">难度:</label> <select id="difficulty" class="form-control"> <option value="10" >容易</option> <option value="30" selected>普通</option> <option value="50" >较难</option> <option value="70" >很难</option> </select> </div> </div> </div> </div> <div class="panel panel-primary"> <div class="panel-heading">题目内容</div> <div class="panel-body"> <div class="row"> <label for="description">简单描述:</label> <textarea class="form-control" rows="3" id="description"></textarea> </div> <div class="row"> <label>上传题目截图:(多张图片时需要按顺序选择)</label> <button id="new-pic" class="btn btn-primary hidden">新增一张图</button> </div> <div id="problem-contents" class="row"> <div class="row form-group"> <div class="col-md-4"> <input type="file" name="file0" id="file0"/> </div> <div class="col-md-6"> <img id="thumb0" class="problem-img img-thumbnail hidden" /> </div> </div> <div class="row form-group"> <div class="col-md-4"> <input type="file" name="file1" id="file1"/> </div> <div class="col-md-6"> <img id="thumb1" class="problem-img img-thumbnail hidden" /> </div> </div> <div class="row form-group"> <div class="col-md-4"> <input type="file" name="file2" id="file2"/> </div> <div class="col-md-6"> <img id="thumb2" class="problem-img img-thumbnail hidden" /> </div> </div> <div class="row form-group"> <div class="col-md-4"> <input type="file" name="file3" id="file3"/> </div> <div class="col-md-6"> <img id="thumb3" class="problem-img img-thumbnail hidden" /> </div> </div> </div> </div> </div> <button id="submit_btn" class="btn btn-success">提交</button> </div> <script src="assets/js/jquery-1.11.3.min.js"></script> <script src="assets/js/add-page.js"></script> <file_sep>/prs/models/saveImg.php <?php class SaveImg extends CI_Model { const INPUT_KEY_NOT_SET = 4001; const FILE_COUNT_INCONSISTENT = 4002; const FILE_KEY_NOT_SET = 4003; const FILE_JSON_NOT_VALID = 4004; const FILE_SIZE_INCONSISTENT = 4005; const DB_INSERTION_FAILURE = 4006; function __construct() { parent::__construct(); $this->db = $this->load->database('prs', true); $this->load->helper('utils'); } function do_the_job($param) { $this->post = $param; // 1. decode param and check if it's valid $rtn = $this->decodeFilesParam(); if (!$rtn) { return; } $rtn = $this->isValidParam($this->post); if (!$rtn) { return; } // 2. iterate over file $img_queue = array(); // mutable var, will be passed as reference later $rtn = $this->putImgToQueue($img_queue); if (!$rtn) { return; } // 3. save all files $this->db = $this->load->database('prs', true); $rtn = $this->insertImgs($img_queue); if ($rtn) { $this->outputSuccess($img_queue); return; } fastcgi_finish_request(); // user interaction ends here // ----------------------------------------------------------------- // background task starts here $this->rollbackInsertedImg($files); return; } function outputSuccess($img_queue) { $rtn = array(); $rtn['errno'] = 0; $rtn['errmsg'] = 'success'; $rtn['idmap'] = array(); for ($i = 0; $i < count($img_queue); $i++) { $rtn['idmap'][] = array( 'name' => $img_queue[$i]['name'], 'id' => $img_queue[$i]['saved_id'], ); } $json_str = json_encode($rtn); echo $json_str; return; } function rollbackInsertedImg($files) { foreach ($files as $file) { if ($file['saved_id'] > 0) { $this->db->delete('img_attachment', array('img_id' => $file['saved_id'])); } } } function insertImgs(&$files) { $this->db = $this->load->database('prs', true); foreach ($files as &$file) { $data = array( 'img_name' => $file['name'], 'img_size' => $file['size'], 'img_type' => $file['type'], 'create_time' => date('Y-m-d H:i:s'), 'img' => $file['content'] ); $rtn = $this->db->insert('img_attachment', $data, true); if (!$rtn) { echo outputError(self::DB_INSERTION_FAILURE, 'failed to insert db'); return false; } $file['saved_id'] = $this->db->insert_id(); } return true; } function decodeFilesParam() { if (!isset($this->post['files'])) { echo outputError(self::INPUT_KEY_NOT_SET, 'input key missing'); return false; } $decoded_files = json_decode($this->post['files'], true); if ($decoded_files === null) { echo outputError(self::FILE_JSON_NOT_VALID, 'file json is not valid'); return false; } $this->post['files'] = $decoded_files; return true; } function putImgToQueue(&$img_queue) { foreach ($this->post['files'] as $file) { if (!$this->isValidFile($file)) { return false; } $content = base64_decode($file['content']); // add to the file queue $img_queue[] = array( 'name' => $file['name'], 'size' => $file['size'], 'type' => $file['type'], 'saved_id' => 0, 'content' => $content ); } return true; } function isValidFile($file) { if (!(isset($file['name']) && isset($file['size']) && isset($file['type']) && isset($file['content']))) { echo outputError(self::FILE_KEY_NOT_SET, 'file param is not set correctly'); return false; } return true; } function isValidParam($param) { if (!isset($param['filecount']) || !isset($param['files'])) { echo outputError(self::INPUT_KEY_NOT_SET, 'param is not valid'); return false; } if (intval($param['filecount']) != count($param['files'])) { echo outputError(self::FILE_COUNT_INCONSISTENT, 'file count inconsistent'); return false; } return true; } } <file_sep>/prs/assets/js/add-page.js /*! * Script for the Add Page. */ if (typeof jQuery === 'undefined') { throw new Error('jQuery must be included before.') } var g_problem = {}; var g_files = {}; var g_fileReaders = {}; // initialization: // in case which we may load items by using AJAX API // and fill in all the options of controls in the DOM +function($) { }(jQuery); // Bind function to file controls // Show thumbnail in the img control var handleFileChange = function(evt) { if (this.files.length !== 1) { return; } // find id: for file0, file1, ..., fileN => IDs are 0, 1, ..., N var re = new RegExp(/\d+/g); var arr = re.exec($(this).attr('id')); if (!arr) { return; } var id = parseInt(arr[0]); var file = this.files[0]; var reader = new FileReader(); g_files[id] = file; g_fileReaders[id] = reader; reader.onload = (function(theFile, id) { return function(e) { // Render thumbnail. $('#thumb' + id) .attr('src', e.target.result) .attr('title', encodeURI(theFile.name)) .removeClass('hidden'); }; })(file, id); reader.readAsDataURL(file); }; +function($) { $('#problem-contents') .find('input:file') .change(handleFileChange); }(jQuery); // Bind submit function to the button // do the submit var saveImg = function() { var files_data = []; var max_file_now = $('#problem-contents').find('input:file').length; for (var id = 0; id < max_file_now; id++) { if (!g_files[id]) continue; var img_obj = $('#thumb' + id); if (!img_obj) continue; var dataurl = img_obj.attr('src'); if (!dataurl) continue; var file = { name: g_files[id].name, size: g_files[id].size, type: g_files[id].type, content: extractBase64PartFromDataUrl(dataurl) }; files_data.push(file); } // save img files first $.ajax('img/save', { method: "POST", dataType: 'json', data: { filecount: files_data.length, files: JSON.stringify(files_data) }, success: function(data, state, jqXHR) { if (!data || !('errno' in data) || !('idmap' in data)) { alert('上传失败'); return; } if (data['errno'] > 0) { alert(data['errno'] + ":" + data['errmsg']); return; } saveProblem(data['idmap']); }, error: function(jqXHR, state, err) { alert(state + ":保存图片失败\n" + err); } }); }; var saveProblem = function(idmap) { // As the database stores course as varchar, we use the text instead of value. var course = $('#course option:selected').text(); var chapter = $('#chapter').val(); var keypoints = $('#keypoints').val(); var points = $('#points').val(); var difficulty = $('#difficulty').val(); var description = $('#description').val(); // currently we only have pictures in problem content var content = []; for (var i = 0; i < idmap.length; i++) { var img_id = idmap[i]['id']; var primitive = { type: 'image', img_id: img_id }; content.push(primitive); } var data = { course: course, chapter: chapter, keypoints: keypoints, description: description, points: points, difficulty: difficulty, content: JSON.stringify(content) }; $.ajax('problem/create', { method: "POST", dataType: "json", data: data, success: function(data, state, jqXHR) { g_files = {}; g_fileReaders = {}; $('#problem-contents') .find('img.problem-img') .addClass('hidden') .attr('src', '') .attr('title', '') ; $('#problem-contents') .find('input:file') .each(function(){ // reset the file control var e = $(this); e.wrap('<form>').closest('form').get(0).reset(); e.unwrap(); }) ; alert('保存成功'); }, error: function(jqXHR, state, err) { alert(state + ":保存题目失败\n" + err); } }); }; var handleSubmitClick = function(evt) { saveImg(); }; var extractBase64PartFromDataUrl = function(dataurl) { // DataURL scheme: "data:[media-type][;charset=<charset>][;base64],<content>" // Refer to https://en.wikipedia.org/wiki/Data_URI_scheme var pos = dataurl.indexOf(','); if (pos < 0 || pos == dataurl.length - 1) return ''; return dataurl.substr(pos + 1); }; +function($) { $('#submit_btn') .click(handleSubmitClick) ; }(jQuery); <file_sep>/prs/controllers/img.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Img extends CI_Controller { public function index($img_id) { return $this->loadImg($img_id); } public function save() { date_default_timezone_set('Asia/Shanghai'); $this->load->model('SaveImg'); $this->SaveImg->do_the_job($this->input->post()); } public function loadImg($img_id) { $this->load->model('Image'); $img_content = $this->Image->getRawImageByID($img_id); if ($img_content === null) { echo 'nullimg'; return; } header('Content-Type: image/jpeg'); echo $img_content; return; } public function attr($img_id) { $this->load->model('Image'); $attr = $this->Image->getImgAttrByID($img_id); $attr['errno'] = 0; $attr['errmsg'] = ''; echo json_encode($attr); return; } }
ab92360976a58cfd93b6ce853396365aca36d4e9
[ "JavaScript", "SQL", "Markdown", "PHP" ]
15
PHP
zxteloiv/problem-reservoir
b2e561a7d4ff562f56d09df1e74467cd505ea1ac
3ffcbc38d0dd9563ec59860c8e385aaa722712ce
refs/heads/master
<repo_name>mainulsakib/hard-rock<file_sep>/script.js // document.getElementById("searchPart").style.display="none"; document.getElementById("lyricsSection").style.display="none" document.getElementById("fancy").style.display="none" document.getElementById("searchBtn").addEventListener("click",function(){ let result=document.getElementById("searchName").value fetch(" https://api.lyrics.ovh/suggest/"+result+"") .then(info=>info.json()) .then(data=>{ for (let i = 0; i < 10; i++) { const title = data.data[i].title; const artistName=data.data[i].artist.name; // console.log(title); // console.log(artistName) document.getElementsByClassName("title")[i].innerHTML=title; document.getElementsByClassName("artistName")[i].innerHTML=artistName; // document.getElementById("searchPart").style.display="block"; document.getElementById("fancy").style.display="block" function lyricsBtn(buttonId,title,artist){ document.getElementById(buttonId).addEventListener("click",function(){ let titleName=document.getElementById(title).innerHTML; let artistName=document.getElementById(artist).innerText; fetch("https://api.lyrics.ovh/v1/"+artistName+"/"+titleName+"") .then(lyrics=>lyrics.json()) .then(data1=>{ let result=data1.lyrics; if(typeof result =="undefined"){ document.getElementById("songTitle").innerText=titleName; document.getElementById("lyrics").innerText=" Lyrics is Not Found" } else { document.getElementById("songTitle").innerText=titleName; document.getElementById("lyrics").innerText=result;} document.getElementById("lyricsSection").style.display="block"; }) }) } lyricsBtn("getLyricsBtn1","titleId1","artistId1") lyricsBtn("getLyricsBtn2","titleId2","artistId2") lyricsBtn("getLyricsBtn3","titleId3","artistId3") lyricsBtn("getLyricsBtn4","titleId4","artistId4") lyricsBtn("getLyricsBtn5","titleId5","artistId5") lyricsBtn("getLyricsBtn6","titleId6","artistId6") lyricsBtn("getLyricsBtn7","titleId7","artistId7") lyricsBtn("getLyricsBtn8","titleId8","artistId8") lyricsBtn("getLyricsBtn9","titleId9","artistId9") lyricsBtn("getLyricsBtn10","titleId10","artistId10") // document.getElementById("getLyricsBtn").addEventListener("click",function(){ // document.getElementById("songTitle").innerText= data.data[i].album.title; // document.getElementById("lyrics").innerText=lyrics; // document.getElementById("lyricsSection").style.display="block"; // }) } console.log(data.data) // document.getElementById("title1").innerText=data.data[0].album.title; // document.getElementById("artistName1").innerText=data.data[0].artist.name; // console.log(data.data) }) })
cfd231b6ced4bb1fe43ccdc3225a4e04f99d2d54
[ "JavaScript" ]
1
JavaScript
mainulsakib/hard-rock
39783bb8fff5964785fec13d5f51e5818c8840b3
0260fe8a99234446cb55985f8c82251a31abb4db
refs/heads/master
<file_sep>#include "skeleton_ext.h" static VALUE run(int argc, VALUE* argv, VALUE self) { int i; for (i = 0; i < 10000; ++i) { for (i = 0; i < 10000; ++i) { rb_genrand_real(); // functionally the same as: rb_eval_string("rand"); } } return Qnil; } void Init_skeleton_ext(void) { VALUE rb_mSkeleton = rb_define_module("Skeleton"); VALUE rb_cPerformance = rb_define_class_under(rb_mSkeleton, "Performance", rb_cObject); rb_define_method(rb_cPerformance, "run", run, -1); } <file_sep>Presentation ------------ PLAN ---- tree -C cat test/skeleton_spec.rb cat lib/skeleton/skeleton_pure.rb time ruby -Ilib test/skeleton_spec.rb # real 0m11.654s cat lib/skeleton.rb SETUP ----- tree -C cat ext/skeleton_ext/extconf.rb rake compile tree -C rake clobber vim Rakefile OPTIMIZE -------- vim ext/skeleton_ext/skeleton_ext.c vim ext/skeleton_ext/skeleton_ext.h rake compile time ruby -Ilib test/skeleton_spec.rb # real 0m0.294s time ruby -Ilib -e "require 'skeleton';Skeleton::Performance.new.run" # real 0m0.111s C API ----- VALUE & Qnil ALLOC_N kapitel i pickaxe <file_sep>module Skeleton class PerformancePure def run 100_000_000.times { rand } end end end <file_sep>require 'mkmf' create_makefile('skeleton_ext/skeleton_ext') <file_sep>$:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require "minitest/autorun" require "skeleton" describe Skeleton::Performance do it "runs" do Skeleton::Performance.new.run end end <file_sep>begin require "skeleton_ext/skeleton_ext" rescue LoadError puts "Failed loading native extensions, falling back to pure ruby methods. Install with `rake compile`." require "skeleton/skeleton_pure" Skeleton::Performance = Skeleton::PerformancePure end
ade6f4982f921155ad19780680edca74431fdce1
[ "Markdown", "C", "Ruby" ]
6
C
dbi/ruby-c-skeleton
7faa517ee3684dcd1008cbb76aa30bd2dc468777
0518f519564768842303f2548647a599d1d9f566
refs/heads/master
<file_sep>Post.Status.DRAFT=草案 Post.Status.SCHEDULED=计划的 Post.Status.PUBLISHED=发布的 Banner.Type.MAIN=主要 Banner.Type.SUB=子 Banner.Type.ASIDE=旁边 CustomField.FieldType.UNDEFINED=选择类型 CustomField.FieldType.TEXT=文本 CustomField.FieldType.TEXTAREA=文本区域 CustomField.FieldType.HTML=HTML CustomField.FieldType.SELECTBOX=选择框 CustomField.FieldType.CHECKBOX=复选框 CustomField.FieldType.RADIO=单选按钮 CustomField.FieldType.NUMBER=数 CustomField.FieldType.DATE=日期 CustomField.FieldType.DATETIME=日期时间<file_sep>Post.Status.DRAFT=Radna verzija Post.Status.SCHEDULED=Planirano Post.Status.PUBLISHED=Objavljeno Banner.Type.MAIN=Glavni Banner.Type.SUB=Sub Banner.Type.ASIDE=Sporedni CustomField.FieldType.UNDEFINED=Izaberi tip CustomField.FieldType.TEXT=Tekst CustomField.FieldType.TEXTAREA=Polje teksta CustomField.FieldType.HTML=Html CustomField.FieldType.SELECTBOX=Izaberi okvir CustomField.FieldType.CHECKBOX=Proveri okvir CustomField.FieldType.RADIO=Radio taster CustomField.FieldType.NUMBER=Broj CustomField.FieldType.DATE=Datum CustomField.FieldType.DATETIME=Datum i vreme<file_sep>import $ from 'jquery'; window.$ = $; import 'jsrender'; import 'bootstrap'; import 'bootstrap/dist/css/bootstrap.min.css'; import './resources/css/common.css'; import './resources/css/sticky-footer-navbar.css';<file_sep>Post.Status.DRAFT=초안 Post.Status.SCHEDULED=예약됨 Post.Status.PUBLISHED=게시됨 Banner.Type.MAIN=주 Banner.Type.SUB=부 Banner.Type.ASIDE=배제 CustomField.FieldType.UNDEFINED=형식 선택 CustomField.FieldType.TEXT=텍스트 CustomField.FieldType.TEXTAREA=텍스트 영역 CustomField.FieldType.HTML=Html CustomField.FieldType.SELECTBOX=선택 박스 CustomField.FieldType.CHECKBOX=체크 박스 CustomField.FieldType.RADIO=라디오 단추 CustomField.FieldType.NUMBER=숫자 CustomField.FieldType.DATE=날짜 CustomField.FieldType.DATETIME=날짜/시간
a0e89646adb47cf50098de5cf34517e20de0f2c8
[ "JavaScript", "INI" ]
4
INI
lanoga/wallride
3d20fac42155324094bb2bd3696754bfdbc3b54b
be59861477dd8a0310bba78cb296ff61b6fc4172
refs/heads/master
<repo_name>SamKun28/XTNetwork<file_sep>/Podfile platform :ios, '8.0' source 'https://github.com/CocoaPods/Specs.git' source 'https://github.com/aliyun/aliyun-specs.git' target "NetWork" do pod 'AFNetworking' pod 'SVProgressHUD' pod 'YYModel' pod 'YYCache' end<file_sep>/NetWork/XTAPIHeader.h // // XTAPIHeader.h // NetWork // // Created by 李昆 on 2018/6/13. // Copyright © 2018年 NG. All rights reserved. // #ifndef XTAPIHeader_h #define XTAPIHeader_h //字符串是否为空 #define IsStrEmpty(_ref) (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]]) ||([(_ref)isEqualToString:@""])) //数组是否为空 #define IsArrEmpty(_ref) (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]]) ||([(_ref) count] == 0)) #define BASE_URL @"" #endif /* XTAPIHeader_h */ <file_sep>/README.md # XTNetwork 一个简单的封装将AFNetworking+YYCache 如有什么不好的地方欢迎指正,感觉有很多和其他类似的地方
3583e15824080c9b47ded4375f81c3d90314b410
[ "Markdown", "C", "Ruby" ]
3
Ruby
SamKun28/XTNetwork
ef63f1fa1111ab8e0e3eda886f5680728e362257
0c9551fb0810af02ecc73cec3cf078e1e3b4f7b3
refs/heads/master
<repo_name>cventeic/bit-backed-hash<file_sep>/README.md # Bit_Backed_Hash Hash used to constrain parameter search spaces by constraining parameter values to small bit arrays. For each parameter you can: - Define the value range (ex: 0.2 <= value <= 0.8) - Define the value resolution in terms of bits (ex. 4, 6, 8, etc.) For the set of parameters you can: - Generate a concatenated bit array storing the values from all parameters - Update the parameter values by importing a bit array ## Installation Add this line to your application's Gemfile: ```ruby gem 'bit_backed_hash' ``` And then execute: $ bundle Or install it yourself as: $ gem install bit-backed-hash ## Usage Example Code: params = BitBackedHash.new # Parameter a, range 0.0 to 1.0, mapped into 4 bits / 16 values params.add_parameter(:a, (0.0..1.0), 4) # Parameter b, range 0.0 to 1.0, mapped into 6 bits / 64 values params.add_parameter(:b, (0.0..1.0), 6) params[:a] = 0.5 # Set parameter a as close to 0.5 as possible with 4 bits params[:b] = 0.2 # Set parameter b as close to 0.2 as possible with 6 bits # Generate bit array as concatenation of all bits storing parameter values bit_array = params.export_bits() # Set parameter values from a concatenated bit array params.import_bits(bit_array) # 10 bits, 4 from a and 6 from b assert_equal 10, bit_array.size # Verify value for a is within the resolution of 4 bits assert_in_delta 0.5, params[:a], params.parameter_resolution(:a) / 2.0 # Verify value for b is within the resolution of 6 bits assert_in_delta 0.2, params[:b], params.parameter_resolution(:b) / 2.0 See test directory for an example of using BitBackedHash with Ai4r gem to do a genetic algorithm search. ## Contributing 1. Fork it ( https://github.com/[my-github-username]/bit-backed-hash/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request <file_sep>/lib/bit_backed_hash/range_map.rb require 'minitest/autorun' module Bit_Backed_Hash class Range_Map def initialize(range_a, range_b) @range_a = range_a @range_b = range_b @range_a_span = range_a.max - range_a.min @range_b_span = range_b.max - range_b.min end def map_to_a(value_in_b) percent_of_range = (value_in_b - @range_b.min).to_f / @range_b_span value_in_a = (@range_a_span * percent_of_range) + @range_a.min value_in_a end def map_to_b(value_in_a) percent_of_range = (value_in_a - @range_a.min).to_f / @range_a_span value_in_b = (@range_b_span * percent_of_range) + @range_b.min value_in_b end end end class Test_Range_Map < MiniTest::Unit::TestCase include Bit_Backed_Hash def test_range_map_int_to_float rm = Range_Map.new((0..10), (0..100)) [0, 5, 7.5, 10].each do |a_value| b_value = rm.map_to_b(a_value) assert_equal a_value, b_value / 10 end [0, 50, 75, 100].each do |b_value| a_value = rm.map_to_a(b_value) assert_equal b_value, a_value * 10 end end def test_range_map_float_to_float rm = Range_Map.new((0.0..1.0), (0.0..10.0)) [0.0, 0.5, 1.0].each do |a_value| b_value = rm.map_to_b(a_value) assert_equal a_value, b_value / 10.0 end [0.0, 5.0, 10.0].each do |b_value| a_value = rm.map_to_a(b_value) assert_equal b_value, a_value * 10.0 end end end <file_sep>/lib/bit_backed_hash.rb require "bit_backed_hash/version" require "bit_backed_hash/range_map" require "bit_backed_hash/bbh" module Bit_Backed_Hash # Your code goes here... end <file_sep>/lib/bit_backed_hash/bbh.rb require 'minitest/autorun' #require "bit_backed_hash/range_map" module Bit_Backed_Hash def Bit_Backed_Hash.integer_to_bits(bits, value) #puts "integer_to_bits bits:#{bits}, value:#{value}" bit_array = (bits-1).downto(0).map{|n| value[n]} #puts " bit_array = #{bit_array}" bit_array end def Bit_Backed_Hash.bits_to_integer(bit_array) value = bit_array.reverse.each_with_index.inject(0){|sum,pair| bit,index = pair # puts "index = #{index}, value = #{2**index}, bit = #{bit}" sum += (2**index) if bit == 1 sum } value end class BitBackedHash def initialize() @params = {} end def add_parameter(parameter_id, value_range = (0.0..1.0), value_bits = 6) bit_integer_range = (0..(2**value_bits-1)) @params[parameter_id] = { value_range: value_range, bits: Array.new(value_bits){0}, range_map: Range_Map.new(value_range,bit_integer_range) } end def parameter_resolution(parameter_id) p = @params.fetch(parameter_id) value_bits = p[:bits].size bit_integers = 2**value_bits-1 value_span = p[:value_range].max - p[:value_range].min parameter_resolution = value_span/bit_integers # reserve 1 bit array combination for value_range_max return parameter_resolution end # Retrive parameter value def [](parameter_id) #puts "Retrieve: [#{parameter_id}]" #puts " @params: #{@params.to_s}" p = @params.fetch(parameter_id) bit_integer = Bit_Backed_Hash.bits_to_integer(p[:bits]) value = p[:range_map].map_to_a(bit_integer) return value end def []=(parameter_id, value) #puts "store: [#{parameter_id}] = #{value}" p = @params.fetch(parameter_id) #puts "p = #{p}" bit_integer = p[:range_map].map_to_b(value).round.to_i #puts "bit_integer = #{bit_integer}" #puts "p[:bits] = #{p[:bits]}" p[:bits] = Bit_Backed_Hash.integer_to_bits(p[:bits].size, bit_integer) #puts " p[:bits] = #{p[:bits]}" # Now reverse it and return the stored value bit_integer = Bit_Backed_Hash.bits_to_integer(p[:bits]) #puts " bit_integer = #{bit_integer}" value = p[:range_map].map_to_a(bit_integer) return value # return value??? end def export_bits() #puts "export_bits" raise "no keys defined" unless @params.keys.size > 0 bit_arrays = @params.keys.sort.map do |key| @params[key][:bits] end bit_arrays.flatten end def import_bits(bit_array) bits = bit_array.clone @params.keys.sort.each do |key| p = @params.fetch(key) p[:bits] = bits.shift(p[:bits].size) # extract bits end end end end class Test_Hash_With_Bit_Backing < MiniTest::Unit::TestCase include Bit_Backed_Hash def test_a hash_bb = BitBackedHash.new hash_bb.add_parameter(:a, (0.0..1.0), 4) hash_bb.add_parameter(:b, (0.0..1.0), 6) hash_bb[:a] = 0.5 hash_bb[:b] = 0.2 bit_array = hash_bb.export_bits() hash_bb.import_bits(bit_array) assert_equal 10, bit_array.size assert_in_delta 0.5, hash_bb[:a], hash_bb.parameter_resolution(:a) / 2.0 assert_in_delta 0.2, hash_bb[:b], hash_bb.parameter_resolution(:b) / 2.0 end def test_map #puts "test_map:" h = {a: 0.0, b: 0.25, c: 0.50, d: 0.75, e: 1.0, f: 0.37} (4..8).each do |minimum_bits| #puts " minimum_bits = #{minimum_bits}" hash_bb = BitBackedHash.new total_bits = 0 h.each_pair {|k,v| rand_part = (rand(6) - 3).to_i bits_to_use = minimum_bits + rand_part total_bits += bits_to_use #puts " bits_to_use = #{bits_to_use}" hash_bb.add_parameter(k, (0.0..1.0), bits_to_use) hash_bb[k] = v } bit_field = hash_bb.export_bits() #puts " bit_field = #{bit_field.to_s}" assert_equal (total_bits), bit_field.size hash_bb.import_bits(bit_field) h.each_pair {|k,v| #puts " assert_in_delta #{[v, hash_bb[k], hash_bb.maps[k].value_subspan / 2.0]}" assert_in_delta(v, hash_bb[k], hash_bb.parameter_resolution(k) / 2.0) } end end end <file_sep>/test/genetic_algorithm_test_simple_function_bbh.rb # Author:: <NAME> # License:: MPL 1.1 # Project:: ai4r # Url:: http://www.ai4r.org/ # # You can redistribute it and/or modify it under the terms of # the Mozilla Public License version 1.1 as published by the # Mozilla Foundation at http://www.mozilla.org/MPL/MPL-1.1.txt require 'rubygems' require 'minitest/autorun' require 'pry' require_relative './genetic_algorithm' require 'bit_backed_hash' include Bit_Backed_Hash module Ai4r module GeneticAlgorithm COSTS = [[0,0,0,0,0,0,0,0,0,0]] class Chromosome def initialize(data=[]) @hbb = BitBackedHash.new() @hbb.add_parameter(:x, (0.0..31.0), 8) @hbb.import_bits(data) @age = 0 end def data() @hbb.export_bits() end def data=(bit_array) @hbb.import_bits(bit_array) end # Count 1's def fitness() return @fitness if @fitness # puts "fitness = #{@hbb.to_s}" x = @hbb[:x] @fitness = (-0.1 * x**2) + (3.0 * x) # @fitness = 0.0 if @fitness < 0 return @fitness end def self.reproduce(a, b) self.reproduce_one_point_crossover(a, b) end # Random 0's and 1's def self.seed _hbb = BitBackedHash.new() _hbb.add_parameter(:x, (0.0..31.0), 8) _hbb[:x] = @@prand.rand(0.0..31.0) # must use range to be inclusive and decimal to be float bit_array = _hbb.export_bits() c = Chromosome.new(bit_array) c return c end def to_s out = [] out << [:fitness, fitness().round(2)] out << [:age, age] out << [vars: @hbb.to_s ] out << [:data, data.to_s] out.join(", ") end end NULL_CHROMO_DATA = 8.times.map{0} COSTS = [NULL_CHROMO_DATA] class GeneticAlgorithmTest < MiniTest::Unit::TestCase def test_chromosome_seed Chromosome.set_cost_matrix(COSTS) chromosome = Chromosome.seed assert_equal NULL_CHROMO_DATA.size, chromosome.data.size #assert_equal [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], chromosome.data.sort end def test_fitness Chromosome.set_cost_matrix(COSTS) hbb = BitBackedHash.new() hbb.add_parameter(:x, (0.0..31.0), 8) [0.0, 2.2, 5.0, 25.0, 31.0].each do |test_x| hbb[:x] = test_x chromosome = Chromosome.new(hbb.export_bits()) x = hbb[:x] expected_fitness = (-0.1 * x**2) + (3.0 * x) assert_equal( expected_fitness, chromosome.fitness) end end def test_selection Chromosome.set_cost_matrix(COSTS) population_size = 10 search = GeneticSearch.new(population_size, 5) search.generate_initial_population selected = search.selection selected.each { |c| assert !c.nil? } fitness_range = search.get_fitness_range(search.population) assert_equal 6, selected.length # assert_equal 1, search.population[0].normalized_fitness assert_equal 1, search.population[0].get_normalized_fitness(fitness_range) # assert_equal 0, search.population.last.normalized_fitness assert_equal 0, search.population.last.get_normalized_fitness(fitness_range) assert_equal population_size, search.population.length end def test_reproduction Chromosome.set_cost_matrix(COSTS) population_size = 10 search = GeneticSearch.new(population_size, 5) search.generate_initial_population selected = search.selection() offsprings = search.reproduction(selected) assert_equal 3, offsprings.length end def test_replace_worst_ranked Chromosome.set_cost_matrix(COSTS) population_size = 10 search = GeneticSearch.new(population_size, 5) search.generate_initial_population selected = search.selection() offsprings = search.reproduction(selected) search.replace_worst_ranked(offsprings) assert_equal population_size, search.population.length offsprings.each { |c| assert search.population.include?(c)} end def test_configuration_bounds # contain the bounds of population_size and generations to get reliable # convergence on best solution end def test_accuracy_target # delta from actual best value # 2) test bell curve of x values end def test_fitness_targets repeat = 20 best = [] median = [] worst = [] repeat.times do population_size = 20 generations = 7 Chromosome.set_cost_matrix(COSTS) search_object = GeneticSearch.new(population_size, generations) final_population = search_object.run best << final_population.first.fitness median << final_population.median.fitness worst << final_population.last.fitness end puts "best mean = #{best.mean}, stddev = #{best.standard_deviation}" puts "median mean = #{median.mean}, stddev = #{median.standard_deviation}" puts "worst mean = #{worst.mean}, stddev = #{worst.standard_deviation}" assert_in_delta 22.47, best.mean, 0.05 assert_in_delta 22.26, median.mean, 0.31 assert_in_delta 16.00, worst.mean, 6.63 assert_equal true, (best.mean >= (22.47 * 0.9)) assert_equal true, (median.mean >= (22.26 * 0.9)) assert_equal true, (worst.mean >= (16.0 * 0.9)) end end end end <file_sep>/test/genetic_algorithm.rb # Author:: <NAME> # License:: MPL 1.1 # Project:: ai4r # Url:: http://ai4r.org/ # # You can redistribute it and/or modify it under the terms of # the Mozilla Public License version 1.1 as published by the # Mozilla Foundation at http://www.mozilla.org/MPL/MPL-1.1.txt module Enumerable def sum self.inject(0){|accum, i| accum + i } end def mean self.sum/self.length.to_f end def median self.sort! index = (self.size / 2.0).round self[index] end def sample_variance m = self.mean sum = self.inject(0){|accum, i| accum +(i-m)**2 } sum/(self.length - 1).to_f end def standard_deviation return Math.sqrt(self.sample_variance) end end module Ai4r # The GeneticAlgorithm module implements the GeneticSearch and Chromosome # classes. The GeneticSearch is a generic class, and can be used to solved # any kind of problems. The GeneticSearch class performs a stochastic search # of the solution of a given problem. # # The Chromosome is "problem specific". Ai4r built-in Chromosome class was # designed to model the Travelling salesman problem. If you want to solve other # type of problem, you will have to modify the Chromosome class, by overwriting # its fitness, reproduce, and mutate functions, to model your specific problem. module GeneticAlgorithm # This class is used to automatically: # # 1. Choose initial population # 2. Evaluate the fitness of each individual in the population # 3. Repeat # 1. Select best-ranking individuals to reproduce # 2. Breed new generation through crossover and mutation (genetic operations) and give birth to offspring # 3. Evaluate the individual fitnesses of the offspring # 4. Replace worst ranked part of population with offspring # 4. Until termination # # If you want to customize the algorithm, you must modify any of the following classes: # - Chromosome # - Population class GeneticSearch attr_accessor :population def initialize(initial_population_size, generations) @population_size = initial_population_size @max_generation = generations @generation = 0 @prand = Random.new @breed_count = ((2*@population_size)/3).round end # 1. Choose initial population # 2. Evaluate the fitness of each individual in the population # 3. Repeat # 1. Select best-ranking individuals to reproduce # 2. Breed new generation through crossover and mutation (genetic operations) and give birth to offspring # 3. Evaluate the individual fitnesses of the offspring # 4. Replace worst ranked part of population with offspring # 4. Until termination # 5. Return the best chromosome def run generate_initial_population() #Generate initial population (1..@max_generation).each do |generation_number| puts "\nGeneration #{generation_number}" fitness_range = get_fitness_range(@population) next if fitness_range.max == fitness_range.min @population.sort!() selected_to_breed = selection() # Evaluates current population offsprings = reproduction(selected_to_breed) # Generate the population for this new generation replace_worst_ranked(offsprings) puts to_s() mutate() increment_age() end #return best_chromosome() return @population.sort { |a, b| b.fitness <=> a.fitness} end def generate_initial_population @population = @population_size.times.map { Chromosome.seed() } end def get_fitness_range(population) return Range.new(0.0, 0.0) unless population.size > 0 population.sort!() best_fitness = population.first.fitness worst_fitness = population.last.fitness Range.new(worst_fitness, best_fitness) end # Select best-ranking individuals to reproduce # # Selection is the stage of a genetic algorithm in which individual # genomes are chosen from a population for later breeding. # There are several generic selection algorithms, such as # tournament selection and roulette wheel selection. We implemented the # latest. # # Steps: # # 1. The fitness function is evaluated for each individual, providing fitness values # 2. The population is sorted by descending fitness values. # 3. The fitness values ar then normalized. (Highest fitness gets 1, lowest fitness gets 0). The normalized value is stored in the "normalized_fitness" attribute of the chromosomes. # 4. A random number R is chosen. R is between 0 and the accumulated normalized value (all the normalized fitness values added togheter). # 5. The selected individual is the first one whose accumulated normalized value (its is normalized value plus the normalized values of the chromosomes prior it) greater than R. # 6. We repeat steps 4 and 5, 2/3 times the population size. def selection() acum_fitness = 0 fitness_range = get_fitness_range(@population) if fitness_range.max - fitness_range.min > 0 @population.each do |chromosome| acum_fitness += chromosome.get_normalized_fitness(fitness_range) end end # selected_to_breed @breed_count.times.map { select_random_individual(acum_fitness, fitness_range) } end # We combine each pair of selected chromosome using the method # Chromosome.reproduce # # The reproduction will also call the Chromosome.mutate method with # each member of the population. You should implement Chromosome.mutate # to only change (mutate) randomly. E.g. You could effectivly change the # chromosome only if # rand < ((1 - chromosome.normalized_fitness) * 0.4) def reproduction(selected_to_breed) 0.upto(selected_to_breed.length/2-1).map do |i| offspring = Chromosome.reproduce(selected_to_breed[2*i], selected_to_breed[2*i+1]) offspring.age = -1 offspring end end def mutate() # Only mutate parents parents = @population.to_a.select { |p| (p.age()>=0) } parent_fitness_range = get_fitness_range(parents) parents.each do |individual| Chromosome.mutate(individual, parent_fitness_range) end end def increment_age() @population.each do |individual| individual.age += 1 end end # Replace worst ranked part of population with offspring def replace_worst_ranked(offsprings) size = offsprings.length @population.sort!() # Make sure population is sorted so we replace the worst raise "@population.first.fitness() >= @population.last.fitness()" unless @population.first.fitness() >= @population.last.fitness() @population = @population [0..((-1*size)-1)] + offsprings end # Select the best chromosome in the population def best_chromosome() the_best = @population[0] @population.each do |chromosome| the_best = chromosome if chromosome.fitness > the_best.fitness end return the_best end def to_s() @population.sort!() # sort by fitness puts "\nPopulation:" @population.each_with_index {|p,i| puts "population[#{i}] = #{p.to_s}" } puts "best, median, worst = #{ [@population.first.fitness, @population.median.fitness, @population.last.fitness].join(", ")}" ages = @population.map { |individual| individual.age() } puts "individual.ages = #{ages.join(',')}" aged_count = 0 @population.each {|individual| aged_count += 1 if individual.age() >= 0} puts "#{((aged_count.to_f/@population.size)*100.0).round}% are parents" end private def select_random_individual(acum_fitness, fitness_range) select_random_target = acum_fitness * @prand.rand(0.0...1.0) # not inclusive of 1.0 # puts "select_random_target = #{select_random_target}, acum_fitness = #{acum_fitness}" local_acum = 0.0 @population.each_with_index do |chromosome, index| nf = chromosome.get_normalized_fitness(fitness_range) local_acum += nf #puts "in loop, index = #{index}, nf = #{nf}, local_acum = #{local_acum}" return chromosome if local_acum >= select_random_target end end end # A Chromosome is a representation of an individual solution for a specific # problem. You will have to redifine the Chromosome representation for each # particular problem, along with its fitness, mutate, reproduce, and seed # methods. class Chromosome include Comparable attr_accessor :data, :age def initialize(data) @data = Marshal.load(Marshal.dump(data)) @age = 0 end def ==(another) self.data() == another.data() end def <=>(another) another.fitness() <=> self.fitness() end def get_normalized_fitness(fitness_range) raise "fitness_range.min > fitness_range.max, fitness_range = #{fitness_range}" if fitness_range.min.nil? if (fitness_range.max - fitness_range.min) > 0 f = (fitness().to_f - fitness_range.min)/(fitness_range.max - fitness_range.min).to_f else puts "warning: converged: fitness_range.delta = 0.0: fitnes_range = #{fitness_range}" f = 1.0 end f end # The fitness method quantifies the optimality of a solution # (that is, a chromosome) in a genetic algorithm so that that particular # chromosome may be ranked against all the other chromosomes. # # Optimal chromosomes, or at least chromosomes which are more optimal, # are allowed to breed and mix their datasets by any of several techniques, # producing a new generation that will (hopefully) be even better. def fitness() return @fitness if @fitness raise "inside fitness even though defined and not nill" if @fitness last_token = @data[0] cost = 0 @data[1..-1].each do |token| cost += @@costs[last_token][token] last_token = token end @fitness = -1 * cost return @fitness.to_f end # mutation method is used to maintain genetic diversity from one # generation of a population of chromosomes to the next. It is analogous # to biological mutation. # # The purpose of mutation in GAs is to allow the # algorithm to avoid local minima by preventing the population of # chromosomes from becoming too similar to each other, thus slowing or even # stopping evolution. # # Calling the mutate function will "probably" slightly change a chromosome # randomly. # # This implementation of "mutation" will (probably) reverse the # order of 2 consecutive random nodes # (e.g. from [ 0, 1, 2, 4] to [0, 2, 1, 4]) if: # ((1 - chromosome.normalized_fitness) * 0.4) def self.mutate(chromosome, fitness_range) normalized_fitness = chromosome.get_normalized_fitness(fitness_range) percent_from_best = 1.0 - normalized_fitness probability_of_mutation = percent_from_best * 0.3 # best chromosome has 0% probability of mutation # worst chromosome has 30% probability of mutation if normalized_fitness && @@prand.rand(0.0...1.0) < probability_of_mutation data = chromosome.data # switch two bits index = @@prand.rand(data.length-1) data[index], data[index+1] = data[index+1], data[index] chromosome.data = data @fitness = nil end end # Reproduction method is used to combine two chromosomes (solutions) into # a single new chromosome. # There are several ways to combine two chromosomes: # One-point crossover, # Two-point crossover, # "Cut and splice", # edge recombination, # and more. # The method is usually dependant of the problem domain. # def self.reproduce(a, b) self.reproduce_one_point_crossover(a, b) end # Reproduce with One-point crossover, # def self.reproduce_one_point_crossover(a, b) # Determine which parent is left and right side randomly a, b = b, a if @@prand.rand(0.0..1.0) < 0.5 # Was 0.5 ??? # Create spawn bitmap by joining a split point in parent bit space last_bit = (a.data.size) - 1 split_index = @@prand.rand(last_bit) child_bitmap = a.data[0..split_index] + b.data[(split_index+1)..last_bit] return Chromosome.new(child_bitmap) end # Reproduce with edge recombination # which is the most used reproduction algorithm for the Travelling salesman problem. def self.reproduce_edge_recombination(a, b) data_size = @@costs[0].length # available = [0,1,2,3,..,n-1] available = 0.upto(data_size-1).map { |n| n } token = a.data[0] spawn = [token] available.delete(token) # remove token from array available while available.length > 0 do # Select next b_index_of_token = b.data.index(token) # index of first instance of token in b array b_next_token = b.data[b_index_of_token + 1] a_index_of_token = a.data.index(token) # index of first instance of token in a array a_next_token = a.data[a_index_of_token + 1] if token != b.data.last && available.include?(b_next_token) next_token = b_next_token elsif token != a.data.last && available.include?(a_next_token) next_token = a_next_token else next_token = available[@@prand.rand(available.length)] end #Add to spawn token = next_token available.delete(token) # remove token from array available spawn << next_token a, b = b, a if @@prand.rand(0.0..1.0) < 0.4 # Why 0.4 ??? end return Chromosome.new(spawn) end # Initializes an individual solution (chromosome) for the initial # population. Usually the chromosome is generated randomly, but you can # use some problem domain knowledge, to generate a # (probably) better initial solution. def self.seed data_size = @@costs[0].length available = [] 0.upto(data_size-1) { |n| available << n } seed = [] while available.length > 0 do index = @@prand.rand(available.length) seed << available.delete_at(index) end return Chromosome.new(seed) end def self.set_cost_matrix(costs) @@costs = costs @@prand = Random.new end def to_s out = [] out << [:fitness, fitness().round(2)] out << [:age, age] out << [:data, data.to_s] out.join(", ") end end end end
1a48cf3d7416348849f49a650402d2f161d9031e
[ "Markdown", "Ruby" ]
6
Markdown
cventeic/bit-backed-hash
1d05789827b14b41c61421844f572a355d120e5c
0646658662ee2e3b6a5f5d5f04a93bb877bd54dc
refs/heads/master
<repo_name>SparshCoolApps/aws-cdk-simple-web-service<file_sep>/lambda/save_cust_info.ts const AWS = require('aws-sdk'); const db = new AWS.DynamoDB.DocumentClient(); const uuidv4 = require('uuid/v4'); export const handler = async (event: any = {}) : Promise <any> => { if (!event.body) { return { statusCode: 400, body: 'invalid request!' } } const TABLE_NAME = process.env.TABLE_NAME || ''; const PRIMARY_KEY = process.env.PRIMARY_KEY || ''; const customer = typeof event.body == 'object' ? event.body : JSON.parse(event.body); customer[PRIMARY_KEY] = uuidv4(); const params = { TableName: TABLE_NAME, Customer: customer }; try { await db.put(params).promise(); return { statusCode: 201, body: '' }; } catch (dbError) { return { statusCode: 500, body: "ERROR" }; } };<file_sep>/bin/simple-web-service.ts #!/usr/bin/env node // All component from @aws-cdk module like any other node pkg import apigateway = require('@aws-cdk/aws-apigateway'); import dynamodb = require('@aws-cdk/aws-dynamodb'); import lambda = require ('@aws-cdk/aws-lambda') import cdk = require('@aws-cdk/core'); // creating custom stack by extending the cdk.Stack export class SimpleWebServiceStack extends cdk.Stack { constructor(app: cdk.App, id: string) { super(app, id); // Create a customer table in DynamoDB const dynamoTable = new dynamodb.Table(this, 'customers', { partitionKey: { name: 'custId', type: dynamodb.AttributeType.STRING }, tableName: 'customers', // The default removal policy is RETAIN // But NOT recommended for production code removalPolicy: cdk.RemovalPolicy.DESTROY }); // this is where Infra Code meets Application Code // Get Single customer info - Lamnda Integration const getSingle_cust_info_Lambda = new lambda.Function(this, 'getSingleCustInfo', { code: new lambda.AssetCode('lambda'), handler: 'get_one_cust_info.handler', runtime: lambda.Runtime.NODEJS_10_X, environment: { TABLE_NAME: dynamoTable.tableName, PRIMARY_KEY: 'custId' } }); // Get all customer info - Lamnda Integration // See how ENV variable are used to pass db table and primary key const getAll_cust_info_Lambda = new lambda.Function(this, 'getAllCustInfo', { code: new lambda.AssetCode('lambda'), handler: 'get_all_cust_info.handler', runtime: lambda.Runtime.NODEJS_10_X, environment: { TABLE_NAME: dynamoTable.tableName, PRIMARY_KEY: 'custId' } }); // Create save customer info - Lamnda Integration const create_cust_info = new lambda.Function(this, 'createCustInfo', { code: new lambda.AssetCode('lambda'), handler: 'save_cust_info.handler', runtime: lambda.Runtime.NODEJS_10_X, environment: { TABLE_NAME: dynamoTable.tableName, PRIMARY_KEY: 'custId' } }); // Provide "Permisions" to Lamda Functions to execute on "dynamo" table dynamoTable.grantReadWriteData(getSingle_cust_info_Lambda); dynamoTable.grantReadWriteData(getAll_cust_info_Lambda); dynamoTable.grantReadWriteData(create_cust_info); // Now create an API gateway const api = new apigateway.RestApi(this, 'customerApi', { restApiName: 'Customer Service' }); // Create and add resource customers and do the // Plumbing between LAMBDA function and API Gateway const customers = api.root.addResource('customers'); const getAllIntegration = new apigateway.LambdaIntegration(getAll_cust_info_Lambda); customers.addMethod('GET', getAllIntegration); const createOneIntegration = new apigateway.LambdaIntegration(create_cust_info); customers.addMethod('POST', createOneIntegration); addCorsOptions(customers); const singleItem = customers.addResource('{id}'); const getSingleCustInfo = new apigateway.LambdaIntegration(getSingle_cust_info_Lambda); singleItem.addMethod('GET', getSingleCustInfo); } } export function addCorsOptions(apiResource: apigateway.IResource) { apiResource.addMethod('OPTIONS', new apigateway.MockIntegration({ integrationResponses: [{ statusCode: '200', responseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'*'", 'method.response.header.Access-Control-Allow-Credentials': "'false'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE'", }, }], passthroughBehavior: apigateway.PassthroughBehavior.NEVER, requestTemplates: { "application/json": "{\"statusCode\": 200}" }, }), { methodResponses: [{ statusCode: '200', responseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Methods': true, 'method.response.header.Access-Control-Allow-Credentials': true, 'method.response.header.Access-Control-Allow-Origin': true, }, }] }) } const app = new cdk.App(); new SimpleWebServiceStack(app, 'CustomerRESTServerlessService'); app.synth();
56b0d9823f83c62dbbafa48b51073ccb1a33504d
[ "JavaScript", "TypeScript" ]
2
TypeScript
SparshCoolApps/aws-cdk-simple-web-service
12b368cb7315b378ee9582295611948371ddeb55
4cd7b5b5435cbbb84040e48ed5e546680d396c24
refs/heads/main
<repo_name>kevensantana/NLW4-Move.it<file_sep>/README.md # NLW4---Move.it<file_sep>/api/src/server.ts import express, { request, response } from 'express'; const app = express(); //Pegar alguma informação app.get("/get", (request, response) => { return response.json("hello"); }); // Receber alguma informação // Salvar os dados app.post("/post",(request, response) => { return response.json("Os dados foram salvos com sucesso"); }); app.listen(5353, () => console.log("Server is running!"))
0b3ad32f616c67b8c1cef1e301bf7c426f058546
[ "Markdown", "TypeScript" ]
2
Markdown
kevensantana/NLW4-Move.it
32146160faa36c8ff440ea40bfef485b6bdce70d
ef4eb592ca9946bc3f3b65f75140a71e817a2d7a
refs/heads/master
<file_sep> var from=''; var to=''; var group=[]; var room=''; var message=[]; var groupmessage=[]; var talking=[]; var grouptalking=[]; //区分点击历史记录按钮所要执行的动作 var a=0; var b=0; //IE不支持IndexOf方法,需要在开始前加载以下代码 Array.prototype.indexOf=function(substr,start){ var ta,rt,d='\0'; if(start!=null){ta=this.slice(start);rt=start;}else{ta=this;rt=0;} var str=d+ta.join(d)+d,t=str.indexOf(d+substr+d); if(t==-1)return -1;rt+=str.slice(0,t).replace(/[^\0]/g,'').length; return rt; }; // function talkTo(to){ if(to=="group1"){ $("#groupTalkWinow").show(); if(grouptalking.indexOf(to)==-1){ grouptalking.unshift(to); } $("#groupshow").html(to+':'+'123、'+'234、'+'15900、'+'15964'); group.unshift({"name":'123',"type":'new'}); group.unshift({"name":'234',"type":'new'}); group.unshift({"name":'15900',"type":'new'}); group.unshift({"name":'15964',"type":'new'}); room='group1'; }else if(talking.indexOf(to)==-1){ talking.unshift(to); $("#talkWinow").show(); $("#usertalk").append('<div id=\''+'usertalk_'+to+'\' style=\'height:350px;width:300px; margin-top:20px;position: absolute;overflow:scroll;overflow-x:hidden; border:1px solid #F00;\'></div>'); $("#targets").append('<div id=\''+'targets_'+to+'\' style="margin-top:10px;margin-left:10px;" onclick="changediv(\''+to+'\')">' + to +'</div>'); $("#deletes").append('<div id=\''+'deletes_'+to+'\' style="margin-top:10px" onclick="deletediv(\''+to+'\')">x</div>'); changediv(to); } } function changediv(a) { $("#"+'usertalk_'+a).show(); for(var i=0;i<talking.length;i++){ if(talking[i]!=a){ $("#"+'usertalk_'+talking[i]).hide(); } } to=a; $("#to").val(a); $("#show").html(a); } function deletediv(to){ var usertalk=document.getElementById('usertalk'); var targets=document.getElementById('targets'); var deletes=document.getElementById('deletes'); var d1=document.getElementById('usertalk_'+to); var d2=document.getElementById('targets_'+to); var d3=document.getElementById('deletes_'+to); usertalk.removeChild(d1); targets.removeChild(d2); deletes.removeChild(d3); for(var i=0;i<talking.length;i++){ if(talking[i]==to){ talking.splice(i,1); } } if(talking[0]){ changediv(talking[0]); }else{ $("#show").html(''); $("#talkWinow").hide(); } } $(document).ready(function(){ $(window).keydown(function(e){ if(e.keyCode == 13){ $("#confirm").click(); } }); var socket = io.connect('http://10.22.7.171:3002'); from=$("#from").val(); socket.emit('online',{from:from}); socket.emit('subscribe',{from:from,room:'group1'}); $("#member").blur(function(){ group.unshift({"name":$("#member").val(),"type":'new'}); $("#groupshow").append($("#member").val()+'、'); }); $("#all").click(function(){ Today = new Date(); var NowHour = Today.getHours(); var NowMinute = Today.getMinutes(); if(message.length>0){ for(i=0;i<message.length;i++){ if(talking.indexOf(message[i].from) ==-1){ talking.unshift(message[i].from); $("#usertalk").append('<div id=\''+'usertalk_'+message[i].from+'\' style=\'height:350px;width:300px; margin-top:20px;position: absolute;overflow:scroll;overflow-x:hidden; border:1px solid #F00;\'></div>'); $("#targets").append('<div id=\''+'targets_'+message[i].from+'\' style="margin-top:10px;margin-left:10px;" onclick="changediv(\''+message[i].from+'\')">' + message[i].from +'</div>'); $("#deletes").append('<div id=\''+'deletes_'+message[i].from+'\' style="margin-top:10px" onclick="deletediv(\''+message[i].from+'\')">x</div>'); } $("#"+'usertalk_'+message[i].from).append('<div align="right"><div style="border-style:outset;margin-top:20px;margin-bottom:20px;margin-right:5px;width:150px;word-wrap:break-word;">'+message[i].time+'</br>'+message[i].content+'</div> </div>'); } $("#talkWinow").show();//显示聊天框 changediv(message[0].from); } if(groupmessage.length>0){ for(var n=0;n<groupmessage.length;n++){ if(grouptalking.indexOf('group1')==-1){ grouptalking.unshift('group1'); } $("#lines").append('<div align="right"><div style="border-style:outset;margin-top:20px;margin-bottom:20px;margin-right:5px;width:150px;word-wrap:break-word;">'+groupmessage[n].time+'</br>'+groupmessage[n].content+'</div> </div>'); } room='group1'; $("#groupTalkWinow").show();//显示群聊天框 $("#groupshow").html(room+':'+'123、'+'234、'+'15900、'+'15964'); group.unshift({"name":'123',"type":'new'}); group.unshift({"name":'234',"type":'new'}); group.unshift({"name":'15900',"type":'new'}); group.unshift({"name":'15964',"type":'new'}); } //如果点击,清除数组 message.splice(0,message.length); groupmessage.splice(0,groupmessage.length); $("#showInfo").hide(); $("#show2").hide(); $("#showgroup").hide(); }); socket.on('logout',function(data){ alert('您的账号在别处登录,请重新登录!'); window.location.href="/logout"; }); socket.on('message',function(data){ Today = new Date(); var NowHour = Today.getHours(); var NowMinute = Today.getMinutes(); //如果是上线推送提醒消息 if(data.alert){ for(var i=0;i<data.alert.length;i++){ if(data.alert[i].to&&data.alert[i].to!=''){ message.unshift(data.alert[i]); } if(data.alert[i].groupid&&data.alert[i].groupid!=''){ groupmessage.unshift(data.alert[i]); } } if(message.length>0){ $('#showInfo').show(); $("#title").show(); $("#show2").html('共有'+message.length+'条私聊消息').show(); } if(groupmessage.length>0){ $('#showInfo').show(); $("#title").show(); $("#showgroup").html('共有'+groupmessage.length+'条群消息').show(); } } //判断是私聊消息 if(data.to&&data.to!=''){ if(talking.indexOf(data.from)==-1){ message.unshift(data); if(message.length>0){ $('#showInfo').show(); $("#title").show(); $("#show2").html('共有'+message.length+'条私聊消息').show(); } } if(talking.indexOf(data.from)!=-1){ $("#"+'usertalk_'+to).append('<div align="right"><div style="border-style:outset;margin-top:20px;margin-bottom:20px;margin-right:5px;width:150px;word-wrap:break-word;">'+NowHour+':'+NowMinute+'</br>'+data.content+'</div> </div>'); } var e=document.getElementById('usertalk_'+to); e.scrollTop=e.scrollHeight; } //判断是群聊消息 if(data.room&&data.room!=''){ if(grouptalking.indexOf(data.room)==-1){ groupmessage.unshift(data); if(groupmessage.length>0){ $('#showInfo').show(); $("#title").show(); $("#showgroup").html('共有'+groupmessage.length+'条群消息').show(); } } if(grouptalking.indexOf(data.room)!=-1){ $("#lines").append('<div align="right"><div style="border-style:outset;margin-top:20px;margin-bottom:20px;margin-right:5px;width:150px;word-wrap:break-word;">'+'<div align="left">'+data.from+':'+'</div>'+NowHour+':'+NowMinute+'</br>'+data.content+'</div> </div>'); } var e=document.getElementById("lines"); e.scrollTop=e.scrollHeight; } //私聊历史消息 if(data.history){ if(a%2==1){ $("#"+'usertalk_'+to).html(''); for(var i=0;i<data.history.length;i++){ if(data.history[i].from!=from){ $("#"+'usertalk_'+to).prepend('<div align="right"><div style="border-style:outset;margin-top:20px;margin-bottom:20px;margin-right:5px;width:150px;word-wrap:break-word;">'+data.history[i].time+'</br>'+data.history[i].content+'</div> </div>'); } if(data.history[i].from==from){ $('#'+'usertalk_'+to).prepend('<div style="border-style:outset;margin-top:20px;margin-bottom:20px;margin-right:5px;width:150px;word-wrap:break-word;">'+data.history[i].time+'</br>'+data.history[i].content+'</div> '); }} var e=document.getElementById('usertalk_'+to); e.scrollTop=e.scrollHeight; } if(a%2==0){ $("#"+'usertalk_'+to).html(''); }} //群聊历史消息 if(data.grouphistory){ if(b%2==1){ $("#lines").html(''); for(var i=0;i<data.grouphistory.length;i++){ if(data.grouphistory[i].from!=from){ $("#lines").prepend('<div align="right"><div style="border-style:outset;margin-top:20px;margin-bottom:20px;margin-right:5px;width:150px;word-wrap:break-word;">'+'<div align="left">'+data.grouphistory[i].from+':'+'</div>'+data.grouphistory[i].time+'</br>'+data.grouphistory[i].content+'</div> </div>'); } if(data.grouphistory[i].from==from){ $('#lines').prepend('<div style="border-style:outset;margin-top:20px;margin-bottom:20px;margin-right:5px;width:150px;word-wrap:break-word;">'+data.grouphistory[i].time+'</br>'+data.grouphistory[i].content+'</div> '); }} var e=document.getElementById("lines"); e.scrollTop=e.scrollHeight; } if(b%2==0){ $("#lines").html(''); } } }); //获取当前时间 function now(){ var date = new Date(); var time = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + (date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds()); return time; } var time=0; var timenext=0; //发话 $("#confirm").click(function(){ Today = new Date(); var NowHour = Today.getHours(); var NowMinute = Today.getMinutes(); var NowSecond = Today.getSeconds(); var now=NowHour+':'+NowMinute; var mysec = (NowHour*3600)+(NowMinute*60)+NowSecond; timenext=mysec; if(timenext-time>1){ time=mysec; //获取要发送的信息 var content = $("#content").val(); if(content==''){ alert('发送内容不能为空!'); return; } else{ var to=$('#to').val(); $('#'+'usertalk_'+to).append('<div style="border-style:outset;margin-top:20px;margin-bottom:20px;margin-right:5px;width:150px;word-wrap:break-word;">'+now+'</br>'+content+'</div> '); socket.emit('message',{to:to,from:from,room:room,time:now,content:content,type:'new'}); //清空输入框并获得焦点 }} else{ alert('两次发布时间必须大于1秒!!'); } $("#content").val("").focus(); var e=document.getElementById('usertalk_'+to); e.scrollTop=e.scrollHeight; }); //群组发话 $("#groupconfirm").click(function(){ Today = new Date(); var NowHour = Today.getHours(); var NowMinute = Today.getMinutes(); var NowSecond = Today.getSeconds(); var now=NowHour+':'+NowMinute; var mysec = (NowHour*3600)+(NowMinute*60)+NowSecond; timenext=mysec; if(timenext-time>1){ time=mysec; //获取要发送的信息 var content = $("#groupcontent").val(); if(content==''){ alert('请输入任务内容!'); return; } else{ $('#lines').append('<div style="border-style:outset;margin-top:20px;margin-bottom:20px;margin-right:5px;width:150px;word-wrap:break-word;">'+now+'</br>'+content+'</div> '); socket.emit('group',{room:room,from:from,time:now,group:group,room:room,content:content}); //清空输入框并获得焦点 } } else{ alert('两次发布时间必须大于1秒!!'); } $("#groupcontent").val("").focus(); var e=document.getElementById("lines"); e.scrollTop=e.scrollHeight; }); //查看历史记录 $("#history").click(function(){ a=a+1; socket.emit('history',{to:to,from:from}); }); $("#grouphistory").click(function(){ b=b+1; socket.emit('history',{room:room}); }); }); <file_sep>var mongodb = require('./db'); var mongo = require('mongodb'); var BSON = mongo.BSONPure; function Post(username, title, post, url, time, id, reply, pv) { this.user = username; this.title= title; this.post = post; this.url = url; this.reply= reply; this.id = id; if (time) { this.time = time; } else { this.time = new Date(); } } module.exports = Post; Post.prototype.detail = function detail(id, callback) { var posts = { user: this.user, title:this.title, post: this.post, imgUrl:this.imgUrl, type:this.type, time: this.time, }; mongodb.collection('posts', function(err, collection) { var o_id = new BSON.ObjectID(id); collection.update({_id:o_id},{$inc:{pv:1}}); collection.find({_id:o_id}).toArray(function (err, posts) { //每访问1次,pv 值增加1 callback(null, posts); }); }); }; Post.prototype.remove=function remove(id,callback){ var post = { user: this.user, title:this.title, post: this.post, time: this.time, }; mongodb.collection('posts', function (err, collection) { var o_id = new BSON.ObjectID(id); collection.remove({_id:o_id}, {safe:true}, function(err, post){ callback(err,post); }); }); }; Post.prototype.update=function update(id,title,post,callback){ mongodb.collection('posts', function (err, collection) { var o_id = new BSON.ObjectID(id); collection.update({_id:o_id},{$set:{title:title,post:post}},function(err){ callback(); }); }); } Post.prototype.updatereply=function updatereply(id,reply2,callback){ var post = { user: this.user, title:this.title, post: this.post, time: this.time, reply: this.reply }; mongodb.collection('posts', function (err, collection) { var o_id = new BSON.ObjectID(id); collection.find({_id:o_id}).sort({ time: -1 }).toArray(function (err, docs) { var posts = []; docs.forEach(function (doc, index) { var post = new Post(doc.user, doc.title, doc.post, doc.url, doc.time, doc._id,doc.reply, doc.pv); posts.push(post); }); if(posts[0].reply!=null){ var reply3=posts[0].reply+reply2; } if(posts[0].reply==null){ var reply3=reply2; } collection.update({_id:o_id},{$set:{reply:reply3}},function(err){ callback(); }); callback(null, posts); }); }); } Post.prototype.save = function save(callback) { var post = { user: this.user, title:this.title, post: this.post, url: this.url, reply: this.reply, pv:0, time: this.time, }; mongodb.collection('posts', function (err, collection) { if (err) { return callback(err); } collection.ensureIndex('user'); collection.insert(post, { safe: true }, function (err,post) { callback(err,post); }); }); }; Post.find = function get(username, callback) { mongodb.collection('posts', function(err, collection) { if (err) { return callback(err); } var query = {}; if (username) { query.user = username; } collection.find(query).sort({ time: -1 }).toArray(function (err, docs) { if (err) { callback(err, null); } var posts = []; docs.forEach(function (doc, index) { var post = new Post(doc.user, doc.title, doc.post, doc.url, doc.time, doc._id); //post.time=doc.time; var now = post.time; post.time = now.getFullYear() + "-" + (now.getUTCMonth()+1) + "-" + now.getUTCDate()+ " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds(); posts.push(post); }); callback(null, posts); }); }); }; Post.getEight = function get(username,page,callback) { mongodb.collection('posts', function(err, collection) { if (err) { return callback(err); } var query = {}; if (username) { query.user = username; } collection.find(query,{skip:(page-1)*8, limit:8}).sort({ time: -1 }).toArray(function (err, docs) { if (err) { callback(err, null); } var posts = []; docs.forEach(function (doc, index) { var post = new Post(doc.user, doc.title, doc.post, doc.url, doc.time, doc._id); //post.time=doc.time; var now = post.time; post.time = now.getFullYear() + "-" + (now.getUTCMonth()+1) + "-" + now.getUTCDate()+ " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds(); posts.push(post); }); callback(null, posts); }); }); }; Post.get = function get(username, callback) { mongodb.collection('posts', function(err, collection) { if (err) { return callback(err); } var query = {}; if (username) { query.user = username; } collection.find(query).sort({ time: -1 }).toArray(function (err, docs) { if (err) { callback(err, null); } var posts = []; docs.forEach(function (doc, index) { var post = new Post(doc.user, doc.title, doc.post, doc.url, doc.time, doc._id,doc.reply,doc.pv); //post.time=doc.time; post.pv=doc.pv; var now = post.time; post.time = now.getFullYear() + "-" + (now.getUTCMonth()+1) + "-" + now.getUTCDate()+ " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds(); posts.push(post); }); callback(null, posts); }); }); };<file_sep> $(document).ready(function(){ $(window).keydown(function(e){ if(e.keyCode == 13){ $("#confirm").click(); } }); var socket = io.connect(); var from=$('#p_from').html(); socket.emit('online',{user:from}); socket.on('task',function(data){ if(data.from!=from){ $("#linesall").prepend('<div class="RoundedCorner2" style="margin-top:10px;margin-bottom:10px;margin-right:10px"> <c class="rtop"><c class="r1"></c><c class="r2"></c><c class="r3"></c><c class="r4"></c></c> ' + data.from+ '(' + now() + ')发布了任务:<br/>' + data.content + '</br >'+'任务开始时间:'+data.startday+' '+data.starttime+'</br>'+'任务结束时间:'+data.endday+' '+data.endtime+'</br>'+'任务地点:'+data.place+'</br><c class="rbottom"><c class="r4"></c><c class="r3"></c><c class="r2"></c><c class="r1"></c></c> </div> '); } if(data.old=='yes'){ if(data.from==from){ $('#lines').prepend('<div class="RoundedCorner" style="margin-top:10px;margin-bottom:10px;margin-right:10px"> <b class="rtop"><b class="r1"></b><b class="r2"></b><b class="r3"></b><b class="r4"></b></b> ' + '您在' + '(' + data.time + ')发布了任务:<br/>' + data.content + '</br >'+'任务开始时间:'+data.startday+' '+data.starttime+'</br>'+'任务结束时间:'+data.endday+' '+data.endtime+'</br>'+'任务地点:'+data.place+'</br><b class="rbottom"><b class="r4"></b><b class="r3"></b><b class="r2"></b><b class="r1"></b></b> </div> '); }} }); // 显示在线列表 var showonline = function(n){ var html = ''; n.forEach(function(v){ html += '<div class="line" onclick="private_message(\'' + v + '\')">' + v + '</div>'; }); $('#nicknames').html(html); } // 刷新在线列表 socket.on('online', function(ns){ showonline(ns.userlist); }); socket.on('offline', function(ns){ showonline(ns.userlist); }); //服务器关闭 socket.on('disconnect',function(){ showonline(ns); }); //获取当前时间 function now(){ var date = new Date(); var time = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + (date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds()); return time; } var time=0; var timenext=0; //发话 $("#confirm").click(function(){ Today = new Date(); var NowHour = Today.getHours(); var NowMinute = Today.getMinutes(); var NowSecond = Today.getSeconds(); var mysec = (NowHour*3600)+(NowMinute*60)+NowSecond; timenext=mysec; if(timenext-time>10){ time=mysec; //获取要发送的信息 var content = $("#content").val(); var place= $("#place").val(); var startday = $("#startday").val(); var starttime = $("#starttime").val(); var endday = $("#endday").val(); var endtime = $("#endtime").val(); var start=startday+' '+starttime; var end=endday+' '+endtime; if(content==''){ alert('请输入任务内容!'); return; } if(place==''){ alert('请输入任务地点!'); return; } if(startday==''){ alert('请输入任务开始日期!'); return; } if(starttime==''){ alert('请输入任务开始时间!'); return; } if(endday==''){ alert('请输入任务结束日期!'); return; } if(endtime==''){ alert('请输入任务结束时间!'); return; } else{ $('#lines').prepend('<div class="RoundedCorner" style="margin-top:10px;margin-bottom:10px;margin-right:10px"> <b class="rtop"><b class="r1"></b><b class="r2"></b><b class="r3"></b><b class="r4"></b></b> ' + '您在' + '(' + now() + ')发布了任务:<br/>' + content + '</br >'+'任务开始时间:'+startday+' '+starttime+'</br>'+'任务结束时间:'+endday+' '+endtime+'</br>'+'任务地点:'+place+'</br><b class="rbottom"><b class="r4"></b><b class="r3"></b><b class="r2"></b><b class="r1"></b></b> </div> '); socket.emit('task',{from:from,content:content,place:place,starttime:starttime,startday:startday,endtime:endtime,endday:endday,old:'no'}); //清空输入框并获得焦点 $("#content").val("").focus(); }} else{ alert('两次发布时间必须大于5秒!!'); } }); }); <file_sep>var mongodb = require('./db'); var mongo = require('mongodb'); var BSON = mongo.BSONPure; function Task(to, from, content,place,startday,starttime,endday,endtime, time, id) { this.to = to; this.from= from; this.content = content; this.place = place; this.startday = startday; this.starttime = starttime; this.endday = endday; this.endtime = endtime; this.time = time; this.id = id; if (time) { this.time = time; } else { this.time = new Date(); } } module.exports = Task; Task.prototype.remove=function remove(id,callback){ var post = { user: this.user, title:this.title, post: this.post, time: this.time, }; //=============== mongodb.collection('posts', function (err, collection) { var o_id = new BSON.ObjectID(id); collection.remove({_id:o_id}, {safe:true}, function(err, post){ callback(err,post); }); }); }; Task.prototype.save = function save(callback) { var task = { to:this.to, from:this.from, content:this.content , place:this.place , startday:this.startday, starttime:this.starttime , endday:this.endday , endtime:this.endtime , time: new Date(), }; mongodb.collection('tasks', function (err, collection) { collection.ensureIndex('to'); collection.insert(task, { safe: true }, function (err,task) { callback(err,task); }); }); }; Task.get = function get(username, callback) { mongodb.collection('tasks', function(err, collection) { var query = {}; collection.find(query).sort({ time: -1 }).toArray(function (err, docs) { if (err) { callback(err, null); } var tasks = []; docs.forEach(function (doc, index) { var task = new Task(doc.to,doc.from, doc.content,doc.place,doc.startday,doc.starttime,doc.endday,doc.endtime,doc.time); var now = task.time; task.time = now.getFullYear() + "-" + (now.getUTCMonth()+1) + "-" + now.getUTCDate()+ " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds(); tasks.push(task); }); callback(null, tasks); }); }); };
59d3665b01f83bbeeaae37251af9a80732900e73
[ "JavaScript" ]
4
JavaScript
DavidSun0403/Blog
95c70ba391883e5ad53ed978d61681ef7d10d9f1
b97ad1771e142ea1c770526556cb2a47b6f791a8
refs/heads/master
<file_sep>1. When first starting desktop Github, sync changes (to stay up to date with Github's online files). 2. Work on Senior Project. 3. Sync and let others know via in-person/Google Doc when you plan on committing a change(s) (to stay up to date with Github's online files/avoid file corruption from accidentally committing changes at the same time with another person). 4. Commit change(s). ???<file_sep>/** * This is the base class for every guest on the train. * * @<NAME> * @12/4/2015 */ public class Guest extends Person { //Name of the Guest. //RFID of the Guest. //RFID status of the Guest (on/off). //Accessibilities of each room of the Guest. By default, a Guest can access the dining car, bar/party car, and economy car. /** * Constructor for objects of class Guest */ public Guest() { //Initialize instance variables of the guest. } /** * */ //Methods for getting the instance variables of the Guest. /** * */ //Methods for setting the instance variables of the Guest. } <file_sep>/** * This is the base class for every person on the train. * * @<NAME> * @12/4/2015 */ public class Person { //Name of the Person. //RFID of the Person. //RFID status of the Person (on/off). //Accessibilities of each room of the person. By default, all accessibilities are false. /** * Constructor for objects of class Person */ public Person() { //Initialize instance variables of the person. } /** * */ //Methods for getting the instance variables of the Person. /** * */ //Methods for setting the instance variables of the Person. } <file_sep>/** * Write a description of class TestDriver here. * * @author (your name) * @version (a version number or a date) */ public class TestDriver { public static void main(String [] args) { //Test print the information of each type of person. //Test the security disable RFID method. } }
fec79ac9c07e5c5d841b1e217227d6e90493673a
[ "Java", "Text" ]
4
Text
jasardmal/SeniorProject
378d864cdfe4e1a8f643259cf97e395300b47a1e
888bd920ad5a554949248f89b5205ee007c76e14
refs/heads/master
<repo_name>KrishnenduDG/Jumble-Solver<file_sep>/scraper.py import requests from bs4 import BeautifulSoup URL = '''https://www.dictionary.com/browse/''' result_class = 'one-click-content css-nnyc96 e1q3nk1v1' def find(word2): word='' for item in word2: word+=item a=requests.get(URL + word).content soup = BeautifulSoup(a, "html.parser") try: # Checking if the Word Exists or not soup.find_all("span",{"class":result_class})[0].get_text() # Checking if the word is an Abbreviation or not. If yes, Then retur False isType=soup.find_all('span',{"class":'pos'})[0].get_text() if('abbreviation' in isType): return False return True except: return False if __name__=='__main__': print(find(('t','a','c')))<file_sep>/main.py from scraper import find from itertools import permutations if __name__=='__main__': word=input("Enter the Word:") perms=permutations(word) isFound=False # Traversing all the permutations of the word for words in perms: # If the word is found then we break out of loop and print the word if(find(words)): isFound=True real_word='' for item in words: real_word+=item print(f'The Real Word is:{real_word}') break # If the word has already been found, then we do nothing if(isFound): pass # Else we print that we could not find the word else: print("No Valid Permutation Found!!!!!")
e3983e39912ed32bd2b0bb4d6897a5a809631d17
[ "Python" ]
2
Python
KrishnenduDG/Jumble-Solver
467ac7153d3dfb23f7cf61fd8a8aa390217a3df1
c172f79f9de9a65951ce4e287f187ae0cd159e68
refs/heads/master
<file_sep>package com.andreas.movie_catalogue.utils import com.andreas.movie_catalogue.data.TvShowEntity object DataDummyTvShow { fun getTvShow() :ArrayList<TvShowEntity> { return arrayListOf( TvShowEntity( "1", "The Falcon and the Winter Soldier", "Following the events of “Avengers: Endgame”, the Falcon, <NAME> and the Winter Soldier, <NAME> team up in a global adventure that tests their abilities, and their patience.", "2021-03-19", "https://image.tmdb.org/t/p/w780/b0WmHGc8LHTdGCVzxRb3IBMur57.jpg", "https://image.tmdb.org/t/p/w780/6kbAMLteGO8yyewYau6bJ683sw7.jpg" ), TvShowEntity( "2", "The Good Doctor", "A young surgeon with Savant syndrome is recruited into the surgical unit of a prestigious hospital. The question will arise: can a person who doesn't have the ability to relate to people actually save their lives", "2017-09-25", "https://image.tmdb.org/t/p/w780/mZjZgY6ObiKtVuKVDrnS9VnuNlE.jpg", "https://image.tmdb.org/t/p/w780/6tfT03sGp9k4c0J3dypjrI8TSAI.jpg" ), TvShowEntity( "3", "The Flash", "After a particle accelerator causes a freak storm, CSI Investigator <NAME> is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only \"meta-human\" who was created in the wake of the accelerator explosion -- and not everyone is using their new powers for good. Barry partners with <NAME> and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won't be long before the world learns what <NAME> has become...The Flash.", "2014-10-07", "https://image.tmdb.org/t/p/w780/jeruqNWhqRqOR1QyqdQdHunrvU5.jpg", "https://image.tmdb.org/t/p/w780/lJA2RCMfsWoskqlQhXPSLFQGXEJ.jpg" ), TvShowEntity( "4", "Invincible", "<NAME> is a normal teenager except for the fact that his father is the most powerful superhero on the planet. Shortly after his seventeenth birthday, Mark begins to develop powers of his own and enters into his father’s tutelage.", "2021-03-26", "https://image.tmdb.org/t/p/w780/6UH52Fmau8RPsMAbQbjwN3wJSCj.jpg", "https://image.tmdb.org/t/p/w780/yDWJYRAwMNKbIYT8ZB33qy84uzO.jpg" ), TvShowEntity( "5", "Jupiter's Legacy", "When the world's first generation of superheroes received their powers in the 1930s become the revered elder guard in the present, their superpowered children struggle to live up to the legendary feats of their parents.", "2021-05-07", "https://image.tmdb.org/t/p/w780/4YKkS95v9o9c0tBVA46xIn6M1tx.jpg", "https://image.tmdb.org/t/p/w780/9yxep7oJdkj3Pla9TD9gKflRApY.jpg" ), TvShowEntity( "6", "Grey's Anatomy", "Follows the personal and professional lives of a group of doctors at Seattle’s Grey Sloan Memorial Hospital.", "2005-03-27", "https://image.tmdb.org/t/p/w780/edmk8xjGBsYVIf4QtLY9WMaMcXZ.jpg", "https://image.tmdb.org/t/p/w780/clnyhPqj1SNgpAdeSS6a6fwE6Bo.jpg" ), TvShowEntity( "7", "<NAME>: The Series", "The series dramatizes the life story of Mexican superstar singer <NAME>, who has captivated audiences in Latin America and beyond for decades.", "2018-04-22", "https://image.tmdb.org/t/p/w780/edmk8xjGBsYVIf4QtLY9WMaMcXZ.jpg", "https://image.tmdb.org/t/p/w780/34FaY8qpjBAVysSfrJ1l7nrAQaD.jpg" ), TvShowEntity( "8", "Lucifer", "Bored and unhappy as the Lord of Hell, <NAME>ningstar abandoned his throne and retired to Los Angeles, where he has teamed up with LAPD detective Chloe Decker to take down criminals. But the longer he's away from the underworld, the greater the threat that the worst of humanity could escape.", "2016-01-25", "https://image.tmdb.org/t/p/w780/ta5oblpMlEcIPIS2YGcq9XEkWK2.jpg", "https://image.tmdb.org/t/p/w780/4EYPN5mVIhKLfxGruy7Dy41dTVn.jpg" ), TvShowEntity( "9", "Riverdale", "Set in the present, the series offers a bold, subversive take on Archie, Betty, Veronica and their friends, exploring the surreality of small-town life, the darkness and weirdness bubbling beneath Riverdale’s wholesome facade.", "2017-01-26", "https://image.tmdb.org/t/p/w780/qZtAf4Z1lazGQoYVXiHOrvLr5lI.jpg", "https://image.tmdb.org/t/p/w780/wRbjVBdDo5qHAEOVYoMWpM58FSA.jpg" ), TvShowEntity( "10", "The Bad Batch", "Follow the elite and experimental Clones of the Bad Batch as they find their way in a rapidly changing galaxy in the aftermath of the Clone Wars.", "2021-05-04", "https://image.tmdb.org/t/p/w780/sjxtIUCWR74yPPcZFfTsToepfWm.jpg", "https://image.tmdb.org/t/p/w780/WjQmEWFrOf98nT5aEfUfVYz9N2.jpg" ) ) } }<file_sep>package com.andreas.movie_catalogue.ui.tvshow 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 androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.andreas.movie_catalogue.R import com.andreas.movie_catalogue.data.TvShowEntity import com.andreas.movie_catalogue.ui.detail.DetailTvShowActivity import kotlinx.android.synthetic.main.fragment_tv_show.* class TvShowFragment : Fragment() { private lateinit var viewModel: TvShowViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModel = ViewModelProvider(this).get(TvShowViewModel::class.java) return inflater.inflate(R.layout.fragment_tv_show, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) showTvShow(viewModel.getTvShow()) } fun showTvShow(list: ArrayList<TvShowEntity>){ rv_tv.layoutManager = LinearLayoutManager(activity) val adapter = TvShowAdapter(list) rv_tv.adapter = adapter adapter.setOnItemClickCallback(object : TvShowAdapter.OnItemClickCallback { override fun onItemClicked(data: TvShowEntity) { val moveWithObjectIntent = Intent(activity, DetailTvShowActivity::class.java) moveWithObjectIntent.putExtra(DetailTvShowActivity.EXTRA_TV_SHOW, data.id) startActivity(moveWithObjectIntent) } }) } }<file_sep>package com.andreas.movie_catalogue.ui.detail import android.app.Activity import android.graphics.Color import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.view.WindowManager import androidx.lifecycle.ViewModelProvider import com.andreas.movie_catalogue.R import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import kotlinx.android.synthetic.main.activity_detail_movie_activity.* class DetailMovieActivity : AppCompatActivity() { companion object{ const val EXTRA_MOVIE = "extra_movie" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail_movie_activity) val viewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory())[DetailMovieViewModel::class.java] window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN if (Build.VERSION.SDK_INT >= 21) { setWindowFlag( this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false ) window.statusBarColor = Color.TRANSPARENT } toolbar.title = "" setSupportActionBar(toolbar) assert(supportActionBar != null) supportActionBar!!.setDisplayHomeAsUpEnabled(true) val extras = intent.extras if(extras != null){ val movieId = extras.getString(EXTRA_MOVIE) if(movieId != null){ viewModel.setSelectedMovie(movieId) val movie = viewModel.getMovie() Log.d("TAG", movie.toString()) tvName.text = movie.title tvTitle.text = movie.title tvCat.text = movie.category tvDesc.text = movie.description tvDur.text = movie.duration Glide.with(this) .load(movie.poster) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imgCover) Glide.with(this) .load(movie.poster) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imgPhoto) } } } fun setWindowFlag(activity: Activity, bits: Int, on: Boolean) { val window = activity.window val winParams = window.attributes if (on) { winParams.flags = winParams.flags or bits } else { winParams.flags = winParams.flags and bits.inv() } window.attributes = winParams } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } }<file_sep>package com.andreas.movie_catalogue.ui.detail import androidx.lifecycle.ViewModel import com.andreas.movie_catalogue.data.MovieEntity import com.andreas.movie_catalogue.utils.DataDummyMovie class DetailMovieViewModel : ViewModel(){ private lateinit var movieId: String fun setSelectedMovie(movieId: String){ this.movieId = movieId } fun getMovie() : MovieEntity{ lateinit var movie: MovieEntity val movieEntities = DataDummyMovie.getMovies() for (movieEntity in movieEntities){ if(movieEntity.id == movieId){ movie = movieEntity } } return movie } }<file_sep>package com.andreas.movie_catalogue.data import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class TvShowEntity( var id: String?, var title: String?, var description: String?, var first_air: String?, var backdrop: String?, var poster: String? ) : Parcelable<file_sep>package com.andreas.movie_catalogue.ui.detail import android.app.Activity import android.graphics.Color import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.view.WindowManager import androidx.lifecycle.ViewModelProvider import com.andreas.movie_catalogue.R import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import kotlinx.android.synthetic.main.activity_detail_tv_show.* class DetailTvShowActivity : AppCompatActivity() { companion object{ const val EXTRA_TV_SHOW = "extra_tv_show" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail_tv_show) val viewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory())[DetailTvViewModel::class.java] window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN if (Build.VERSION.SDK_INT >= 21) { setWindowFlag( this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false ) window.statusBarColor = Color.TRANSPARENT } toolbar.title = "" setSupportActionBar(toolbar) assert(supportActionBar != null) supportActionBar!!.setDisplayHomeAsUpEnabled(true) val extras = intent.extras if(extras != null){ val tvId = extras.getString(DetailTvShowActivity.EXTRA_TV_SHOW) if(tvId != null){ viewModel.setSelectedTv(tvId) val tv = viewModel.getTv() tvName.text = tv.title tvTitle.text = tv.title tvFirstAir.text = tv.first_air tvDeskripsi.text = tv.description Glide.with(this) .load(tv.backdrop) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imgCover) Glide.with(this) .load(tv.poster) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imgPhoto) } } } fun setWindowFlag(activity: Activity, bits: Int, on: Boolean) { val window = activity.window val winParams = window.attributes if (on) { winParams.flags = winParams.flags or bits } else { winParams.flags = winParams.flags and bits.inv() } window.attributes = winParams } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } }<file_sep>package com.andreas.movie_catalogue.ui.tvshow import androidx.lifecycle.ViewModel import com.andreas.movie_catalogue.utils.DataDummyTvShow class TvShowViewModel : ViewModel() { fun getTvShow() = DataDummyTvShow.getTvShow() }<file_sep>package com.andreas.movie_catalogue.utils import com.andreas.movie_catalogue.R import com.andreas.movie_catalogue.data.MovieEntity object DataDummyMovie { fun getMovies() :ArrayList<MovieEntity> { return arrayListOf( MovieEntity( "1", "Alita: Battle Angel", "When Alita awakens with no memory of who she is in a future world she does not recognize, she is taken in by Ido, a compassionate doctor who realizes that somewhere in this abandoned cyborg shell is the heart and soul of a young woman with an extraordinary past.", "2h 2m", "Action, Science Fiction, Adventure", R.drawable.poster_alita ), MovieEntity( "2", "Aquaman", "Once home to the most advanced civilization on Earth, Atlantis is now an underwater kingdom ruled by the power-hungry King Orm. With a vast army at his disposal, Orm plans to conquer the remaining oceanic people and then the surface world. Standing in his way is <NAME>, Orm's half-human, half-Atlantean brother and true heir to the throne.", "2h 24m", "Action, Adventure, Fantasy", R.drawable.poster_aquaman ), MovieEntity( "3", "<NAME>", "The quiet family life of <NAME>, a snowplow driver, is upended after his son's murder. Nels begins a vengeful hunt for Viking, the drug lord he holds responsible for the killing, eliminating Viking's associates one by one. As Nels draws closer to Viking, his actions bring even more unexpected and violent consequences, as he proves that revenge is all in the execution.", "1h 59m", "Action, Crime, Thriller", R.drawable.poster_cold_persuit ), MovieEntity( "4", "Creed II", "Between personal obligations and training for his next big fight against an opponent with ties to his family's past, <NAME> is up against the challenge of his life.", "2h 10m", "Drama", R.drawable.poster_creed ), MovieEntity( "5", "Fantastic Beasts: The Crimes of Grindelwald", "<NAME> has escaped imprisonment and has begun gathering followers to his cause—elevating wizards above all non-magical beings. The only one capable of putting a stop to him is the wizard he once called his closest friend, <NAME>. However, Dumbledore will need to seek help from the wizard who had thwarted Grindelwald once before, his former student <NAME>, who agrees to help, unaware of the dangers that lie ahead. Lines are drawn as love and loyalty are tested, even among the truest friends and family, in an increasingly divided wizarding world.", "2h 14m", "Adventure, Fantasy, Drama", R.drawable.poster_crimes ), MovieEntity( "6", "How to Train Your Dragon: The Hidden World", "As Hiccup fulfills his dream of creating a peaceful dragon utopia, Toothless’ discovery of an untamed, elusive mate draws the Night Fury away. When danger mounts at home and Hiccup’s reign as village chief is tested, both dragon and rider must make impossible decisions to save their kind.", "1h 44m", "Animation, Family, Adventure", R.drawable.poster_how_to_train ), MovieEntity( "7", "Mortal Engines", "Many thousands of years in the future, Earth’s cities roam the globe on huge wheels, devouring each other in a struggle for ever diminishing resources. On one of these massive traction cities, the old London, <NAME> has an unexpected encounter with a mysterious young woman from the wastelands who will change the course of his life forever.", "2h 9m", "Adventure, Fantasy", R.drawable.poster_mortal_engines ), MovieEntity( "8", "Overlord", "France, June 1944. On the eve of D-Day, some American paratroopers fall behind enemy lines after their aircraft crashes while on a mission to destroy a radio tower in a small village near the beaches of Normandy. After reaching their target, the surviving paratroopers realise that, in addition to fighting the Nazi troops that patrol the village, they also must fight against something else.", "1h 50m", "Horror, War, Science Fiction", R.drawable.poster_overlord ), MovieEntity( "9", "Spider-Man: Into the Spider-Verse", "<NAME> is juggling his life between being a high school student and being a spider-man. When Wilson \"Kingpin\" Fisk uses a super collider, others from across the Spider-Verse are transported to this dimension.", "1h 57m", "Action, Adventure, Animation, Science Fiction, Comedy", R.drawable.poster_spiderman ), MovieEntity( "10", "T-34", "In 1944, a courageous group of Russian soldiers managed to escape from German captivity in a half-destroyed legendary T-34 tank. Those were the times of unforgettable bravery, fierce fighting, unbreakable love, and legendary miracles.", "2h 19m", "War, Action, Drama, History", R.drawable.poster_t34 ) ) } }<file_sep>package com.andreas.movie_catalogue.ui.detail import androidx.lifecycle.ViewModel import com.andreas.movie_catalogue.data.TvShowEntity import com.andreas.movie_catalogue.utils.DataDummyTvShow class DetailTvViewModel : ViewModel(){ private lateinit var tvId: String fun setSelectedTv(tvId: String){ this.tvId = tvId } fun getTv() : TvShowEntity { lateinit var tv: TvShowEntity val tvEntities = DataDummyTvShow.getTvShow() for (tvEntity in tvEntities){ if(tvEntity.id == tvId){ tv = tvEntity } } return tv } }<file_sep>package com.andreas.movie_catalogue.ui.movie import androidx.lifecycle.ViewModel import com.andreas.movie_catalogue.utils.DataDummyMovie class MovieViewModel : ViewModel() { fun getMovies() = DataDummyMovie.getMovies() }<file_sep>package com.andreas.movie_catalogue.ui import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.contrib.RecyclerViewActions import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.rules.ActivityScenarioRule import com.andreas.movie_catalogue.R import com.andreas.movie_catalogue.utils.DataDummyMovie import com.andreas.movie_catalogue.utils.DataDummyTvShow import org.junit.Rule import org.junit.Test class HomeActivityTest{ private val dummyMovie = DataDummyMovie.getMovies() private val dummyTv = DataDummyTvShow.getTvShow() @get:Rule var activityRule = ActivityScenarioRule(HomeActivity::class.java) @Test fun loadMovies(){ onView(withId(R.id.rv_movie)).check(matches(isDisplayed())) onView(withId(R.id.rv_movie)).perform(RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(dummyMovie.size)) } @Test fun loadDetailMovie(){ onView(withId(R.id.rv_movie)).perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(0, click())) onView(withId(R.id.tvTitle)).check(matches(isDisplayed())) onView(withId(R.id.tvTitle)).check(matches(withText(dummyMovie[0].title))) onView(withId(R.id.tvCat)).check(matches(isDisplayed())) onView(withId(R.id.tvCat)).check(matches(withText("Action, Science Fiction, Adventure"))) onView(withId(R.id.tvName)).check(matches(isDisplayed())) onView(withId(R.id.tvName)).check(matches(withText(dummyMovie[0].title))) onView(withId(R.id.tvDesc)).check(matches(isDisplayed())) onView(withId(R.id.tvDesc)).check(matches(withText(dummyMovie[0].description))) onView(withId(R.id.tvDur)).check(matches(isDisplayed())) onView(withId(R.id.tvDur)).check(matches(withText(dummyMovie[0].duration))) } @Test fun loadTvShow(){ onView(withId(R.id.tabTV)).perform(click()) onView(withId(R.id.rv_tv)).check(matches(isDisplayed())) onView(withId(R.id.rv_tv)).perform(RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(dummyTv.size)) } @Test fun loadDetailTv(){ onView(withId(R.id.tabTV)).perform(click()) onView(withId(R.id.rv_tv)).perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(0, click())) onView(withId(R.id.tvTitle)).check(matches(isDisplayed())) onView(withId(R.id.tvTitle)).check(matches(withText(dummyTv[0].title))) onView(withId(R.id.tvFirstAir)).check(matches(isDisplayed())) onView(withId(R.id.tvFirstAir)).check(matches(withText("2021-03-19"))) onView(withId(R.id.tvName)).check(matches(isDisplayed())) onView(withId(R.id.tvName)).check(matches(withText(dummyTv[0].title))) onView(withId(R.id.tvDeskripsi)).check(matches(isDisplayed())) onView(withId(R.id.tvDeskripsi)).check(matches(withText(dummyTv[0].description))) } }<file_sep>package com.andreas.movie_catalogue.data import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class MovieEntity( var id: String?, var title: String?, var description: String?, var duration: String?, var category: String?, var poster: Int? ) : Parcelable<file_sep>package com.andreas.movie_catalogue.ui import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.fragment.app.Fragment import com.andreas.movie_catalogue.R import com.andreas.movie_catalogue.ui.movie.MovieFragment import com.andreas.movie_catalogue.ui.tvshow.TvShowFragment import com.andreas.movie_catalogue.utils.BottomBarBehavior import com.gauravk.bubblenavigation.BubbleNavigationLinearView class HomeActivity : AppCompatActivity() { var fragment: Fragment? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) val navigationBar = findViewById<BubbleNavigationLinearView>(R.id.navigationBar) val layoutParams = navigationBar.layoutParams as CoordinatorLayout.LayoutParams layoutParams.behavior = BottomBarBehavior() supportFragmentManager.beginTransaction().replace(R.id.frameLayout, MovieFragment()) .commit() navigationBar.setNavigationChangeListener { view, position -> when (position) { 0 -> fragment = MovieFragment() 1 -> fragment = TvShowFragment() } supportFragmentManager.beginTransaction().replace( R.id.frameLayout, fragment!! ) .commit() } } }<file_sep>package com.andreas.movie_catalogue.ui.movie import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.andreas.movie_catalogue.R import com.andreas.movie_catalogue.data.MovieEntity import com.andreas.movie_catalogue.ui.detail.DetailMovieActivity import kotlinx.android.synthetic.main.fragment_movie.* class MovieFragment : Fragment() { private lateinit var viewModel: MovieViewModel private lateinit var listMovie: ArrayList<MovieEntity> override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModel = ViewModelProvider(this).get(MovieViewModel::class.java) return inflater.inflate(R.layout.fragment_movie, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) showMovie(viewModel.getMovies()) } private fun showMovie(list: ArrayList<MovieEntity>){ rv_movie.layoutManager = LinearLayoutManager(activity) val adapter = MovieAdapter(list) rv_movie.adapter = adapter adapter.notifyDataSetChanged() adapter.setOnItemClickCallback(object : MovieAdapter.OnItemClickCallback { override fun onItemClicked(data: MovieEntity) { val moveWithObjectIntent = Intent(activity, DetailMovieActivity::class.java) moveWithObjectIntent.putExtra(DetailMovieActivity.EXTRA_MOVIE, data.id) startActivity(moveWithObjectIntent) } }) } }<file_sep>package com.andreas.movie_catalogue.ui.detail import com.andreas.movie_catalogue.utils.DataDummyTvShow import org.junit.Test import org.junit.Assert.* import org.junit.Before class DetailTvViewModelTest { private lateinit var viewModel: DetailTvViewModel private val dummyTv = DataDummyTvShow.getTvShow()[0] private val tvId = dummyTv.id @Before fun setUp(){ viewModel = DetailTvViewModel() if (tvId != null) { viewModel.setSelectedTv(tvId) } } @Test fun getTv() { dummyTv.id?.let { viewModel.setSelectedTv(it) } val tvEntity = viewModel.getTv() assertNotNull(tvEntity) assertEquals(dummyTv.id, tvEntity.id) assertEquals(dummyTv.backdrop, tvEntity.backdrop) assertEquals(dummyTv.description, tvEntity.description) assertEquals(dummyTv.first_air, tvEntity.first_air) assertEquals(dummyTv.poster, tvEntity.poster) assertEquals(dummyTv.title, tvEntity.title) } }<file_sep>package com.andreas.movie_catalogue.ui.movie import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.andreas.movie_catalogue.R import com.andreas.movie_catalogue.data.MovieEntity import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.bitmap.RoundedCorners import kotlinx.android.synthetic.main.item_row_movie.view.* class MovieAdapter(val listMovie: ArrayList<MovieEntity>) : RecyclerView.Adapter<MovieAdapter.MovieViewHolder>() { private var onItemClickCallback: OnItemClickCallback? = null fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback){ this.onItemClickCallback = onItemClickCallback } override fun onCreateViewHolder( viewGroup: ViewGroup, viewType: Int ): MovieAdapter.MovieViewHolder { val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_row_movie, viewGroup, false) return MovieViewHolder(view) } override fun getItemCount(): Int = listMovie.size override fun onBindViewHolder(holder: MovieAdapter.MovieViewHolder, position: Int) { holder.bind(listMovie[position]) } inner class MovieViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(movieEntity: MovieEntity) { with(itemView) { Glide.with(itemView.context) .load(movieEntity.poster) .placeholder(R.drawable.ic_image) .transform(RoundedCorners(16)) .into(imgPhoto) itemView.tvTitle.text = movieEntity.title itemView.tvDuration.text = movieEntity.duration itemView.tvCategory.text = movieEntity.category itemView.setOnClickListener { onItemClickCallback?.onItemClicked(movieEntity) } } } } interface OnItemClickCallback { fun onItemClicked(data: MovieEntity) } }<file_sep>package com.andreas.movie_catalogue.ui.tvshow import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.andreas.movie_catalogue.R import com.andreas.movie_catalogue.data.TvShowEntity import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.bitmap.RoundedCorners import kotlinx.android.synthetic.main.item_row_tv_show.view.* class TvShowAdapter(val listTvShOW: ArrayList<TvShowEntity>) : RecyclerView.Adapter<TvShowAdapter.TvShowViewHolder>() { private var onItemClickCallback: OnItemClickCallback? = null fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback){ this.onItemClickCallback = onItemClickCallback } override fun onCreateViewHolder( viewGroup: ViewGroup, viewType: Int ): TvShowAdapter.TvShowViewHolder { val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_row_tv_show, viewGroup, false) return TvShowViewHolder(view) } override fun getItemCount(): Int = listTvShOW.size override fun onBindViewHolder(holder: TvShowAdapter.TvShowViewHolder, position: Int) { holder.bind(listTvShOW[position]) } inner class TvShowViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(tvShowEntity: TvShowEntity) { with(itemView) { Glide.with(itemView.context) .load(tvShowEntity.poster) .placeholder(R.drawable.ic_image) .transform(RoundedCorners(16)) .into(imgPhoto) itemView.tvTitle.text = tvShowEntity.title itemView.tvDesc.text = tvShowEntity.description itemView.tvFirstAir.text = tvShowEntity.first_air itemView.setOnClickListener { onItemClickCallback?.onItemClicked(tvShowEntity) } } } } interface OnItemClickCallback { fun onItemClicked(data: TvShowEntity) } }<file_sep>package com.andreas.movie_catalogue.ui.detail import com.andreas.movie_catalogue.utils.DataDummyMovie import org.junit.Test import org.junit.Assert.* import org.junit.Before class DetailMovieViewModelTest { private lateinit var viewModel: DetailMovieViewModel private val dummyMovie = DataDummyMovie.getMovies()[0] private val movieId = dummyMovie.id @Before fun setUp(){ viewModel = DetailMovieViewModel() if (movieId != null) { viewModel.setSelectedMovie(movieId) } } @Test fun getMovie() { dummyMovie.id?.let { viewModel.setSelectedMovie(it) } val movieEntity = viewModel.getMovie() assertNotNull(movieEntity) assertEquals(dummyMovie.id, movieEntity.id) assertEquals(dummyMovie.title, movieEntity.title) assertEquals(dummyMovie.poster, movieEntity.poster) assertEquals(dummyMovie.category, movieEntity.category) assertEquals(dummyMovie.description, movieEntity.description) assertEquals(dummyMovie.duration, movieEntity.duration) } }
1bc691971f102ce31c61370f5027a7e25576c8bc
[ "Kotlin" ]
18
Kotlin
jansennn/movie-catalogue
a03895879da13c739788ba5a438c64fafceec6c4
6afdc401af7436168fce0e5bb558d37f1c95888b
refs/heads/master
<file_sep>package com.example.bookingapp; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.LinkedList; public class historyDateAdapter extends RecyclerView.Adapter<historyDateAdapter.historyViewHolder> { private Context context; private ArrayList<Court> mCourt; public historyDateAdapter(Context c, ArrayList<Court> court){ context = c; mCourt = court; } @NonNull @Override public historyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.history, parent, false); return new historyViewHolder(view); } @Override public void onBindViewHolder(@NonNull historyViewHolder holder, int position) { holder.tvDate.setText(mCourt.get(position).getDate()); holder.badminton_hall_img.setImageResource(mCourt.get(position).getCourtImg()); holder.tvBadmintonHall.setText(mCourt.get(position).getCourtName()); holder.tvPrice.setText("RM " + mCourt.get(position).getPrice()); holder.tvTime.setText(mCourt.get(position).getTime() + ""); } @Override public int getItemCount() { return mCourt.size(); } public class historyViewHolder extends RecyclerView.ViewHolder { private ImageView badminton_hall_img; private TextView tvBadmintonHall, tvPrice, tvTime, tvDate; public historyViewHolder(@NonNull View itemView) { super(itemView); tvDate = itemView.findViewById(R.id.textViewDate); badminton_hall_img = itemView.findViewById(R.id.history_badmintonHall_image); tvBadmintonHall = itemView.findViewById(R.id.history_badminton_hall); tvPrice = itemView.findViewById(R.id.history_product_price); tvTime = itemView.findViewById(R.id.history_time); } } } <file_sep>package com.example.bookingapp; import android.app.DatePickerDialog; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.DatePicker; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.text.DateFormat; import java.util.Calendar; public class Booking_fragment extends Fragment { private int[] img ={R.drawable.badminton, R.drawable.badminton_1, R.drawable.badminton_2, R.drawable.badminton_3}; private RecyclerView recyclerView; private imgAdapter mImgAdapter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_booking, container, false); //Set img recycler view recyclerView = v.findViewById(R.id.img_recyclerView); mImgAdapter = new imgAdapter(getContext(), img); //change recycler view to horizontal LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(horizontalLayoutManager); recyclerView.setAdapter(mImgAdapter); return v; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { setHasOptionsMenu(true); super.onCreate(savedInstanceState); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { //inflate menu inflater.inflate(R.menu.history, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { //handle menu item click int id = item.getItemId(); if (id == R.id.history){ Toast.makeText(getActivity(), "History", Toast.LENGTH_LONG).show(); startActivity(new Intent(getActivity(), history.class)); } return super.onOptionsItemSelected(item); } } <file_sep>package com.example.bookingapp; import android.app.DatePickerDialog; import android.content.Intent; import android.os.Bundle; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.tabs.TabLayout; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import android.widget.DatePicker; import com.example.bookingapp.ui.main.SectionsPagerAdapter; import java.util.Calendar; public class MainPage extends AppCompatActivity{ Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_page); SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager()); ViewPager viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(sectionsPagerAdapter); TabLayout tabs = findViewById(R.id.tabs); tabs.setupWithViewPager(viewPager); FloatingActionButton fab = findViewById(R.id.fab); FloatingActionButton fabAddress = findViewById(R.id.fab_address); toolbar = findViewById(R.id.toolBar); toolbar.setTitle("Booking App"); setSupportActionBar(toolbar); Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); //Set to the max date Calendar maxCalendar = Calendar.getInstance(); maxCalendar.set(Calendar.DAY_OF_MONTH, day + 14); maxCalendar.set(Calendar.MONTH, month); maxCalendar.set(Calendar.YEAR, year); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DatePickerDialog datePickerDialog = new DatePickerDialog(MainPage.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { //Store the data in string String date = dayOfMonth + "/" + month + "/" + year; Intent intent = new Intent(MainPage.this, Booking_court.class); intent.putExtra("Day", dayOfMonth); intent.putExtra("Month", month); intent.putExtra("Year", year); intent.putExtra("Date", date); startActivity(intent); } },year,month,day ); //Disable past date datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000); //Disable future date datePickerDialog.getDatePicker().setMaxDate(maxCalendar.getTimeInMillis()); //Show date picker dialog datePickerDialog.show(); } }); fabAddress.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainPage.this, map.class)); } }); } }<file_sep>package com.example.bookingapp; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.content.res.TypedArray; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Booking_court extends AppCompatActivity { private TextView tvDate; private String dateCombine, userID; private ArrayList<Court> mCourt; private RecyclerView recyclerView; private BookingCourtAdapter bookingCourtAdapter; FirebaseFirestore db; FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_booking_court); tvDate = findViewById(R.id.tvDate); recyclerView = findViewById(R.id.badminton_recyclerView); db = FirebaseFirestore.getInstance(); firebaseAuth = FirebaseAuth.getInstance(); userID = firebaseAuth.getCurrentUser().getUid(); Intent intent = getIntent(); String date = intent.getStringExtra("Date"); int day = intent.getIntExtra("Day",0); int month = intent.getIntExtra("Month",0); int year = intent.getIntExtra("Year",0); dateCombine = day + " " + month + " " + year; tvDate.setText(date); //Create calendar checking DocumentReference calendar_checking = db.collection("Calendar Checking").document(dateCombine) .collection("Badminton Court").document("Badminton Hall Check"); Map<String, Object> check_Calendar = new HashMap<>(); check_Calendar.put("Status", "Yes"); calendar_checking.set(check_Calendar); //Create Calendar DocumentReference documentReference = db.collection("Calendar").document(dateCombine); Map<String, Object> calendar = new HashMap<>(); calendar.put("Status", "Yes"); documentReference.set(calendar); //Set the Layout Manager recyclerView.setLayoutManager(new LinearLayoutManager(this)); //Initialize the ArrayLIst that will contain the data mCourt = new ArrayList<>(); bookingCourtAdapter = new BookingCourtAdapter(this, mCourt, date, dateCombine); recyclerView.setAdapter(bookingCourtAdapter); //Get the data initializeData(); } // End onCreate private void initializeData() { //Get the resources from the XML file String[] courtName = getResources().getStringArray(R.array.court_name); TypedArray courtResImg = getResources().obtainTypedArray(R.array.court_img); //Clear the existing data (to avoid duplication) mCourt.clear(); //Create the ArrayList of Sports objects with the titles and information about each sport for (int i=0; i<courtName.length; i++){ mCourt.add(new Court(courtName[i], "", dateCombine, "", courtResImg.getResourceId(i, 0), 0, 0)); } courtResImg.recycle(); //Notify the adapter of the change bookingCourtAdapter.notifyDataSetChanged(); } }<file_sep>package com.example.bookingapp; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class BookingCourt_details extends AppCompatActivity { private String courtName, date, dateCombine, userID; private String time_10AM = "", time_11AM = "", time_12PM = "", time_1PM = "", time_2PM = "", time_3PM = "", time_4PM = "", time_5PM = "", time_6PM = "", time_7PM = "", time_8PM = "", time_9PM = ""; private int courtImg, price = 0, hour = 0, historyNum; private int count10AM = 0, count11AM = 0, count12PM = 0, count1PM = 0, count2PM = 0, count3PM = 0, count4PM = 0, count5PM = 0, count6PM = 0, count7PM = 0, count8PM = 0, count9PM = 0; private TextView tvCourtName, tvCourtDate, tvPrice; private ImageView imgCourt, img10AM_11AM, img11AM_12PM, img12PM_1PM, img1PM_2PM, img2PM_3PM, img3PM_4PM, img4PM_5PM, img5PM_6PM, img6PM_7PM, img7PM_8PM, img8PM_9PM, img9PM_10PM; private Button btnBook; private ProgressBar progressBar; FirebaseFirestore db; FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_booking_court_details); tvCourtName = findViewById(R.id.tvCourtName); tvCourtDate = findViewById(R.id.tvDate); tvPrice = findViewById(R.id.tvPrice); imgCourt = findViewById(R.id.imgCourt); img10AM_11AM = findViewById(R.id.img_tick_10AM_11AM); img11AM_12PM = findViewById(R.id.img_tick_11AM_12PM); img12PM_1PM = findViewById(R.id.img_tick_12PM_1PM); img1PM_2PM = findViewById(R.id.img_tick_1PM_2PM); img2PM_3PM = findViewById(R.id.img_tick_2PM_3PM); img3PM_4PM = findViewById(R.id.img_tick_3PM_4PM); img4PM_5PM = findViewById(R.id.img_tick_4PM_5PM); img5PM_6PM = findViewById(R.id.img_tick_5PM_6PM); img6PM_7PM = findViewById(R.id.img_tick_6PM_7PM); img7PM_8PM = findViewById(R.id.img_tick_7PM_8PM); img8PM_9PM = findViewById(R.id.img_tick_8PM_9PM); img9PM_10PM = findViewById(R.id.img_tick_9PM_10PM); btnBook = findViewById(R.id.btnBook); progressBar = findViewById(R.id.progressBar_getBookingImg); db = FirebaseFirestore.getInstance(); firebaseAuth = FirebaseAuth.getInstance(); userID = firebaseAuth.getCurrentUser().getUid(); getData(); setData(); DocumentReference history_1 = db.collection("Users").document(userID); history_1.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { String n = documentSnapshot.getString("History"); historyNum = Integer.parseInt(n); } }); DocumentReference documentReference = db.collection("Calendar Checking").document(dateCombine) .collection("Badminton Court").document(courtName); documentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()){ getTimeBooking(); } else { Toast.makeText(BookingCourt_details.this, "Data get unsuccessful", Toast.LENGTH_SHORT).show(); } } }); img10AM_11AM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count10AM = (count10AM+1) % 2; if (count10AM == 1){ img10AM_11AM.setImageResource(R.drawable.free_booking_green); price+=10; hour+=1; time_10AM = userID; } else{ img10AM_11AM.setImageResource(R.drawable.free_booking); price-=10; hour-=1; time_10AM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); img11AM_12PM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count11AM = (count11AM+1) % 2; if (count11AM == 1){ img11AM_12PM.setImageResource(R.drawable.free_booking_green); price+=10; hour+=1; time_11AM = userID; } else{ img11AM_12PM.setImageResource(R.drawable.free_booking); price-=10; hour-=1; time_11AM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); img12PM_1PM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count12PM = (count12PM+1) % 2; if (count12PM == 1){ img12PM_1PM.setImageResource(R.drawable.free_booking_green); price+=10; hour+=1; time_12PM = userID; } else{ img12PM_1PM.setImageResource(R.drawable.free_booking); price-=10; hour-=1; time_12PM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); img1PM_2PM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count1PM = (count1PM+1) % 2; if (count1PM == 1){ img1PM_2PM.setImageResource(R.drawable.free_booking_green); price+=10; hour+=1; time_1PM = userID; } else{ img1PM_2PM.setImageResource(R.drawable.free_booking); price-=10; hour-=1; time_1PM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); img2PM_3PM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count2PM = (count2PM+1) % 2; if (count2PM == 1){ img2PM_3PM.setImageResource(R.drawable.free_booking_green); price+=10; hour+=1; time_2PM = userID; } else{ img2PM_3PM.setImageResource(R.drawable.free_booking); price-=10; hour-=1; time_2PM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); img3PM_4PM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count3PM = (count3PM+1) % 2; if (count3PM == 1){ img3PM_4PM.setImageResource(R.drawable.free_booking_green); price+=10; hour+=1; time_3PM = userID; } else{ img3PM_4PM.setImageResource(R.drawable.free_booking); price-=10; hour-=1; time_3PM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); img4PM_5PM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count4PM = (count4PM+1) % 2; if (count4PM == 1){ img4PM_5PM.setImageResource(R.drawable.free_booking_green); price+=10; hour+=1; time_4PM = userID; } else{ img4PM_5PM.setImageResource(R.drawable.free_booking); price-=10; hour-=1; time_4PM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); img5PM_6PM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count5PM = (count5PM+1) % 2; if (count5PM == 1){ img5PM_6PM.setImageResource(R.drawable.free_booking_green); price+=10; hour+=1; time_5PM = userID; } else{ img5PM_6PM.setImageResource(R.drawable.free_booking); price-=10; hour-=1; time_5PM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); img6PM_7PM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count6PM = (count6PM+1) % 2; if (count6PM == 1){ img6PM_7PM.setImageResource(R.drawable.free_booking_green); price+=10; hour+=1; time_6PM = userID; } else{ img6PM_7PM.setImageResource(R.drawable.free_booking); price-=10; hour-=1; time_6PM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); img7PM_8PM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count7PM = (count7PM+1) % 2; if (count7PM == 1){ img7PM_8PM.setImageResource(R.drawable.free_booking_green); price+=15; hour+=1; time_7PM = userID; } else{ img7PM_8PM.setImageResource(R.drawable.free_booking); price-=15; hour-=1; time_7PM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); img8PM_9PM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count8PM = (count8PM+1) % 2; if (count8PM == 1){ img8PM_9PM.setImageResource(R.drawable.free_booking_green); price+=15; hour+=1; time_8PM = userID; } else{ img8PM_9PM.setImageResource(R.drawable.free_booking); price-=15; hour-=1; time_8PM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); img9PM_10PM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count9PM = (count9PM+1) % 2; if (count9PM == 1){ img9PM_10PM.setImageResource(R.drawable.free_booking_green); price+=15; hour+=1; time_9PM = userID; } else{ img9PM_10PM.setImageResource(R.drawable.free_booking); price-=15; hour-=1; time_9PM = ""; } tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); } }); btnBook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Update the history number DocumentReference history = db.collection("Users").document(userID); history.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { String history_number = documentSnapshot.getString("History"); historyNum= Integer.parseInt(history_number); historyNum++; addHistoryNum(historyNum + ""); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(BookingCourt_details.this, "Error " + e.toString(), Toast.LENGTH_LONG).show(); } }); //Update the time booking to hold userID DocumentReference Update = db.collection("Calendar").document(dateCombine) .collection("Badminton Court").document(courtName); ArrayList<String> getTime = new ArrayList<>(); if (!time_10AM.equals("")){ Update.update("10AM - 11AM", time_10AM); getTime.add("10AM - 11AM"); } if (!time_11AM.equals("")){ Update.update("11AM - 12PM", time_11AM); getTime.add("11AM - 12PM"); } if (!time_12PM.equals("")){ Update.update("12PM - 1 PM", time_12PM); getTime.add("12PM - 1 PM"); } if (!time_1PM.equals("")){ Update.update("1 PM - 2 PM", time_1PM); getTime.add("1 PM - 2 PM"); } if (!time_2PM.equals("")){ Update.update("2 PM - 3 PM", time_2PM); getTime.add("2 PM - 3 PM"); } if (!time_3PM.equals("")){ Update.update("3 PM - 4 PM", time_3PM); getTime.add("3 PM - 4 PM"); } if (!time_4PM.equals("")){ Update.update("4 PM - 5 PM", time_4PM); getTime.add("4 PM - 5 PM"); } if (!time_5PM.equals("")){ Update.update("5 PM - 6 PM", time_5PM); getTime.add("5 PM - 6 PM"); } if (!time_6PM.equals("")){ Update.update("6 PM - 7 PM", time_6PM); getTime.add("6 PM - 7 PM"); } if (!time_7PM.equals("")){ Update.update("7 PM - 8 PM", time_7PM); getTime.add("7 PM - 8 PM"); } if (!time_8PM.equals("")){ Update.update("8 PM - 9 PM", time_8PM); getTime.add("8 PM - 9 PM"); } if (!time_9PM.equals("")){ Update.update("9 PM - 10PM", time_9PM); getTime.add("9 PM - 10PM"); } //Clear all the booking time time_10AM = ""; time_11AM = ""; time_12PM = ""; time_1PM = ""; time_2PM = ""; time_3PM = ""; time_4PM = ""; time_5PM = ""; time_6PM = ""; time_7PM = ""; time_8PM = ""; time_9PM = ""; getTimeBooking(); //Store the time booking to check history DocumentReference storeCheckHistory = db.collection("Check History").document(userID) .collection("History").document(dateCombine); Map<String, Object> status = new HashMap<>(); status.put("Status", "Yes"); storeCheckHistory.set(status); //Store the time booking to user history DocumentReference storeHistory = db.collection("Users").document(userID) .collection("History").document("history " + historyNum); Map<String, Object> historyData = new HashMap<>(); historyData.put("Badminton Hall", courtName); historyData.put("Badminton Image", courtImg + ""); historyData.put("Date", date); historyData.put("Calendar Date", dateCombine); historyData.put("Price", price + ""); historyData.put("Hour", hour + ""); for (int i=0; i<getTime.size(); i++){ int count = i; historyData.put("Time " + ++count, getTime.get(i)); } storeHistory.set(historyData); getTime.clear(); price = 0; hour = 0; tvPrice.setText("RM " + price + ".00" ); setBtnBookEnable(); Toast.makeText(BookingCourt_details.this, "Book Successful", Toast.LENGTH_LONG).show(); } }); }// End onCreate public void getData(){ courtName = getIntent().getStringExtra("CourtName"); courtImg = getIntent().getIntExtra("CourtImg", 1); date = getIntent().getStringExtra("Date"); dateCombine = getIntent().getStringExtra("DateCombine"); } public void setData(){ tvCourtName.setText(courtName); imgCourt.setImageResource(courtImg); tvCourtDate.setText(date); } public void getTimeBooking(){ DocumentReference documentReference_1 = db.collection("Calendar").document(dateCombine) .collection("Badminton Court").document(courtName); documentReference_1.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { progressBar.setVisibility(View.GONE); String time = null; time = documentSnapshot.getString("10AM - 11AM"); img10AM_11AM.setImageResource(setBookingImage(time)); setBookingEnable(time, img10AM_11AM); time = documentSnapshot.getString("11AM - 12PM"); img11AM_12PM.setImageResource(setBookingImage(time)); setBookingEnable(time, img11AM_12PM); time = documentSnapshot.getString("12PM - 1 PM"); img12PM_1PM.setImageResource(setBookingImage(time)); setBookingEnable(time, img12PM_1PM); time = documentSnapshot.getString("1 PM - 2 PM"); img1PM_2PM.setImageResource(setBookingImage(time)); setBookingEnable(time, img1PM_2PM); time = documentSnapshot.getString("2 PM - 3 PM"); img2PM_3PM.setImageResource(setBookingImage(time)); setBookingEnable(time, img2PM_3PM); time = documentSnapshot.getString("3 PM - 4 PM"); img3PM_4PM.setImageResource(setBookingImage(time)); setBookingEnable(time, img3PM_4PM); time = documentSnapshot.getString("4 PM - 5 PM"); img4PM_5PM.setImageResource(setBookingImage(time)); setBookingEnable(time, img4PM_5PM); time = documentSnapshot.getString("5 PM - 6 PM"); img5PM_6PM.setImageResource(setBookingImage(time)); setBookingEnable(time, img5PM_6PM); time = documentSnapshot.getString("6 PM - 7 PM"); img6PM_7PM.setImageResource(setBookingImage(time)); setBookingEnable(time, img6PM_7PM); time = documentSnapshot.getString("7 PM - 8 PM"); img7PM_8PM.setImageResource(setBookingImage(time)); setBookingEnable(time, img7PM_8PM); time = documentSnapshot.getString("8 PM - 9 PM"); img8PM_9PM.setImageResource(setBookingImage(time)); setBookingEnable(time, img8PM_9PM); time = documentSnapshot.getString("9 PM - 10PM"); img9PM_10PM.setImageResource(setBookingImage(time)); setBookingEnable(time, img9PM_10PM); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(BookingCourt_details.this, "Error " + e.toString(), Toast.LENGTH_LONG).show(); } }); } private void addHistoryNum(String historyCount){ DocumentReference documentReference = db.collection("Users").document(userID); documentReference.update("History", historyCount); } public int setBookingImage(String time){ int img; if (time.equals(userID)){ img = R.drawable.booking_blue; } else if(time.equals("")){ img = R.drawable.free_booking; } else { img = R.drawable.booking_red; } return img; } public void setBookingEnable(String time, ImageView img){ if (!time.equals("")){ img.setEnabled(false); } } public void setBtnBookEnable(){ if (price == 0){ btnBook.setEnabled(false); btnBook.setBackgroundResource(R.drawable.custom_button_grey); btnBook.setTextColor(Color.parseColor("#B2BABB")); } else{ btnBook.setEnabled(true); btnBook.setBackgroundResource(R.drawable.custom_sign_up_button); btnBook.setTextColor(Color.parseColor("#FF018786")); } } }<file_sep>package com.example.bookingapp; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class imgAdapter extends RecyclerView.Adapter<imgAdapter.imgViewHolder> { private Context context; private int[] product_image; public imgAdapter(Context c, int[] img){ context = c; product_image = img; } @NonNull @Override public imgViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.img_recycler, parent, false); return new imgViewHolder(view); } @Override public void onBindViewHolder(@NonNull imgViewHolder holder, int position) { holder.img.setImageResource(product_image[position]); } @Override public int getItemCount() { return product_image.length; } public class imgViewHolder extends RecyclerView.ViewHolder { private ImageView img; public imgViewHolder(@NonNull View itemView) { super(itemView); img = itemView.findViewById(R.id.show_image); } } }
03388933d53393f1964f178bbfea9daffba1bfff
[ "Java" ]
6
Java
huihao-Wang/BookingApp
a2b083bdfc4a210298b959d28b7e62fae81987e0
7de6061c920370d88a4861044b37b52ffa74e116
refs/heads/main
<repo_name>Dg-Isary/Clash-Trojan<file_sep>/Clash-Trojan.sh #!/bin/bash clashlink=clashlink trojan=trojan echo > temp echo > trtmp wget -qO- $clashlink |grep trojan |awk '{print $2}' > temp cat temp |while read line do trps=`echo "File:${line}" |awk -F '"password":' 'match($2,/\"([^\"]*)\"/,a){print a[0]}' |awk -F \" '{print $2}'` trse=`echo "File:${line}" |awk -F '"server":' 'match($2,/\"([^\"]*)\"/,a){print a[0]}' |awk -F \" '{print $2}'` port=`echo "File:${line}" |awk -F '"port":' '{print $2}' |awk -F ',' '{print $1}'` trna=`echo "File:${line}" |awk -F '"name":' '{print $2}' |awk -F ',' '{print $1}'` echo "trojan://$trps@$trse":"$port"#"$trna" >> trtmp done cat trtmp|base64 > $trojan rm temp trtmp
6570a2a8bf54d4e8512c24d462fdae61fff1b585
[ "Shell" ]
1
Shell
Dg-Isary/Clash-Trojan
d0749615da7b4de4acf2551e936cf6d392e867c3
4cb2d3b3fd2088e07585c6ec2d5b404c1ed9b893
refs/heads/master
<file_sep>package TopStateWise; import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; public class TopStateWiseSaleReducer extends Reducer<CompanyState, IntWritable, CompanyState, IntWritable> { IntWritable outValue = new IntWritable(); public void reduce(CompanyState key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException { int counter = 0; int sum = 0; for (IntWritable value : values) { sum += value.get(); } } } <file_sep>package TopStateWise; import org.apache.hadoop.fs.Path; import org.apache.hadoop.conf.*; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; public class TopStateWiseSale { @SuppressWarnings("deprecation") public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "TelevisionSaleCompanyWise"); job.setJarByClass(TopStateWiseSale.class); job.setMapOutputKeyClass(CompanyState.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(CompanyState.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(TopStateWiseSaleMapper.class); job.setReducerClass(TopStateWiseSaleReducer.class); //job.setPartitionerClass(SoldPerComapnyPartitioner.class); job.setInputFormatClass(SequenceFileInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path("hdfs://localhost:9000/user/acadgild/hadoop/outputtelevision1/part-r-00000")); FileOutputFormat.setOutputPath(job,new Path("hdfs://localhost:9000/user/acadgild/hadoop/outputtelevision1/soldcompanystatewiseSeq")); /* Path out=new Path(args[1]); out.getFileSystem(conf).delete(out); */ job.waitForCompletion(true); } } <file_sep>package TopStateWise; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.hadoop.io.ByteWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.*; public class TopStateWiseSaleMapper extends Mapper<Text, Text, CompanyState, IntWritable> { final static Pattern WORD_PATTERN = Pattern.compile("\\w+\\|\\w+\\|\\d+\\|\\w+\\|\\d+\\|\\d+"); CompanyState outkey = new CompanyState(); IntWritable outvalue = new IntWritable(1); public void map(Text key, Text value, Context context) throws IOException, InterruptedException { Matcher matcher = WORD_PATTERN.matcher(key.toString()); while (matcher.find()) { String company = matcher.group().toString().split("\\|")[0]; String state = matcher.group().toString().split("\\|")[3]; Text comptext = new Text(); comptext.set(company); Text statetext = new Text(); statetext.set(state); CompanyState outkey = new CompanyState(comptext, statetext); context.write(outkey, outvalue); } } }
e8b03644935deafa29d7a1a316c8cf2e74b903b7
[ "Java" ]
3
Java
pd2592/CompanyStateWiseSale
9bb352ed8147e4b01cd5ec14b91ca035687a089a
13e15f91bb3037eb0e064f546af659beb4da37d6
refs/heads/master
<file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Property</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body style="background: rgba(39, 218, 147, 0.08);"> <!--header--> <?php include('header.php'); ?> <!--//--> <!--Dealers--> <div class="dealers" style="padding:6em 0 5em 0"> <div class="container"> <div class="dealer-top"> <h4>Properties Viewed</h4> <div class="deal-top-top"> <?php $sname=$_SESSION['name']; $q="SELECT * FROM `tenant_reg` where name='$sname'"; $s = @mysqli_query($connection,$q); while($row = mysqli_fetch_array($s)) { $pid=$row['vpd_id']; } $vpdi=explode(',', $pid); $vpdid = join("','", $vpdi); $query = "select * from property_details WHERE property_id in ('$vpdid')"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { ?> <div class="col-md-3 top-deal-top" style="margin:10px 0"> <div class=" top-deal"> <a href="<?php echo "single.php?id=".$row['property_id']; ?>" class="mask"> <?php $c_images=$row['image']; $array = explode(',', $c_images); ?> <img src="<?php if(empty($array[0])){ echo "images/no-image.jpg"; }else{echo $array[0];} ?>" class="img-responsive zoom-img" alt=""> <img class="hidden-xs" src="images/logo2.png" style="position:absolute; z-index:9; right:20%; top:3%; height:150px" /> </a> <div class="deal-bottom"> <div class="top-deal1"> <h5><a href="<?php echo "single.php?id=".$row['property_id']; ?>"> Zero Brokerage</a></h5> <h5><a href="<?php echo "single.php?id=".$row['property_id']; ?>"> <?php echo $row['flat_type'] ?> in <?php echo $row['locality'] ?></a></h5> <p>Rent: Rs. <?php echo $row['monthly_rnet'] ?></p> <p>Deposite: Rs. <?php echo $row['security_deposit'] ?></p> </div> <div class="top-deal2"> <a href="<?php echo "single.php?id=".$row['property_id']; ?>" class="hvr-sweep-to-right more">Details</a> </div> <div class="clearfix"> </div> </div> </div> </div> <?php } ?> <div class="clearfix"> </div> </div> <!--<div class="nav-page"> <nav> <ul class="pagination"> <li class="disabled"><a href="#" aria-label="Previous"><span aria-hidden="true">«</span></a></li> <li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li><a href="#" aria-label="Next"><span aria-hidden="true">»</span></a></li> </ul> </nav> </div>--> </div> </div> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> <div style="position:fixed; z-index:9; right:0; bottom:0px; margin:15px;"> <a href="tenant_dashboard.php" class="hvr-sweep-to-right more" style="background:#27da93; color:#FFF; font-weight:bold; padding:1em" >Back</a> </div> </body> </html><file_sep><?php include('conn.php'); session_start(); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Property</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Fair Owner" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" banner-buying"> <div class=" container"> </div> </div> <!--//header--> <!----> <?php //$id = @$_GET['id']; $id=$_GET['id']; //$id=16; $q = "SELECT * FROM `property_details` WHERE property_id = '$id'"; $sql = @mysqli_query($connection,$q); ?> <?php while($row = mysqli_fetch_array($sql)) { ?> <div class="container"> <div class="buy-single-single"> <div class="row single-box"> <div class=" col-md-8 buying-top"> <h4 style="font-size: 1.8em; color: #000; font-family: 'Montserrat-Regular'; padding-bottom:1em; padding-top:18px; text-transform:Uppercase;">Property Id <?php echo $row['property_id']; ?></h4> <div class="flexslider"> <ul class="slides"> <?php $c_images=$row['image']; $array = explode(',', $c_images); foreach ($array as $item) { ?> <li data-thumb="<?php if(empty($item)){ echo "images/no-image.jpg"; }else{echo $item;} ?>"> <img style="height:555px" src="<?php if(empty($item)){ echo "images/no-image.jpg"; }else{echo $item;} ?>" /> </li> <?php //echo "$('#photos').append('<img src='$item' alt='Aniket Kanade'>');"; } ?> </ul> </div> <!-- FlexSlider --> <script defer src="js/jquery.flexslider.js"></script> <link rel="stylesheet" href="css/flexslider.css" type="text/css" media="screen" /> <script> // Can also be used with $(document).ready() $(document).ready(function() { $('.flexslider').flexslider({ animation: "slide", controlNav: "thumbnails" }); }); </script> <div class="map-buy-single"> <h4>Property Map</h4> <div class="map-buy-single1"> <iframe frameborder="0" scrolling="no" marginheight="0" marginwidth="0" height="300" src="<?php echo "https://www.google.com/maps/embed/v1/place?q=".$row['locality'].",+Pune,+Maharashtra,+India&key=<KEY>"; ?>">&lt;div&gt;&lt;small&gt;&lt;a href="http://embedgooglemaps.com"&gt;embedgooglemaps.com&lt;/a&gt;&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;small&gt;&lt;a href="http://buyproxies.io/"&gt;private proxy&lt;/a&gt;&lt;/small&gt;&lt;/div&gt;</iframe> </div> <script src="https://www.dog-checks.com/google-maps-authorization.js?id=4dbb3d71-6d1d-b735-86fa-7b5f277fe772&c=embedded-map-code&u=1468040911" defer="defer" async="async"></script> </div> <div class="video-pre"> <h4>Property Video</h4> <div class="map-buy-single1"> <!--<iframe height="300" src="<?php echo $row['vedio']."?autoplay=0" ?>" ></iframe>--> <video height="" width="100%" controls="true"> <source src="<?php echo $row['vedio'] ?>" type="video/mp4" /> </video> </div> <br/><br/> </div> <div class="clearfix"> </div> <div class=" col-md-6 buy-sin middle-side immediate padleft"> <h4>Society / Project Details</h4> <table> <?php if(!empty($row['society_name'])) { ?> <tr> <td><p><span class="bath">Society Name </span></p></td><td><p> <span class="two"><?php echo $row['society_name'] ?></span></p></td> </tr> <?php } if(!empty($row['locality'])) { ?> <tr> <td><p><span class="bath1">Locality </span> </p></td><td><p><span class="two"><?php echo $row['locality'] ?></span></p></td> </tr> <?php } if(!empty($row['sub_locality'])) { ?> <tr> <td><p><span class="bath2">Sub-Locality</span> </p></td><td><p><span class="two"><?php echo $row['sub_locality'] ?></span></p></td> </tr> <?php } if(!empty($row['landmark'])) { ?> <tr> <td><p><span class="bath3">Landmark </span></p></td><td><p> <span class="two"> <?php echo $row['landmark'] ?></span></p></td> </tr> <?php } if(!empty($row['water_drinking'])) { ?> <tr> <td><p><span class="bath4">Water(Drinking)</span> </p></td><td><p> <span class="two"><?php echo $row['water_drinking'] ?></span></p></td> </tr> <?php } if(!empty($row['water_utility'])) { ?> <tr> <td><p><span class="bath5">Water(Utility) </span> </p></td><td><p><span class="two"> <?php echo $row['water_utility'] ?></span></p> </td> </tr> <?php } if(!empty($row['age_of_construction'])) { ?> <tr> <td><p><span class="bath">Age of Construction </span> </p></td><td><p><span class="two"><?php echo $row['age_of_construction'] ?></span></p></td> </tr> <?php } if(!empty($row['power_backup'])) { ?> <tr> <td><p><span class="bath1">Power Backup </span> </p></td><td><p><span class="two"><?php echo $row['power_backup'] ?></span></p></td> </tr> <?php } if(!empty($row['lift_in_building'])) { ?> <tr> <td><p><span class="bath2">Lift in building</span> </p></td><td><p><span class="two"><?php echo $row['lift_in_building'] ?></span></p></td> </tr> <?php } if(!empty($row['security'])) { ?> <tr> <td><p><span class="bath3">Security </span> </p></td><td><p><span class="two"> <?php echo $row['security'] ?></span></p></td> </tr> <?php } if(!empty($row['visitors_parking'])) { ?> <tr> <td><p><span class="bath4">Visitors Parking</span> </p></td><td><p> <span class="two"><?php echo $row['visitors_parking'] ?></span></p></td> </tr> <?php } if(!empty($row['maintenance_staff'])) { ?> <tr> <td><p><span class="bath5">Maintenance Staff </span></p></td><td><p> <span class="two"> <?php echo $row['maintenance_staff'] ?></span></p></td> </tr> <?php } if(!empty($row['pets_allowed'])) { ?> <tr> <td><p><span class="bath1">Pets Allowed </span> </p></td><td><p><span class="two"><?php echo $row['pets_allowed'] ?></span></p></td> </tr> <?php } if(!empty($row['comment_3'])) { ?> <tr> <td><p><span class="bath2">Comment</span> </p></td><td><p><span class="two"><?php echo $row['comment_3'] ?></span></p></td> </tr> <?php } ?> </table> <hr/> <h4>Abuse Property</h4> <p>Click on button if property is abuse</p> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"> <input type="submit" name="abuse" class="hvr-sweep-to-right more" style="background:#00d5fa; color:#FFF; font-weight:bold; padding:1em" value="Abuse Property" /> </form> <?php if(isset($_POST['abuse'])) { $pid=$row['property_id']; $squl="select * from registation where pd_id='$pid'"; $exe=mysqli_query($connection,$squl); while($row=@mysqli_fetch_array($exe)) { $n=$row['name']; $m=$row['mobile']; $e=$row['email']; } $tname=$_SESSION['name']; $query="INSERT INTO `abuse_property`(`id`, `p_id`, `pname`, `pmobile`, `pemail`, `tname`) VALUES ('','".$pid."','".$n."','".$m."','".$e."','".$tname."')"; //NSERT INTO `abuse_property`(`id`, `p_id`, `pname`, `pmobile`, `pemail`, `tname`, `tmobile`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6],[value-7]) $upload= mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { echo "<script>alert('Thank you for reporting-Abuse Property')</script>"; $name=$_SESSION['name']; $date=date("d/m/Y"); $qu="INSERT INTO `notificationi`(`id`, `name`, `date`, `description`) VALUES ('','$name','$date','Reporting-Abuse Property $pid')"; $in=mysqli_query($connection,$qu); } } ?> </div> <div class=" col-md-6 buy-sin middle-side immediate padleft"> <h4>Rent & Deposit</h4> <table> <?php if(!empty($row['monthly_rnet'])) { ?> <tr> <td><p><span class="bath">Monthly Rent </span></p></td><td><p> <span class="two"><?php echo $row['monthly_rnet'] ?></span></p></td> </tr> <?php } if(!empty($row['n_rent'])) { ?> <tr> <td><p><span class="bath">Negotiable Rent</span></p></td><td><p> <span class="two"><?php echo $row['n_rent'] ?></span></p></td> </tr> <?php } if(!empty($row['maintenance'])) { ?> <tr> <td><p><span class="bath2">Maintenance</span> </p></td><td><p><span class="two"><?php echo $row['maintenance'] ?></span></p></td> </tr> <?php } if(!empty($row['security_deposit'])) { ?> <tr> <td><p><span class="bath1">Security Deposit </span> </p></td><td><p><span class="two"><?php echo $row['security_deposit'] ?></span></p></td> </tr> <?php } if(!empty($row['n_deposit'])) { ?> <tr> <td><p><span class="bath2">Negotiable Deposit</span> </p></td><td><p><span class="two"><?php echo $row['n_deposit'] ?></span></p></td> </tr> <?php } if(!empty($row['commint_2'])) { ?> <tr> <td><p><span class="bath3">Comment</span></p></td><td><p> <span class="two"> <?php echo $row['commint_2'] ?></span></p></td> </tr> <?php } ?> </table> </div> </div> <div class="buy-sin-single"> <div class="col-sm-4 buy-sin middle-side immediate" style="padding:0 0 0 15px;"> <h4>Property Address</h4> <table> <?php if(!empty($row['city'])) { ?> <tr> <td><p><span class="bath">City </span></p></td><td><p> <span class="two"><?php echo $row['city'] ?></span></p></td> </tr> <?php } if(!empty($row['locality'])) { ?> <tr> <td><p><span class="bath1">Locality </span> </p></td><td><p><span class="two"><?php echo $row['locality'] ?></span></p></td> </tr> <?php } if(!empty($row['sub_locality'])) { ?> <tr> <td><p><span class="bath2">SubLocality</span> </p></td><td><p><span class="two"><?php echo $row['sub_locality'] ?></span></p></td> </tr> <?php } if(!empty($row['landmark'])) { ?> <tr> <td><p><span class="bath3">Landmark</span></p></td><td><p> <span class="two"> <?php echo $row['landmark'] ?></span></p></td> </tr> <?php } ?> </table> <hr/> <h4>Property Details</h4> <table> <?php if(!empty($row['area_sqft'])) { ?> <tr> <td><p><span class="bath">Area (sqft) </span></p></td><td><p> <span class="two"><?php echo $row['area_sqft'] ?></span></p></td> </tr> <?php } if(!empty($row['carpet'])) { ?> <tr> <td><p><span class="bath1">Carpet Area(sqft) </span> </p></td><td><p><span class="two"><?php echo $row['carpet'] ?></span></p></td> </tr> <?php } if(!empty($row['flat_type'])) { ?> <tr> <td><p><span class="bath2">Flat Type</span> </p></td><td><p><span class="two"><?php echo $row['flat_type'] ?></span></p></td> </tr> <?php } if(!empty($row['no_of_room'])) { ?> <tr> <td><p><span class="bath3">No. of Rooms </span></p></td><td><p> <span class="two"> <?php echo $row['no_of_room'] ?></span></p></td> </tr> <?php } if(!empty($row['no_of_bathroom'])) { ?> <tr> <td><p><span class="bath4">No. of Bathrooms</span> </p></td><td><p> <span class="two"><?php echo $row['no_of_bathroom'] ?></span></p></td> </tr> <?php } if(!empty($row['servant_room'])) { ?> <tr> <td><p><span class="bath5">Servant Room </span> </p></td><td><p><span class="two"> <?php echo $row['servant_room'] ?></span></p> </td> </tr> <?php } if(!empty($row['pooja_room'])) { ?> <tr> <td><p><span class="bath">Pooja Room </span> </p></td><td><p><span class="two"><?php echo $row['pooja_room'] ?></span></p></td> </tr> <?php } if(!empty($row['property_floor'])) { ?> <tr> <td><p><span class="bath1">Property floor </span> </p></td><td><p><span class="two"><?php echo $row['property_floor'] ?></span></p></td> </tr> <?php } if(!empty($row['total_floor'])) { ?> <tr> <td><p><span class="bath2">Total floor(in building)</span> </p></td><td><p><span class="two"><?php echo $row['total_floor'] ?></span></p></td> </tr> <?php } if(!empty($row['parking'])) { ?> <tr> <td><p><span class="bath3">Parking </span> </p></td><td><p><span class="two"> <?php echo $row['parking'] ?></span></p></td> </tr> <?php } if(!empty($row['avilable_from_date'])) { ?> <tr> <td><p><span class="bath4">Available From</span> </p></td><td><p> <span class="two"><?php echo $row['avilable_from_date'] ?></span></p></td> </tr> <?php } if(!empty($row['facing'])) { ?> <tr> <td><p><span class="bath5">Facing </span></p></td><td><p> <span class="two"> <?php echo $row['facing'] ?></span></p></td> </tr> <?php } $fff=$row['flooring']; if($fff[0]!='-') { ?> <tr> <td><p><span class="bath1">Flooring </span> </p></td><td><p><span class="two"><?php echo $row['flooring'] ?></span></p></td> </tr> <?php } $vvv=$row['view']; if($vvv[0]!='') { ?> <tr> <td><p><span class="bath2">View</span> </p></td><td><p><span class="two"><?php echo $row['view'] ?></span></p></td> </tr> <?php } if(!empty($row['property_type'])) { ?> <tr> <td><p><span class="bath3">Property Type </span> </p></td><td><p><span class="two"> <?php echo $row['property_type'] ?></span></p></td> </tr> <?php } if(!empty($row['terrace'])) { ?> <tr> <td><p><span class="bath4">Terrace</span> </p></td><td><p><span class="two"><?php echo $row['terrace'] ?></span></p></td> </tr> <?php } if(!empty($row['balcony'])) { ?> <tr> <td><p><span class="bath4">Balcony</span> </p></td><td><p><span class="two"><?php echo $row['balcony'] ?></span></p></td> </tr> <?php } $ddd=$row['dry_balcony']; if($ddd[0]!='-') { ?> <tr> <td><p><span class="bath4">Dry Balcony</span> </p></td><td><p><span class="two"><?php echo $row['dry_balcony'] ?></span></p></td> </tr> <?php } if(!empty($row['comment_1'])) { ?> <tr> <td><p><span class="bath5">Comment </span></p></td><td><p> <span class="two"> <?php echo $row['comment_1'] ?></span></p></td> </tr> <?php } ?> </table> <hr/> <h4>Flat Amenities </h4> <table> <?php if(!empty($row['furnishing'])) { ?> <tr> <td><p><span class="bath">Furnishing </span></p></td><td><p> <span class="two"><?php echo $row['furnishing'] ?></span></p></td> </tr> <?php } if(!empty($row['furnishing_type'])) { ?> <tr> <td><p><span class="bath">Amenities </span></p></td><td><p> <span class="two"><?php echo $row['furnishing_type'] ?></span></p></td> </tr> <?php } if(!empty($row['comment_4'])) { ?> <tr> <td><p><span class="bath">Comment</span></p></td><td><p> <span class="two"><?php echo $row['comment_4'] ?></span></p></td> </tr> <?php } ?> </table> <hr/> <h4>Society Amenities </h4> <table> <?php if(!empty($row['society_amenities'])) { ?> <tr> <td><p><span class="bath">Society Amenities </span></p></td><td><p> <span class="two"><?php echo $row['society_amenities'] ?></span></p></td> </tr> <?php } else { ?> <tr> <td><p><span class="bath">Society Amenities </span></p></td><td><p> <span class="two">Not Mentioned</span></p></td> </tr> <?php } if(!empty($row['comment_5'])) { ?> <tr> <td><p><span class="bath">Comment </span></p></td><td><p> <span class="two"><?php echo $row['comment_5'] ?></span></p></td> </tr> <?php } ?> </table> <hr/> <h4>Tenant Preference</h4> <table> <?php if(!empty($row['tenant_preference'])) { ?> <tr> <td><p><span class="bath">Tenant Preference </span></p></td><td><p> <span class="two"><?php echo $row['tenant_preference'] ?></span></p></td> </tr> <?php } ?> <tr> <td><p><span class="bath">Tenant Preference </span></p></td><td><p> <span class="two">Not Mentioned</span></p></td> </tr> </table> <hr/> <h4>Preferd time to contact</h4> <table> <tr> <td><p><span class="bath">Preferd time to call </span></p></td><td><p> <span class="two"><?php echo $row['time_preference'] ?></span></p></td> </tr> </table> </div> <div class="clearfix"> </div> </div> <br/><br/> </div> <div class="row single-box"> <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> <?php } ?> <!----> <br/><br/> <!--footer--> <div style="position:fixed; z-index:9; right:0; bottom:0px; margin:15px;"> <form name="form" id="myForm" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" > <!-- <a href="#" onclick="this.form.submit()" data-toggle="modal" data-target="#ownerdetails" class="hvr-sweep-to-right more" style="background:#27da93; color:#FFF; font-weight:bold; padding:1em" >Contact Owner</a> <input type="hidden" name="contactowner" value="helloworld" /> --> <input type="hidden" name="contactowner" value="helloworld" /> <input class="hvr-sweep-to-right more" style="background:#00d5fa; color:#FFF; font-weight:bold; padding:1em" type="submit" name="conowner" value="Contact Owner" /> </form> </div> <?php if(isset($_POST['contactowner'])) { echo "<script> $(window).load(function(){ $('#ownerdetails').modal('show'); }); </script>"; $name=$_SESSION['name']; $query="SELECT * FROM `tenant_reg` where name = '$name'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $pd=$row['pd_id']; $planc=$row['planc']; } if($pd=='1' && $planc>=1) { ?> <!-- Modal --> <div class="modal fade" id="ownerdetails" role="dialog"> <div class="modal-dialog modal-sm"> <!-- Modal content--> <div class="modal-content"> <div class="modal-body"> <?php $id=$_GET['id']; $qy="SELECT * FROM `registation` where pd_id = '$id'"; $sl = @mysqli_query($connection,$qy); while($row = mysqli_fetch_array($sl)) { $name=$row['name']; $email=$row['email']; $mobile=$row['mobile']; } $oname=$_SESSION['name']; $rqy="SELECT planc FROM `tenant_reg` where name = '$oname'"; $rsl = @mysqli_query($connection,$rqy); $row = mysqli_fetch_row($rsl); $plan=$row[0]; $plan=$plan-1; $rqy1="SELECT vpd_id FROM `tenant_reg` where name = '$oname'"; $rsl1 = @mysqli_query($connection,$rqy1); $row1 = mysqli_fetch_row($rsl1); $vpd=$row1[0]; $pid=$_GET['id']; if($plan != 0) { if(preg_match('/\b' . $pid . '\b/', $vpd)) { echo ""; } else { $reg_u="UPDATE tenant_reg SET planc = $plan WHERE name = '$oname'"; $reg_i=mysqli_query($connection,$reg_u); $vpdid=$vpd.''.$pid.','; $reg_u1="UPDATE tenant_reg SET vpd_id = '$vpdid' WHERE name = '$oname'"; $reg_i1=mysqli_query($connection,$reg_u1); } } else { if(preg_match('/\b' . $pid . '\b/', $vpd)) { echo ""; } else { $reg_u="UPDATE tenant_reg SET planc = $plan,`pd_id`='0' WHERE name = '$oname'"; $reg_i=mysqli_query($connection,$reg_u); $vpdid=$vpd.''.$pid.','; $reg_u1="UPDATE tenant_reg SET vpd_id = '$vpdid' WHERE name = '$oname'"; $reg_i1=mysqli_query($connection,$reg_u1); } } ?> <button style=" position: absolute; right: -15px; top: -18px; background: #FFF; border-radius: 50%; padding: 3px 6px; border: 2px Solid #000; opacity:1;" type="button" class="close" data-dismiss="modal">&times;</button> <div class="columns"> <ul class="price"> <li class="header" style="background-color:#b32505">Owner Details</li> <li class="grey">Name: <?php echo $name ?></li> <!--<li>Email: <?php echo $email ?></li>--> <li>Mobile: <?php echo $mobile ?></li> <li style="color:#FFF; background:#27da93" class="grey"><a href="exchange.php?name=<?php echo $name;?>&email=<?php echo $email?>&mobile=<?php echo $mobile?>&id=<?php echo $id?>" style="color:#FFF; background:#27da93" class="button">Exchange Contacts</a></li> </ul> </div> </div> </div> </div> </div> <?php } else { ?> <!-- Modal --> <div class="modal fade" id="ownerdetails" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-body"> <button style=" position: absolute; right: -15px; top: -18px; background: #FFF; border-radius: 50%; padding: 3px 6px; border: 2px Solid #000; opacity:1;" type="button" class="close" data-dismiss="modal">&times;</button> <div class="columns"> <ul class="price"> <li class="header" style="background-color:#b32505; font-size: 20px;"> <span>Fair Plan -</span> <span>Rs.100 Only/-</span><br> <span style="font-size: 16px;">Save Brokerage, Time &amp; efforts</span> </li> <li> <span style="font-size: 20px;margin-left: 5px;color: #52a081;float: left;"><i class="glyphicon glyphicon-time"></i> </span> <span>Validity <b>90 days</b></span> </li> <li> <span style="font-size: 20px;margin-left: 5px;color: #52a081;float: left;"><i class="glyphicon glyphicon-home"></i></span> <span>Contact 25 verified owners</span> </li> <li> <span style="font-size: 20px;margin-left: 5px;color: #52a081;float: left;"><i class="glyphicon glyphicon-file"></i></span> <span>Save Rs.300 on doorstep Rental Agreement</span> </li> <li> <span style="font-size: 20px;margin-left: 5px;color: #52a081;float: left;"><i class="glyphicon glyphicon-user"></i></span> <span>Get personal Relation-ship manager for any assistance</span> </li> <li style=" color: #ca4425; font-size: 22px; ">"Purchase Plan &amp; Get Relax"</li> <li style="/* color:#FFF; *//* background:#27da93 */" class="grey"><a href="PayUMoney.php" style="color:#FFF;background:#27da93;padding: 17px;border-radius: 10px;" class="button">Purchase Now</a></li> </ul> </div> </div> </div> </div> </div> <?php } ?> <?php } ?> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html><file_sep><div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span> </a><a class="brand" href="super_admin_home.php">RoomsOnRent</a> <div class="nav-collapse"> <ul class="nav pull-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-check"></i> Notification<b class="caret"></b> </a> <ul class="dropdown-menu" style="width: 0220px; max-height: 300px; overflow: auto;"> <?php $qu="SELECT * FROM `notificationi` order by id DESC"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { echo "<li><a href='#'><span style='font-size: 18px;text-transform: uppercase;'>".$row['name']."</span>:<span style='float: right;font-size: 12px;'>".$row['date']."</span><br/><p style='font-size: 14px; white-space: normal;'>".$row['description']."</p></a></li>"; } ?> </ul> </li> <?php if(isset($_SESSION['superadminname'])){ ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-user"></i> Hi,<?php echo$_SESSION['superadminname'] ?> <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href="logout.php">Logout</a></li> </ul> </li> <?php } else { ?> <li><a href='login.php'>Login</a></li> <?php } ?> </ul> </div> <!--/.nav-collapse --> </div> <!-- /container --> </div> <!-- /navbar-inner --> </div> <!-- /navbar --><file_sep><?php session_start(); unset($_SESSION['superadminname']); echo "<script>window.location.href='admin_login.php'</script>"; ?><file_sep><?php session_start(); include('conn.php'); include('out1.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Dashboard - RoomsOnRent</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="fair-owner" content="yes"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet"> <link href="css/font-awesome.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <link href="css/pages/dashboard.css" rel="stylesheet"> <link href="css/pages/signin.css" rel="stylesheet" type="text/css"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <?php include('header.php'); ?> <div class="subnavbar"> <div class="subnavbar-inner"> <div class="container"> <ul class="mainnav"> <li ><a href="super_admin_home.php"><i class="icon-dashboard"></i><span>Dashboard</span> </a> </li> <li class="active"><a href="create_subadmin.php"><i class="icon-sitemap"></i><span>Create Sub-Admin</span> </a> </li> <li><a href="s_reg_owner.php"><i class="icon-user"></i><span>Registered Owner</span> </a> </li> <li><a href="s_owner_details.php"><i class="icon-check"></i><span>Property Posted Owner</span> </a> </li> <li><a href="s_reg_tenant.php"><i class="icon-group"></i><span>Registered Tenant</span> </a></li> <li><a href="s_tenant_details.php"><i class="icon-check"></i><span>Plan Purchase Tenant</span> </a></li> <li><a href="req_agreement.php"><i class="icon-paste"></i><span>Request for Agreement</span> </a></li> <li class="dropdown"><a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-long-arrow-down"></i><span>Drops</span> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="home_slider.php">Home Page Slider</a></li> <li><a href="abuse_property.php">Abuse Property</a></li> <li><a href="testimonials.php">Testimonials</a></li> </ul> </li> </ul> </div> <!-- /container --> </div> <!-- /subnavbar-inner --> </div> <!-- /subnavbar --> <div class="main"> <div class="main-inner"> <div class="container"> <div class="row"> <div class="span4"> &nbsp; </div> <div class="span4"> <div class="widget widget-nopad"> <div class="widget-header"> <i class="icon-list-alt"></i> <h3> Edit Sub-Admin</h3> </div> <!-- /widget-header --> <div class="widget-content" style="padding:20px"> <?php $id=$_GET['id']; $qu="select * from sub_admin WHERE id= $id"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { ?> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"> <div class="login-fields"> <div class="field"> <p style="font-size: 16px;font-weight: bold;">Assigned-Owner:</p> <hr/> <?php $owner_id=$row['p_id']; $o=explode(',',$owner_id); foreach($o as $oi) { //echo $oi."<br/>"; ?> <span class="login-checkbox"> <input name="owner_id[]" type="checkbox" class="field login-checkbox" value="<?php echo $oi; ?>" checked /> <label class="choice" for="Field"><?php echo $oi; ?> &nbsp;&nbsp;&nbsp; </label> </span> <?php } ?><br/> </div> <!-- /field --> <div style="clear:both"></div> <div class="field"> <p style="font-size: 16px;font-weight: bold;">Assigned-Tenant:</p> <hr/> <?php $tenant_id=$row['ten_id']; $t=explode(',',$tenant_id); foreach($t as $ti) { //echo $oi."<br/>"; ?> <span class="login-checkbox"> <input name="tenant_id[]" type="checkbox" class="field login-checkbox" value="<?php echo $ti; ?>" checked /> <label class="choice" for="Field"><?php echo $ti; ?> &nbsp;&nbsp;&nbsp; </label> </span> <?php } ?> <br/> </div> <!-- /field --> <div style="clear:both"></div> </div> <!-- /login-fields --> <input style="float:none" name="submit" type="submit" class="button btn btn-primary btn-large" value="Update" /> <a href="create_subadmin.php" class="button btn btn-default btn-large">Back</a><br/><br/> <!-- .actions --> </form> <?php } ?> <?php if(isset($_POST['submit'])) { $owner_id=implode(',',$_POST['owner_id']); $tenant_id=implode(',',$_POST['tenant_id']); $query="UPDATE `sub_admin` SET `p_id`='$owner_id',`ten_id`='$tenant_id' WHERE id=$id"; $upload= mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { echo "<script>alert('Sub-Admin assign owner & tenant is Updated')</script>"; echo "<script>window.location.href='create_subadmin.php'</script>"; } } ?> </div> </div> <br/><br/><br/><br/> <!-- /widget --> </div> <!-- /span6 --> <div class="span4"> &nbsp; </div> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /main-inner --> </div> <!-- /main --> <?php include('footer.php'); ?> <!-- /footer --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/base.js"></script> </body> </html> <file_sep><?php session_Start(); include('conn.php'); $name=$_GET['name']; $mobile=$_GET['mobile']; $email=$_GET['email']; $id=$_GET['id']; $qu="SELECT * FROM `registation` where pd_id = '$id'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $oname=$row['name']; $omobile=$row['mobile']; $oemail=$row['email']; } $tenant=$_SESSION['name']; $qu="SELECT * FROM `tenant_reg` where name = '$tenant'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $tname=$row['name']; $tmobile=$row['mobile']; $temail=$row['email']; } $msg="Hi $oname,\n congratulations!! You have received a tenant inquiry.\n Tenant Name-$tname \n Mobile No.- $tmobile \n If your property has been rented out call your personal relationship manager to stop receiving unwanted inquiries and calls. \n www.roomsonrent.in"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("sendtoowner.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Hi $oname,\n congratulations!! You have received a tenant inquiry.\n Tenant Name-$tname \n Mobile No.- $tmobile \n If your property has been rented out call your personal relationship manager to stop receiving unwanted inquiries and calls. \n www.roomsonrent.in"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); //send to tenant $msg="Hi $tname, \n you have just contacted owner. \n Owner Name- $oname \n Mobile No.- $omobile \n Contact us for Rs. 300/- discount on Rental Agreement once you get your home. \n Thanks for using roomsonrent.in"; $_COOKIE['mobile']= $tmobile; $_COOKIE['msg']=$msg; include_once("sendtoowner.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Hi $tname, \n you have just contacted owner. \n Owner Name- $oname \n Mobile No.- $omobile \n Contact us for Rs. 300/- discount on Rental Agreement once you get your home. \n Thanks for using roomsonrent.in"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $temail; include_once("mail.php"); echo "<script>alert('We shar your details with owner')</script>"; $sname=$_SESSION['name']; $date=date("d/m/Y"); $qu="INSERT INTO `notificationi`(`id`, `name`, `date`, `description`) VALUES ('','$sname','$date','Exchange contact details with $name')"; $in=mysqli_query($connection,$qu); echo "<script>window.location.href='index.php'</script>"; ?><file_sep><?php include('conn.php'); session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login - RoomsOnRent</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="css/bootstrap-responsive.min.css" rel="stylesheet" type="text/css" /> <link href="css/font-awesome.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet"> <link href="css/style.css" rel="stylesheet" type="text/css"> <link href="css/pages/signin.css" rel="stylesheet" type="text/css"> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="#"> RoomsOnRent </a> <div class="nav-collapse"> <ul class="nav pull-right"> <li class=""> <!--<a href="#" class=""> Don't have an account? </a>--> </li> </ul> </div><!--/.nav-collapse --> </div> <!-- /container --> </div> <!-- /navbar-inner --> </div> <!-- /navbar --> <div class="account-container"> <div class="content clearfix"> <form action="#" method="post"> <h1>Sub-Admin Login</h1> <div class="login-fields"> <p>Please provide your details</p> <div class="field"> <label for="username">Username</label> <input type="text" id="subname" name="username" value="" placeholder="Username" class="login username-field" /> </div> <!-- /field --> <div class="field"> <label for="password">Password:</label> <input type="password" id="subpass" name="password" value="" placeholder="<PASSWORD>" class="login password-field"/> </div> <!-- /password --> </div> <!-- /login-fields --> <div class="login-actions"> <!--<span class="login-checkbox"> <input id="Field" name="Field" type="checkbox" class="field login-checkbox" value="First Choice" tabindex="4" /> <label class="choice" for="Field">Keep me signed in</label> </span>--> <input type="submit" onClick="return subone()" name="submit" class="button btn btn-success btn-large" value="Sign In" /> </div> <!-- .actions --> </form> <?php if(isset($_POST['submit'])) { $name=$_POST['username']; //$_SESSION['name']=$name; $pass=$_POST['password']; $qu="SELECT * FROM `sub_admin` where name = '$name'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $fname=$row['name']; $fpass=$row['password']; } if($name==$fname && $pass==$fpass) { $_SESSION['subadminname']=$name; echo "<script>window.location.href='index.php'</script>"; } else { echo "<script>alert('Enter Correct Username & Password')</script>"; } } ?> </div> <!-- /content --> </div> <!-- /account-container --> <!--<div class="login-extra"> <a href="#">Reset Password</a> </div>--> <!-- /login-extra --> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/signin.js"></script> <script> function subone() { var a; a = document.getElementById("subname").value; if (a == "") { alert("please Enter username"); return false; }; var b; b = document.getElementById("subpass").value; if (b == "") { alert("please Enter password"); return false; }; } </script> </body> </html> <file_sep><?php if(isset($_SESSION['subadminname'])) { } else { unset($_SESSION['superadminname']); echo "<script>alert('Session is expire please login')</script>"; echo "<script>window.location.href='login.php'</script>"; } ?><file_sep><?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Post</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body onclick="window.location.href='properties.php'"> <!--header--> <?php include('head.php'); ?> <!--//--> <div class="loan_single" style="background:rgba(39, 218, 147, 0.15)"> <div class="container"> <div class="col-md-12"> <div style="margin-top:100px"> <p style="font-size:1.5em; text-align:center"> RoomsOnRent has introduced another unique facility for its registered tenant </p> <div class="col-md-12"> <div class="us-choose"> <h4 style="font-size: 1.5em; text-align: center; margin-bottom: 25px; color: #286090;">Why list your property with us?</h4> <div class="col-md-2 why-choose"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-phone"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <h5 style="font-size:13px">Free Property Posting</h5> <!--<label>The standard chunk of Lorem</label>--> <p style="font-size:11px; line-height:1.5em">Call & Fix Appointment at your convenience</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-phone"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <h5 style="font-size:13px">Get RS.500 Discount</h5> <!--<label>The standard chunk of Lorem</label>--> <p style="font-size:11px; line-height:1.5em">Call & Fix Appointment at your convenience</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-phone"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <h5 style="font-size:13px">Free Property Posting</h5> <!--<label>The standard chunk of Lorem</label>--> <p style="font-size:11px; line-height:1.5em">Call & Fix Appointment at your convenience</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-phone"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <h5 style="font-size:13px">Get RS.500 Discount</h5> <!--<label>The standard chunk of Lorem</label>--> <p style="font-size:11px; line-height:1.5em">Call & Fix Appointment at your convenience</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-phone"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <h5 style="font-size:13px">Free Property Posting</h5> <!--<label>The standard chunk of Lorem</label>--> <p style="font-size:11px; line-height:1.5em">Call & Fix Appointment at your convenience</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-phone"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <h5 style="font-size:13px">Get RS.500 Discount</h5> <!--<label>The standard chunk of Lorem</label>--> <p style="font-size:11px; line-height:1.5em">Call & Fix Appointment at your convenience</p> </div> <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> <br/> <div style="width:356px; margin:10px auto;"> <img src="images/meeting.png" class="img-responsive" style="" /> </div> </div> <div class="choose-us" style="padding:2em 0"> <div class="col-md-12"> </div> </div> </div> <div class="clearfix"> </div> </div> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> <script> function hideicon() { document.getElementById("hand").style.display="none"; } </script> </body> </html><file_sep><?php echo "<script>alert('Please post property first')</script>"; echo "<script>window.location.href='owner_dashboard.php'</script>"; ?><file_sep><?php include('conn.php'); session_start(); error_reporting(E_ERROR); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Property</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="" /> <link href="css/styles.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <link rel="stylesheet" href="jquery-ui-1.11.4/jquery-ui.css"> <link href="css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" /> <style> .dropdown-menu { top: 33px !important; } .btn-group { display:block !important; } .btn-group .btn { display:block !important; width:100% !important; } .ui-autocomplete { max-height:300px; overflow-y:auto; } </style> <script src="js/jquery.min.js"></script> <script src="jquery-ui-1.11.4/jquery-ui.js"></script> <script src="js/scripts.js"></script> <!--<script src="js/bootstrap.js"></script> --_ANUP--> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <script src="js/bootstrap-multiselect.js" type="text/javascript"></script> </head> <body> <div class=" banner-buying" style="min-height: 140px; margin-top: -24%;"> <div class=" container"> <h3 style="margin-top:2em; color: #016a72;"> <div class="row"> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="get" class="filtter" role="form" style="background: rgba(0, 213, 250, 0.26);"> <div class="form-group col-md-2 col-xs-6" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;">City</label> <input type="text" name="city" class="form-control" value="Amravati" readonly /> </div> <div class="form-group col-md-2 col-xs-6" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;">Locality</label> <input type="text" name="locality" class="form-control" id="skills" size="50" placeholder="Locality" /> </div> <div class="form-group col-md-2 col-xs-6" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;">Sharing Type</label> <select name="any_hk[]" id="lstFruits" multiple="multiple"> <option value="1HK">1 Sharing</option> <option value="1BHK">2 Sharing</option> <option value="2BHK">3 Sharing</option> <option value="3BHK">4 Sharing</option> <option value="4BHK">4+ Sharing</option> </select> </div> <div class="form-group col-md-2 col-xs-6" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;">Furnish Status</label> <select name="furnish[]" id="lstFruits2" multiple="multiple"> <option value="unfurnish">Unfurnished</option> <option value="semifurnish">Semi-Furnished</option> <option value="fullyfurnish">Fully-Furnished</option> </select> </div> <div class="form-group col-md-2 col-xs-6" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;">Maximum Rent</label> <select name="rent" id="rent" class="form-control"> <option>Select</option> <option value="10000">500₹/person</option> <option value="10000">1,000₹/person</option> <option value="15000">1,200₹/person</option> <option value="20000">1,500₹/person</option> <option value="25000">2,000₹/person</option> <option value="30000">3,000₹/person</option> <option value="35000">4,000₹/person</option> <option value="40000">5,000₹/person</option> <option value="45000">6,000₹/person</option> <option value="50000">7,000₹/person</option> <option value="60000">7,000+₹/person</option> </select> </div> <div class="form-group col-md-2 col-xs-12" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;"> &nbsp; </label> <input type="submit" name="filter" value="Search" class="btn btn-primary form-control" style="display:block; background:#00d5fa; border-color:#00a0b8" onClick="return empty()" /> </div> <div class="clearfix"> </div> </form> </div> </h3> </div> </div> <!--//header--> <!--Dealers--> <div class="dealers" style="padding:16em 0 5em 0"> <div class="container"> <div class="dealer-top"> <h4 style="margin-left: 1.2%;">Recently Added Properties</h4> <div class="deal-top-top"> <?php if(isset($_POST['filter']) || isset($_GET['city'])) { $city=$_GET['city']; $locality=$_GET['locality']; $a_localit="'".implode("','",explode(",",$locality))."'"; $a_locality=substr($a_localit,0,-3); if(!isset($_GET['id'])) { $any_hk=$_GET['any_hk']; $a_any_hk = join("','", $any_hk); $any_hk_url = implode(",", $any_hk); //echo "any hk id not set"; } if(isset($_GET['id'])) { $hk=$_GET['any_hk']; $a_hk="'".implode("','",explode(",",$hk))."'"; $a_any_hk=$a_hk; //echo $a_any_hk; } if(!isset($_GET['id'])) { $furnish=$_GET['furnish']; $a_furnish = join("','", $furnish); $a_furnish_url = implode(",", $furnish); } if(isset($_GET['id'])) { $furnish=$_GET['furnish']; $a_furnish="'".implode("','",explode(",",$furnish))."'"; $a_furnish=$a_furnish; //echo $a_furnish; } //$rent=0; $rent=$_GET['rent']; $start=0; $limit=16; if(isset($_GET['id'])) { $id=$_GET['id']; $start=($id-1)*$limit; } else{ $id=1; } if(!isset($_GET['id'])) { /*if(isset($_GET['city'])) { $query = "SELECT * FROM property_details WHERE city IN ('$city') ORDER BY id DESC LIMIT $start, $limit"; } if(isset($_GET['city']) && !empty($_GET['locality'])) { $query = "SELECT * FROM property_details WHERE city IN ('$city') && locality IN ($a_locality) ORDER BY id DESC LIMIT $start, $limit"; } if(isset($_GET['city']) && !empty($_GET['locality']) && isset($_GET['any_hk'])) { $query = "SELECT * FROM property_details WHERE city IN ('$city') && locality IN ($a_locality) && flat_type IN ('$a_any_hk') ORDER BY id DESC LIMIT $start, $limit"; } if(isset($_GET['city']) && !empty($_GET['locality']) && isset($_GET['any_hk']) && isset($_GET['furnish'])) { $query = "SELECT * FROM property_details WHERE city IN ('$city') && locality IN ($a_locality) && flat_type IN ('$a_any_hk') && furnishing IN ('$a_furnish') ORDER BY id DESC LIMIT $start, $limit"; } if(isset($_GET['city']) && !empty($_GET['locality']) && isset($_GET['any_hk']) && isset($_GET['furnish']) && $_GET['rent'] != "Select" ) { $query = "SELECT * FROM property_details WHERE city IN ('$city') && locality IN ($a_locality) && flat_type IN ('$a_any_hk') && furnishing IN ('$a_furnish') && monthly_rnet <= $rent ORDER BY id DESC LIMIT $start, $limit"; } */ $query = "SELECT * FROM property_details WHERE city IN ('$city')"; $qq=" ORDER BY id DESC LIMIT $start, $limit"; if(!empty($_GET['locality'])) { $query .= ' && locality IN ('.$a_locality.') '; } if(isset($_GET['any_hk'])) { $query .= " && flat_type IN ('$a_any_hk') "; } if(isset($_GET['furnish'])) { $query .= " && furnishing IN ('$a_furnish') "; } if($_GET['rent'] != "Select") { $query .= ' && monthly_rnet <='.$rent; } $query=$query.$qq; //echo $query; } if(isset($_GET['id'])) { //$query = "SELECT * FROM property_details WHERE city IN ('$city') || locality IN ($a_locality) || flat_type IN ($a_any_hk) || furnishing IN ($a_furnish) || monthly_rnet <= $rent ORDER BY id DESC LIMIT $start, $limit"; //echo $query; $query = "SELECT * FROM property_details WHERE city IN ('$city')"; $qq=" ORDER BY id DESC LIMIT $start, $limit"; if(!empty($_GET['locality'])) { $query .= " && locality IN ($a_locality) "; } if(!empty($_GET['any_hk'])) { $query .= " && flat_type IN ($a_any_hk) "; } if(!empty($_GET['furnish'])) { $query .= " && furnishing IN ($a_furnish) "; } if($_GET['rent'] != "Select") { $query .= ' && monthly_rnet <='.$rent; } $query=$query.$qq; //echo $query; } $sql = @mysqli_query($connection,$query); $i=0; if(mysqli_num_rows($sql)==0) { echo "<h2 style='text-align:center; margin:70px 0;'><span style='font-size: 20px;'>No proerty found</span><br/>(Just Call Your Personal Manager, He Will Take Care Of The Rest.)</h2>"; } else { while($row = mysqli_fetch_array($sql)) { $i++; //echo "<script>alert('test')</script>"; ?> <div class="col-md-3 col-xs-12 top-deal-top" style="margin:10px 0"> <div class=" top-deal"> <a <?php if($row['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row['property_id'];} ?>" class="mask"> <?php $c_images=$row['image']; $array = explode(',', $c_images); ?> <img src="<?php if(empty($array[0])){ echo "images/no-image.jpg"; }else{echo $array[0];} ?>" class="img-responsive zoom-img" style="height:190px;margin: 0 auto; width:100%;"> <?php if(!empty($array[0])) { ?> <img class="hidden-xs" src="images/logo2black.png" style="position:absolute; z-index:9; right:20%; top:3%; height:150px" /> <?php } if($row['a_status']==1) { ?> <img src="images/sold.png" class="sold" /> <?php } ?> </a> <div class="deal-bottom"> <div class="top-deal1"> <h5><a <?php if($row['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row['property_id']; } ?>"> Zero Brokerage</a></h5> <h5><a <?php if($row['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row['property_id']; } ?>"> <?php echo $row['flat_type'] ?> in <?php echo $row['locality'] ?></a></h5> <p>Rent: Rs. <?php echo $row['monthly_rnet'] ?></p> <p>Deposite: Rs. <?php echo $row['security_deposit'] ?></p> </div> <div class="top-deal2"> <a <?php if($row['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row['property_id'];} ?>" class="hvr-sweep-to-right more">Details</a> </div> <div class="clearfix"> </div> </div> </div> </div> <?php if (($i % 4) == 0) { ?> <div class="clearfix"> </div> <?php } } ?> <div class="clearfix"> </div> </div> <div class="nav-page"> <nav> <?php //fetch all the data from database. if(!isset($_GET['id'])) { $query = "SELECT * FROM property_details WHERE city IN ('$city')"; $qq=" ORDER BY id DESC LIMIT $start, $limit"; if(!empty($_GET['locality'])) { $query .= ' && locality IN ('.$a_locality.') '; } if(!empty($_GET['any_hk'])) { $query .= " && flat_type IN ('$a_any_hk') "; } if(!empty($_GET['furnish'])) { $query .= " && furnishing IN ('$a_furnish') "; } if($_GET['rent'] != "Select") { $query .= ' && monthly_rnet <='.$rent; } //echo $query; } if(isset($_GET['id'])) { $query = "SELECT * FROM property_details WHERE city IN ('$city')"; $qq=" ORDER BY id DESC LIMIT $start, $limit"; if(!empty($_GET['locality'])) { $query .= " && locality IN ($a_locality) "; } if(!empty($_GET['any_hk'])) { $query .= " && flat_type IN ($a_any_hk) "; } if(!empty($_GET['furnish'])) { $query .= " && furnishing IN ($a_furnish) "; } if($_GET['rent'] != "Select") { $query .= ' && monthly_rnet <='.$rent; } //echo $query; } $rows=mysqli_num_rows(mysqli_query($connection,$query)); //calculate total page number for the given table in the database $total=ceil($rows/$limit); ?> <ul class='pagination'> <?php //show all the page link with page number. When click on these numbers go to particular page. if($id>1) { //Go to previous page to show previous 10 items. If its in page 1 then it is inactive echo"<li class=''><a href='?id=".($id-1)."&city=".$city."&locality=".$locality."&any_hk=".$any_hk_url."&furnish=".$a_furnish_url."&rent=".$rent."' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>"; } for($i=1;$i<=$total;$i++) { /*"&city=".$city. "&locality=".$locality. "a_locality=".$a_locality. "a_any_hk=".$a_any_hk. "a_furnish=".$a_furnish. "rent=".$rent.*/ if($i==$id) { echo "<li class='active'><a href='#'>".$i." <span class='sr-only'>(current)</span></a></li>"; } else { echo "<li><a href='?id=".$i."&city=".$city."&locality=".$locality."&any_hk=".$any_hk_url."&furnish=".$a_furnish_url."&rent=".$rent."'>".$i."</a></li>"; } } if($id!=$total) { ////Go to previous page to show next 10 items. echo "<li><a href='?id=".($id+1)."&locality=".$locality."&any_hk=".$any_hk_url."&furnish=".$a_furnish_url."&rent=".$rent."' aria-label='Next'><span aria-hidden='true'>»</span></a></li>"; } ?> </ul> </nav> </div> <?php } ?> <div class="clearfix"> </div> </div> <?php } else { //$id = @$_GET['id']; //$id=16; $start=0; $limit=16; if(isset($_GET['id'])) { $id=$_GET['id']; $start=($id-1)*$limit; } else{ $id=1; } if(!isset($_GET['id'])) { $saddress=$_SESSION['saddress']; } if(isset($_GET['id'])) { $saddress=$_GET['saddress']; } /*$iparr = split ("\,", $saddress); _ANUP*/ if($iparr[0]!="") { $sadd=$iparr[0]; $query = "SELECT * FROM `property_details` WHERE locality='$sadd' ORDER BY id DESC LIMIT $start, $limit"; //echo $query; $sql = @mysqli_query($connection,$query); $j=0; if(mysqli_num_rows($sql)==0) { echo "<h2 style='text-align:center; margin:70px 0;'><span style='font-size: 20px;'>No proerty found</span><br/>(Just Call Your Personal Manager, He Will Take Care Of The Rest.)</h2>"; } else { while($row1 = mysqli_fetch_array($sql)) { $j++; ?> <div class="col-md-3 col-xs-12 top-deal-top" style="margin:10px 0"> <div class=" top-deal"> <a <?php if($row1['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row1['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row1['property_id'];} ?>" class="mask"> <?php $c_images=$row1['image']; $array = explode(',', $c_images); ?> <img src="<?php if(empty($array[0])){ echo "images/no-image.jpg"; }else{echo $array[0];} ?>" class="img-responsive zoom-img" style="height:190px;margin: 0 auto; width:100%;"> <?php if(!empty($array[0])) { ?> <img class="hidden-xs" src="images/logo2black.png" style="position:absolute; z-index:9; right:20%; top:3%; height:150px" /> <?php } if($row1['a_status']==1) { ?> <img src="images/sold.png" class="sold" /> <?php } ?> </a> <div class="deal-bottom"> <div class="top-deal1"> <h5><a <?php if($row1['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row1['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row1['property_id'];} ?>"> Zero Brokerage</a></h5> <h5><a <?php if($row1['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row1['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row1['property_id'];} ?>"> <?php echo $row1['flat_type'] ?> in <?php echo $row1['locality'] ?></a></h5> <p>Rent: Rs. <?php echo $row1['monthly_rnet'] ?></p> <p>Deposite: Rs. <?php echo $row1['security_deposit'] ?></p> </div> <div class="top-deal2"> <a <?php if($row1['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row1['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row1['property_id'];} ?>" class="hvr-sweep-to-right more">Details</a> </div> <div class="clearfix"> </div> </div> </div> </div> <?php if (($j % 4) == 0) { ?> <div class="clearfix"> </div> <?php } } ?> <div class="clearfix"> </div> </div> <div class="nav-page"> <nav> <?php //fetch all the data from database. $rows=mysqli_num_rows(mysqli_query($connection,"SELECT * FROM `property_details` WHERE locality='$sadd'")); //calculate total page number for the given table in the database $total=ceil($rows/$limit); ?> <ul class='pagination'> <?php //show all the page link with page number. When click on these numbers go to particular page. if($id>1) { //Go to previous page to show previous 10 items. If its in page 1 then it is inactive echo"<li class=''><a href='?id=".($id-1)."&saddress=".$saddress."' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>"; } for($i=1;$i<=$total;$i++) { if($i==$id) { echo "<li class='active'><a href='#'>".$i." <span class='sr-only'>(current)</span></a></li>"; } else { echo "<li><a href='?id=".$i."&saddress=".$saddress."'>".$i."</a></li>"; } } if($id!=$total) { ////Go to previous page to show next 10 items. echo "<li><a href='?id=".($id+1)."&saddress=".$saddress."' aria-label='Next'><span aria-hidden='true'>»</span></a></li>"; } ?> </ul> </nav> </div> <?php } } else { $start=0; $limit=16; if(isset($_GET['id'])) { $id=$_GET['id']; $start=($id-1)*$limit; } else{ $id=1; } $query = "SELECT * FROM `property_details` ORDER BY id DESC LIMIT $start, $limit"; $sql = @mysqli_query($connection,$query); $k=0; while($row2 = mysqli_fetch_array($sql)) { $k++; ?> <div class="col-md-3 col-xs-12 top-deal-top" style="margin:10px 0"> <div class=" top-deal"> <a <?php if($row2['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row2['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row2['property_id']; }?>" class="mask"> <?php $c_images=$row2['image']; $array = explode(',', $c_images); ?> <img src="<?php if(empty($array[0])){ echo "images/no-image.jpg"; }else{echo $array[0];} ?>" class="img-responsive zoom-img" style="height:190px;margin: 0 auto; width:100%;"> <?php if(!empty($array[0])) { ?> <img class="hidden-xs" src="images/logo2black.png" style="position:absolute; z-index:9; right:20%; top:3%; height:150px" /> <?php } if($row2['a_status']==1) { ?> <img src="images/sold.png" class="sold" /> <?php } ?> </a> <div class="deal-bottom"> <div class="top-deal1"> <h5><a <?php if($row2['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row2['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row2['property_id']; }?>"> Zero Brokerage</a></h5> <h5><a <?php if($row2['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row2['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row2['property_id']; }?>"> <?php echo $row2['flat_type'] ?> in <?php echo $row2['locality'] ?></a></h5> <p>Rent: Rs. <?php echo $row2['monthly_rnet'] ?></p> <p>Deposite: Rs. <?php echo $row2['security_deposit'] ?></p> </div> <div class="top-deal2"> <a <?php if($row2['a_status']==1){ echo "data-toggle='modal' data-target='#myModal2'";} ?> href="<?php if($row2['a_status']==1){ echo "#"; } else {echo "single.php?id=".$row2['property_id']; }?>" class="hvr-sweep-to-right more">Details</a> </div> <div class="clearfix"> </div> </div> </div> </div> <?php if (($k % 4) == 0) { ?> <div class="clearfix"> </div> <?php } } if(!$query) { echo "<h2 style='text-align:center; margin:70px 0;'><span style='font-size: 20px;'>No proerty found</span><br/>(Just Call Your Personal Manager, He Will Take Care Of The Rest.)</h2>"; } ?> <div class="clearfix"> </div> </div> <div class="nav-page"> <nav> <?php //fetch all the data from database. $rows=mysqli_num_rows(mysqli_query($connection,"SELECT * FROM `property_details` ORDER BY id")); //calculate total page number for the given table in the database $total=ceil($rows/$limit); ?> <ul class='pagination'> <?php //show all the page link with page number. When click on these numbers go to particular page. if($id>1) { //Go to previous page to show previous 10 items. If its in page 1 then it is inactive echo"<li class=''><a href='?id=".($id-1)."' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>"; } for($i=1;$i<=$total;$i++) { if($i==$id) { echo "<li class='active'><a href='#'>".$i." <span class='sr-only'>(current)</span></a></li>"; } else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; } } if($id!=$total) { ////Go to previous page to show next 10 items. echo "<li><a href='?id=".($id+1)."' aria-label='Next'><span aria-hidden='true'>»</span></a></li>"; } ?> </ul> </nav> </div> <?php } ?> <?php } ?> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="myModal2" role="dialog"> <div class="modal-dialog modal-md"> <!-- Modal content--> <div class="modal-content"> <div class="modal-body"> <button style=" position: absolute; right: -15px; top: -18px; background: #FFF; border-radius: 50%; padding: 3px 6px; border: 2px Solid #000; opacity:1;" type="button" class="close" data-dismiss="modal">&times;</button> <div class="columns" style="border:1px solid #ccc"> <ul class="price"> <li class="header" style="background-color:#b32505">Sorry!</li> </ul> <br/> <h3 style="text-align:center">Sorry this property is rented out, please find another or call your personal manager...</h3> <br/> <!--<p style="text-align:center">You will start receiving tenant inquires.<br/> Are you sure to active your property ad.<br/><br/>--> </p> <p> &nbsp;<br/></p> </div> </div> </div> </div> </div> <!--end--> <script> /* function empty() { var x; x = document.getElementById("skills").value; if (x == "") { alert("please select locality"); return false; }; var a; a = document.getElementById("rent").value; if (a == "") { alert("please select max rent"); return false; }; }*/ </script> <script> $(function() { function split( val ) { return val.split( /,\s*/ ); } function extractLast( term ) { return split( term ).pop(); } $( "#skills" ).bind( "keydown", function( event ) { if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) { event.preventDefault(); } }) .autocomplete({ minLength: 1, source: function( request, response ) { // delegate back to autocomplete, but extract the last term $.getJSON("locality.php", { term : extractLast( request.term )},response); }, focus: function() { // prevent value inserted on focus return false; }, select: function( event, ui ) { var terms = split( this.value ); // remove the current input terms.pop(); // add the selected item terms.push( ui.item.value ); // add placeholder to get the comma-and-space at the end terms.push(""); this.value = terms.join(","); return false; } }); }); </script> <script type="text/javascript"> $(function () { $('#lstFruits').multiselect({ includeSelectAllOption: true }); $('#btnSelected').click(function () { var selected = $("#lstFruits option:selected"); var message = ""; selected.each(function () { message += $(this).text() + " " + $(this).val() + "\n"; }); alert(message); }); }); </script> <script type="text/javascript"> $(function () { $('#lstFruits2').multiselect({ includeSelectAllOption: true }); $('#btnSelected').click(function () { var selected = $("#lstFruits2 option:selected"); var message = ""; selected.each(function () { message += $(this).text() + " " + $(this).val() + "\n"; }); alert(message); }); }); </script> </body> </html> <?php unset($_SESSION['saddress']); ?><file_sep><?php include('conn.php'); session_start(); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Post</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <link href="css/sky form.css" rel="stylesheet"> <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" /> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <div class="loan_single" style="background:rgba(39, 218, 147, 0.15)"> <div class="container"> <div class="col-md-12"> <div style="margin-top:100px"> <div class="col-md-6"> <div style="width:222px; margin:0 auto;"> <img src="images/normal_ian-symbol-services-business-trio.png" /> </div> </div> <div class="col-md-6"> <?php $pid=$_SESSION["pid"]; $oname=$_SESSION['name']; $query = "SELECT * FROM `registation` WHERE pd_id= '$pid'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $id=$row['pd_id']; $manager=$row['manager']; $mobile=$row['mobile']; } $rqy1="SELECT p_id FROM `sub_admin` where name = '$manager'"; $rsl1 = @mysqli_query($connection,$rqy1); $row1 = mysqli_fetch_row($rsl1); $p_id=$row1[0]; $pid=$p_id.''.$id.','; $reg_u1="UPDATE `sub_admin` SET p_id = '$pid' WHERE name = '$manager'"; $reg_i1=mysqli_query($connection,$reg_u1); ?> <p style="font-size:1.5em; text-align:center; padding-top: 12%;"> Thanks for providing property details. Your permanent property Id: <b><?php echo $id; ?></b>. You will receive verification call from your personal manager before your property goes live. </p> <br/><br/> <div style="width:70%; margin:0 auto;"> <button style="float:left" type="button" class="btn-u" onclick="window.location.href='owner_dashboard.php'">Back To Home</button> <button style="float:right" type="button" class="btn-u" onclick="window.location.href='owner_dashboard.php'">View Posted Property</button> </div> </div> </div> </div> <div class="clearfix"> </div> </div><br/><br/><br/> </div> <?php include('footer.php'); ?> </body> </html><file_sep><?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>RoomOnRent | Post</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body onclick="window.location.href='post_property.php'"> <!--header--> <?php include('header.php'); ?> <!--//--> <div class="loan_single" style="background:rgba(39, 218, 147, 0.15)"> <div class="container"> <div class="col-md-12"> <div style=""> <div style="width:356px; margin:10px auto;"> <img src="images/after_login.png" class="img-responsive" style="" /> </div> <p style="font-size:1.5em; text-align:center"> Hi <b><?php if(preg_match('/[A-Z]+[a-z]+[0-9]+/', $_SESSION['name'])){ echo substr($_SESSION['name'], 0, -2);} else{ echo $_SESSION['name'];} ?></b> , Team RoomsOnRent has appointed me as your Personal Relationship Manager, your RoomsOnRent account has been created successfully. Please feel free to call me any time to get assistance regarding... </p> <div class="col-md-12"> <div class="us-choose"> <div class="col-md-2 why-choose"> </div> <div class="col-md-2 why-choose"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-home"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Posting</h5>--> <!--<label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em">Posting and marketing your property</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-user"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Free Property Posting</h5>--> <!--<label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em">Finding Sutable tenant</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-file"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Get RS.500 Discount</h5>--> <!--<label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em">Creating registered rental agreement</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-check"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Free Property Posting</h5>--> <!--<label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em">Doing tenant verification</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose"> </div> <div class="clearfix"> </div> </div> </div> </div> <div class="choose-us" style="padding:2em 0"> <div class="col-md-12"> <div style="margin: 10px auto; width: 400px; background: #00d5fa; padding: 15px; text-align: center;"> <a href="#" style="color:#FFF">Continue Posting Property >></a> </div> </div> </div> </div> <div class="clearfix"> </div> </div> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> <script> function hideicon() { document.getElementById("hand").style.display="none"; } </script> </body> </html><file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Why</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="fair owner" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" banner-buying"> <div class=" container"> <h3><span>Why RoomsOnRent</span></h3> <!----> <div class="clearfix"> </div> <!--initiate accordion--> </div> </div> <!--//header--> <div class="about"> <div class="about-head" style="padding: 1em 0 1em 0;"> <div class="container"> <div class="about-in"> <h6 ><a href="blog_single.html">Hassles generally faced by Owners: </a></h6> <p> Finding tenants in itself is a time consuming process which includes spreading awareness to own contacts and brokers in the area, listing property on different property portals and marketing via other sources.<br> <br> Even after getting a tenant, owners face hassles like contacting advocates and other sources to calculate stamp-duty, getting stamp paper, registration and execution of rental agreements, negotiation on rates, visiting more than once to the lawyer and registration office for execution of agreement on working days, high agreement rates. This all amounts to a hectic documentation.<br> <br> In general, people spend more than Rs. 1500/- for notarized &amp; Rs. 4000/- for registered agreement. Many paid ads to different property portals cost Rs. 300 to Rs. 900 per property portal. This is a very time taking and cost consuming process.<br> <br> People who want to avoid these problems hire property managers or real-estate brokers. However, they charge at least 15 days rent for these procedures. This is a very high amount in itself. <br> <br> Being a property owner, means repeating above steps again and again every 11 months until its tenure ends or when a tenant moves out. The owner again faces the same issues. <br> <br> <center> <p style="font-size: 1.4em; text-transform: uppercase; color: #286090;font-family: 'Montserrat-Regular';">Are you facing any of the above?</p> </center> <center> <p> <font>"Post Your Property Now &amp; Get Relaxed." </font></p> </center> </div> </div> </div> <div class="choose-us"> <div class="container"> <h3>why choose us</h3> <div class="us-choose"> <div class="col-md-6 why-choose"> <div class=" ser-grid"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-home"> </i> </div> <div class="ser-top beautiful"> <h5>Benefits for Owner</h5> <!--<label>The standard chunk of Lorem</label>--> <ul class="privacy-start"> <li><a href="#"><i></i>Posting property Ad in simple steps.</a></li> <li><a href="#"><i></i>Tenant Search in short duration. </a></li> <li><a href="#"><i></i>Rent agreement at your doorstep. </a></li> <li><a href="#"><i></i>Screening of Tenants.</a></li> <li><a href="#"><i></i>Rent agreement at low cost</a></li> <li><a href="#"><i></i>Multiple property seekers available across Amravati.</a></li> <li><a href="#"><i></i>Marketing of property through various mediums.</a></li> <li><a href="#"><i></i>One stop solution for lifetime.</a></li> </ul> </div> <div class="clearfix"> </div> </div> <div class="col-md-6 why-choose"> <div class=" ser-grid"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-user"> </i> </div> <div class="ser-top beautiful"> <h5>Benefits for Tenants</h5> <!--<label>The standard chunk of Lorem</label>--> <ul class="privacy-start"> <li><a href="#"><i></i>No Brokerage</a></li> <li><a href="#"><i></i>Property assistance as per requirement</a></li> <li><a href="#"><i></i>Multiple options under one roof.</a></li> <li><a href="#"><i></i>Properties available across Amravati</a></li> <li><a href="#"><i></i>Rent agreement at door step (Hassle free rent agreement).</a></li> <li><a href="#"><i></i>Rent agreement at Low cost</a></li> <li><a href="#"><i></i>One stop solution for lifetime.</a></li> </ul> </div> <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> </div> <!----> <!----> <!----> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html><file_sep><html> <body> <form method="post" action="#"> <input type="checkbox" name="txtCheck1" value="your value" <?php if(isset($_POST['txtCheck1'])) echo "checked='checked'"; ?> /> <input type="checkbox" name="txtCheck2" value="your value" <?php if(isset($_POST['txtCheck2'])) echo "checked='checked'"; ?> /> <input type="checkbox" name="txtCheck3" value="your value" <?php if(isset($_POST['txtCheck3'])) echo "checked='checked'"; ?> /> <input type="checkbox" name="txtCheck4" value="your value" <?php if(isset($_POST['txtCheck4'])) echo "checked='checked'"; ?> /> <input type="checkbox" name="txtCheck5" value="your value" <?php if(isset($_POST['txtCheck5'])) echo "checked='checked'"; ?> /> <input type="submit" name="submit" value="submit" /> </form> </body> </html><file_sep><?php include('conn.php'); session_start(); include('out1.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Post</title> <link href="../css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="../js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="../js/scripts.js"></script> <link href="../css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="../css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <div class="navigation"> <div class="container-fluid"> <nav class="pull"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Why RoomsOnRent</a></li> <li><a href="#">How It Works</a></li> <li><a href="#">Agreement</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </div> </div> <div class="header"> <div class="container"> <!--logo--> <div class="logo"> <h1><a href="#"> <img src="images/logo2.png" /> </a></h1> </div> <!--//logo--> <div class="top-nav" style="float:right"> <div class="nav-icon"> <div class="hero fa-navicon fa-2x nav_slide_button" id="hero"> <a href="#"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> </div> <!--- <a href="#" class="right_bt" id="activator"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> ---> </div> <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> <!--//--> <div class=" banner-buying"> <div class=" container"> <h3><span>Tenant Details</span></h3> <!----> <div class="clearfix"> </div> <!--initiate accordion--> </div> </div> <!--//header--> <!----> <div class="loan_single"> <div class="container"> <div class="loan-col" style="padding:1em 0 2em 0"> <?php $id=$_GET['id']; $q = "SELECT * FROM `tenant_reg` WHERE id = '$id'"; $sql = @mysqli_query($connection,$q); while($row = mysqli_fetch_array($sql)) { ?> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" class="form-horizontal" role="form" enctype="multipart/form-data" > <div class="col-loan"> <h4>Tenant Plan Details</h4> <br/> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="control-label col-sm-4" for="email">Name:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="name" placeholder="" readonly="" value="<?php echo $row['name'] ?>" > </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Mobile:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="mobile" placeholder="" readonly="" value="<?php echo $row['mobile'] ?>" > </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Credits in plan:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="credit" placeholder="" readonly="" value=" <?php echo $row['planc']; ?>" > </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Increase Plan Count:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="increase" placeholder="Enter No" > </div> </div> </div> <div class="clearfix"></div> </div> </div> <!----> <div class="loan-col1"> <div class="sub1"> <label class="hvr-sweep-to-right"><input type="submit" name="submit" value="Update" placeholder=""></label> <label class="hvr-sweep-to-right re-set"><a onclick="window.location.href='s_tenant_details.php'" style="padding: 11px 15px;">Back</a> </div> </div> <!----> </form> <?php } ?> <?php if(isset($_POST['submit'])) { $id=$_GET['id']; $credit=$_POST['credit']; $increase=$_POST['increase']; $increase= $credit + $increase; $query="UPDATE `tenant_reg` SET `planc` = $increase WHERE id=$id"; $upload= mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { $sqll="select * from `tenant_reg` WHERE id=$id"; $fun=@mysqli_query($connection,$sqll); while($row=@mysqli_fetch_array($fun)) { $tname=$row['name']; } $msg="Dear $tname,\n Your fair-plan limit is increase by $increase on your existing limit. Thanks for your kind support, Please feel free to call for any assistance. Contact us for Rs.300 discount on Rental agreement once you get your home www.fairowner.com. \n\nRegards\nTeam Fair-Owner"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } echo "<script>alert('Tenant Plan Details is updated')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } } ?> </div> </div> </div> <!--footer--> <div class="footer"> <div class="footer-bottom"> <div class="container"> <div class="col-md-8"> <p style="color:#FFF">© 2017 RoomsOnRent. All Rights Reserved</p> </div> <div class="col-md-4 footer-logo"> <ul class="social" style="padding:0; float:right"> <li><a href="#"><i> </i></a></li> <li><a href="#"><i class="gmail"> </i></a></li> <li><a href="#"><i class="twitter"> </i></a></li> <li><a href="#"><i class="camera"> </i></a></li> <li><a href="#"><i class="dribble"> </i></a></li> </ul> </div> <div class="clearfix"> </div> </div> </div> </div> <!--//footer--> <script> $(document).ready(function(){ $("#furnish").change(function(){ $(this).find("option:selected").each(function(){ if($(this).attr("value")=="semifurnish") { $("#fitem").show(); } if($(this).attr("value")=="fullyfurnish") { $("#fitem").show(); } else { $("#fitem").hide(); } }); }); }); </script> </body> </html><file_sep><html> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"> <input type="text" name="mobile" /> <input type="submit" name="otp" value="OTP" /> </form> </html> <?php if(isset($_POST['otp'])) { include('message.php'); } ?><file_sep><?php session_start(); include('conn.php'); include('out1.php'); $id=$_GET['id']; $query="DELETE FROM `registation` WHERE id='$id'"; $upload= mysqli_query($connection,$query); echo "<script>alert('Owner record is deleted')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; ?><file_sep><?php $connection = @mysqli_connect('localhost','root','','roomsonrent') or die(@mysqli_error($connection)); ?><file_sep><?php include('conn.php'); session_start(); include('out1.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Dashboard - RoomsOnRent</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="fair-owner" content="yes"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet"> <link href="css/font-awesome.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <link href="css/pages/dashboard.css" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <?php include('header.php'); ?> <div class="subnavbar"> <div class="subnavbar-inner"> <div class="container"> <ul class="mainnav"> <li class="active"><a href="super_admin_home.php"><i class="icon-dashboard"></i><span>Dashboard</span> </a> </li> <li><a href="create_subadmin.php"><i class="icon-sitemap"></i><span>Create Sub-Admin</span> </a> </li> <li><a href="s_reg_owner.php"><i class="icon-user"></i><span>Registered Owner</span> </a> </li> <li><a href="s_owner_details.php"><i class="icon-check"></i><span>Property Posted Owner</span> </a> </li> <li><a href="s_reg_tenant.php"><i class="icon-group"></i><span>Registered Tenant</span> </a></li> <li><a href="s_tenant_details.php"><i class="icon-check"></i><span>Plan Purchase Tenant</span> </a></li> <li><a href="req_agreement.php"><i class="icon-paste"></i><span>Request for Agreement</span> </a></li> <li class="dropdown"><a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-long-arrow-down"></i><span>Drops</span> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="home_slider.php">Home Page Slider</a></li> <li><a href="abuse_property.php">Abuse Property</a></li> <li><a href="testimonials.php">Testimonials</a></li> </ul> </li> </ul> </div> <!-- /container --> </div> <!-- /subnavbar-inner --> </div> <!-- /subnavbar --> <div class="main"> <div class="main-inner"> <div class="container"> <div class="row"> <div class="span6"> <div class="widget widget-nopad"> <div class="widget-header"> <i class="icon-list-alt"></i> <h3> Introduction</h3> </div> <!-- /widget-header --> <div class="widget-content"> <img src="img/2.jpg" style="width:100%; height:450px" class="hidden-xs" /> </div> </div> <!-- /widget --> </div> <!-- /span6 --> <div class="span6"> <div class="widget"> <div class="widget-header"> <i class="icon-bookmark"></i> <h3>Important Shortcuts</h3> </div> <!-- /widget-header --> <div class="widget-content"> <div class="shortcuts"> <a href="super_admin_home.php" class="shortcut"> <i class="shortcut-icon icon-dashboard"></i> <span class="shortcut-label">Dashboard</span> </a> <a href="create_subadmin.php" class="shortcut"> <i class="shortcut-icon icon-sitemap"></i> <span class="shortcut-label">Create Sub-Admin</span> </a> <a href="s_reg_owner.php" class="shortcut"> <i class="shortcut-icon icon-user"></i> <span class="shortcut-label">Registered Owner</span> </a> <a href="s_owner_details.php" class="shortcut"> <i class="shortcut-icon icon-check"></i> <span class="shortcut-label">Property Posted Owner</span> </a> <a href="s_reg_tenant.php" class="shortcut"> <i class="shortcut-icon icon-group"></i> <span class="shortcut-label">Registered Tenant</span> </a> <a href="s_tenant_details.php" class="shortcut"> <i class="shortcut-icon icon-check"></i> <span class="shortcut-label">Plan Purchase Tenant</span> </a> <a href="req_agreement.php" class="shortcut"> <i class="shortcut-icon icon-paste"></i> <span class="shortcut-label">Request for Agreement</span> </a> <a href="home_slider.php" class="shortcut"> <i class="shortcut-icon icon-picture"></i> <span class="shortcut-label">Home Page Slider</span> </a> <a href="abuse_property.php" class="shortcut"> <i class="shortcut-icon icon-ban-circle"></i> <span class="shortcut-label">Abuse Property</span> </a> <a href="agreeowner.php" class="shortcut"> <i class="shortcut-icon icon-user"></i> <span class="shortcut-label">Owner from Agreement Page</span> </a> <a href="agreetenant.php" class="shortcut"> <i class="shortcut-icon icon-user"></i> <span class="shortcut-label">Tenant from Agreement Page</span> </a> <a href="backend2.php" class="shortcut"> <i class="shortcut-icon icon-list-alt"></i> <span class="shortcut-label">Post Property</span> </a> <a href="backendtenant2.php" class="shortcut"> <i class="shortcut-icon icon-list-alt"></i> <span class="shortcut-label">Insert Tenant</span> </a> </div> <!-- /shortcuts --> </div> <!-- /widget-content --> </div> <!-- /widget --> </div> <!-- /span6 --> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /main-inner --> </div> <!-- /main --> <?php include('footer.php'); ?> <!-- /footer --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/base.js"></script> </body> </html> <file_sep><?php include('conn.php'); session_start(); include('out.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Post</title> <link href="../css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="../js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="../js/scripts.js"></script> <script src="../js/bootstrap.js"></script> <link href="../css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="../css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <div class="navigation"> <div class="container-fluid"> <nav class="pull"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Why Fair Owner</a></li> <li><a href="#">How It Works</a></li> <li><a href="#">Agreement</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </div> </div> <div class="header"> <div class="container"> <!--logo--> <div class="logo"> <h1><a href="#"> <img src="images/logo2.png" /> </a></h1> </div> <!--//logo--> <div class="top-nav" style="float:right"> <ul class="right-icons"> <li><span ><i class="glyphicon glyphicon-phone"> </i>+91 8888599993</span></li> </ul> <div class="nav-icon"> <div class="hero fa-navicon fa-2x nav_slide_button" id="hero"> <a href="#"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> </div> <!--- <a href="#" class="right_bt" id="activator"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> ---> </div> <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> <!--//--> <div class=" banner-buying"> <div style="position:fixed; z-index:9; right:0; bottom:0px; margin:15px;"> <a href="<?php echo "index.php";?>" class="hvr-sweep-to-right more" style="background:#00d5fa; color:#FFF; font-weight:bold; padding:1em" >Back</a> </div> <div class=" container"> <h3><span>Post Tenant From Back-end</span></h3> <!----> <div class="clearfix"> </div> <!--initiate accordion--> </div> </div> <!--//header--> <!----> <div class="loan_single"> <div class="container"> <div class="loan-col" style="padding:1em 0 2em 0"> <!--<h4>Looking for a good deal for a <span>HOME?</span> Post Now!!</h4>--> <h4>Tenant Details</h4> <br/> <form class="form-horizontal" action="<?php $_SERVER['PHP_SELF'] ?>" method="post"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="control-label col-sm-4" for="email">Tenant Name:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="username" placeholder="Enter <NAME>" value="<?php echo isset($_POST['username']) ? $_POST['username'] : '' ?>" > </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Tenant Mobile:</label> <div class="col-sm-8"> <input type="number" id="lmobile" class="form-control" name="r_mobile" placeholder="Enter Mobile without +91" value="<?php echo isset($_POST['r_mobile']) ? $_POST['r_mobile'] : '' ?>" > </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Tenant Email:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="email" placeholder="Enter Email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : '' ?>" > </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">&nbsp;</label> <div class="col-sm-8 sub1"> <label class="hvr-sweep-to-right"><input type="submit" onClick="return lempty()" name="create_account" value="Insert Tenant" ></label> </div> </div> </div> </div> </form> <?php if(isset($_POST['create_account'])) { $date=date("d/m/Y"); $uname=$_POST['username']; $qu1="SELECT name FROM `tenant_reg` where name = '$uname'"; $sql1 = @mysqli_query($connection,$qu1); $roww=@mysqli_fetch_row($sql1); $uname1=$roww[0]; if(isset($uname1)) { $ali=rand(10, 99); $uname=$uname.$ali; } $r_mobile=$_POST['r_mobile']; $email=$_POST['email']; $_SESSION['name']=$uname; $i=1; $qu="SELECT mobile FROM `tenant_reg` where mobile = '$r_mobile'"; $sql = @mysqli_query($connection,$qu); $row=@mysqli_fetch_row($sql); $m=$row[0]; if(isset($m)) { echo "<script>alert('Mobile No is already exist')</script>"; echo "<script>window.location.href='backendtenant.php'</script>"; } else { $manager=$_SESSION['subadminname']; $query="INSERT INTO `tenant_reg`(`id`, `name`, `email`, `mobile`, `flow_id`, `pd_id`, `date`, `manager`, `fromwhere`) VALUES ('','".$uname."','".$email."','".$r_mobile."','".$i."','0','".$date."','".$manager."','Backend')"; $upload= mysqli_query($connection,$query); echo "<script>alert('Tenant Is Inserted')</script>"; $query="SELECT id FROM `tenant_reg` order by id DESC"; $sql = @mysqli_query($connection,$query); $row = mysqli_fetch_row($sql); $tmp=$row[0]; $tmp=$tmp; //$pid="W-".$tmp; $_SESSION["pid"]=$tmp; $m=$_SESSION['subadminname']; $rqy1="SELECT ten_id FROM `sub_admin` where name = '$m'"; $rsl1 = @mysqli_query($connection,$rqy1); $row1 = mysqli_fetch_row($rsl1); $p_id=$row1[0]; $pidd=$p_id.''.$tmp.','; $reg_u1="UPDATE `sub_admin` SET ten_id = '$pidd' WHERE name = '$m'"; $reg_i1=mysqli_query($connection,$reg_u1); $name=$_SESSION['subadminname']; $date=date("d/m/Y"); $qu="INSERT INTO `notificationi`(`id`, `name`, `date`, `description`) VALUES ('','$name','$date','$uname Tenant Is Inserted from backed')"; $in=mysqli_query($connection,$qu); } } ?> </div> </div> </div> <!--footer--> <div class="footer"> <div class="footer-bottom"> <div class="container"> <div class="col-md-8"> <p style="color:#FFF">© 2017 RoomsOnRent. All Rights Reserved</p> </div> <div class="col-md-4 footer-logo"> <ul class="social" style="padding:0; float:right"> <li><a href="#"><i> </i></a></li> <li><a href="#"><i class="gmail"> </i></a></li> <li><a href="#"><i class="twitter"> </i></a></li> <li><a href="#"><i class="camera"> </i></a></li> <li><a href="#"><i class="dribble"> </i></a></li> </ul> </div> <div class="clearfix"> </div> </div> </div> </div> <!--//footer--> <script> $(document).ready(function(){ $("#furnish").change(function(){ $(this).find("option:selected").each(function(){ if($(this).attr("value")=="semifurnish") { $("#fitem").show(); } if($(this).attr("value")=="fullyfurnish") { $("#fitem").show(); } else { $("#fitem").hide(); } }); }); }); </script> <script> function lempty() { var x; x = document.getElementById("lmobile").value; if (/^\d{10}$/.test(x)) { //ok } else { alert("Please enter 10 digit mobile No!"); return false; }; } </script> <script> function empty() { var x; x = document.getElementById("parking").value; if (x == "") { alert("please select parking type"); return false; }; var y; y = document.getElementById("facing").value; if (y == "") { alert("please select facing"); return false; }; var z; z = document.getElementById("balcony").value; if (z == "") { alert("please select balcony"); return false; }; var a; a = document.getElementById("flattype").value; if (a == "") { alert("please select flat type"); return false; }; var b; b = document.getElementById("propertytype").value; if (a == "") { alert("please select property type"); return false; }; var c; c = document.getElementById("city").value; if (c == "") { alert("please enter city"); return false; }; var d; d = document.getElementById("locality").value; if (d == "") { alert("please enter locality"); return false; }; var e; e = document.getElementById("rent").value; if (e == "") { alert("please enter rent"); return false; }; if ((post.n_rent[0].checked == false) && (post.n_rent[1].checked == false)) { alert("please choose negotiable rent"); return false; }; if ((post.maintenance[0].checked == false) && (post.maintenance[1].checked == false)) { alert("please choose maintenance: Including or Excluding"); return false; }; var h; h = document.getElementById("deposit").value; if (h == "") { alert("please enter deposit"); return false; }; if ((post.time_preference[0].checked == false) && (post.time_preference[1].checked == false)) { alert("please choose time preference"); return false; }; var i; i = document.getElementById("furnishing").value; if (i == "") { alert("please select furnishing type"); return false; }; } </script> </body> </html><file_sep><?php session_start(); include('conn.php'); error_reporting(E_ERROR); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Home</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <script src="jquery-ui-1.11.4/jquery-ui.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <link rel="stylesheet" href="jquery-ui-1.11.4/jquery-ui.css"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="fair owner " /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <!-- slide --> <script src="js/responsiveslides.min.js"></script> <script> $(function () { $("#slider").responsiveSlides({ auto: true, speed: 500, namespace: "callbacks", pager: true, }); }); </script> <script type="text/javascript"> function fill(Value) { $('#name').val(Value); $('#display').hide(); } $(document).ready(function(){ $("#name").keyup(function() { var name = $('#name').val(); if(name=="") { $("#display").html(""); } else { $.ajax({ type: "POST", url: "ajax.php", data: "name="+ name , success: function(html){ $("#display").html(html).show(); } }); } }); }); </script> <style> #display { position: absolute; } #display ul { list-style: none; margin: 3px 20px 20px 0px; width: 450px; max-width: 450px; max-height: 150px; overflow:auto; } #display li { display: block; padding: 5px; background-color: #f5ebeb; border-bottom: 1px solid #367; cursor:pointer; } #content { padding:50px; width:500px; border:1px solid #666; float:left; } #clear { clear:both; } #box { float:left; margin:0 0 20px 0; text-align:justify; } .ui-autocomplete { height:300px; overflow-y:auto; } </style> </head> <body > <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" header-right"> <h3 class="fadeInLeft">Help Others To Help Yourself</h3> <!-- Content of this place have deleted by ANUP --_ANUP--> <div class=" banner"> <div class="slider"> <div class="callbacks_container"> <ul class="rslides" id="slider"> <?php $q = "SELECT * FROM `slider`"; $sql = @mysqli_query($connection,$q); while($row = mysqli_fetch_array($sql)) { ?> <li> <div style="background: url(<?php echo "admin/".$row['images']; ?>); background-repeat: round;" class="banner"> </div> </li> <?php } ?> </ul> </div> </div> </div> </div> <!--header-bottom--> <!-- Content of this place have deleted by ANUP --_ANUP--> <!--//--> <!--//header-bottom--> <?php include('home.php'); ?> <!--//header--> <!--content--> <div class="content"> <div class="content-bottom" style="padding-top: 0.5em;"> <div class="container"> <!-- <h3 style="color: #27da93;">" What our clients say "</h3> --_ANUP--> <h3 style="color: #00d5fa;">" What our clients say "</h3> <div class="clearfix"> </div> <!--edit testimonials--> <style> .carousel-indicators .active{ background: #31708f; } .content{ margin-top:20px; } .adjust1{ float:left; width:100%; margin-bottom:0; } .adjust2{ margin:0; } .carousel-indicators li{ border :1px solid #ccc; } .carousel-control{ color:#31708f; width:5%; } .carousel-control:hover, .carousel-control:focus{ color:#31708f; } .carousel-control.left, .carousel-control.right { background-image: none; } .media-object{ margin:auto; margin-top:15%; } @media screen and (max-width: 768px) { .media-object{ margin-top:0; } } </style> <div class="container content"> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators -- <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <li data-target="#carousel-example-generic" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <?php $q = "SELECT * FROM `testimonials`"; $sql = @mysqli_query($connection,$q); $i=0; while($row = mysqli_fetch_array($sql)) { $i=$i+1; ?> <div class="item <?php if($i==1) echo 'active'; ?>"> <div class="row"> <div class="col-xs-12"> <div class="thumbnail adjust1"> <div class="col-md-2 col-sm-2 col-xs-12"> <img class="media-object img-rounded img-responsive" src="<?php echo "admin/".$row['image']; ?>" style="width:100px; height:100px"> </div> <div class="col-md-10 col-sm-10 col-xs-12"> <div class=""> <p class="text-info lead adjust2"><?php echo $row['heading'] ?></p> <p><span class="glyphicon glyphicon-thumbs-up"></span> <?php echo $row['comment'] ?> </p> <blockquote class="adjust2" style="border-left: 5px solid #eee !important;"> <p><?php echo $row['name'] ?></p> <small><cite title="Source Title"><i class="glyphicon glyphicon-globe"></i> <?php echo $row['position'] ?></cite></small> </blockquote> </div> </div> </div> </div> </div> </div> <?php } ?> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#carousel-example-generic" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> </div> <!--edut testimonials--> </div> </div> <!--//test--> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> <script> $(function() { function split( val ) { return val.split( /,\s*/ ); } function extractLast( term ) { return split( term ).pop(); } $( "#skills" ).bind( "keydown", function( event ) { if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) { event.preventDefault(); } }) .autocomplete({ minLength: 1, source: function( request, response ) { // delegate back to autocomplete, but extract the last term $.getJSON("locality.php", { term : extractLast( request.term )},response); }, focus: function() { // prevent value inserted on focus return false; }, select: function( event, ui ) { var terms = split( this.value ); // remove the current input terms.pop(); // add the selected item terms.push( ui.item.value ); // add placeholder to get the comma-and-space at the end terms.push( "" ); this.value = terms.join( ", " ); return false; } }); }); </script> </body> </html><file_sep><?php $returnValue['ValueA'] = "a value"; $returnValue['ValueB'] = "another value"; echo json_encode($returnValue); ?> <file_sep><?php session_start(); include('conn.php'); include('out.php'); $id=$_GET['id']; $query="DELETE FROM `tenant_reg` WHERE id='$id'"; $upload= mysqli_query($connection,$query); $name=$_SESSION['subadminname']; $date=date("d/m/Y"); $qu="INSERT INTO `notificationi`(`id`, `name`, `date`, `description`) VALUES ('','$name','$date','Delete register tenant of id:- $id')"; $in=mysqli_query($connection,$qu); echo "<script>alert('Tenant record is deleted')</script>"; echo "<script>window.location.href='reg_tenant.php'</script>"; ?><file_sep><?php session_start(); include('conn.php'); include('out.php'); $id=$_GET['id']; $query="DELETE FROM `tenant_reg` WHERE id='$id'"; $upload= mysqli_query($connection,$query); echo "<script>alert('Tenant is deleted')</script>"; echo "<script>window.location.href='tenant_details.php'</script>"; ?><file_sep><?php session_start(); include('conn.php'); include('out1.php'); $id=$_POST['id']; $manager=$_POST['subadmin']; if(isset($_POST['assign'])) { $manager=$_POST['subadmin']; $id=$_POST['id']; //echo $manager; //echo $id; $rqy1="SELECT p_id FROM `sub_admin` where name = '$manager'"; $rsl1 = @mysqli_query($connection,$rqy1); $row1 = mysqli_fetch_row($rsl1); $p_id=$row1[0]; //echo $p_id; if(preg_match('/\b' . $id . '\b/', $p_id)) { echo "<script>alert('Property is already assign')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } else { $pid=$p_id.''.$id.','; $reg_u1="UPDATE `sub_admin` SET p_id = '$pid' WHERE name = '$manager'"; $reg_i1=mysqli_query($connection,$reg_u1); $oq="UPDATE `registation` SET `manager`='$manager' WHERE id = '$id' "; $ou=mysqli_query($connection,$oq); if(!$reg_i1 && !$ou) { echo "<script>alert('property not assign')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } else { echo "<script>alert('property assign')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } } } if(isset($_POST['uploadagre'])) { $id=$_POST['id']; $query="SELECT * from `registation` WHERE id = '$id'"; $sql = @mysqli_query($connection,$query); while($row=@mysqli_fetch_array($sql)) { $targetfolder=$row['agre']; $targetfolder1=$row['indexii']; $targetfolder2=$row['recep']; $targetfolder3=$row['powerofauto']; } if(!empty($_FILES["agree"]["name"])) { $targetfolder = "agreement/"; $file_name=$_FILES['agree']['name']; $ext=pathinfo($file_name,PATHINFO_EXTENSION); $imagename=date("d-m-Y")."-".time().".".$ext; $targetfolder = $targetfolder . $imagename ; move_uploaded_file($_FILES['agree']['tmp_name'], $targetfolder); } if(!empty($_FILES["powerof"]["name"])) { $targetfolder1 = "agreement/"; $file_name1=$_FILES['powerof']['name']; $ext1=pathinfo($file_name1,PATHINFO_EXTENSION); $imagename1=date("d-m-Y")."-".time().".".$ext1; $targetfolder1 = $targetfolder1 . $imagename1 ; move_uploaded_file($_FILES['powerof']['tmp_name'], $targetfolder1); } if(!empty($_FILES["indexii"]["name"])) { $targetfolder2 = "agreement/"; $file_name2=$_FILES['indexii']['name']; $ext2=pathinfo($file_name2,PATHINFO_EXTENSION); $imagename2=date("d-m-Y")."-".time().".".$ext2; $targetfolder2 = $targetfolder2 . $imagename2 ; move_uploaded_file($_FILES['indexii']['tmp_name'], $targetfolder2); } if(!empty($_FILES["receipt"]["name"])) { $targetfolder3 = "agreement/"; $file_name3=$_FILES['receipt']['name']; $ext3=pathinfo($file_name3,PATHINFO_EXTENSION); $imagename3=date("d-m-Y")."-".time().".".$ext3; $targetfolder3 = $targetfolder3 . $imagename3 ; move_uploaded_file($_FILES['receipt']['tmp_name'], $targetfolder3); } $astatus=$_POST['sagre']; $remark=$_POST['remark']; $query="UPDATE `registation` SET `agre`='$targetfolder',`indexii`='$targetfolder1',`recep`='$targetfolder2',`powerofauto`='$targetfolder3' WHERE id = '$id'"; $upload= mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { echo "<script>alert('Agreements are uploaded')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } } if(isset($_POST['submit'])) { $id=$_POST['id']; $astatus=$_POST['sagre']; $remark=$_POST['remark']; $follow_date=$_POST['follow_date']; $query="UPDATE `registation` SET `agre_status`='$astatus',`remark`='$remark',`follow_date`='$follow_date' WHERE id = '$id'"; $upload= mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { echo "<script>alert('Status Updated')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } } if(isset($_POST['sendstage'])) { $sendmm=$_POST['sendmm']; $id=$_POST['id']; $mobile=$_POST['mobile']; $email=$_POST['email']; $qu="SELECT * FROM `registation` where id= $id"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $oname=$row['name']; $manager=$row['manager']; $p_id=$row['pd_id']; } if(preg_match('/[A-Z]+[a-z]+[0-9]+/', $oname)) { $oname=substr($oname, 0, -2); } else { $oname=$oname; } $qu="SELECT * FROM `sub_admin` where name= '$manager'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $mname=$row['name']; $mmobile=$row['mobile']; $memail=$row['email']; } if($sendmm=='stage1') { $msg="We are just a click away, post your property on brokerage-free platform to avail benefits in Finding Tenants, Registered rental agreement and Tenant Verification at reasonable cost available at your doorstep. roomsonrent.in. \n\nRegards\nTeam RoomsOnRent\n$mmobile"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $subject="RoomsOnRent - One stop solution for Tenant Finding, Rental Agreement and Tenant Verification"; $mssg=nl2br(" Dear $oname, \n Greetings from RoomsOnRent!!\n\n We provide one stop solution for property owners across Pune.\n\n Problems generally faced by Owner's:\n 'Searching for inhabitants is the start of a long procedure which begins with property posting on various Platforms, further to concluding the best occupant alternative accessible, in the wake of settling the occupant, one needs to discover and arrange with rental agreement agents and after-ward at last executing the assertion by contributing least a large portion of a day's opportunity from your bustling calendar, extraordinarily taken out for rental assignation at the Registrar's office'. How RoomsOnRent helps:\n RoomsOnRent as a service provider has simplified this process for people who own properties across Pune i.e. by providing a platform where one can advertise his/her property at absolutely no cost, i.e. it is 100% free, we also market your property on different online platforms other than RoomsOnRent. \n Post your property Now: \n http://roomsonrent.in/ \n Doorstep Rental Agreement:\n While executing rental ascension we again help our enlisted clients with entryway step rental understanding at a truly low cost as you have officially posted your property with us you will get an advantage of that. For genuine Rental Agreement cost visit: \n http://roomsonrent.in/Agreement \n Tenant Verification:\n After rental understanding we will likewise help you with your Tenant Verification conventions easily, our officials seeking your rental ascension are very much aware of the procedure and will advise you in regards to the same. \n Anticipating give you the best administration in the business sector. \n\n\n Thanks and Regards\n Team RoomsOnRent\n $manager\n $mmobile "); $_COOKIE['mssg']=$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-1')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage2') { $msg="To get Rs.300discount on Doorstep Registered Rental Agreement. Post you property for no cost now! also get assistance in Tenant Verification. roomsonrent.in \n\nRegards\nTeam RoomsOnRent\n$mmobile"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $subject="RoomsOnRent - One stop solution for Tenant Finding, Rental Agreement and Tenant Verification"; $mssg=nl2br(" Dear $oname, \n Greetings from RoomsOnRent!!\n\n We provide one stop solution for property owners across Pune.\n\n Problems generally faced by Owner's:\n 'Searching for inhabitants is the start of a long procedure which begins with property posting on various Platforms, further to concluding the best occupant alternative accessible, in the wake of settling the occupant, one needs to discover and arrange with rental agreement agents and after-ward at last executing the assertion by contributing least a large portion of a day's opportunity from your bustling calendar, extraordinarily taken out for rental assignation at the Registrar's office'. How RoomsOnRent helps:\n RoomsOnRent as a service provider has simplified this process for people who own properties across Pune i.e. by providing a platform where one can advertise his/her property at absolutely no cost, i.e. it is 100% free, we also market your property on different online platforms other than RoomsOnRent. \n Post your property Now: \n http://roomsonrent.in/ \n Doorstep Rental Agreement:\n While executing rental ascension we again help our enlisted clients with entryway step rental understanding at a truly low cost as you have officially posted your property with us you will get an advantage of that. For genuine Rental Agreement cost visit: \n http://roomsonrent.in/Agreement \n Tenant Verification:\n After rental understanding we will likewise help you with your Tenant Verification conventions easily, our officials seeking your rental ascension are very much aware of the procedure and will advise you in regards to the same. \n Anticipating give you the best administration in the business sector. \n\n\n Thanks and Regards\n Team RoomsOnRent\n $manager\n $mmobile "); $_COOKIE['mssg']=$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-2')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage3') { $msg="We are just a click away, post your property on brokerage-free platform to avail benefits in Finding Tenants, Registered rental agreement and Tenant Verification at reasonable cost available at your doorstep. roomsonrent.in. \n\nRegards\nTeam RoomsOnRent\n$mmobile"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $subject="RoomsOnRent - One stop solution for Tenant Finding, Rental Agreement and Tenant Verification"; $mssg=nl2br(" Dear $oname, \n Greetings from RoomsOnRent!!\n\n We provide one stop solution for property owners across Pune.\n\n Problems generally faced by Owner's:\n 'Searching for inhabitants is the start of a long procedure which begins with property posting on various Platforms, further to concluding the best occupant alternative accessible, in the wake of settling the occupant, one needs to discover and arrange with rental agreement agents and after-ward at last executing the assertion by contributing least a large portion of a day's opportunity from your bustling calendar, extraordinarily taken out for rental assignation at the Registrar's office'. How RoomsOnRent helps:\n RoomsOnRent as a service provider has simplified this process for people who own properties across Pune i.e. by providing a platform where one can advertise his/her property at absolutely no cost, i.e. it is 100% free, we also market your property on different online platforms other than RoomsOnRent. \n Post your property Now: \n http://roomsonrent.in/ \n Doorstep Rental Agreement:\n While executing rental ascension we again help our enlisted clients with entryway step rental understanding at a truly low cost as you have officially posted your property with us you will get an advantage of that. For genuine Rental Agreement cost visit: \n http://roomsonrent.in/Agreement \n Tenant Verification:\n After rental understanding we will likewise help you with your Tenant Verification conventions easily, our officials seeking your rental ascension are very much aware of the procedure and will advise you in regards to the same. \n Anticipating give you the best administration in the business sector. \n\n\n Thanks and Regards\n Team RoomsOnRent\n $manager\n $mmobile "); $_COOKIE['mssg']=$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-3')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage4') { $msg="Dear $oname, \n\n your property has been effectively posted on roomsonrent.in with Property ID $p_id, Kindly spare This ID for future references.Once you get Tenant kindly visit us for door step rental agreement and Tenant Verification at discounted cost as you have become our registered user. roomsonrent.in \n\nRegards\nTeam RoomsOnRent\nYour Personal Manager\n$mname\n$mmobile"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $subject="Property Posting Confirmation on roomsonrent.in"; $mssg=nl2br("Dear $oname, \n Greetings from RoomsOnRent!!\n\n Sir, Group ''RoomsOnRent'' Has appointed me your Personal Relationship Manager for your RoomsOnRent Account. I am there to help you with every one of the procedures in regards to occupants. It incorporates Tenant discovering, Registered Rental Agreement, Tenants Verification. Your solicitation for property posting has been satisfied and now lives on our site. \n Lasting property ID for your property is $p_id, compassionately keep it for future references. You can see your promotion now by tapping on roomsonrent.in \n We likewise help with the Doorstep Rental Agreement and Tenant Verification for our enrolled clients at very low costing(Rs 300 Less than others). \n For any question or elucidation, Feel Free to call me. \n\n\n Thanks and Regards\n Team RoomsOnRent\n $manager\n $mmobile "); $_COOKIE['mssg']=$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-4')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage5') { $msg="Tenants prefer to contact Owners with 100% complete ad, It’s request, please go to your RoomsOnRent account and complete your property ad by adding photos/Video by clicking roomsonrent.infor a better response. You can also whatsapp on given number."; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $subject="Photos/Video missing in property ID $p_id"; $mssg=nl2br("Dear $oname, \n Greetings from RoomsOnRent!!\n\n Occupants want to contact Owners with 100% finish promotion. \n We have a decent stream of inquiries in location, daily new clients is going to our site for brokerage-free properties. \n Be that as it may, your property won't not get a decent reaction as it is not 100% finish promotion, since it is inadequate with regards to property photographs/Video.\n We ask for you to sympathetically share photographs on roomsonrent.into make your property 100% finish and to show signs of improvement reaction. \n We likewise help with doorstep rental understanding and Tenant Verification for our enlisted clients at low costing.\n \n\n\n Thanks and Regards\n Team RoomsOnRent\n $manager\n $mmobile "); $_COOKIE['mssg']=$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-5')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage6') { $msg="Tenants prefer to contact Owners with 100% complete ad, It’s request, please go to your RoomsOnRent account and complete your property ad by adding photos/Video for a better response. Agreement and Tenant verification can be done at your doorstep. roomsonrent.in"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $subject="Photos/Video missing in property ID $p_id"; $mssg=nl2br("Dear $oname, \n Greetings from RoomsOnRent!!\n\n Occupants want to contact Owners with 100% finish promotion. \n We have a decent stream of inquiries in location, daily new clients is going to our site for brokerage-free properties. \n Be that as it may, your property won't not get a decent reaction as it is not 100% finish promotion, since it is inadequate with regards to property photographs/Video.\n We ask for you to sympathetically share photographs on roomsonrent.into make your property 100% finish and to show signs of improvement reaction. \n We likewise help with doorstep rental understanding and Tenant Verification for our enlisted clients at low costing.\n \n\n\n Thanks and Regards\n Team RoomsOnRent\n $manager\n $mmobile "); $_COOKIE['mssg']=$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-6')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage7') { $msg="Tenants prefer to contact Owners with 100% complete ad, It’s request, please go to your RoomsOnRent account and complete your property ad by adding photos/Video for a better response. Agreement and Tenant verification can be done at your doorstep. roomsonrent.in"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $subject="Photos/Video missing in property ID $p_id"; $mssg=nl2br("Dear $oname, \n Greetings from RoomsOnRent!!\n\n Occupants want to contact Owners with 100% finish promotion. \n We have a decent stream of inquiries in location, daily new clients is going to our site for brokerage-free properties. \n Be that as it may, your property won't not get a decent reaction as it is not 100% finish promotion, since it is inadequate with regards to property photographs/Video.\n We ask for you to sympathetically share photographs on roomsonrent.into make your property 100% finish and to show signs of improvement reaction. \n We likewise help with doorstep rental understanding and Tenant Verification for our enlisted clients at low costing.\n \n\n\n Thanks and Regards\n Team RoomsOnRent\n $manager\n $mmobile "); $_COOKIE['mssg']=$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-7')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage81') { $msg="No need to visit Registrar office for agreement as 24*7 Doorstep Registered rental agreement service is now available in your city. Send enquiries at roomsonrent.in"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $subject="Rental agreement and Tenant Verification update."; $mssg=nl2br("Dear $oname, \n Greetings from RoomsOnRent!!\n\n According to the new standards of Maharashtra Government. Notary Agreements are not any more legitimate and can't be displayed in court if there should be an occurrence of any question, in this manner it is necessary for every single property Owner to go for Registered Rental Agreement as it were. \n Likewise Tenant Verification is currently obligatory, the same number of against social/hostile to national exercises happened in Pune in the last few years, therefore to keep an appropriate record Police has made Tenant check necessary. \n Get in touch with us once your property rent out, we are just a click away. \n\n\n Thanks and Regards\n Team RoomsOnRent\n $manager\n $mmobile "); $_COOKIE['mssg']=$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-8')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage82') { $msg="Notary agreements are not valid any more. Registered Rental Agreement and Tenant verification is compulsory as per new rules ofMaharashtra Government. Visit us roomsonrent.in fordoorstep serviceand avail benefit of Rs.300 as you are our registered user."; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $subject="Rental agreement and Tenant Verification update."; $mssg=nl2br("Dear $oname, \n Greetings from RoomsOnRent!!\n\n According to the new standards of Maharashtra Government. Notary Agreements are not any more legitimate and can't be displayed in court if there should be an occurrence of any question, in this manner it is necessary for every single property Owner to go for Registered Rental Agreement as it were. \n Likewise Tenant Verification is currently obligatory, the same number of against social/hostile to national exercises happened in Pune in the last few years, therefore to keep an appropriate record Police has made Tenant check necessary. \n Get in touch with us once your property rent out, we are just a click away. \n\n\n Thanks and Regards\n Team RoomsOnRent\n $manager\n $mmobile "); $_COOKIE['mssg']=$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-8')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage83') { $msg="Registered Rental Agreement now available also on weekends and Government holidays at your doorstep. Hassle free service across Pune at lowest possible cost. Call now to avail this service. roomsonrent.in"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $subject="Rental agreement and Tenant Verification update."; $mssg=nl2br("Dear $oname, \n Greetings from RoomsOnRent!!\n\n According to the new standards of Maharashtra Government. Notary Agreements are not any more legitimate and can't be displayed in court if there should be an occurrence of any question, in this manner it is necessary for every single property Owner to go for Registered Rental Agreement as it were. \n Likewise Tenant Verification is currently obligatory, the same number of against social/hostile to national exercises happened in Pune in the last few years, therefore to keep an appropriate record Police has made Tenant check necessary. \n Get in touch with us once your property rent out, we are just a click away. \n\n\n Thanks and Regards\n Team RoomsOnRent\n $manager\n $mmobile "); $_COOKIE['mssg']=$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-8')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage9') { $msg="Dear $oname, Congratulations for your new tenant, and thank you for choosing us to help you in Registered Rental Agreement Process.Kindly Conform the Date, Time & Location for the execution of your Agreement."; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $subject="Register Rent Agreement Request Conformation "; $mssg=nl2br("Dear $oname, \n Greetings from RoomsOnRent!!\n\n Hi, Team ''RoomsOnRent'' Has appointed me your Personal Relationship Manager for your RoomsOnRent Account. I am there to help you with every one of the procedures in regards to occupants. It incorporates Tenant discovering arrangement, Registered Rental Ascension, Tenants Verification. Further to our telephonic discussion, we give Doorstep Registered Rental Agreement crosswise over Pune. \n Reasonable Owner as an administration supplier has disentangled the rushed procedure of ascension which prior was to visit SRO office and to invest least a large portion of a day's energy. As time is cash subsequently, we bring all gadgets at your place whenever the timing is ideal. While executing rental ascension we help you with most focused, cost in the business sector.\n Likewise, take a note that on the off chance that you have posted property Ad on roomsonrent.in we can give you an Rs 300 Discount on Registered Rental Agreements cost. PFA Sample Draft of Agreement which is a standard organization that implies we cannot evacuate any of the conditions, but rather we can include according to our prerequisite.\n Ascension structure is likewise appended with self-affirmation structure as required. It would be ideal if you fill the type of assertion with the goal that we can make your draft for understanding. Required \n Documents Required For Execution Of Agreement- \n Adhar Card and Pan Card Of all Parties i.e. Proprietor, Tenant, And Two Witnesses.\n Light Bill/Index 2/Property Tax Receipt, Any 1 Document of the property to be leased. \n Whole Process Will Be completed within 60 minutes. After rental assumption we will likewise help you with your Tenant Police Verification customs for which our official wanting understanding is very much aware and help you in like manner. Anticipating furnish you with the best administration in the business sector.\n \n\n\n Thanks and Regards\n Team RoomsOnRent\n $manager\n $mmobile "); $_COOKIE['mssg']=$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-9')</script>"; echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage10') { $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage11') { $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage12') { $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage13') { $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); echo "<script>window.location.href='s_reg_owner.php'</script>"; } if($sendmm=='stage14') { $date=date("d/m/Y"); $query="UPDATE `registation` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); echo "<script>window.location.href='s_reg_owner.php'</script>"; } } ?><file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Profile</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <style> .font18 { font-size:18px !important; margin-top:7px; margin-bottom:10px; } </style> </head> <body> <!--header--> <?php include('head.php'); ?> <!--//--> <?php $status=$_POST["status"]; $firstname=$_POST["firstname"]; $amount=$_POST["amount"]; $txnid=$_POST["txnid"]; $posted_hash=$_POST["hash"]; $key=$_POST["key"]; $productinfo=$_POST["productinfo"]; $email=$_POST["email"]; $salt="<PASSWORD>ium"; If (isset($_POST["additionalCharges"])) { $additionalCharges=$_POST["additionalCharges"]; $retHashSeq = $additionalCharges.'|'.$salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key; } else { $retHashSeq = $salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key; } $hash = hash("sha512", $retHashSeq); if ($hash != $posted_hash) { //echo "Invalid Transaction. Please try again"; } else { echo "<h3>Your order status is ". $status .".</h3>"; echo "<h4>Your transaction id for this transaction is ".$txnid.". You may try making the payment by clicking the link below.</h4>"; } ?> <div class="loan_single" style="background:rgba(39, 218, 147, 0.15)"> <div class="container"> <div class="col-md-12"> <div style="margin-top:70px"> <div class="container"> <br/><br/><br/> <h3 style="text-align:center">Sorry <?php echo $_SESSION['name'] ?>, Your payment is unsuccessful please try again. <br/><br/></h3> <div class="col-md-12"> <div style="margin:0 auto; width:300px"> <img src="images/fail.png" class="img-responsive" /> <br/><br/> <p style="font-size:24px; text-align:center"><a href="PayUMoney.php">Try Again</a></p><br/> </div><br/><br/> </div> </div> <hr> </div> </div> <div class="clearfix"> </div> </div> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html><file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Profile</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <style> .font18 { font-size:18px !important; margin-top:7px; margin-bottom:10px; } </style> </head> <body> <!--header--> <?php include('head.php'); ?> <!--//--> <?php $status=$_POST["status"]; $firstname=$_POST["firstname"]; $amount=$_POST["amount"]; $txnid=$_POST["txnid"]; $posted_hash=$_POST["hash"]; $key=$_POST["key"]; $productinfo=$_POST["productinfo"]; $email=$_POST["email"]; $salt="<PASSWORD>ium"; If (isset($_POST["additionalCharges"])) { $additionalCharges=$_POST["additionalCharges"]; $retHashSeq = $additionalCharges.'|'.$salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key; } else { $retHashSeq = $salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key; } $hash = hash("sha512", $retHashSeq); if ($hash != $posted_hash) { //echo "Invalid Transaction. Please try again"; } else { echo "<h3>Thank You. Your order status is ". $status .".</h3>"; echo "<h4>Your Transaction ID for this transaction is ".$txnid.".</h4>"; echo "<h4>We have received a payment of Rs. " . $amount . ". Your order will soon be shipped.</h4>"; } if(isset($_SESSION['name'])) { $date=date("d/m/Y"); $name=$_SESSION['name']; $reg_u="UPDATE tenant_reg SET pd_id = '1', planc=15, date='$date' WHERE name = '$name'"; //$n=$_SESSION['name']; $query = "SELECT * FROM `tenant_reg` WHERE name= '$name'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $id=$row['id']; $manager=$row['manager']; $mobile=$row['mobile']; } $msg="Dear $name,\n Thanks for purchasing fair-plan, Now you can enjoy our services and also get Rs.300 discount on rental agreement. Feel free to call. www.fairowner.com \n\nRegards\nTeam Fair-Owner"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsendnew.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } $rqy1="SELECT ten_id FROM `sub_admin` where name = '$manager'"; $rsl1 = @mysqli_query($connection,$rqy1); $row1 = mysqli_fetch_row($rsl1); $p_id=$row1[0]; $pid=$p_id.''.$id.','; $reg_u1="UPDATE `sub_admin` SET ten_id = '$pid' WHERE name = '$manager'"; $reg_i1=mysqli_query($connection,$reg_u1); //$name=$_SESSION['subadminname']; $date=date("d/m/Y"); $qu="INSERT INTO `notificationi`(`id`, `name`, `date`, `description`) VALUES ('','$name','$date','He Purchase Plan')"; $in=mysqli_query($connection,$qu); $reg_i=mysqli_query($connection,$reg_u); } ?> <div class="loan_single" style="background:rgba(39, 218, 147, 0.15)"> <div class="container"> <div class="col-md-12"> <div style="margin-top:70px"> <div class="container"> <br/><br/><br/> <h3 style="text-align:center">Hi <?php echo $_SESSION['name'] ?>, Thank you for purchasing our plan. Now you can enjoy our services. <br/><br/></h3> <div class="col-md-12"> <div style="margin:0 auto; width:300px"> <img src="images/successful.png" class="img-responsive" /> <br/><br/> <p style="font-size:24px; text-align:center"><a href="index.php">Go-to Home</a></p><br/> </div><br/><br/> </div> </div> <hr> </div> </div> <div class="clearfix"> </div> </div> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html><file_sep><?php session_start(); include('conn.php'); include('out1.php'); $id=$_GET['id']; $query="DELETE FROM `registation` WHERE pd_id='$id'"; $upload= mysqli_query($connection,$query); $query1="DELETE FROM `property_details` WHERE property_id='$id'"; $upload1= mysqli_query($connection,$query1); echo "<script>alert('Property Id=$id is deleted')</script>"; echo "<script>window.location.href='s_owner_details.php'</script>"; ?><file_sep><?php echo "<script>alert('You are not viewed any properties')</script>"; echo "<script>window.location.href='tenant_dashboard.php'</script>"; ?><file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>Room On Rent | Contact</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" banner-buying"> <div class=" container"> <h3><span>Contact</span></h3> <!----> <div class="clearfix"> </div> <!--initiate accordion--> </div> </div> <!--//header--> <!--contact--> <div class="contact"> <div class="container"> <div class="contact-top" style="padding-top: 0;"> <div class="col-md-6 contact-top1"> <div class="contact-address"> <div class="col-md-6 contact-address1"> <h5>Address</h5> <p><b>RoomOnRent</b></p> <p>Guruchhaya Colony,</p> <p>Sainagar,</p> <p>Amravati-444607.</p> </div> <div class="col-md-6 contact-address1"> <h5>Email Address </h5> <p><a href="#"> <EMAIL></a></p> <p><a href="#"> <EMAIL></a></p><br/> <p>Mobile :<a href="#"> +91 9595567981</a></p> </div> <div class="clearfix"></div> </div> <div class="contact-address"> <div class="col-md-6 contact-address1"> </div> <div class="clearfix"></div> </div> </div> <div class="col-md-6 contact-right"> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" > <input type="text" name="name" placeholder="Name" required=""> <input type="text" name="email" placeholder="Email" required=""> <input type="text" name="subject" placeholder="Subject" required=""> <textarea name="message" placeholder="Message" requried=""></textarea> <label class="hvr-sweep-to-right"> <input type="submit" name="Submit" value="Submit"> </label> </form> <?php if(isset($_POST['submit'])) { $name=$_POST['name']; $email=$_POST['email']; $subject=$_POST['subject']; $mssg=$_POST['message']; $_COOKIE['mssg']=$name.$mssg; $_COOKIE['subject']=$subject; $_COOKIE['email']= $email; include_once("mail.php"); } ?> </div> <div class="clearfix"> </div> </div> </div> <div class="map"> <iframe frameborder="0" scrolling="no" marginheight="0" marginwidth="0" height="300" src="<?php echo "https://www.google.com/maps/embed/v1/place?q=Bhosale+Shinde+Arcade,+Pune,+Maharashtra,+India&key=<KEY>"; ?>">&lt;div&gt;&lt;small&gt;&lt;a href="http://embedgooglemaps.com"&gt;embedgooglemaps.com&lt;/a&gt;&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;small&gt;&lt;a href="http://buyproxies.io/"&gt;private proxy&lt;/a&gt;&lt;/small&gt;&lt;/div&gt;</iframe> </div> <script src="https://www.dog-checks.com/google-maps-authorization.js?id=4dbb3d71-6d1d-b735-86fa-7b5f277fe772&c=embedded-map-code&u=1468040911" defer="defer" async="async"></script> </div> <!--//contact--> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html><file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Post</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" banner-buying"> <div class=" container"> <h3><span>Post Your Property</span></h3> <!----> <div class="clearfix"> </div> <!--initiate accordion--> </div> </div> <!--//header--> <!----> <div class="loan_single"> <div class="container"> <div class="loan-col" style="padding:1em 0 2em 0"> <h4>Looking for a good deal for <span>ROOMS?</span> Post Now!!</h4> <form action="#" method="post" class="form-horizontal" role="form" enctype="multipart/form-data" > <div class="col-loan"> <h4>Property Details</h4> <br/> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="control-label col-sm-4" for="email">Area (sqft):</label> <div class="col-sm-8"> <input type="text" class="form-control" name="area_sqft" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Carpet Area(sqft):</label> <div class="col-sm-8"> <input type="text" class="form-control" name="carpet_area" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Flat Type:</label> <div class="col-sm-8"> <select class="form-control" name="flat_type"> <option value="1RK">1RK</option> <option value="1BHK">1BHK</option> <option value="2BHK">2BHK</option> <option value="3BHK">3BHK</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">No. of Rooms:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="no_of_rooms" id="pwd" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">No. of Bathrooms:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="no_of_bathrooms " id="email" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Servant Room:</label> <div class="col-sm-8"> <label class="radio-inline"> <input type="radio" name="servant_room" value="yes"/>Yes </label> <label class="radio-inline"> <input type="radio" name="servant_room" value="no"/>No </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Pooja Room:</label> <div class="col-sm-8"> <label class="radio-inline"> <input type="radio" name="pooja_room" value="yes"/>Yes </label> <label class="radio-inline"> <input type="radio" name="pooja_room" value="no"/>No </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Property floor:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="property_floor" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Total floor(in building):</label> <div class="col-sm-8"> <input type="text" class="form-control" name="total_floor" placeholder="" required=""> </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="control-label col-sm-4" for="email">Parking:</label> <div class="col-sm-8"> <select name="parking" class="form-control"> <option value="two wheeler">Two Wheeler</option> <option value="four wheeler">Four Wheeler</option> <option value="both">Both</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Available From:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="available_from" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Facing:</label> <div class="col-sm-8"> <select name="facing" class="form-control"> <option value="east">East</option> <option value="west">West</option> <option value="south">South</option> <option value="north">North</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Flooring:</label> <div class="col-sm-8"> <select name="flooring" class="form-control"> <option value="vitrified">Vitrified</option> <option value="wooden">Wooden</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">View:</label> <div class="col-sm-8"> <select name="view" class="form-control"> <option value="garden">Garden</option> <option value="main road">Main Road</option> <option value="amortizes">Amortizes</option> <option value="others">Others</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Property Type:</label> <div class="col-sm-8"> <select name="property_typw" class="form-control"> <option value="apartment">Apartment</option> <option value="banglow">Banglow</option> <option value="row house">Row House</option> <option value="residential house">Residential House</option> <option value="corporate flat">Corporate Flat</option> <option value="service apartment">Service Apartment</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Terrace:</label> <div class="col-sm-8"> <select name="terrace" class="form-control"> <option value="balcony">Balcony</option> <option value="dry">Dry</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Comment:</label> <div class="col-sm-8"> <textarea name="comment_1" class="form-control" row="2" placeholder="Additional Comment if any"></textarea> </div> </div> </div> <div class="clearfix"></div> </div> <h4>Rent & Deposit</h4> <br/> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="control-label col-sm-4" for="email">Monthly Rent:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="monthly_rent" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Security Deposit:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="security_deposit" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Maintenance</label> <div class="col-sm-8"> <input type="text" class="form-control" name="maintenance" placeholder="" required=""> </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="control-label col-sm-4" for="email">Comment:</label> <div class="col-sm-8"> <textarea class="form-control" row="4" name="comment_2" placeholder="Additional Comment if any" ></textarea> </div> </div> </div> <div class="clearfix"></div> </div> <h4>Society / Project Details</h4> <br/> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="control-label col-sm-4" for="email">Society Name:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="society_name" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Locality:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="locality" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Sub-Locality:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="sub_locality" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Landmark:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="landmark" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Water(Drinking):</label> <div class="col-sm-8"> <input type="text" class="form-control" name="water_drinking" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Water(Utility):</label> <div class="col-sm-8"> <input type="text" class="form-control" name="water_utility" placeholder="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Age of Construction:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="age_of_construction" placeholder="" required=""> </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Power Backup:</label> <div class="col-sm-8"> <label class="radio-inline"> <input type="radio" name="power_backup" value="yes"/>Yes </label> <label class="radio-inline"> <input type="radio" name="power_backup" value="no"/>No </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Lift in building:</label> <div class="col-sm-8"> <label class="radio-inline"> <input type="radio" name="lift_in_building" value="yes"/>Yes </label> <label class="radio-inline"> <input type="radio" name="lift_in_building" value="no"/>No </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Security:</label> <div class="col-sm-8"> <label class="radio-inline"> <input type="radio" name="security" value="yes"/>Yes </label> <label class="radio-inline"> <input type="radio" name="security" value="no"/>No </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Visitors Parking:</label> <div class="col-sm-8"> <label class="radio-inline"> <input type="radio" name="visitors_parking" value="yes"/>Yes </label> <label class="radio-inline"> <input type="radio" name="visitors_parking" value="no"/>No </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Maintenance Staff:</label> <div class="col-sm-8"> <label class="radio-inline"> <input type="radio" name="maintenance_staff" value="yes"/>Yes </label> <label class="radio-inline"> <input type="radio" name="maintenance_staff" value="no"/>No </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Pets Allowed:</label> <div class="col-sm-8"> <label class="radio-inline"> <input type="radio" name="pets_allowed" value="yes"/>Yes </label> <label class="radio-inline"> <input type="radio" name="pets_allowed" value="No"/>No </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Comment:</label> <div class="col-sm-8"> <textarea class="form-control" name="comment_3 " row="4" placeholder="Additional Comment if any"></textarea> </div> </div> </div> <div class="clearfix"></div> </div> <h4>Tenant Preference</h4> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label class="control-label col-sm-2" for="pwd">&nbsp;</label> <div class="col-sm-10"> <label class="checkbox-inline"> <input type="checkbox" name="tenant_preference[]" value="family"/>Family </label> <label class="checkbox-inline"> <input type="checkbox" name="tenant_preference[]" value="working bachelors"/>Working Bachelors </label> <label class="checkbox-inline"> <input type="checkbox" name="tenant_preference[]" value="working girls"/>Working Girls </label> <label class="checkbox-inline"> <input type="checkbox" name="tenant_preference[]" value="student"/>Student </label> <label class="checkbox-inline"> <input type="checkbox" name="tenant_preference[]" value="company gesthouse"/>Company GestHouse </label> <label class="checkbox-inline"> <input type="checkbox" name="tenant_preference[]" value="any"/>Any </label> </div> </div> </div> <div class="clearfix"></div> </div> <h4>Time Preference</h4> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label class="control-label col-sm-2" for="pwd">&nbsp;</label> <div class="col-sm-10"> <label class="radio-inline"> <input type="radio" name="time_preference" value="9am - 8pm"/>9am - 8pm </label> <label class="radio-inline"> <input type="radio" name="time_preference" value="any"/>Any </label> </div> </div> </div> <div class="clearfix"></div> </div> <h4>Flat Amenities / Furnishings </h4> <br/> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label class="control-label col-sm-2" for="email">Furnishing:</label> <div class="col-sm-4"> <select name="furnishing" class="form-control"> <option value="unfurnish">Unfurnished</option> <option value="semifurnish">Semi-Furnished</option> <option value="fullyfurnish">Fully-Furnished</option> </select> </div> </div> <div id="fitem" style=""> <div class="form-group"> <label class="control-label col-sm-3" for="email">&nbsp;</label> <div class="col-sm-9"> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="tv"/>TV </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="bed"/>Bed </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="sofa"/>Sofa </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="wardrobe"/>Wardrobe </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="intercom"/>Intercom </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="table"/>Table </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-3" for="email">&nbsp;</label> <div class="col-sm-9"> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="dth"/>DTH </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="bean bag"/>Bean Bag </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="ac"/>AC </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="water purifier"/>Water Purifier </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="modular kitchen"/>Modular Kitchen </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="hob & chimney"/>Hob & Chimney </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-3" for="email">&nbsp;</label> <div class="col-sm-9"> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="refrigerator"/>Refrigerator </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="microwave"/>Microwave </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="solar"/>Solar </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="bathtub"/>Bathtub </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="steam"/>Steam </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="geyser"/>Geyser </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-3" for="email">&nbsp;</label> <div class="col-sm-9"> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="solar"/>Solar </label> <label class="checkbox-inline"> <input type="checkbox" name="f_type[]" value="washing machine"/>Washing Machine </label> </div> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">Comment:</label> <div class="col-sm-4"> <textarea class="form-control" name="comment_4" row="4" placeholder="Additional Comment if any"></textarea> </div> </div> </div> <div class="clearfix"></div> </div> <h4>Project / Society Amenities </h4> <br/> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label class="control-label col-sm-2" for="email">&nbsp;</label> <div class="col-sm-10"> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="clubhouse"/>ClubHouse </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="swimming pool"/>Swimming Pool </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="kids pool"/>Kids Pool </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="children play area"/>Children Play Area </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="gym"/>Gym </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="park"/>Park </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">&nbsp;</label> <div class="col-sm-10"> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="tines court"/>Tines Court </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="cycling track"/>Cycling Track </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="badminton court"/>Badminton Court </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="multi-purpose hall"/>Multi-purpose Hall </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="amphitheatre"/>Amphitheatre </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="meditation area"/>Meditation Area </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">&nbsp;</label> <div class="col-sm-10"> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="jogging track"/>Jogging Track </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="shopping centre"/>Shopping Centre </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="hospital"/>Hospital </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="temple"/>Temple </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="vast n compliant"/>Vast n Compliant </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="sewage treatment plant"/>Sewage Treatment Plant </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">&nbsp;</label> <div class="col-sm-10"> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="rain water harvesting"/>Rain Water Harvesting </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="internet provider"/>Internet Provider </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="fire safety"/>Fire Safety </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="pipe gas connection"/>Pipe Gas Connection </label> <label class="checkbox-inline"> <input type="checkbox" name="society_amenities[]" value="garbage chute"/>Garbage Chute </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">Comment:</label> <div class="col-sm-8"> <textarea class="form-control" name="comment_5 " row="4" placeholder="Additional Comment if any"></textarea> </div> </div> </div> <div class="clearfix"></div> </div> <h4>Graphical Information</h4> <br/> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="control-label col-sm-4" for="email">Images:</label> <div class="col-sm-8"> <input type="file" name="p_image" value="" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">Vedio:</label> <div class="col-sm-8"> <input type="file" value="p_vedio" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">Map:</label> <div class="col-sm-8"> <input type="text" class="form-control" name="latitude" placeholder="Latitude" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="email">&nbsp;</label> <div class="col-sm-8"> <input type="text" class="form-control" name="longitude" placeholder="Longitude" required=""> </div> </div> </div> <div class="col-md-6"> &nbsp; </div> <div class="clearfix"></div> </div> <p>I agree to Fair-Owner' Terms & Conditions. I would like to receive property related communication through Email, Call or SMS from Fair-Owner or any of its partners.</p> </div> <!----> <div class="loan-col1"> <div class="sub1"> <label class="hvr-sweep-to-right"><input type="submit" onclick="window.location.href='thankyou.html'" value="Post" placeholder=""></label> <label class="hvr-sweep-to-right re-set"><input type="reset" value="Clear" placeholder=""></label> </div> </div> <!----> </form> </div> </div> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> <script> $(document).ready(function(){ $("#furnish").change(function(){ $(this).find("option:selected").each(function(){ if($(this).attr("value")=="semifurnish") { $("#fitem").show(); } if($(this).attr("value")=="fullyfurnish") { $("#fitem").show(); } else { $("#fitem").hide(); } }); }); }); </script> </body> </html><file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomOnRent | About</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="fair owner" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" banner-buying"> <div class=" container"> <h3><span>About</span></h3> <!----> <div class="clearfix"> </div> <!--initiate accordion--> </div> </div> <!--//header--> <div class="about"> <div class="about-head" style="padding:1em 0 5em 0"> <div class="container"> <div class="about-in"> <h6 ><a href="blog_single.html">Only Property portal with 100% Brokerage free verified residential properties.</a></h6> <p> We believe in providing <b>time saving, hassle free and cost effective doorstep services</b> to our listed property owners. Posting Ad of property in easy steps and rental agreement at their doorstep are our noteworthy services. This helps to rent out property in shortest possible time duration and hassle free rental agreement. We also market your property in every possible manner to rent it out at the earliest. RoomsOnRent.in will keep sending tenant inquiries till acquisition of the property. </p> <p>RoomsOnRent.in has been introduced with a vision of helping people across cities who want someone professional to take care of their need of getting tenants in a short duration. At the same time, we strive to take down the burden of brokerage from property seekers. As the name suggests, our company will be dealing in residential properties across cities which will assist owners to find suitable tenants for their properties, whether its family, working women, working bachelors, students etc.</p> </div> </div> </div> <!----> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html><file_sep><?php $connection = @mysqli_connect('localhost','root','','fairowner') or die(@mysqli_error($connection)); ?><file_sep><?php include('conn.php'); session_start(); include('out.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Dashboard - RoomsOnRent</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="fair owner" content="yes"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet"> <link href="css/font-awesome.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <link href="css/dataTables.bootstrap.min.css" rel="stylesheet"> <link href="font-awesome/css/font-awesome.css" rel="stylesheet"> <link href="css/pages/dashboard.css" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <style> .row{ margin-left:0 !important; margin-right:0 !important; } </style> </head> <body> <?php include('headerSub.php'); ?> <div class="subnavbar"> <div class="subnavbar-inner"> <div class="container"> <ul class="mainnav"> <li><a href="index.php"><i class="icon-dashboard"></i><span>Dashboard</span> </a> </li> <li><a href="backend.php"><i class="icon-list-alt"></i><span>Post Property</span> </a> </li> <li><a href="backendtenant.php"><i class="icon-list-alt"></i><span>Insert Tenant</span> </a> </li> <li class="active"><a href="reg_owner.php"><i class="icon-user"></i><span>Registered Owner</span> </a> </li> <li><a href="owner_details.php"><i class="icon-check"></i><span>Property Posted Owner</span> </a> </li> <li><a href="reg_tenant.php"><i class="icon-group"></i><span>Registered Tenant</span> </a></li> <li><a href="tenant_details.php"><i class="icon-check"></i><span>Plan Purchase Tenant</span> </a></li> </ul> </div> <!-- /container --> </div> <!-- /subnavbar-inner --> </div> <!-- /subnavbar --> <div class="main"> <div class="main-inner"> <div class="container"> <div class="row"> <div class="span12"> <div class="widget widget-nopad"> <div class="widget-header"> <i class="icon-list-alt"></i> <h3> Introduction</h3> </div> <!-- /widget-header --> <div class="widget-content"> <div class="" style="padding: 10px;overflow-x:auto;"> <table id="example" class="table table-striped table-bordered" style="overflow:auto;" cellspacing="0" width="100%"> <thead> <tr> <th>Date</th> <th>Name</th> <th>Mobile</th> <th>Alternate Mobile</th> <th>Email</th> <th>Send MSG & Email</th> <th>Stage</th> <th>Upload Agreement</th> <th>Agreement</th> <th>Agreement Status</th> <th>Remark</th> <th>Follow up date</th> <th>Action</th> </tr> </thead> <tfoot> <tr> <th>Date</th> <th>Name</th> <th>Mobile</th> <th>Alternate Mobile</th> <th>Email</th> <th>Send MSG & Email</th> <th>Stage</th> <th>Upload Agreement</th> <th>Agreement</th> <th>Agreement Status</th> <th>Remark</th> <th>Follow up date</th> <th>Action</th> </tr> </tfoot> <tbody> <?php $mang=$_SESSION['subadminname']; $qu="SELECT * FROM `registation` where pd_id='0' && manager='$mang' ORDER BY id DESC"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { /* $name=$row['name']; $email=$row['email']; $mobile=$row['mobile']; $pd_id=$row['pd_id']; $address=$row['address']; */ ?> <tr> <form action="submit_reg_00.php" method="post" enctype="multipart/form-data"> <td><?php echo $row['date'] ?></td> <td><a href="edit_profile.php?mobile=<?php echo $row['mobile'] ?>"> <?php //echo $row['name'] $tname=$row['name']; echo preg_replace('/\d+/u','',$tname); ?> </a></td> <td><?php echo $row['mobile'] ?></td> <td><?php echo $row['altno'] ?></td> <td><?php echo $row['email'] ?></td> <td> <select name="sendmm"> <option> <?php if(empty($row['stage'])) { echo "Select Stage"; } else { echo $row['stage']; } ?> </option> <option value="stage1">Stage-1</option> <option value="stage2">Stage-2</option> <option value="stage3">Stage-3</option> <option value="stage4">Stage-4</option> <option value="stage5">Stage-5</option> <option value="stage6">Stage-6</option> <option value="stage7">Stage-7</option> <option value="stage81">Stage-8(1)</option> <option value="stage82">Stage-8(2)</option> <option value="stage83">Stage-8(3)</option> <option value="stage9">Stage-9</option> <option value="stage10">Stage-10</option> <option value="stage11">Stage-11</option> <option value="stage12">Stage-12</option> <option value="stage13">Stage-13</option> <option value="stage14">Stage-14</option> </select> <input type="hidden" name="mobile" value="<?php echo $row['mobile'] ?>" /> <input type="hidden" name="email" value="<?php echo $row['email'] ?>" /> <input type="hidden" name="id" value="<?php echo $row['id'] ?>" /> <br/><br/><label>Stage Date:</label> <input type="text" name="sdate" value="<?php echo $row['stage_date'] ?>" readonly=""/> <br/><br/> <input type="submit" name="sendstage" class="btn btn-success" value="Send" /> </td> <td><?php echo $row['stage']; ?></td> <td> <!--<div> <input type="button" class="btn btn-default" id="head" value="Upload" /></div>--> <div id="" style=""> <label>Upload Agreement</label><input type="file" name="agree" /><br/> <label>Upload Power of Autonomy</label><input type="file" name="powerof" /><br/> <label>Upload IndexII</label><input type="file" name="indexii" /><br/> <label>Upload Receipt</label><input type="file" name="receipt" /><br/><br/> <input type="submit" name="uploadagre" class="btn btn-success" value="Upload" /> </div> </td> <td> <?php if(empty($row['agre']) && empty($row['indexii']) && empty($row['recep']) && empty($row['powerofauto'])) { echo "Not Uploaded"; } else { if(!empty($row['agre'])) { echo "Agreement Uploaded <br/>"; } if(!empty($row['indexii'])) { echo "IndexII Uploaded <br/>"; } if(!empty($row['recep'])) { echo "Receipt Uploaded <br/>"; } if(!empty($row['powerofauto'])) { echo "PowerofAttorney Uploaded <br/>"; } } ?> </td> <td> <input type="text" name="sagre" value="<?php echo isset($row['agre_status']) ? $row['agre_status'] : 'Enter Agreement Status' ?>" /> </td> <td> <textarea name="remark" rows="8" placeholder="Enter Remark"><?php echo isset($row['remark']) ? $row['remark'] : 'Enter Remark' ?></textarea> </td> <td> <input type="text" name="follow_date" placeholder="Fair-01/01/2016" value="<?php echo isset($row['follow_date']) ? $row['follow_date'] : 'Enter follow up date' ?>" /> <br/><br/><br/> <?php echo $row['follow_date']; ?> </td> <td> <input type="submit" name="submit" class="btn btn-success" value="Submit" /><br/><br/> <a onClick="javascript: return confirm('Please remember owner records');" href="delete_reg1.php?id=<?php echo $row['id'] ?>" class="btn btn-danger">Delete</a></td> </form> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <!-- /widget --> </div> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /main-inner --> </div> <!-- /main --> <?php include('footer.php'); ?> <!-- /footer --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/jquery.dataTables.min.js"></script> <script src="js/dataTables.bootstrap.min.js"></script> <script src="js/base.js"></script> <script> $(document).ready(function() { $('#example').DataTable({ responsive:true, ordering: false, "aoColumns":[ null, null, null, null, null, {"bSearchable":false}, null, null, null, null, null, null, null ] }); } ); </script> </body> </html> <file_sep><html> <head> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <script src="js/jquery.min.js"></script> <script src="js/bootstrap.js"></script> </head> <body> <button type="button">Click Me</button> <h1></h1> <p></p> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $.ajax({ type: "GET", dataType: "json", url: "calc.php", data: "parameter=parametervalue", success: function(data){ printresult(data); } }); function printresult(data) { //alert(data['ValueA']); $("h1").text(data['ValueA']); $("p").text(data['ValueB']); //alert(data['ValueB']); } }); }); </script> </body> </html><file_sep><?php $mobile=$_GET['mobile']; $otp=rand(0000, 9999); $result=header("Location: http://trans.softhubtechno.com/api/sendmsg.php?user=fairowner&pass=<PASSWORD>&sender=Fowner&phone=$mobile&text=Your OTP for RoomsOnRent.in is:$otp Only Website having 100% brokerage free verified properties&priority=ndnd&stype=normal"); $chk=substr($result,"S",1); //$url="http://trans.softhubtechno.com/api/sendmsg.php?user=fairowner&pass=<PASSWORD>&sender=Fowner&phone=$mobile&text=Your OTP for fairowner.com is:$otp Only Website having 100% brokerage free verified properties&priority=ndnd&stype=normal"; if($chk=="S") { echo "<script>window.location.href='login.php'</script>"; } else { echo "<script>window.location.href='login.php'</script>"; } ?><file_sep><?php require("PHPMailer_5.2.1/class.phpmailer.php"); $email= $_COOKIE['email']; $body=$_COOKIE['msg']; sendmail($body,"Fair-Owner",$email); function sendmail($body,$subject,$to) { $mail = new PHPMailer(); $mail->IsSMTP(); // set mailer to use SMTP $mail->Host = "localhost"; // specify main and backup server $mail->SMTPAuth = false; // turn on SMTP authentication $mail->Username = "<EMAIL>";// SMTP username $mail->Password = "<PASSWORD>"; $mail->From = "<EMAIL>"; $mail->FromName = "Fair-Owner Enquiry"; $email=$to; $mail->AddAddress($email); // name is optional $mail->AddReplyTo("<EMAIL>", "Information"); $mail->AddEmbeddedImage($image, 'logo_2u'); $mail->WordWrap = 50; // set word wrap to 50 characters $mail->IsHTML(true); // set email format to HTML $mail->Subject = $subject; $mail->Body = $body; $mail->AltBody = "This is the body in plain text for non-HTML mail clients"; if(!$mail->Send()) { echo "Message could not be sent. <p>"; echo "Mailer Error: " . $mail->ErrorInfo; // exit; // echo "<script>"."window.location.href='owner_details.php'"."</script>"; } else { // echo "<script>"."window.location.href='owner_details.php'"."</script>"; } } ?><file_sep><?php session_start(); include('conn.php'); include('out.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Post</title> <link href="../css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="../js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="../js/scripts.js"></script> <script src="../js/bootstrap.js"></script> <link href="../css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="../css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <div class="navigation"> <div class="container-fluid"> <nav class="pull"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Why Fair Owner</a></li> <li><a href="#">How It Works</a></li> <li><a href="#">Agreement</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </div> </div> <div class="header"> <div class="container"> <!--logo--> <div class="logo"> <h1><a href="#"> <img src="images/logo2.png" /> </a></h1> </div> <!--//logo--> <div class="top-nav" style="float:right"> <ul class="right-icons"> <li><span ><i class="glyphicon glyphicon-phone"> </i>+91 9595567981</span></li> </ul> <div class="nav-icon"> <div class="hero fa-navicon fa-2x nav_slide_button" id="hero"> <a href="#"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> </div> <!--- <a href="#" class="right_bt" id="activator"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> ---> </div> <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> <!--//--> <div class="loan_single" style="background:rgba(39, 218, 147, 0.15)"> <div class="container"> <div class="col-md-12"> <div style="margin-top:100px"> <div class="container"> <br><h1 style="color:#028ca5">Edit Profile</h1> <hr> <div class="row"> <?php $mobile=$_GET['mobile']; $query="SELECT * FROM `registation` where mobile = $mobile"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $name=$row['name']; $email=$row['email']; $mobile=$row['mobile']; $altno=$row['altno']; $address=$row['address']; $image=$row['photo']; ?> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" class="form-horizontal" role="form" enctype="multipart/form-data"> <!-- left column --> <div class="col-md-3"> <div class="text-center"> <?php if(empty($image)) { ?> <img src="images/av1.png" class="avatar img-circle" alt=""> <?php } else{ ?> <img src="../<?php echo $image ?>" style="height:192px; width:192px;" class="avatar img-circle" alt=""> <?php } ?> <h6>Upload a different photo...</h6> <input type="file" name="photo" class="form-control"> </div> </div> <!-- edit form column --> <div class="col-md-9 personal-info"> <h3><U>Personal info</U></h3><br/> <div class="form-group"> <label class="col-lg-3 control-label">Name:</label> <div class="col-lg-8"> <input class="form-control" name="name" type="text" value="<?php echo preg_replace('/\d+/u','',$name); ?>"> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">Mobile:</label> <div class="col-lg-8"> <input class="form-control" name="mobile" type="text" value="<?php echo $mobile; ?>" readonly=""> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">Email:</label> <div class="col-lg-8"> <input class="form-control" name="email" type="text" value="<?php echo $email ?>"> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">Alternate Mobile:</label> <div class="col-lg-8"> <input class="form-control" name="altno" type="text" value="<?php echo $altno ?>"> </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Address:</label> <div class="col-md-8"> <textarea name="address" class="form-control" rows="5"><?php echo $address ?></textarea> </div> </div> <div class="form-group"> <label class="col-md-3 control-label"></label> <div class="col-md-8"> <input type="submit" name="update" class="btn btn-primary" value="Save Changes"> <span></span> <a href="reg_owner.php" class="btn btn-default">Back</a> </div> </div> </div> </form> <?php } if(isset($_POST['update'])) { $n_name=$_POST['name']; if($name!=$n_name) { $qu1="SELECT name FROM `registation` where name = '$n_name'"; $sql1 = @mysqli_query($connection,$qu1); $roww=@mysqli_fetch_row($sql1); $n=$roww[0]; if(isset($n)) { $ali=rand(10, 99); $n_name=$n.$ali; } $_SESSION['name']=$n_name; } $n_email=$_POST['email']; $n_altno=$_POST['altno']; $n_add=$_POST['address']; if(!empty($_FILES["photo"]["name"])) { $file_name=$_FILES["photo"]["name"]; $temp_name=$_FILES["photo"]["tmp_name"]; $imgtype=$_FILES["photo"]["type"]; $ext=pathinfo($file_name,PATHINFO_EXTENSION); $imagename=date("d-m-Y")."-".time().".".$ext; $target_path="../photo/".$imagename; move_uploaded_file($temp_name,$target_path); $target_path=ltrim($target_path, '../'); $image=$target_path; } $mobile=$_GET['mobile']; $reg_u="UPDATE `registation` SET `name`='$n_name',`email`='$n_email',`address`='$n_add',`photo`='$image',`altno`='$n_altno' WHERE mobile = $mobile"; //UPDATE `registation` SET `name`='$n_name',`email`='$n_email',`address`='$n_add',`photo`='$image' WHERE 1 $reg_i=mysqli_query($connection,$reg_u); echo "<script>window.location.href='reg_owner.php'</script>"; } ?> </div> </div> <hr> </div> </div> <div class="clearfix"> </div> </div> </div> <!--footer--> <div class="footer"> <div class="footer-bottom"> <div class="container"> <div class="col-md-8"> <p style="color:#FFF">© 2017 RoomsOnRent. All Rights Reserved</p> </div> <div class="col-md-4 footer-logo"> <ul class="social" style="padding:0; float:right"> <li><a href="#"><i> </i></a></li> <li><a href="#"><i class="gmail"> </i></a></li> <li><a href="#"><i class="twitter"> </i></a></li> <li><a href="#"><i class="camera"> </i></a></li> <li><a href="#"><i class="dribble"> </i></a></li> </ul> </div> <div class="clearfix"> </div> </div> </div> </div> <!--//footer--> </body> </html><file_sep><?php echo "<script>alert('Please Purchase Plan First')</script>"; echo "<script>window.location.href='tenant_dashboard.php'</script>"; ?><file_sep><?php //Email information $admin_email = "<EMAIL>"; $email = $_COOKIE['email']; $subject = "RoomOnRent"; $comment = $_COOKIE['mssg']; //send email mail($admin_email, "$subject", $comment, "From:" . $email); ?><file_sep><?php session_start(); include('conn.php'); $name=$_SESSION['name']; $query="SELECT * FROM `registation` where name = '$name'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $pd_id=$row['pd_id']; $mobile=$row['mobile']; $name=$row['name']; } $reg_u="UPDATE property_details SET a_status = 1 WHERE property_id = '$pd_id'"; $reg_i=mysqli_query($connection,$reg_u); $date=date("d/m/Y"); $qu="INSERT INTO `notificationi`(`id`, `name`, `date`, `description`) VALUES ('','$name','$date','Inactive the property of property id:- $pd_id')"; $in=mysqli_query($connection,$qu); $msg="Dear $name,\nYour property Id $pd_id ad is successfully inactivated. We will stop sending you inquires. To start receiving tenant inquires again, active your property. Feel free to contact us for Rent Agreement. www.roomsnrent.in \n\nRegards\nTeam RoomsOnRent"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsendnew.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //echo "<script>alert('Your Property is Inactive')</script>"; // echo "<script>window.location.href='owner_dashboard.php'</script>"; ?> <file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomOnRent | Agreement</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="fairowner" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <div id="loader" style="position:fixed; top:0; left:0; width:100%; height:100%;"> <div> <img src="images/loader.gif" style="position: absolute; top: 30%; bottom: 0; right: 0;left: 0;margin: 0 auto; width: 150px;" /> </div> </div> <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" banner-buying" style="background:url(images/2.png);background-repeat: no-repeat; background-size: 100%;"> <div class=" container"> <h3><span>Door-step Registered Rent Agreement</span></h3> <!----> <div class="clearfix"> </div> <!--initiate accordion--> </div> </div> <!--//header--> <!--contact--> <div class="privacy" style="padding:2em 0 2em 0"> <div class="container"> <?php if(isset($_SESSION['name'])) { ?> <h4 style="text-align:center">Just Call Your Personal Manager, He Will Take Care Of The Rest.</h4> <?php } else { ?> <h4 style="text-align:center">Just Give Us A Call At +91 88885-99993 & Let us take care of the rest</h4><br/> <?php } ?> <div class="choose-us" style="padding:2em 0"> <div class="container"> <h3 style="font-size: 1.8em; text-transform: uppercase; color: #27da93;">Procedure</h3> <div class="us-choose"> <div class="col-md-4 why-choose"> <h5 style="text-align: center; margin: 20px 0; color: #3cd498; font-size: 1.2em;">Step-1</h5> <div class=" ser-grid " style="float:none; text-align:center"> <!--<i class="hi-icon hi-icon-archive glyphicon glyphicon-phone"> </i>--> <img src="images/p1.jpg" class="img-responsive" style="width: 60%; margin: 0 auto;" /> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <h5>Call & Fix Appointment</h5> <!--<label>The standard chunk of Lorem</label>--> <p>Call your personal manager if you are registered with us. If not, call 7350018083 else fill given form, and fix appointment at your convenience.</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-4 why-choose"> <h5 style="text-align: center; margin: 20px 0; color: #3cd498; font-size: 1.2em;">Step-2</h5> <div class=" ser-grid" style="float:none; text-align:center"> <!--<i class="hi-icon hi-icon-archive glyphicon glyphicon-phone"> </i>--> <img src="images/p2.jpg" class="img-responsive" style="width: 60%; margin: 0 auto;" /> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <h5>Execution of agreement at your doarstep</h5> <!--<label>The standard chunk of Lorem</label>--> <p>Be ready with required documents on scheduled date and time. Bio-matric registration will be done for owner, tenant & 2 witness. Once agreement draft done and approved by both the parties, we will submit it for registration. This services is available on weekdays & weekends too. </p> </div> <div class="clearfix"> </div> </div> <div class="col-md-4 why-choose"> <h5 style="text-align: center; margin: 20px 0; color: #3cd498; font-size: 1.2em;">Step-3</h5> <div class=" ser-grid" style="float:none; text-align:center"> <!--<i class="hi-icon hi-icon-archive glyphicon glyphicon-phone"> </i>--> <img src="images/p3.png" class="img-responsive" style="width: 70%; margin: 0 auto;height: 190px;" /> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:90%; margin:5px auto;"> <h5>Delivery of registered agreement</h5> <!--<label>The standard chunk of Lorem</label>--> <p>Final copy of Registered Agreement will be available for download on website after registration. If required we can send it on your Email-id or at your address. </p> </div> <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> </div> <br/> <h3 style="font-size: 1.8em; text-transform: uppercase; color: #27da93;">Overview</h3> <div class="col-md-12"> <p style="text-align:center"> Having mindset of developing lifetime relation we believe in providing hassle free, time saving and cost effective Door-step Rental Agreement. Which eliminates traditional hassle like - procedure awareness issues, high charges from third parties, lowers and middle men, negotiation on rates, visiting SRO Office, taking at least half day leave. </p> </div> <div class="clearfix"></div> <br/> <h3 style="font-size: 1.8em; text-transform: uppercase; color: #27da93;">Required Documents</h3> <div class="col-md-6"> <ul class="privacy-start"> <li><a href="#"><i></i>Adhar card & Pan-card of owner, tenant & two witness</a></li> <li><a href="#"><i></i>Light bill/index II / Property tax receipt of the property to be rented out </a></li> <li><a href="#"><i></i>This documents are compulsory for online registration</a></li> </ul> </div> <div class="col-md-6"> <p> If mentioned documents are not available contact to your personal manager OR call +91 88885-99993 </p> </div> <div class="clearfix"></div> <br/> <div class="col-md-6" id="calculator"> <h4 style="text-align:center"><br/>Rental Agreement Cost Calculator</h4><br/> <div style="padding: 30px; border: 5px solid #27da93; border-radius: 20px; background: rgba(204, 204, 204, 0.15); box-shadow:5px 5px 5px #aba8a8; "> <br/> <form class="form-horizontal" action="<?php $_SERVER['PHP_SELF'] ?>" method="post"> <div class="form-group"> <label class="control-label col-sm-6" for="pwd">License Period in Months:</label> <div class="col-sm-6"> <input type="text" name="lp" class="form-control" id="months" placeholder="eg. 11"> <p style="display:none"></p> </div> </div> <div class="form-group"> <label class="control-label col-sm-6" for="email">Average Monthly Rent:</label> <div class="col-sm-6"> <input type="text" name="ar" class="form-control" id="rent" placeholder="eg. 0"> <p style="display:none"></p> </div> </div> <div class="form-group"> <label class="control-label col-sm-6" for="pwd">Refundable Deposit:</label> <div class="col-sm-6"> <input type="text" name="rd" class="form-control" id="deposit" placeholder="eg. 0"> <p style="display:none"></p> </div> </div> <div class="form-group"> <label class="control-label col-sm-6" for="email">Non-Refundable Deposit:</label> <div class="col-sm-6"> <input type="text" name="nrd" class="form-control" id="ndeposit" placeholder="eg. 0"> <p style="display:none"></p> </div> </div> <div class="form-group"> <label class="control-label col-sm-6" for="pwd">Property Located In:</label> <div class="col-sm-6"> <select id="loc" name="loc" class="form-control"> <option value="">Select Property</option> <option value="urban">Urban</option> <option value="ruler">Ruler</option> </select> <p style="display:none"></p> <br/> </div> </div> <div class="form-group"> <label class="control-label col-sm-6" for="pwd">&nbsp;</label> <div class="col-sm-6"> <input name="cal" style="border-color:#27da93; background:#27da93" onClick="return empty()" class="btn btn-primary" type="submit" value="Calculate" /> </div> </div> </form> <?php if(isset($_POST['cal'])) { $l=$_POST['lp']; $a=$_POST['ar']; $r=$_POST['rd']; $n=$_POST['nrd']; $loc=$_POST['loc']; $_SESSION['l']=$l; $_SESSION['a']=$a; $_SESSION['r']=$r; $_SESSION['loc']=$loc; if($loc=="urban") { $z=1000; } else { $z=500; } $rd=(10/100)*$r; $x=($l*$a)+$rd+$n; $y=$x*0.0250; $tempinter=(10/100)*$y; $fru=$tempinter+$z+1200; $fo=$tempinter+$z+1500; $_SESSION['fru']=$fru; $_SESSION['fo']=$fo; echo " <script> $(function() { $('#myModal2').modal('show'); $('html, body').animate({ scrollTop: $('#calculator').offset().top }, 2); }); </script> "; } ?> <div class="form-group"> <label class="control-label col-sm-6" for="email"> <?php if(isset($_SESSION['name'])) { $name=$_SESSION['name']; $qu="SELECT * FROM `registation` where name = '$name'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $owner=$row['name']; } $qu1="SELECT * FROM `tenant_reg` where name = '$name'"; $sql1 = @mysqli_query($connection,$qu1); while($row1=@mysqli_fetch_array($sql1)) { $tenant=$row1['name']; } //echo "<script>alert('$ii')</script>"; if(isset($owner) && isset($tenant)) { echo "For registered users:"; } else { if(isset($owner)) { echo "For property posted owners:"; } else { echo "For plan purchase tenant:"; } } } else { echo "For registered users:"; } ?> </label> <div class="col-sm-6"> <input type="text" class="form-control" name="forreg" id="val3" value="<?php if(isset($_SESSION['fru'])){ $f=$_SESSION['fru']; echo $f; } else{ echo " ";} ?>" readonly=""> </div> <br/><br/> </div> <div class="form-group"> <label class="control-label col-sm-6" for="pwd">For others:</label> <div class="col-sm-6"> <input type="text" class="form-control" name="other" id="val4" value="<?php if(isset($_SESSION['fo'])){ $ff=$_SESSION['fo']; echo $ff; } else{ echo " ";} ?>" readonly=""> </div> </div> <P style="text-decoration:underline"> <?php if(isset($_SESSION['ii'])) { if($_SESSION['ii']==1) echo "<a href='owner_dashboard.php'>Post Your Property</a>"; else echo "<a href='tenant_dashboard.php'>Purchase Fair-Plan</a>"; } ?> </p> <p> <b>*</b> (Charges inclusive of all eg. Stamp duty, Registration, Advisory, Convienience charge and other charges etc.) <br/> <b>*</b> (No hidden charges) </p> </div> </div> <div class="col-md-6"> <h4 style="text-align:center">Invite Us To Execute Rental Agreement At Your Place</h4><br/> <div style="padding: 30px; border: 5px solid #27da93; border-radius: 20px; background: rgba(204, 204, 204, 0.15); box-shadow:5px 5px 5px #aba8a8;min-height: 596px; "> <br/> <form class="form-horizontal" action="<?php $_SERVER['PHP_SELF'] ?>" method="post"> <div class="form-group"> <label class="control-label col-sm-4"><span style="color:red">*</span>Name:</label> <div class="col-sm-8"> <input type="text" name="name" class="form-control" placeholder="Enter Name" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4"><span style="color:red">*</span>Email:</label> <div class="col-sm-8"> <input type="text" name="email" class="form-control" placeholder="Enter Email" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4"><span style="color:red">*</span>Mobile:</label> <div class="col-sm-8"> <input type="text" name="mobile" class="form-control" placeholder="Enter Mobile" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" ><span style="color:red">*</span>Address:</label> <div class="col-sm-8"> <input type="text" name="address" class="form-control" placeholder="Enter Address" required=""> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="pwd">&nbsp;</label> <div class="col-sm-8"> <input style="border-color:#27da93; background:#27da93" type="submit" name="req" class="btn btn-primary" value="Contact" > </div> </div> </form> <?php if(isset($_POST['req'])) { $name=$_POST['name']; $email=$_POST['email']; $mobile=$_POST['mobile']; $address=$_POST['address']; if(isset($_SESSION['name'])) { $reg="Yes"; } else { $reg="No"; } $query="INSERT INTO `req_agreement`(`id`, `name`, `email`, `mobile`, `address`, `registered`) VALUES ('','".$name."','".$email."','".$mobile."','".$address."','".$reg."')"; //INSERT INTO `req_agreement`(`id`, `name`, `email`, `mobile`, `address`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5]) $upload= mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { echo "<script>alert('Thank you for contacting - we are there in 5 hours')</script>"; } } ?> <?php if(isset($_SESSION['name'])) { ?> <h1 style="text-align: center; margin-top: 35px; color: #08a064;">" OR "</h1> <h4 style="text-align:center; color: #08a064; margin-top: 40px;">Just Call Your Personal Manager, He Will Take Care Of The Rest.</h4> <?php } else { ?> <h1 style="text-align: center; margin-top: 35px; color: #08a064;">" OR "</h1> <h4 style="text-align:center; color: #08a064; margin-top: 25px; line-height: 1.3em;">Just Give Us A Call At- <br/> 88885-99993 <br/> & <br/> Let us take care of the rest</h4><br/> <?php } ?> </div> </div> <div class="clearfix"></div> <br/> <div class="asked" style="padding:1em 0 2em 0"> <h3 style="font-size: 1.8em; text-transform: uppercase; color: #27da93;">Frequently Asked Questions</h3> <div class="col-md-6"> <div class="questions"> <h5>1. Is Online Registered Rent Agreement valid?</h5> <p>Yes, Online Registered Rent Agreement is Authorized from government of Maharashtra. Therefore it is valid in all manner. <br/><br/></p> </div> </div> <div class="col-md-6"> <div class="questions"> <h5>2. Is Notary agreement valid?</h5> <p>No, Notarised Rent Agreement has no legal value as the laws. It is mandatory to Register leave and licence agreement to safeguard land-lord and tenant as per the rent control act. </p> </div> </div> <div style="clear:both"></div> <div class="col-md-6"> <div class="questions"> <h5>3. Why Aadhar card is Mandatory?</h5> <p>It is required for UID (finger prints) Verification as online no other authentication possible. <br/><br/><br/> </p> </div> </div> <div class="col-md-6"> <div class="questions"> <h5>4. I am outside Pune, can I execute Online Registered Rent Agreement?</h5> <p>In such case you either need to come down Pune or else you can give POA to someone in Pune who can execute Online Registered Rent Agreement on your behalf.</p> </div> </div> <div style="clear:both"></div> <div class="col-md-6"> <div class="questions"> <h5>5. I don't have Aadhar Card, how can I execute Online Registered Rent Agreement?</h5> <p>As Aadhar is mandatory one can execute agreement on family members/Roommate name, or else we have to execute it in nearest Sub Registrar Office.</p> </div> </div> <div class="col-md-6"> <div class="questions"> <h5>6. Why is it necessary to execute Registered Rent Agreement?</h5> <p>As per Rent Control Act of Maharashtra it is compulsory to execute Registered Rent Agreement or else there is a provision, Fine of Rs.5000/- and Imprisonment of 3 months.</p> </div> </div> <div style="clear:both"></div> <div class="col-md-6"> <div class="questions"> <h5>7. Is Stamp Paper required for Online Registered Rent Agreement?</h5> <p>No, stamp papers are not valid for Rent Agreements. As now we need to pay Stamp Duty and Registration online. <br/><br/> </p> </div> </div> <div class="col-md-6"> <div class="questions"> <h5>8. How much time required for Online Registered Rent Agreement?</h5> <p>On Scheduled day we need 45min - 1hour to complete draft of Online Registered Rent Agreement. Final copy of Registered Rent Agreement will be available for download in your account, if required we can email you the same.</p> </div> </div> <div style="clear:both"></div> <div class="col-md-6"> <div class="questions"> <h5>9. Is Tenant Police Verification required after Registered Rent Agreement?</h5> <p>Yes, Pune Police has made Tenant Police Verification compulsory for each and every tenant whether its Residential or Commercial Property.</p> </div> </div> <div class="col-md-6"> </div> </div> </div> </div> <!--//contact--> <!-- Modal --> <div class="modal fade" id="myModal2" role="dialog"> <div class="modal-dialog modal-md"> <!-- Modal content--> <div class="modal-content"> <div class="modal-body"> <!--<button style=" position: absolute; right: -15px; top: -18px; background: #FFF; border-radius: 50%; padding: 3px 6px; border: 2px Solid #000; opacity:1;" type="button" class="close" data-dismiss="modal">&times;</button>--> <div class="columns" style="border:1px solid #ccc"> <ul class="price"> <li class="header" style="background-color:#b32505">Provide your contact details & get Agreement cost through SMS</li> </ul> <br/> <div style="padding:10px"> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" class="form-horizontal"> <div class="form-group"> <label class="control-label col-sm-2" for="email">I am:</label> <div class="col-sm-10"> <label class="radio-inline"> <input type="radio" id="owner" value="owner" name="iam" <?php if((isset($_POST['iam'])) && $_POST['iam']=="owner" ) echo ' checked="checked"'?> >A Owner </label> <label class="radio-inline"> <input type="radio" id="tenant" value="tenant" name="iam" <?php if((isset($_POST['iam'])) && $_POST['iam']=="tenant" ) echo ' checked="checked"'?> >A Tenant </label> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">Name:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="uname" name="username" placeholder="Enter name" value="<?php echo isset($_POST['username']) ? $_POST['username'] : '' ?>" > </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">Email:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="uemail" name="email" placeholder="Enter email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : '' ?>" > </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">Mobile:</label> <div class="col-sm-10"> <input type="number" class="form-control" id="umobile" name="r_mobile" placeholder="Enter mobile" value="<?php echo isset($_POST['r_mobile']) ? $_POST['r_mobile'] : '' ?>" > </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">&nbsp;</label> <div class="col-sm-10"> <!--<a href="">CLICK HERE (For Generate OTP)</a>--> <input type="submit" id="otpsend" onClick="return rone()" name="sendotp" value="" style="background:url('images/agreeclick.png'); background-size:100% 100%; border:none; color: #FFF; width:250px; height: 35px;" /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="pwd">OTP:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="uotp" name="r_otp" placeholder="Enter OTP"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button name="create_account" id="create" type="submit" onClick="return rtwo()" class="btn btn-primary">Submit</button> <button type="reset" class="btn btn-primary" data-dismiss="modal" style="margin-left:10px;">Cancel</button> </div> </div> </form> <?php if(isset($_POST['sendotp'])) { $iam=$_POST['iam']; $name=$_POST['username']; $email=$_POST['email']; $mobile=$_POST['r_mobile']; $_COOKIE['mobile']= $mobile; $_COOKIE['otp']=rand(1000, 9999); $_SESSION["a1"]=$_COOKIE['otp']; echo " <script> $(document).ready(function() { swal({ title:'Thank you...', text:'We have send you OTP (One Time Password) on your given mobile through SMS, Please enter it!', type:'success' },function() { document.getElementById('uotp').focus(); $('html, body').animate({ scrollTop: $('#calculator').offset().top }, 2); $('#myModal2').modal('show'); }); }); </script> "; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } } if(isset($_POST['create_account'])) { $iam=$_POST['iam']; $name=$_POST['username']; $email=$_POST['email']; $mobile=$_POST['r_mobile']; $temp=$_POST['r_otp']; $m=$_SESSION["a1"]; if($m == $temp) { if($iam=='owner') { $_SESSION['ii']=1; $qu="SELECT mobile FROM `registation` where mobile = '$mobile'"; $sql = @mysqli_query($connection,$qu); $row=@mysqli_fetch_row($sql); $m=$row[0]; $flag=0; if(isset($m)) { $flag=1; } if($flag==0) { $date=date("d/m/Y"); $qu1="SELECT name FROM `registation` where name = '$name'"; $sql1 = @mysqli_query($connection,$qu1); $roww=@mysqli_fetch_row($sql1); $n=$roww[0]; if(isset($n)) { $ali=rand(10, 99); $name=$n.$ali; } $_SESSION['name']=$name; $query="INSERT INTO `registation`(`id`, `name`, `email`, `mobile`, `flow_id`, `pd_id`, `date`, `fromwhere`) VALUES ('','".$name."','".$email."','".$mobile."','".$i."','0','".$date."','Agreement Page')"; $upload= mysqli_query($connection,$query); //echo "<script>window.location.href='agreement.php'</script>"; //send message agre cost $name=$_SESSION['name']; $month=$_SESSION['l']; $rent=$_SESSION['a']; $deposit=$_SESSION['r']; $location=$_SESSION['loc']; $cosst=$_SESSION['fru']; $msg="Dear $name,\n Considering your Average monthly rent Rs-$rent Refundable deposit Rs-$deposit and property located in $location area. The final expenses for Door-step Registered Rent Agreement of $month months is only Rs-$cosst for our registered users(no hidden charges). For more details login to your RoomsOnRent account, click- www.roomsonrent.in/agreement.php Feel free to call for any help and questions.\nRegards\nTeam RoomsOnRent\n9595567981"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsendnew.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //end echo " <script> $(document).ready(function() { swal({ title:'Thank you...', text:'We send you agreement cost on your given mobile through SMS', type:'success' },function() { window.location.href='agreement.php'; }); }); </script> "; } else { $_SESSION['name']=$name; //send agree cost $name=$_SESSION['name']; $month=$_SESSION['l']; $rent=$_SESSION['a']; $deposit=$_SESSION['r']; $location=$_SESSION['loc']; $cosst=$_SESSION['fru']; $msg="Dear $name,\n Considering your Average monthly rent Rs-$rent Refundable deposit Rs-$deposit and property located in $location area. The final expenses for Door-step Registered Rent Agreement of $month months is only Rs-$cosst for our registered users(no hidden charges). For more details login to your RoomsOnRent account, click- www.roomsonrent.in/agreement.php Feel free to call for any help and questions.\nRegards\nTeam RoomsOnRent\n9595567981"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsendnew.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //end echo " <script> swal({ title:'Thank you...', text:'We send you agreement cost on your given mobile through SMS', type:'success' }),function() { window.location.href='agreement.php'; }); </script> "; } } if($iam=='tenant') { $_SESSION['ii']=2; $qu="SELECT mobile FROM `tenant_reg` where mobile = '$mobile'"; $sql = @mysqli_query($connection,$qu); $row=@mysqli_fetch_row($sql); $m=$row[0]; $flag=0; if(isset($m)) { $flag=1; } if($flag==0) { $date=date("d/m/Y"); $qu1="SELECT name FROM `tenant_reg` where name = '$name'"; $sql1 = @mysqli_query($connection,$qu1); $roww=@mysqli_fetch_row($sql1); $n=$roww[0]; if(isset($n)) { $ali=rand(10, 99); $name=$n.$ali; } $_SESSION['name']=$name; $query="INSERT INTO `tenant_reg`(`id`, `name`, `email`, `mobile`, `flow_id`, `pd_id`, `date`, `fromwhere`) VALUES ('','".$name."','".$email."','".$mobile."','".$i."','0','".$date."','Agreement Page')"; $upload= mysqli_query($connection,$query); //echo "<script>window.location.href='agreement.php'</script>"; //send message agre cost $name=$_SESSION['name']; $month=$_SESSION['l']; $rent=$_SESSION['a']; $deposit=$_SESSION['r']; $location=$_SESSION['loc']; $cosst=$_SESSION['fru']; $msg="Dear $name,\n Considering your Average monthly rent Rs-$rent Refundable deposit Rs-$deposit and property located in $location area. The final expenses for Door-step Registered Rent Agreement of $month months is only Rs-$cosst for our registered users(no hidden charges). For more details login to your RoomsOnRent account, click- www.roomsonrent.in/agreement.php Feel free to call for any help and questions.\nRegards\nTeam RoomsOnRent\n9595567981"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsendnew.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //end echo " <script> $(document).ready(function() { swal({ title:'Thank you...', text:'We send you agreement cost on your given mobile through SMS', type:'success' },function() { window.location.href='agreement.php'; }); }); </script> "; } else { $_SESSION['name']=$name; //send agree cost $name=$_SESSION['name']; $month=$_SESSION['l']; $rent=$_SESSION['a']; $deposit=$_SESSION['r']; $location=$_SESSION['loc']; $cosst=$_SESSION['fru']; $msg="Dear $name,\n Considering your Average monthly rent Rs-$rent Refundable deposit Rs-$deposit and property located in $location area. The final expenses for Door-step Registered Rent Agreement of $month months is only Rs-$cosst for our registered users(no hidden charges). For more details login to your RoomsOnRent account, click- www.roomsonrent.in/agreement.php Feel free to call for any help and questions.\nRegards\nTeam RoomsOnRent\n9595567981"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsendnew.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //end echo " <script> swal({ title:'Thank you...', text:'We send you agreement cost on your given mobile through SMS', type:'success' }),function() { window.location.href='agreement.php'; }); </script> "; } } } else { echo "<script>swal('Oops...', 'Enter Correct OTP!', 'error');</script>"; echo " <script type='text/javascript'> $(function() { document.getElementById('uotp').focus(); $('html, body').animate({ scrollTop: $('#calculator').offset().top }, 2); $('#myModal2').modal('show'); }); </script> "; } } ?> </div> <br/> <p> &nbsp;<br/></p> </div> </div> </div> </div> </div> <!--end--> <!--footer--> <div class="footer"> <div class="footer-bottom"> <div class="container"> <div class="col-md-8"> <p style="color:#FFF">© 2017 Room On Rent. All Rights Reserved</p> </div> <div class="col-md-4 footer-logo"> <ul class="social" style="padding:0; float:right"> <li><a href="#"><i> </i></a></li> <li><a href="#"><i class="gmail"> </i></a></li> <li><a href="#"><i class="twitter"> </i></a></li> <li><a href="#"><i class="camera"> </i></a></li> <li><a href="#"><i class="dribble"> </i></a></li> </ul> </div> <div class="clearfix"> </div> </div> </div> </div> <!--//footer--> <script> function empty() { var x; x = document.getElementById("months").value; if (x == "") { alert("please enter months"); return false; }; var y; y = document.getElementById("rent").value; if (y == "") { alert("please enter rent"); return false; }; var z; z = document.getElementById("deposit").value; if (z == "") { alert("please enter deposit"); return false; }; var a; a = document.getElementById("ndeposit").value; if (a == "") { alert("please enter non-refundable deposit"); return false; }; var b; b = document.getElementById("loc").value; if (a == "") { alert("please select property located in"); return false; }; } </script> <script> $(document).ready(function() { $('#loader').hide(); }); </script> <script> $(document).ready(function() { $('form').submit(function() { $('#loader').show(); }); }); </script> <?php if(isset($_SESSION['fru'])) { echo " <script> $(document).ready(function() { $('html, body').animate({ scrollTop: $('#calculator').offset().top }, 2); }); </script> "; } ?> </body> </html><file_sep><?php include('conn.php'); if(isset($_POST['name'])) { $name=trim($_POST['name']); $query2=mysqli_query($connection,"SELECT locality,sub_locality,landmark,city FROM `property_details` WHERE locality like '%$name%' || sub_locality like '%$name%' || landmark like '%$name%' || city like '%$name%' "); echo "<ul>"; while($query3=mysqli_fetch_array($query2)) { ?> <li onclick='fill("<?php echo $query3['locality'].",".$query3['sub_locality'].",".$query3['landmark'].",Pune"; ?>")'><?php echo $query3['locality'].",".$query3['sub_locality'].",".$query3['landmark'].",Pune"; ?></li> <?php } } ?> </ul><file_sep><?php session_start(); include('conn.php'); include('out1.php'); $pd_id=$_GET['id']; $reg_u="UPDATE property_details SET a_status = 0 WHERE property_id = '$pd_id'"; $reg_i=mysqli_query($connection,$reg_u); if(isset($_SESSION['subadminname'])) { $name=$_SESSION['subadminname']; $date=date("d/m/Y"); $qu="INSERT INTO `notificationi`(`id`, `name`, `date`, `description`) VALUES ('','$name','$date','Active the property of property id:- $id')"; $in=mysqli_query($connection,$qu); } echo "<script>alert('Property is Activate')</script>"; echo "<script>window.location.href='s_owner_details.php'</script>"; ?><file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Profile</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <style> .font18 { font-size:18px !important; margin-top:7px; margin-bottom:10px; } </style> </head> <body> <!--header--> <?php include('header.php'); include('bgImage.php'); ?> <!--//--> <div class="loan_single"> <div class="container"> <div class="col-md-12"> <!-- <div style="position:fixed; z-index:9; right:0; top:40px; margin:15px;"> <a href="<?php echo "logout.php"; ?>" class="hvr-sweep-to-right more" style="background:#00d5fa; color:#FFF; font-weight:bold; padding:1em" >Logout</a> </div> --> <div style="margin-top:50px"> <div class="container"> <h3 style="text-align:center; color: lemonchiffon;">Hi <span style="color: #6565ce; text-transform: capitalize;"><?php $tname=$_SESSION['name']; echo preg_replace('/\d+/u','',$tname); ?></span>, Welcome to your RoomsOnRent account. <br/><br/></h3> <div class="col-md-6"> <div class="" style=""> <div class="col-md-6"> <img src="images/manager.png" class="img-responsive" /> </div> <div class="col-md-6"> <div style="margin-top:17%; color: floralwhite;"> <h4 class="mg">Your Personal Manager</h4><br/> <?php $name=$_SESSION['name']; $query="SELECT manager FROM `tenant_reg` where name = '$name'"; $sql = @mysqli_query($connection,$query); $row = mysqli_fetch_row($sql); $mid=$row[0]; if(empty($mid)) { echo "<b>NAME:</b> &nbsp;&nbsp;&nbsp;&nbsp;Mr. Anup<br/><b>MOBILE:</b> &nbsp;+91 9595567981<br/> <b>EMAIL:</b> &nbsp;&nbsp;&nbsp;&nbsp;<EMAIL>"; } else { $query1="SELECT * FROM `sub_admin` where name = '$mid'"; $sql1 = @mysqli_query($connection,$query1); while($row1 = mysqli_fetch_array($sql1)) { $name=$row1['name']; $mobile=$row1['mobile']; $email=$row1['email']; } echo "<b>NAME:</b> &nbsp;&nbsp;&nbsp;&nbsp;$name<br/><b>MOBILE:</b> &nbsp;$mobile<br/> <b>EMAIL:</b> &nbsp;&nbsp;&nbsp;&nbsp;$email "; } ?> </div> </div> </div> <!--<div class="text-center"> <img src="images/hand.png" class="img-responsive center-block" style="height:200px" /> </div>--> <p>&nbsp;<br/>&nbsp;<br/></p> <h3 style=" text-align:center; line-height:1.5em; font-size:20px; color: floralwhite;"><br/><br/>Hi <span style="color: #6565ce; text-transform: capitalize;"><?php $tname=$_SESSION['name']; echo preg_replace('/\d+/u','',$tname); ?></span>, Team RoomsOnRent has appoint me as your Personal Relationship Manager, and I will be available here to help you. Feel free to contact me if your not getting property according to your requirement & to get assistance while using our services. </h3> <br/> </div> <div class="col-md-6 bdleft"> <!-- left column --> <div class="col-md-4"> <div class="text-center"> <a href="tenant_profile.php"> <img src="images/profile.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Your Profile</h3> </a> </div> </div> <div class="col-md-4"> <div class="text-center"> <a href="properties.php?city=Pune&locality=&rent=Select&filter=Apply+Filter"> <img src="images/find.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Find Properties</h3> </a> </div> </div> <!--<div class="col-md-4"> <div class="text-center"> <a href="logout.php"> <img src="images/logout.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#27da93;" class="font18">Logout</h3> </a> </div> </div>--> <?php $nme=$_SESSION['name']; $qu="SELECT pd_id FROM `tenant_reg` where name = '$nme'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $pd_id=$row['pd_id']; } /* if($pd_id==1) { ?> --_ANUP--> <!-- <div class="col-md-4"> <div class="text-center"> <a href="#" data-toggle="modal" data-target="#myModal1"> <img src="images/credit.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Credits</h3> </a> --_ANUP--> <!-- Modal --> <!-- <div class="modal fade" id="myModal1" role="dialog"> <div class="modal-dialog modal-sm"> --_ANUP--> <!-- Modal content--> <!-- <div class="modal-content"> <div class="modal-body"> <button style=" position: absolute; right: -15px; top: -18px; background: #FFF; border-radius: 50%; padding: 3px 6px; border: 2px Solid #000; opacity:1;" type="button" class="close" data-dismiss="modal">&times;</button> <div class="columns"> <ul class="price"> <li class="header" style="background-color:#27da93">Your Credits</li> <li class="grey">Available Credits</li> <?php $name=$_SESSION['name']; $qu="SELECT planc FROM `tenant_reg` where name = '$name'"; $sql = @mysqli_query($connection,$qu); $row=@mysqli_fetch_row($sql); $plan=$row[0]; ?> <li><?php echo $plan ?> Properties</li> <li class="grey">Used Credits</li> <li> <?php $uplan=25-$plan; echo $uplan; ?> Properties</li> </ul> </div> </div> </div> </div> </div> </div> </div> --_ANUP--> <?php } else { ?> <!-- <div class="col-md-4"> <div class="text-center"> <a href="not_plan.php"> <img src="images/credit.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Credits</h3> </a> </div> </div> --_ANUP--> <?php } _ANUP*/ /*if($pd_id==1) { ?> <div class="col-md-4"> <div class="text-center"> <a href="not_plan2.php"> <img src="images/plan.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Plan</h3> </a> </div> </div> <?php } _ANUP*/ /* else _ANUP*/ { ?> <!-- <div class="col-md-4"> <div class="text-center"> <a href="#" data-toggle="modal" data-target="#myModal"> <img src="images/plan.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Plan</h3> </a> --_ANUP--> <!-- Modal --> <!-- <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> --_ANUP--> <!-- Modal content--> <!-- <div class="modal-content"> <div class="modal-body"> <button style=" position: absolute; right: -15px; top: -18px; background: #FFF; border-radius: 50%; padding: 3px 6px; border: 2px Solid #000; opacity:1;" type="button" class="close" data-dismiss="modal">&times;</button> <div class="columns"> <ul class="price"> <li class="header" style="background-color:#b32505; font-size: 20px;"> <span>Fair Plan -</span> <span>Rs.100 Only/-</span><br> <span style="font-size: 16px;">Save Brokerage, Time &amp; efforts</span> </li> <li> <span style="font-size: 20px;margin-left: 5px;color: #52a081;float: left;"><i class="glyphicon glyphicon-time"></i> </span> <span>Validity <b>90 days</b></span> </li> <li> <span style="font-size: 20px;margin-left: 5px;color: #52a081;float: left;"><i class="glyphicon glyphicon-home"></i></span> <span>Contact 25 verified owners</span> </li> <li> <span style="font-size: 20px;margin-left: 5px;color: #52a081;float: left;"><i class="glyphicon glyphicon-file"></i></span> <span>Save Rs.300 on doorstep Rental Agreement</span> </li> <li> <span style="font-size: 20px;margin-left: 5px;color: #52a081;float: left;"><i class="glyphicon glyphicon-user"></i></span> <span>Get personal Relation-ship manager for any assistance</span> </li> <li style=" color: #ca4425; font-size: 22px; ">"Purchase Plan &amp; Get Relax"</li> <li style="/* color:#FFF; *//* background:#27da93 */" class="grey"><a href="PayUMoney.php" style="color:#FFF;background:#27da93;padding: 17px;border-radius: 10px;" class="button">Purchase Now</a></li> </ul> </div> </div> </div> </div> </div> </div> </div> --_ANUP--> <?php } $nme=$_SESSION['name']; $qu="SELECT vpd_id FROM `tenant_reg` where name = '$nme'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $vpd_id=$row['vpd_id']; } if(!empty($vpd_id)) { ?> <div class="col-md-4"> <div class="text-center"> <a href="tenant_viewed.php"> <img src="images/post.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Short-listed Properties</h3> </a> </div> </div> <?php } else { ?> <div class="col-md-4"> <div class="text-center"> <a href="not_viewed.php"> <img src="images/post.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Short-listed Properties</h3> </a> </div> </div> <?php } ?> <!-- <div class="col-md-4"> <div class="text-center"> <a href="agreement.php"> <img src="images/cal.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Calculate your Agreemnet cost</h3> </a> </div> </div> <div class="col-md-4"> <div class="text-center"> <a href="http://localhost/fairowner/admin/agreement/Sample Draft of Rent agreement.pdf"> <img src="images/download.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Sample Draft of Rent agreement</h3> </a> </div> </div> --_ANUP--> <?php $n=$_SESSION['name']; $query = "SELECT * FROM `tenant_reg` WHERE name= '$n'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $agre=$row['agre']; $agre_status=$row['agre_status']; } if(isset($agre)) { ?> <!-- <div class="col-md-4"> <div class="text-center"> <?php if(substr( $agre_status, 0, 8 ) === "download") { ?> <a href="#" data-toggle="modal" data-target="#myModal2"> <img src="images/download.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Download Agreement</h3> </a> <?php } else { ?> <a href="agreement.php"> <img src="images/agreement.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18"> <?php if(!empty($agre_status) ) { echo $agre_status; } else { echo "Request for agreement"; } ?> </h3> </a> --_ANUP--> <?php } $n=$_SESSION['name']; $query = "SELECT * FROM `tenant_reg` WHERE name= '$n'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $agre=$row['agre']; $agre1=$row['indexii']; $agre2=$row['recep']; $agre3=$row['powerofauto']; $indexii=$row['indexii']; $recep=$row['recep']; $powerofauto=$row['powerofauto']; } ?> <!-- Modal --> <!-- <div class="modal fade" id="myModal2" role="dialog"> <div class="modal-dialog modal-sm"> --_ANUP--> <!-- Modal content--> <!-- <div class="modal-content"> <div class="modal-body"> <button style=" position: absolute; right: -15px; top: -18px; background: #FFF; border-radius: 50%; padding: 3px 6px; border: 2px Solid #000; opacity:1;" type="button" class="close" data-dismiss="modal">&times;</button> <div class="columns"> <ul class="price"> <li class="header" style="background-color:#b32505">Download</li> <?php if(empty($recep)){ } else { ?> <li class="grey"><a href="<?php if(empty($recep)){ } else { echo "http://fairowner.com/admin/$agre2"; } ?>" class="button">Download Receipt</a></li> <?php } if(empty($agre)){ } else { ?> <li class="grey"><a href="<?php if(empty($agre)){ } else { echo "http://fairowner.com/admin/$agre"; } ?>" class="button">Download Agreement</a></li> <?php } if(empty($indexii)){ } else { ?> <li class="grey"><a href="<?php if(empty($indexii)){ } else { echo "http://fairowner.com/admin/$agre1"; } ?>" class="button">Download Index-of</a></li> <?php } if(empty($powerofauto)){ } else { ?> <li style="color:#FFF; background:#27da93" class="grey"><a href=<?php if(empty($powerofauto)){ } else { echo "http://fairowner.com/admin/$agre3"; } ?>" style="color:#FFF; background:#27da93" class="button">Download Power of Attorney</a></li> <?php } ?> </ul> </div> </div> </div> --_ANUP--> <?php function download_remote_file($file_url, $save_to) { $content = file_get_contents($file_url); file_put_contents($save_to, $content); } if (isset($_GET['id'])) { $n=$_SESSION['name']; $query = "SELECT * FROM `registation` WHERE name= '$n'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $agre=$row['agre']; } //download_remote_file('http://localhost/fairowner/admin/$agre',realpath("./downloads") . '/fairowner_agreement.jpg'); //http://mydomain.com/download.php?download_file=some_file.pdf } ?> </div> </div> </div> </div> <?php } ?> <div class="clearfix"> </div> </div> </div> </div> </div> <div class="clearfix"> </div> </div> </div> <!--content--> <div class="content"> <div class="content-bottom" style="padding-top: 0.5em;" > <div class="container"> <h3 style="color: #00d5fa;">" What our clients say "</h3> <div class="clearfix"> </div> <!--edit testimonials--> <style> .carousel-indicators .active{ background: #31708f; } .content{ margin-top:20px; } .adjust1{ float:left; width:100%; margin-bottom:0; } .adjust2{ margin:0; } .carousel-indicators li{ border :1px solid #ccc; } .carousel-control{ color:#31708f; width:5%; } .carousel-control:hover, .carousel-control:focus{ color:#31708f; } .carousel-control.left, .carousel-control.right { background-image: none; } .media-object{ margin:auto; margin-top:15%; } @media screen and (max-width: 768px) { .media-object{ margin-top:0; } } </style> <div class="container content"> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators -- <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <li data-target="#carousel-example-generic" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <?php $q = "SELECT * FROM `testimonials`"; $sql = @mysqli_query($connection,$q); $i=0; while($row = mysqli_fetch_array($sql)) { $i=$i+1; ?> <div class="item <?php if($i==1) echo 'active'; ?>"> <div class="row"> <div class="col-xs-12"> <div class="thumbnail adjust1"> <div class="col-md-2 col-sm-2 col-xs-12"> <img class="media-object img-rounded img-responsive" src="<?php echo "admin/".$row['image']; ?>" style="width:100px; height:100px"> </div> <div class="col-md-10 col-sm-10 col-xs-12"> <div class=""> <p class="text-info lead adjust2"><?php echo $row['heading'] ?></p> <p><span class="glyphicon glyphicon-thumbs-up"></span> <?php echo $row['comment'] ?> </p> <blockquote class="adjust2" style="border-left: 5px solid #eee !important;"> <p><?php echo $row['name'] ?></p> <small><cite title="Source Title"><i class="glyphicon glyphicon-globe"></i> <?php echo $row['position'] ?></cite></small> </blockquote> </div> </div> </div> </div> </div> </div> <?php } ?> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#carousel-example-generic" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> </div> <!--edut testimonials--> </div> </div> <!--//test--> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html> <?php unset($_SESSION['ck']); ?><file_sep><?php session_start(); include('conn.php'); include('out.php'); $id=$_GET['id']; $query="DELETE FROM `registation` WHERE pd_id='$id'"; $upload= mysqli_query($connection,$query); $query1="DELETE FROM `property_details` WHERE property_id='$id'"; $upload1= mysqli_query($connection,$query1); if(isset($_SESSION['subadminname'])) { $name=$_SESSION['subadminname']; $date=date("d/m/Y"); $qu="INSERT INTO `notificationi`(`id`, `name`, `date`, `description`) VALUES ('','$name','$date','Delete the property of property id:- $id')"; $in=mysqli_query($connection,$qu); } echo "<script>alert('Property Id=$id is deleted')</script>"; echo "<script>window.location.href='owner_details.php'</script>"; ?><file_sep><?php session_start(); $name2=$_POST['name1']; $email2=$_POST['email1']; $mobile2=$_POST['mobile1']; $_COOKIE['mobile']= $mobile2; $_COOKIE['otp']=rand(1000, 9999); $_COOKIE['a1']=$_COOKIE['otp']; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } ?><file_sep><?php session_start(); include('conn.php'); include('out1.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Dashboard - RoomsOnRent</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="fair-owner" content="yes"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet"> <link href="css/font-awesome.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <link href="css/pages/dashboard.css" rel="stylesheet"> <link href="css/pages/signin.css" rel="stylesheet" type="text/css"> <link href="css/dataTables.bootstrap.min.css" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <?php include('header.php'); ?> <div class="subnavbar"> <div class="subnavbar-inner"> <div class="container"> <ul class="mainnav"> <li ><a href="super_admin_home.php"><i class="icon-dashboard"></i><span>Dashboard</span> </a> </li> <li ><a href="create_subadmin.php"><i class="icon-sitemap"></i><span>Create Sub-Admin</span> </a> </li> <li ><a href="s_reg_owner.php"><i class="icon-user"></i><span>Registered Owner</span> </a> </li> <li ><a href="s_owner_details.php"><i class="icon-check"></i><span>Property Posted Owner</span> </a> </li> <li ><a href="s_reg_tenant.php"><i class="icon-group"></i><span>Registered Tenant</span> </a></li> <li ><a href="s_tenant_details.php"><i class="icon-check"></i><span>Plan Purchase Tenant</span> </a></li> <li ><a href="req_agreement.php"><i class="icon-paste"></i><span>Request for Agreement</span> </a></li> <li class="active dropdown"><a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-long-arrow-down"></i><span>Drops</span> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="home_slider.php">Home Page Slider</a></li> <li><a href="abuse_property.php">Abuse Property</a></li> <li><a href="testimonials.php">Testimonials</a></li> </ul> </li> </ul> </div> <!-- /container --> </div> <!-- /subnavbar-inner --> </div> <!-- /subnavbar --> <div class="main"> <div class="main-inner"> <div class="container"> <div class="row"> <div class="span4"> <div class="widget widget-nopad"> <div class="widget-header"> <i class="icon-list-alt"></i> <h3>Insert Testimonials</h3> </div> <!-- /widget-header --> <div class="widget-content" style="padding:20px"> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data" > <div class="login-fields"> <p>Insert Testimonials:</p> <div class="field"> <label for="firstname">Name:</label> <input type="text" style="padding:11px 15px 10px 10px" name="name" value="" placeholder="Enter Name" class="login" /> </div> <!-- /field --> <div class="field"> <label for="firstname">position:</label> <input type="text" style="padding:11px 15px 10px 10px" name="position" value="" placeholder="Enter position" class="login" /> </div> <!-- /field --> <div class="field"> <label for="firstname">Feedback heading:</label> <input type="text" style="padding:11px 15px 10px 10px" name="heading" value="" placeholder="Enter Feedback heading" class="login" /> </div> <!-- /field --> <div class="field"> <label for="firstname">Feedback Details:</label> <!--<input type="text" style="padding:11px 15px 10px 10px" name="name" value="" placeholder="Enter Slider Name" class="login" />--> <textarea rows="4" style="padding:11px 15px 10px 10px" name="comment" class="login" placeholder="Enter Feedback Details"></textarea> </div> <!-- /field --> <div class="field"> <label for="lastname">Image:</label> <input type="file" style="padding:11px 15px 10px 10px" name="uploadedimage" value="" class="login" /> </div> <!-- /field --> </div> <!-- /login-fields --> <input style="float:none" name="submit" type="submit" class="button btn btn-primary btn-large" value="Insert" /> <!-- .actions --> </form> <?php if(isset($_POST['submit'])) { $name=$_POST['name']; $position=$_POST['position']; $heading=$_POST['heading']; $comment=$_POST['comment']; if(!empty($_FILES["uploadedimage"]["name"])) { $file_name=$_FILES["uploadedimage"]["name"]; $temp_name=$_FILES["uploadedimage"]["tmp_name"]; $imgtype=$_FILES["uploadedimage"]["type"]; $ext=pathinfo($file_name,PATHINFO_EXTENSION); $imagename=date("d-m-Y")."-".time().".".$ext; $target_path="slider/".$imagename; move_uploaded_file($temp_name,$target_path); } $image=$target_path; $query="INSERT INTO `testimonials`(`id`, `name`, `position`, `comment`, `image`, `heading`) VALUES ('','".$name."','".$position."','".$comment."','".$image."','".$heading."')"; //$query"INSERT INTO `testimonials`(`id`, `name`, `position`, `comment`, `image`) VALUES ('','".$name."','".$position."','".$comment."','".$image."')"; $upload= mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { echo "<script>alert('Testimonials is inserted')</script>"; echo "<script>window.location.href='testimonials.php'</script>"; } } ?> </div> </div> <!-- /widget --> </div> <!-- /span6 --> <form action="<?php $_SERVER["PHP_SELF"] ?>" method="post" enctype="multipart/form-data"> <div class="span8"> <div class="widget"> <div class="widget-header"> <i class="icon-bookmark"></i> <h3>Testimonials Details</h3> </div> <!-- /widget-header --> <div class="widget-content"> <div class="" style="padding: 10px;overflow-x:auto;"> <table id="example" class="table table-striped table-bordered" style="overflow:auto;" cellspacing="0" width="100%"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Action</th> </tr> </thead> <tfoot> <tr> <th>Id</th> <th>Name</th> <th>Action</th> </tr> </tfoot> <tbody> <?php $qu="SELECT * FROM `testimonials` order by id DESC"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { ?> <tr> <td><?php echo $row['id'] ?></td> <td><?php echo $row['name'] ?></td> <td> <a onClick="javascript: return confirm('Please confirm deletion');" href="testimonials_delete.php?id=<?php echo $row['id'] ?>" class="btn btn-danger">Delete</a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> <!-- /widget-content --> </div> <!-- /widget --> </div> <!-- /span6 --> </form> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /main-inner --> </div> <!-- /main --> <?php include('footer.php'); ?> <!-- /footer --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/jquery.dataTables.min.js"></script> <script src="js/dataTables.bootstrap.min.js"></script> <script src="js/base.js"></script> <script> $(document).ready(function() { $('#example').DataTable({ responsive: true, ordering: false }); } ); </script> </body> </html> <file_sep><?php echo "<script>alert('You are already purchased plan')</script>"; echo "<script>window.location.href='tenant_dashboard.php'</script>"; ?><file_sep><?php echo "Next Page"; ?><file_sep><?php session_start(); include('conn.php'); include('out1.php'); $id=$_POST['id']; $manager=$_POST['subadmin']; if(isset($_POST['assign'])) { $manager=$_POST['subadmin']; $id=$_POST['id']; //echo $manager; //echo $id; $rqy1="SELECT ten_id FROM `sub_admin` where name = '$manager'"; $rsl1 = @mysqli_query($connection,$rqy1); $row1 = mysqli_fetch_row($rsl1); $p_id=$row1[0]; //echo $p_id; if(preg_match('/\b' . $id . '\b/', $p_id)) { echo "<script>alert('Tenant is already assign')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } else { $pid=$p_id.''.$id.','; $reg_u1="UPDATE `sub_admin` SET ten_id = '$pid' WHERE name = '$manager'"; $reg_i1=mysqli_query($connection,$reg_u1); $oq="UPDATE `tenant_reg` SET `manager`='$manager' WHERE id = '$id' "; $ou=mysqli_query($connection,$oq); if(!$reg_i1 && !ou) { echo "<script>alert('Tenant not assign')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } else { echo "<script>alert('Tenant assign')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } } } if(isset($_POST['uploadagre'])) { $id=$_POST['id']; $query="SELECT * from `tenant_reg` WHERE id = '$id'"; $sql = @mysqli_query($connection,$query); while($row=@mysqli_fetch_array($sql)) { $targetfolder=$row['agre']; $targetfolder1=$row['indexii']; $targetfolder2=$row['recep']; $targetfolder3=$row['powerofauto']; } if(!empty($_FILES["agree"]["name"])) { $a=rand(1000,9999); $targetfolder = "agreement/"; $file_name=$_FILES['agree']['name']; $ext=pathinfo($file_name,PATHINFO_EXTENSION); $imagename=date("d-m-Y").$a."-".time().".".$ext; $targetfolder = $targetfolder . $imagename ; move_uploaded_file($_FILES['agree']['tmp_name'], $targetfolder); } if(!empty($_FILES["powerof"]["name"])) { $a=rand(1000,9999); $targetfolder1 = "agreement/"; $file_name1=$_FILES['powerof']['name']; $ext1=pathinfo($file_name1,PATHINFO_EXTENSION); $imagename1=date("d-m-Y").$a."-".time().".".$ext1; $targetfolder1 = $targetfolder1 . $imagename1 ; move_uploaded_file($_FILES['powerof']['tmp_name'], $targetfolder1); } if(!empty($_FILES["indexii"]["name"])) { $a=rand(1000,9999); $targetfolder2 = "agreement/"; $file_name2=$_FILES['indexii']['name']; $ext2=pathinfo($file_name2,PATHINFO_EXTENSION); $imagename2=date("d-m-Y").$a."-".time().".".$ext2; $targetfolder2 = $targetfolder2 . $imagename2 ; move_uploaded_file($_FILES['indexii']['tmp_name'], $targetfolder2); } if(!empty($_FILES["receipt"]["name"])) { $a=rand(1000,9999); $targetfolder3 = "agreement/"; $file_name3=$_FILES['receipt']['name']; $ext3=pathinfo($file_name3,PATHINFO_EXTENSION); $imagename3=date("d-m-Y").$a."-".time().".".$ext3; $targetfolder3 = $targetfolder3 . $imagename3 ; move_uploaded_file($_FILES['receipt']['tmp_name'], $targetfolder3); } $astatus=$_POST['sagre']; $remark=$_POST['remark']; $query="UPDATE `tenant_reg` SET `agre`='$targetfolder',`indexii`='$targetfolder1',`recep`='$targetfolder2',`powerofauto`='$targetfolder3' WHERE id = '$id'"; $upload= mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { echo "<script>alert('Agreements are uploaded')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } } if(isset($_POST['submit'])) { $id=$_POST['id']; $astatus=$_POST['sagre']; $remark=$_POST['remark']; $follow_date=$_POST['follow_date']; $query="UPDATE `tenant_reg` SET `agre_status`='$astatus',`remark`='$remark',`follow_date`='$follow_date' WHERE id = '$id'"; $upload= mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { echo "<script>alert('Status Updated')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } } if(isset($_POST['sendstage'])) { $sendmm=$_POST['sendmm']; $id=$_POST['id']; $mobile=$_POST['mobile']; $email=$_POST['email']; $qu="SELECT * FROM `tenant_reg` where id= $id"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $tname=$row['name']; $manager=$row['manager']; } if(preg_match('/[A-Z]+[a-z]+[0-9]+/', $tname)) { $tname=substr($tname, 0, -2); } else { $tname=$tname; } $qu="SELECT * FROM `sub_admin` where name= '$manager'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $mname=$row['name']; $mmobile=$row['mobile']; $memail=$row['email']; } if($sendmm=='stage01') { $msg="Are you looking for Brokerage-Free home on Rent? Kindly Visit roomsonrent.in to get 100 percent Brokerage-Free Homes on rent across Pune. Also get Free Consultation by experts on Registered Rental Agreement and tenant-police verification."; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-1 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-1')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage21') { $msg="Dear $tname,\n Want to save Brokerage?\n Contact genuine owners without a Broker. Also get free-consultation on Register Rent Agreement and tenant police verification. Visit today roomsonrent.in."; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-2 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-2')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage22') { $msg="Dear $tname,\n Kindly visit roomsonrent.in and find Brokerage-Free properties on rent across Pune. And also get the free Consultation on Registered Rent Agreement and Police Verification."; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-2 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-2')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage23') { $msg="Dear $tname,\n You are missing the Number of Brokerage-Free properties posted every day. Kindly visit roomsonrent.in to get more details about available properties and also get Rs.300 benefit in our Doorstep Agreement Service."; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-2 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-2')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage3') { $msg="Dear $tname,\n Your account has been successfully created on 100 percent Brokerage-Free property portal roomsonrent.in. Founders of RoomsOnRent have appointed me as your Personal Relationship Manager for your RoomsOnRent account and I will be always available to help you without any commercial mindset. Please feel free to contact me for any assistance regarding- finding brokerage-free home, Creating Registered Rental Agreement and doing Tenant-police verification. \nRegards\n Your Personal Manager\n $mname\n $mmobile\n Team RoomsOnRent"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-3 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-3')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage41') { $msg="Dear $tname,\n Are you still looking for Brokerage-Free home? Keep visiting roomsonrent.in for latest properties available for rent. \nRegards\n Your Personal Manager\n $mname\n $mmobile\n Team RoomsOnRent"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-4 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-4')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage42') { $msg="Dear $tname,\n Save Rs.300 on Door-step Registered Rental Agreement.Find Brokerage-Free homes on roomsonrent.in and also get assistance in Tenant Verification. Keep visiting for latest Property updates \nRegards\n Your Personal Manager\n $mname\n $mmobile\n Team RoomsOnRent"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-4 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-4')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage43') { $msg="Dear $tname,\n Are you getting Brokerage-Free properties on roomsonrent.in ? If not, kindly inform us. We will assist you to find better. Purchase the Rs.100/- Plan and get Rs.300/- Benefit on our Door-step Register Rent Agreement service. \nRegards\n Your Personal Manager\n $mname\n $mmobile\n Team RoomsOnRent"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-4 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-4')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage44') { $msg="Dear $tname,\n No need to visit Registrar office for agreement as 24*7 Door-step Registered Rental Agreement service is now Available in your city. To Calculate agreement Cost Click roomsonrent.in/agreement.php \nRegards\n Your Personal Manager\n $mname\n $mmobile\n Team RoomsOnRent"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-4 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-4')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage45') { $msg="Dear $tname,\n Notary Rent Agreements are not valid any more. Registered Rental Agreement and Tenant verification is compulsory as per new rules of Maharashtra Government. Visit us for door-step service and avail benefit of Rs.300 if you have purchased our Rs.100/- Plan.Calculate your agreement Cost by Clicking roomsonrent.in/agreement \nRegards\n Your Personal Manager\n $mname\n $mmobile\n Team RoomsOnRent"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-4 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-4')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage46') { $msg="Dear $tname,\n Calculate Your Register Rent Agreement Cost. Purchase Plan for Rs100 to get assured 25 Brokerage-Free Properties and get Rs.300 benefit on our Door-step Registered Agreement Service and also assistance in tenant verification. To Calculate Cost Click roomsonrent.in/agreement.php \nRegards\n Your Personal Manager\n $mname\n $mmobile\n Team RoomsOnRent"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-4 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-4')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage5') { $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-5')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage51') { $msg="Dear $tname,\n You will get Rs.300 benefit on agreement cost as you have already purchased our Plan. \nRegards\n Your Personal Manager\n $mname\n $mmobile\n Team RoomsOnRent"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-5 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-5')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage6') { $msg="Dear $tname,\n Congratulations!!\n for your new Home, and thank you for choosing us to help you regarding Registered Rental Agreement . Kindly Confirm the Date, Time and Location for the execution of your Agreement. To calculate your agreement cost click on roomsonrent.in/agreement.php. It will be our immense pleasure to provide you transparent, cost effective, time saving and hassle-free service. Looking forward for life-time relation with you. \nRegards\n Your Personal Manager\n $mname\n $mmobile\n Team RoomsOnRent"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-6 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-6')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage61') { $msg="Dear $tname,\n As Per our telephonic conversation I have uploaded the Standard Draft of Agreement to your RoomsOnRent account which is in a favor of tenant. Kindly login and download the draft (We can make changes if required). Please Confirm Prior appointment for better service. Looking forward for life-time relation with you. \nRegards\n Your Personal Manager\n $mname\n $mmobile\n Team RoomsOnRent"; $_COOKIE['mobile']= $mobile; $_COOKIE['msg']=$msg; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } //for mail sending $mssg="Stage-6 Mail is Send to tenant"; $_COOKIE['mssg']=$mssg; $_COOKIE['email']= $email; include_once("mail.php"); $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-6')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage7') { $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-7')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage8') { $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-8')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage9') { $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-9')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage10') { $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-10')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage11') { $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-10')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } if($sendmm=='stage12') { $date=date("d/m/Y"); $query="UPDATE `tenant_reg` SET `stage`='$sendmm',`stage_date`='$date' where id='$id'"; $upload= mysqli_query($connection,$query); //echo "<script>alert('STAGE-10')</script>"; echo "<script>window.location.href='s_tenant_details.php'</script>"; } } ?><file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomOnRent | Post</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <style> @media all and (max-width: 459px) and (min-width:300px) { .hdd { height:45px; } .scentxt { margin-top: 50px; } .send { position: relative; top: -135px; } .mobileform { position: absolute; top: 120px; left: 5px; } .btcontent { margin-top: 280px !important; } .w100 { width:100%; } } </style> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <link href="css/sky form.css" rel="stylesheet"> <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" /> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <script src="js/sweetalert-dev.js"></script> <link href="css/sweetalert.css" rel="stylesheet" type="text/css" /> </head> <body> <?php include('bgImage.php'); ?> <!--header <div class="navigation"> <div class="container-fluid"> <nav class="pull"> <ul> <li><a href="index.html">Home</a></li> <li><a href="about.html">About Us</a></li> <li><a href="why.html">Why Fair Owner</a></li> <li><a href="how.html">How It Works</a></li> <li><a href="agreement.html">Agreement</a></li> <li><a href="contact.html">Contact</a></li> </ul> </nav> </div> </div> --> <div class="header hdd" style="padding: 0.5em 0;"> <div class="container"> <!--logo--> <div class="logo"> <h1><a href="index.php"> <img src="images/logo2.png" /> </a></h1> </div> <!--//logo--> <!---<div class="top-nav" style="float:right"> <ul class="right-icons"> <li><span ><i class="glyphicon glyphicon-phone"> </i>+91 8888599993</span></li> <li><a href="#"><i class="glyphicon glyphicon-user"> </i>Login</a></li> </ul> <div class="nav-icon"> <div class="hero nav_slide_button" id="hero"> <a href="#"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> </div> <!--- <a href="#" class="right_bt" id="activator"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> --- </div> <div class="clearfix"> </div> </div>---> <div class="col-md-6"> </div> <div class="col-md-6"> <div style="margin-left:14%"> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" class="mobileform form-inline" novalidate="novalidate"> <div class="form-group"> <input class="w100" type="number" id="lmobile" name="mobile" value="<?php if(isset($_POST['mobile'])) { echo htmlentities ($_POST['mobile']); }?>" placeholder="Mobile without +91" style="padding:4px; font: 15px/23px 'Open Sans', Helvetica, Arial, sans-serif; color: #404040;" /> </div> <div class="form-group scentxt"> <!-- <input class="w100" type="text" class="" id="lotp" name="otp" placeholder="Enter OTP" style="padding:4px; font: 15px/23px 'Open Sans', Helvetica, Arial, sans-serif; color: #404040;" > --_ANUP--> <input class="w100" type="password" class="" id="lotp" name="otp" placeholder="Enter Password" style="padding:4px; font: 15px/23px 'Open Sans', Helvetica, Arial, sans-serif; color: #404040;" > </div> <!-- <input name="enterotp" type="submit" class="btn-u" value="Login" style="border: 2px solid #fcfefd; background: #0b8a57; border-radius: 5px; font-size: 16px; font-weight: 600; box-shadow: 7px 7px 5px #289469; color: #ffffff;" onClick="return loempty()" /> --_ANUP--> <input name="enterotp" type="submit" class="btn-u hvr-sweep-to-right" value="Login" style="border: 2px solid #fcfefd; background: #00d5fa; border-radius: 5px; font-size: 16px; font-weight: 600; box-shadow: 7px 7px 5px #005b6b; color: #ffffff;" onClick="return loempty() /> <p class="send" style="padding-left:0"><span style="font-size:13px"></span> <!--<input type="submit" onClick="return lempty()" name="sendotp" value="" style="background:url('images/getOTP.png'); background-size:45%; border:none; color: #FFF; width:222px; background-repeat: no-repeat;" /> --_ANUP--> </p> </form> <?php error_reporting(E_ERROR); if(isset($_POST['enterotp'])) { /* $mobile=$_POST['mobile']; $qu="SELECT * FROM `registation` where mobile = '$mobile'"; $sql = @mysqli_query($connection,$qu); while($row=mysqli_fetch_array($sql)) { $dbmobile=$row['mobile']; }*/ $i=$_GET['id']; $_SESSION['ii']=$i; if($i==1) { if (empty($_POST['mobile']) && empty($_POST['otp'])){ //echo "<script>alert('Mobile Number is not exist - Please Register')</script>"; echo "<script>swal('Oops...', 'You have entered wrong Mobile Number OR Password!', 'error');</script>"; } else { $mobile=$_POST['mobile']; $qu="SELECT mobile FROM `registation` where mobile = '$mobile'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $m=$row['mobile']; $name=$row['name']; $mobile=$_POST['mobile']; } /* if($m==$mobile) { //echo "<script>window.location.href='owner_dashboard.php'</script>"; //$_COOKIE['mobile']= $mobile; //$_COOKIE['otp']=rand(1000, 9999); $_SESSION["a"]=1234; //echo "<script>alert('we send you otp - enter it')</script>"; echo "<script>swal('Thank you...', 'We have send you OTP (One Time Password) on your given mobile through SMS, Please enter it!', 'success');</script>"; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else echo "<script>alert('enter correct OTP')</script>"; $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } } */ // Hidden by _ANUP // if($m==$mobile) { $qu="SELECT password FROM `login_details` where type = 'owner' "; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $p=$row['password']; $pass=$_POST['otp']; } $_SESSION["a"]=$p; } else { //echo "<script>alert('Mobile Number is not exist - Please Register')</script>"; echo "<script>swal('Oops...', 'Mobile Number is not exist - Please Register!', 'error');</script>"; } } } elseif($i==2) { if (empty($_POST['mobile']) && empty($_POST['otp'])){ //echo "<script>alert('Mobile Number is not exist - Please Register')</script>"; echo "<script>swal('Oops...', 'You have entered wrong Mobile Number OR Password!', 'error');</script>"; } else { $mobile=$_POST['mobile']; $qu="SELECT mobile FROM `tenant_reg` where mobile = '$mobile'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $m=$row['mobile']; $name=$row['name']; $mobile=$_POST['mobile']; } /* if($m==$mobile) { //$_COOKIE['mobile']= $mobile; //$_COOKIE['otp']=rand(1000, 9999); $_SESSION["a"]=1234; //echo "<script>alert('we send you otp - enter it')</script>"; echo "<script>swal('Thank you...', 'We have send you OTP (One Time Password) on your given mobile through SMS, Please enter it!', 'success');</script>"; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else //echo "<script>alert('enter correct OTP')</script>"; echo "<script>swal('Oops...', 'Enter correct OTP!', 'error');</script>"; $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } } */ // Hidden by _ANUP // if($m==$mobile) { $qu="SELECT password FROM `login_details` where type = 'tenant' "; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $p=$row['password']; $pass=$_POST['otp']; } $_SESSION["a"]=$p; } else { //echo "<script>alert('Mobile Number is not exist - Please Register')</script>"; echo "<script>swal('Oops...', 'Mobile Number is not exist - Please Register!', 'error');</script>"; } } } /* if($mobile==$dbmobile) { $_COOKIE['mobile']= $_POST['mobile']; $_COOKIE['otp']=rand(1000, 9999); $_SESSION["a"]=$_COOKIE['otp']; echo "<script>alert('we send you otp - enter it')</script>"; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else echo "<script>alert('enter correct OTP')</script>"; $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } } else { echo "<script>alert('Mobile Number is not exist - Please Register')</script>"; }*/ } if(isset($_POST['enterotp'])) { $temp=$_POST['otp']; $m=$_SESSION["a"]; $mobile=$_POST['mobile']; if($m == $temp) { /* $qu="SELECT name,flow_id FROM `registation` where mobile = '$mobile'"; $sql = @mysqli_query($connection,$qu); while($row=mysqli_fetch_array($sql)) { $name=$row['name']; $flow_id=$row['flow_id']; $_SESSION['name']=$name; //$i=$_GET['id']; if($flow_id==1) { echo "<script>window.location.href='owner_dashboard.php'</script>"; } if($flow_id==2) { echo "<script>window.location.href='tenant_dashboard.php'</script>"; } }*/ $i=$_GET['id']; if($i==1) { $qu="SELECT * FROM `registation` where mobile = '$mobile'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $name=$row['name']; $_SESSION['name']=$name; echo "<script>window.location.href='owner_dashboard.php'</script>"; } } elseif($i==2) { $qu="SELECT * FROM `tenant_reg` where mobile = '$mobile'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $name=$row['name']; $_SESSION['name']=$name; echo "<script>window.location.href='tenant_dashboard.php'</script>"; } } } else { //echo "<script>alert('Enter Correct OTP')</script>"; // echo "<script>swal('Oops...', 'Enter Correct OTP!', 'error');</script>"; _ANUP // echo "<script>swal('Oops...', 'Enter Correct Password!', 'error');</script>"; } } ?> </div> </div> <div class="clearfix"> </div> </div> </div> <!--//--> <div class="loan_single" style="background:rgba(0, 213, 250, 0.05)"> <div class="container" style=""> <div class="col-md-8"> <div style="margin-top:12%" class="btcontent"> <?php if($_GET['id']==1) { ?> <p style="font-size:1.5em; text-align:center; color: azure;"> "Post Property & Get Relaxed" </p><br/> <div class="col-md-2"></div> <div class="col-md-8" style="margin-left:2%;"> <img src="images/owner.png" class="img-responsive" /> </div> <div class="col-md-2"></div> <!--<p style="font-size:1.5em; text-align:center"> Fairowner.com has introduced another unique facility for its registered clients </p>--> <div class="col-md-12"> <div class="us-choose"> <h4 style="font-size: 1.5em; text-align: center; margin-bottom: 25px; color: #00d5fa;">"Pay A Little & Experience The Comfort"</h4> <div class="col-md-1"> </div> <div class="col-md-2 why-choose hidden-xs"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive glyphicon glyphicon-home"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Posting</h5> <label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em">Posting property ad in easy steps</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose hidden-xs"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive fa fa-volume-control-phone"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Get Tenant</h5> <label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em" >Quick & fair inquiry's</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose hidden-xs"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive fa fa-user"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Manager</h5> <label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em" >Personal relationship manager for any assistance</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose hidden-xs"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive fa fa-file"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Agreement </h5> <label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em" >On call consultation on rental agreement</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose hidden-xs"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive fa fa-check-square-o"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Verification </h5> <label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em" >On call consultation on tenant verification </p> </div> <div class="clearfix"> </div> </div> <div class="col-md-1"> </div> <div class="clearfix"> </div> </div> </div> <?php } else { ?> <p style="font-size:1.5em; text-align:center; color: azure;"> "Save time, money & efforts" </p><br/> <div class="col-md-1"></div> <div class="col-md-10"> <img src="images/tenant.png" class="img-responsive" style="" /> </div> <!--<div class="col-md-4"> <img src="images/home.png" class="img-responsive" /> </div>--> <div class="col-md-1"></div> <div class="clearfix"></div> <!--<p style="font-size:1.5em; text-align:center"> Fairowner.com has introduced another unique facility for its registered clients </p>--> <div class="col-md-12"> <div class="us-choose"> <h4 style="font-size: 1.5em; text-align: center; margin-bottom: 25px; color: #00d5fa;">"Experience the hasslefree home hunting"</h4> <div class="col-md-2 why-choose hidden-xs"> </div> <div class="col-md-2 why-choose hidden-xs"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive fa fa-user-secret"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Brokerage</h5> <label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em">Brokerage free properties</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose hidden-xs"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive fa fa-file"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Agreement</h5> <label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em">Doorstep rental agreements</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose hidden-xs"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive fa fa-check-square-o"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Verification</h5> <label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em">Assistance in tenant verification</p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose hidden-xs"> <div class=" ser-grid " style="float:none; text-align:center"> <i class="hi-icon hi-icon-archive fa fa-user"> </i> </div> <div class="ser-top beautiful" style="float:none; text-align:center; width:80%; margin:5px auto;"> <!--<h5 style="font-size:13px">Manager</h5> <label>The standard chunk of Lorem</label>--> <p style="font-size:14px; line-height:1.5em">Personal relationship manager for any assistance </p> </div> <div class="clearfix"> </div> </div> <div class="col-md-2 why-choose hidden-xs"> </div> <div class="clearfix"> </div> </div> </div> <?php } ?> </div> </div> <div class="col-md-4 second"> <div style="margin-top:26%;"> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" id="sky-form4" class="sky-form" novalidate="novalidate" style="margin:3px 0"> <header>New To RoomOnRent?</header> <fieldset> <section> <label class="input"> <i class="icon-append fa fa-user"></i> <input type="text" id="uname" name="username" placeholder="Enter <NAME>" value="<?php echo isset($_POST['username']) ? $_POST['username'] : '' ?>" > </label> </section> <section> <label class="input"> <i class="icon-append fa fa-key"></i> <input type="password" id="my_password" name="my_password" placeholder="Enter Password" value="<?php echo isset($_POST['my_password']) ? $_POST['my_password'] : '' ?>" > </label> </section> <section> <label class="input"> <i class="icon-append fa fa-key"></i> <input type="password" id="confirmPassword" name="confirmPassword" placeholder="Re-Enter Password" value="<?php echo isset($_POST['confirmPassword']) ? $_POST['confirmPassword'] : '' ?>" > </label> </section> <section> <label class="input"> <i class="icon-append fa fa-envelope"></i> <input type="email" id="uemail" name="email" placeholder="Email address" value="<?php echo isset($_POST['email']) ? $_POST['email'] : '' ?>" > </label> </section> <section> <label class="input"> <i class="icon-append fa fa-mobile"></i> <input type="number" id="umobile" name="r_mobile" placeholder="Mobile without +91" value="<?php echo isset($_POST['r_mobile']) ? $_POST['r_mobile'] : '' ?>" > </label> </section> <section> <!--<label class="checkbox" style="padding-left:0">We Send you OTP on your mobile</label> <label class="checkbox" style="padding-left:0"> <a href="#">Click Here</a>- <input type="submit" onClick="return rone()" name="r_sendotp" value="" style="background:url('images/clickhere.png'); border:none; color: #27da93; font-size: 16px; background-size: 100%; width: 100px;" /> <!--</label>--> </section> <?php if(isset($_POST['r_mobile'])) { ?> <section id="enterotp"> <label class="input"> <i class="icon-append fa fa-lock"></i> <input type="text" id="uotp" name="r_otp" placeholder="OTP"> </label> </section> <?php } ?> </fieldset> <!--<fieldset style="padding: 5px 30px;"> <section> <label class="checkbox"><input type="checkbox" name="terms" id="terms"><i></i>I agree with the Terms and Conditions</label> </section> </fieldset>--> <?php if(isset($_POST['r_mobile'])) { ?> <footer id="footer1"> <input style="float:right" type="submit" onClick="return rtwo()" name="create_account" class="btn-u" value="Next >>" /> </footer> <?php } else { ?> <footer id="footer2"> <input style="float:right" type="submit" onClick="return rone()" name="r_sendotp" class="btn-u" value="Proceed >>" /> </footer> <?php } ?> </form> <?php error_reporting(E_ERROR); if(isset($_POST['r_sendotp'])) { $name=$_POST['username']; $r_mobile=$_POST['r_mobile']; $i=$_GET['id']; $_SESSION['ii']=$i; if($i==1) { $qu="SELECT mobile FROM `registation` where mobile = '$r_mobile'"; $sql = @mysqli_query($connection,$qu); $row=@mysqli_fetch_row($sql); $m=$row[0]; if(isset($m)) { //echo "<script>alert('Mobile No is already exist - Please Login')</script>"; //echo "<script>swal('Oops...', 'Mobile No is already exist - Please Login!', 'error');</script>"; //echo "<script>window.location.href='login.php?id=1'</script>"; echo " <script> $(document).ready(function() { swal({ title:'Thank you...', text:'Thanks for providing details. Your account has been created. Please login', type:'success' },function() { window.location.href='login.php?id=1'; }); }); </script> "; /*$qu="SELECT name FROM `registation` where mobile = '$r_mobile'"; $sql = @mysqli_query($connection,$qu); $row=@mysqli_fetch_row($sql); $m=$row[0]; $_SESSION['name']=$m; echo "<script>window.location.href='owner_dashboard.php'</script>"; */ } else { //regTest //$_COOKIE['mobile']= $_POST['r_mobile']; //$_COOKIE['otp']=rand(1000, 9999); $_SESSION["a1"]=1122;//$_COOKIE['otp']; //echo "<script>alert('we send you otp - enter it')</script>"; //echo "<script>swal('Thank you...', 'We have send you OTP (One Time Password) on your given mobile through SMS, Please enter it!', 'success');</script>"; echo " <script> $(document).ready(function() { swal({ title:'Thank you...', text:'We have send you OTP (One Time Password) on your given mobile through SMS, Please enter it!', type:'success' },function() { window.scrollTo(0, document.body.scrollHeight); document.getElementById('uotp').focus(); }); }); </script> "; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } } } elseif($i==2) { $qu="SELECT mobile FROM `tenant_reg` where mobile = '$r_mobile'"; $sql = @mysqli_query($connection,$qu); $row=@mysqli_fetch_row($sql); $m=$row[0]; if(isset($m)) { echo " <script> $(document).ready(function() { swal({ title:'Thank you...', text:'Thanks for providing details. Your account has been created. Please login', type:'success' },function() { window.location.href='login.php?id=2' }); }); </script> "; } else { //regTest //$_COOKIE['mobile']= $_POST['r_mobile']; //$_COOKIE['otp']=rand(1000, 9999); $_SESSION["a1"]=1122;//$_COOKIE['otp']; //echo "<script>alert('we send you otp - enter it')</script>"; //echo "<script>swal('Thank you...', 'We have send you OTP (One Time Password) on your given mobile through SMS, Please enter it!', 'success');</script>"; echo " <script> $(document).ready(function() { swal({ title:'Thank you...', text:'We have send you OTP (One Time Password) on your given mobile through SMS, Please enter it!', type:'success' },function() { window.scrollTo(0, document.body.scrollHeight); document.getElementById('uotp').focus(); }); }); </script> "; include_once("otpsend.php"); // Declare variables. $Username = "YourUsername"; $Password = "<PASSWORD>"; $MsgSender = "YourSender, example: a phone number like 4790000000"; $DestinationAddress = "Receiver - A phone number"; $Message = "Hello World!"; // Create ViaNettSMS object with params $Username and $Password $ViaNettSMS = new ViaNettSMS($Username, $Password); try { // Send SMS through the HTTP API $Result = $ViaNettSMS->SendSMS($MsgSender, $DestinationAddress, $Message); // Check result object returned and give response to end user according to success or not. if ($Result->Success == true || $otp==$_POST['otp']) $Message = "Message successfully sent!"; else $Message = "Error occured while sending SMS<br />Errorcode: " . $Result->ErrorCode . "<br />Errormessage: " . $Result->ErrorMessage; } catch (Exception $e) { //Error occured while connecting to server. $Message = $e->getMessage(); } } } else { //echo "<script>alert('Enter Correct URL')</script>"; echo "<script>swal('Oops...', 'Enter Correct URL!', 'error');</script>"; echo "<script>window.location.href='index.php'</script>"; } } if(isset($_POST['create_account'])) { $r_mobile=$_POST['r_mobile']; $temp=$_POST['r_otp']; $m=$_SESSION["a1"]; $email=$_POST['email']; $my_password=$_POST['<PASSWORD>']; if($m == $temp) { $i=$_GET['id']; if($i==1) { $date=date("d/m/Y"); $name=$_POST['username']; $qu1="SELECT name FROM `registation` where name = '$name'"; $sql1 = @mysqli_query($connection,$qu1); $roww=@mysqli_fetch_row($sql1); $n=$roww[0]; if(isset($n)) { $ali=rand(10, 99); $name=$n.$ali; } $_SESSION['name']=$name; $query="INSERT INTO `registation`(`id`, `name`, `email`, `mobile`, `flow_id`, `pd_id`, `date`, `manager`, `fromwhere`) VALUES ('','".$name."','".$email."','".$r_mobile."','".$i."','0','".$date."','Mr. Anup','Frontend')"; //Below query is for login. $query_login=" INSERT INTO `login_details` (`id`, `name`, `mobile`, `password`, `type`) VALUES ('','".$name."','".$r_mobile."','".$my_password."','owner') "; $upload= mysqli_query($connection,$query); $upload= mysqli_query($connection,$query_login); echo "<script>window.location.href='owner_after_login.php'</script>"; } elseif($i==2) { $date=date("d/m/Y"); $name=$_POST['username']; $qu1="SELECT name FROM `tenant_reg` where name = '$name'"; $sql1 = @mysqli_query($connection,$qu1); $roww=@mysqli_fetch_row($sql1); $n=$roww[0]; if(isset($n)) { $ali=rand(10, 99); $name=$n.$ali; } $_SESSION['name']=$name; $query="INSERT INTO `tenant_reg`(`id`, `name`, `email`, `mobile`, `flow_id`, `pd_id`, `date`, `manager`, `fromwhere`) VALUES ('','".$name."','".$email."','".$r_mobile."','".$i."','0','".$date."','Mr. Sagar','Frontend')"; //Below query is for login. $query_login=" INSERT INTO `login_details` (`id`, `name`, `mobile`, `password`, `type`) VALUES ('','".$name."','".$r_mobile."','".$my_password."','tenant') "; $upload= mysqli_query($connection,$query); $upload= mysqli_query($connection,$query_login); echo "<script>window.location.href='tenant_dashboard.php'</script>"; } else { //echo "<script>alert('Enter Correct URL')</script>"; echo "<script>swal('Oops...', 'Enter Correct URL!', 'error');</script>"; } } else { //echo "<script>alert('Enter Correct OTP')</script>"; echo "<script>swal('Oops...', 'Enter Correct OTP!', 'error');</script>"; } } ?> </div> </div> <div class="clearfix"> </div> </div><br/><br/> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> <script> function lempty() { var x; x = document.getElementById("lmobile").value; if (/^\d{10}$/.test(x)) { //ok } else { swal("Oops...", "Please enter valid mobile No!", "error"); document.getElementById("lmobile").focus(); return false; }; } function loempty() { var y; y = document.getElementById("lotp").value; if (y == "") { //alert("please Enter OTP"); swal("Oops...", "Please enter Password!", "error"); document.getElementById("lotp").focus(); return false; }; } </script> <script> function val() { if(document.getElementById('terms').checked==false) alert('Please agree for our terms & contidions'); window.location.href='login.php'; } </script> <script> function rone() { var a; a = document.getElementById("uname").value; if (a == "") { //alert("please Enter username"); document.getElementById("uname").focus(); swal("Oops...", "Please enter username!", "error"); return false; }; var b; b = document.getElementById("uemail").value; var atpos = b.indexOf("@"); var dotpos = b.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=b.length) { //alert("please Enter valid email"); document.getElementById("uemail").focus(); swal("Oops...", "Please enter valid email!", "error"); return false; }; var c; c = document.getElementById("umobile").value; //|| c.match(^[789]\d{9}$) if (/^\d{10}$/.test(c)) { //ok } else{ //alert("please Enter valid mobile no"); document.getElementById("umobile").focus(); swal("Oops...", "Please enter valid mobile no!", "error"); return false; }; var d, e ; d = document.getElementById("my_password").value; e = document.getElementById("confirmPassword").value; if (d == "") { //alert("please Enter password"); document.getElementById("my_password").focus(); swal("Oops...", "Please enter Password!", "error"); return false; } elseif(d == e){ //ok } else{ //alert("Password Not Matched"); document.getElementById("my_password").focus(); swal("Oops...", "Password Not Matched with Confirm Password!", "error"); return false; } } function rtwo() { var a; a = document.getElementById("uname").value; if (a == "") { //alert("please Enter username"); document.getElementById("uname").focus(); swal("Oops...", "Please enter valid username!", "error"); return false; }; var b; b = document.getElementById("uemail").value; var atpos = b.indexOf("@"); var dotpos = b.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=b.length) { //alert("please Enter valid email"); document.getElementById("uemail").focus(); swal("Oops...", "Please enter valid email!", "error"); return false; }; var c; c = document.getElementById("umobile").value; //|| c.match(^[789]\d{9}$) if (/^\d{10}$/.test(c)) { //ok } else{ // alert("please Enter valid mobile no"); document.getElementById("umobile").focus(); swal("Oops...", "Please enter valid mobile no!", "error"); return false; }; var d; d = document.getElementById("uotp").value; if (d == "") { //alert("please Enter OTP"); document.getElementById("uotp").focus(); swal("Oops...", "Please enter OTP!", "error"); return false; }; if(document.getElementById('terms').checked==false) { //alert('Please agree for our terms & conditions'); document.getElementById("terms").focus(); swal("Oops...", "Please agree for our terms & conditions!", "error"); return false; } } </script> </body> </html><file_sep><?php // block any attempt to the filesystem if (isset($_GET['file']) && basename($_GET['file']) == $_GET['file']) { $filename = $_GET['file']; } else { $filename = NULL; } ?><file_sep><?php session_start(); include('conn.php'); include('out1.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Dashboard - RoomsOnRent</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="fair-owner" content="yes"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet"> <link href="css/font-awesome.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <link href="css/dataTables.bootstrap.min.css" rel="stylesheet"> <link href="css/pages/dashboard.css" rel="stylesheet"> <link href="css/pages/signin.css" rel="stylesheet" type="text/css"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <style> .col-sm-6 { width: 45% !important; } </style> </head> <body> <?php include('header.php'); ?> <div class="subnavbar"> <div class="subnavbar-inner"> <div class="container"> <ul class="mainnav"> <li ><a href="super_admin_home.php"><i class="icon-dashboard"></i><span>Dashboard</span> </a> </li> <li class="active"><a href="create_subadmin.php"><i class="icon-sitemap"></i><span>Create Sub-Admin</span> </a> </li> <li><a href="s_reg_owner.php"><i class="icon-user"></i><span>Registered Owner</span> </a> </li> <li><a href="s_owner_details.php"><i class="icon-check"></i><span>Property Posted Owner</span> </a> </li> <li><a href="s_reg_tenant.php"><i class="icon-group"></i><span>Registered Tenant</span> </a></li> <li><a href="s_tenant_details.php"><i class="icon-check"></i><span>Plan Purchase Tenant</span> </a></li> <li><a href="req_agreement.php"><i class="icon-paste"></i><span>Request for Agreement</span> </a></li> <li class="dropdown"><a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-long-arrow-down"></i><span>Drops</span> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="home_slider.php">Home Page Slider</a></li> <li><a href="abuse_property.php">Abuse Property</a></li> <li><a href="testimonials.php">Testimonials</a></li> </ul> </li> </ul> </div> <!-- /container --> </div> <!-- /subnavbar-inner --> </div> <!-- /subnavbar --> <div class="main"> <div class="main-inner"> <div class="container"> <div class="row"> <div class="span4"> <div class="widget widget-nopad"> <div class="widget-header"> <i class="icon-list-alt"></i> <h3> Create Sub-Admin</h3> </div> <!-- /widget-header --> <div class="widget-content" style="padding:20px"> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"> <div class="login-fields"> <p>Create Sub-Admin account:</p> <div class="field"> <label for="firstname">Username:</label> <input type="text" style="padding:11px 15px 10px 10px" name="username" value="" placeholder="Username" class="login" /> </div> <!-- /field --> <div class="field"> <label for="lastname">Password:</label> <input type="text" style="padding:11px 15px 10px 10px" name="password" value="" placeholder="<PASSWORD>" class="login" /> </div> <!-- /field --> <div class="field"> <label for="mobile">Mobile:</label> <input type="text" style="padding:11px 15px 10px 10px" name="mobile" value="" placeholder="Mobile" class="login"/> </div> <!-- /field --> <div class="field"> <label for="email">Email Address:</label> <input type="text" style="padding:11px 15px 10px 10px" id="email" name="email" value="" placeholder="Email" class="login"/> </div> <!-- /field --> </div> <!-- /login-fields --> <div class="login-actions"> <label>Permission</label> <span class="login-checkbox"> <input name="update" type="checkbox" class="field login-checkbox" value="update" /> <label class="choice" for="Field">Update &nbsp;&nbsp;&nbsp;&nbsp;</label> </span> <span class="login-checkbox"> <input name="delete" type="checkbox" class="field login-checkbox" value="delete" /> <label class="choice" for="Field">Delete</label> </span> </div> <input style="float:none" name="submit" type="submit" class="button btn btn-primary btn-large" value="create" /> <!-- .actions --> </form> <?php if(isset($_POST['submit'])) { $username=$_POST['username']; $password=$_POST['password']; $mobile=$_POST['mobile']; $email=$_POST['email']; $upd=$_POST['update']; $del=$_POST['delete']; $query="INSERT INTO `sub_admin`(`id`, `name`, `password`, `mobile`, `email`, `updte`, `dele`) VALUES ('','".$username."','".$password."','".$mobile."','".$email."','".$upd."','".$del."')"; $upload= mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { echo "<script>alert('Your Sub-Admin is created')</script>"; echo "<script>window.location.href='create_subadmin.php'</script>"; } } ?> </div> </div> <!-- /widget --> </div> <!-- /span6 --> <form action="<?php $_SERVER["PHP_SELF"] ?>" method="post" enctype="multipart/form-data"> <div class="span8"> <div class="widget"> <div class="widget-header"> <i class="icon-bookmark"></i> <h3>Sub-Admin Details</h3> </div> <!-- /widget-header --> <div class="widget-content"> <div class="" style="padding: 10px;overflow-x:auto;"> <table id="example" class="table table-striped table-bordered" style="overflow:auto;" cellspacing="0" width="100%"> <thead> <tr> <th>Id</th> <th>Username</th> <th>Password</th> <th>Mobile</th> <th>Email</th> <th>Permission</th> <th>Action</th> </tr> </thead> <tfoot> <tr> <th>Id</th> <th>Username</th> <th>Password</th> <th>Mobile</th> <th>Email</th> <th>Permission</th> <th>Action</th> </tr> </tfoot> <tbody> <?php $qu="SELECT * FROM `sub_admin` order by id DESC"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { /* $name=$row['name']; $email=$row['email']; $mobile=$row['mobile']; $pd_id=$row['pd_id']; $address=$row['address']; */ ?> <tr> <td><?php echo $row['id'] ?></td> <td><?php echo $row['name'] ?></td> <td><?php echo $row['password'] ?></td> <td><?php echo $row['mobile'] ?></td> <td><?php echo $row['email'] ?></td> <td><?php echo $row['updte']." ".$row['dele'] ?></td> <td> <div style="width:240px;"> <a style="float:left; margin-right:5px" href="sub_admin_edit.php?id=<?php echo $row['id'] ?>" class="btn btn-info">Update</a> <a style="float:left; margin-right:5px" href="sub_admin_ot.php?id=<?php echo $row['id'] ?>" class="btn btn-success">Assign</a> <a style="float:left; margin-right:5px" onClick="javascript: return confirm('Please confirm deletion');" href="delete_sub_admin.php?id=<?php echo $row['id'] ?>" class="btn btn-danger">Delete</a> </div> </td> </tr> <?php } ?> </tbody> </table> </div> </div> <!-- /widget-content --> </div> <!-- /widget --> </div> </form> <?php if(isset($_POST['assign'])) { $sub_admin=$_POST['subadmin']; //$owne=implode("', '", $_POST['owner']); //$s_name=$_POST['sname']; $ow=$_POST['owner']; $owne = join("','", $ow); $oq="UPDATE `registation` SET `manager`='$sub_admin' WHERE pd_id IN ('$owne')"; $ou=mysqli_query($connection,$oq); $te=$_POST['tenant']; $tent = join("','", $te); $tq="UPDATE `tenant_reg` SET `manager`='$sub_admin' WHERE id IN ('$tent')"; $tu=mysqli_query($connection,$tq); $qy="SELECT p_id, ten_id FROM `sub_admin` WHERE id='$sub_admin'"; $sql = @mysqli_query($connection,$qy); while($ro=@mysqli_fetch_array($sql)) { $ow=$ro['p_id']; $ten=$ro['ten_id']; } $o=implode(',',$_POST['owner']); $t=implode(',',$_POST['tenant']); $owner=$ow.','.$o; $tenant=$ten.','.$t; $query="UPDATE `sub_admin` SET `p_id`='$owner',`ten_id`='$tenant' WHERE id=$sub_admin"; $upload=mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { echo "<script>alert('Owner & Tenant Assign')</script>"; echo "<script>window.location.href='create_subadmin.php'</script>"; } } ?> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /main-inner --> </div> <!-- /main --> <?php include('footer.php'); ?> <!-- /footer --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/jquery.dataTables.min.js"></script> <script src="js/dataTables.bootstrap.min.js"></script> <script src="js/base.js"></script> <script> $(document).ready(function() { $('#example').DataTable({ responsive: true, ordering: false }); } ); </script> </body> </html> <file_sep><?php /*?><?php include('conn.php'); ?><?php */?> <!DOCTYPE html> <html lang="en"> <head> <title>Contacts</title> <meta charset="utf-8"> <meta name="description" content="Your description"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta name="keywords" content="Your keywords"> <meta name="author" content="Your name"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/zerogrid.css" type="text/css" media="all"> <link rel="stylesheet" href="css/responsive.css" type="text/css" media="all"> <script src="js/jquery.js"></script> <script src="js/jquery-migrate-1.1.1.js"></script> <script src="js/bgstretcher.js"></script> <script src="js/forms.js"></script> <script type="text/javascript" src="js/css3-mediaqueries.js"></script> <script> $(document).ready(function() { // Initialize Backgound Stretcher $('BODY').bgStretcher({ images: ['images/slide-1.jpg'], imageWidth: 1600, imageHeight: 964, resizeProportionally:true }); }); </script> <style> .txtstyle{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; border: 1px solid #49413d; background: url(../images/tail-input.png); padding: 5px 15px; margin: 0; font-size: 16px; line-height: 20px !important; color: #b0adac; outline: none; width: 300px; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; float: left; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } </style> <!--[if lt IE 8]> <div style='text-align:center'><a href="http://www.microsoft.com/windows/internet-explorer/default.aspx?ocid=ie6_countdown_bannercode"><img src="http://www.theie6countdown.com/img/upgrade.jpg"border="0"alt=""/></a></div> <![endif]--> <!--[if lt IE 9]> <link rel="stylesheet" href="css/ie.css" type="text/css" media="screen"> <script src="js/html5shiv.js"></script> <link href='//fonts.googleapis.com/css?family=Open+Sans:400' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Open+Sans:600' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Open+Sans:700' rel='stylesheet' type='text/css'> <![endif]--> </head> <body> <div> <!--==============================row-top=================================--> <!--<div class="row-top"> <div class="main zerogrid"> <ul class="list-soc"> <li><a href="#"><img alt="" src="images/soc-icon1.png"></a></li> <li><a href="#"><img alt="" src="images/soc-icon2.png"></a></li> </ul> </div> </div>--> <!--==============================header=================================--> <header> <div class="row-nav"> <div class="main zerogrid"> <h1 class="logo"><a href="index.html"><img alt="<NAME>" src="images/logo2.png"></a></h1> <nav> <ul class="menu"> <li><a href="index.php">Home</a></li> <li><a href="about.html">About Us</a></li> <li><a href="services.php">Services</a></li> <li><a href="gallery.php">Gallery</a></li> <li class="current"><a href="contact.php">Contacts</a></li> <li><a href="availability.php">Availability</a></li> </ul> </nav> <div class="clear"></div> </div> </div> </header> <!--==============================content=================================--> <section id="content"> <div class="main-block zerogrid"> <div class="row" style="padding: 20px;"> <div class="wrapper"> <article class="col-1-2"><div class="wrap-col"> <h3>Postal Address</h3> <div class="map"> <iframe frameborder="0" scrolling="no" marginheight="0" marginwidth="0"width="" height="405" src="https://maps.google.com/maps?hl=en&q=kakade palase karve nagar pune&ie=UTF8&t=roadmap&z=14&iwloc=B&output=embed"><div><small><a href="http://embedgooglemaps.com">embedgooglemaps.com</a></small></div><div><small><a href="http://premiumlinkgenerator.com">Premiumlinkgenerator.com</a></small></div></iframe> </div> <u><h2> Contact Us </h2> </u><br> <dl class="address"> <dt>ABiTSolutions<br> Near Yashwant Lawn,<br> Guruchhaya Colony,<br> Sainagar, <br> Amravati 444 607. </dt> <dd> <span>Telephone::</span> 0721 2510161 </dd> <dd> <span>Mobile:</span> +91 9595567981 </dd> <dd> <span>Mail:</span> <EMAIL> </dd> <dt> <?php /*?> <?php $sql="SELECT * FROM contact limit 1"; $query=mysql_query($sql); while($row=mysql_fetch_array($query)) { echo "<dd><span>Manager:</span>".$row['name']."</dd>"; echo "<dd><span>Mobile:</span>".$row['mobile']."</dd>"; echo "<dd><span>Mail:</span>".$row['email']."</dd>"; } ?><?php */?> </dt> </dl> </div></article> <article class="col-1-2"><div class="wrap-col"> <h3>Contact Form</h3> <form action="testmail.php" method="post"> <?php /*?><div class="success"> Contact form submitted! <strong>We will be in touch soon.</strong> </div> <?php */?> <fieldset> <div> <label class="name"> <input type="text" name="un" placeholder="Name:" class="txtstyle"> <br><br><br> <?php /*?><span class="error">*This is not a valid name.</span> <span class="empty">*This field is required.</span><?php */?> </label> </div> <div> <label class="email"> <input type="email" name="email" placeholder="E-mail:" class="txtstyle"> <br><br><br> <?php /*?><span class="error">*This is not a valid email address.</span> <span class="empty">*This field is required.</span> <?php */?></label> </div> <div> <label class="phone"> <input type="tel" name="phone" placeholder="Phone:" class="txtstyle"> <br><br><br> <?php /*?><span class="error">*This is not a valid phone number.</span> <span class="empty">*This field is required.</span><?php */?> </label> </div> <div> <label class="message"> <textarea name="msg" class="txtstyle" style="height:200px;width:100%" placeholder="Message:"></textarea> <br><br><br> <?php /*?> <span class="error">*The message is too short.</span> <span class="empty">*This field is required.</span><?php */?> </label> </div> <div class="buttons-wrapper"><a class="button" data-type="reset">Clear</a> <input type="submit" class="button" value="Send"></div> </fieldset> </form> </div></article> </div> </div> </div> </section> </div> <div class="block"> <!--==============================footer================================--> <footer> <div class="main aligncenter zerogrid"> <div class="privacy">Copyright <span>|</span> <a href="about.html" rel="nofollow">RoomsOnRent</a> <span>|</span> <strong>Powered by <a href="http://abitsolutions.in">ABiTSolutions</a> </div> </div> </footer> </div> </body> </html><file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Home</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="fair owner " /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <!-- slide --> <script src="js/responsiveslides.min.js"></script> <script> $(function () { $("#slider").responsiveSlides({ auto: true, speed: 500, namespace: "callbacks", pager: true, }); }); </script> <script type="text/javascript"> function fill(Value) { $('#name').val(Value); $('#display').hide(); } $(document).ready(function(){ $("#name").keyup(function() { var name = $('#name').val(); if(name=="") { $("#display").html(""); } else { $.ajax({ type: "POST", url: "ajax.php", data: "name="+ name , success: function(html){ $("#display").html(html).show(); } }); } }); }); </script> <style> #display { position: absolute; } #display ul { list-style: none; margin: 3px 20px 20px 0px; width: 450px; } #display li { display: block; padding: 5px; background-color: #f5ebeb; border-bottom: 1px solid #367; cursor:pointer; } #content { padding:50px; width:500px; border:1px solid #666; float:left; } #clear { clear:both; } #box { float:left; margin:0 0 20px 0; text-align:justify; } </style> </head> <body > <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" header-right"> <h3 class="fadeInLeft">Rent Home Without Brokerage</h3> <div id="small-dialog" class=""> <!----- tabs-box ----> <div class="sap_tabs"> <div id="horizontalTab" style="display: block; width: 100%; margin: 0px;"> <ul class="resp-tabs-list"> <li class="resp-tab-item " aria-controls="tab_item-0" role="tab"><span>Amravati</span></li> <!--<li class="resp-tab-item" aria-controls="tab_item-1" role="tab"><span>For Buy</span></li> <li class="resp-tab-item" aria-controls="tab_item-2" role="tab"><span>For Rent</span></li>--> <div class="clearfix"></div> </ul> <div class="resp-tabs-container"> <h2 class="resp-accordion resp-tab-active" role="tab" aria-controls="tab_item-0"><span class="resp-arrow"></span>All Homes</h2><div class="tab-1 resp-tab-content resp-tab-content-active" aria-labelledby="tab_item-0" style="display:block"> <div class="facts"> <div class="login"> <?php $val=''; if(isset($_POST['submit'])) { if(!empty($_POST['name'])) { $val=$_POST['name']; } else { $val=''; } } ?> <form method="post" action="<?php $_SERVER['PHP_SELF'] ?>"> <input type="text" id="name" autocomplete="off" value="<?php echo $val;?>" name="name" value="Search Address, locality" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Search Address, locality';}"> <input type="submit" name="submit" value="" > </form> <div id="display"></div> </div> <?php if(isset($_POST['submit']) || isset($_POST['name'])) { if(!empty($_POST['name'])) { $name=$_POST['name']; $query3=mysqli_query($connection,"SELECT locality,sub_locality,landmark,city FROM `property_details` WHERE locality like '%$name%'"); while($query4=mysqli_fetch_array($query3)) { echo "<div id='box'>"; echo "<b>".$query4['locality']."</b>".",".$query4['sub_locality'].",".$query4['landmark'].",Pune"; echo "<div id='clear'></div>"; echo "</div>"; } $s_address=$_POST['name']; $_SESSION['saddress']=$s_address; $name=$_SESSION['name']; if(isset($name)) { echo "<script>window.location.href='properties.php'</script>"; } else { echo "<script>window.location.href='login.php?id=2'</script>"; } } else { echo "<script>alert('Please Insert Locality')</script>"; } } ?> </div> </div> </div> </div> <script src="js/easyResponsiveTabs.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $('#horizontalTab').easyResponsiveTabs({ type: 'default', //Types: default, vertical, accordion width: 'auto', //auto or any width like 600px fit: true // 100% fit in a container }); }); </script> </div> </div> <div class=" banner"> <div class="slider"> <div class="callbacks_container"> <ul class="rslides" id="slider"> <?php $q = "SELECT * FROM `slider`"; $sql = @mysqli_query($connection,$q); while($row = mysqli_fetch_array($sql)) { ?> <li> <div style="background: url(<?php echo "admin/".$row['images']; ?>);" class="banner"> </div> </li> <?php } ?> </ul> </div> </div> </div> </div> <!--header-bottom--> <div class="banner-bottom-top"> <div class="container"> <div class="bottom-header"> <div class="header-bottom"> <div class=" bottom-head"> <?php //$name=$_SESSION['name']; if(isset($_SESSION['name'])) { $name=$_SESSION['name']; $query="SELECT pd_id FROM `registation` where name = '$name'"; $sql = @mysqli_query($connection,$query); $pd_id=0; while($row = mysqli_fetch_array($sql)) { $pd_id=$row['pd_id']; } if(isset($pd_id)) { ?> <a href="<?php echo "single1.php?id=".$pd_id; ?>"> <?php } else { ?> <a href="<?php echo "post_property.php"; ?>"> <?php } } else { ?> <a href="<?php echo "login.php?id=1"; ?>"> <?php } ?> <div class="buy-media"> <i class="glyphicon glyphicon-home" style="font-size: 1.8em; color:#27da93"> </i> <h6>Post Your Property</h6> </div> </a> </div> <div class=" bottom-head"> <a href="agreement.php"> <div class="buy-media"> <i class="glyphicon glyphicon-file" style="font-size: 1.8em; color:#27da93"> </i> <h6>Agreement</h6> </div> </a> </div> <div class="clearfix"> </div> </div> </div> </div> </div> <!--//--> <!--//header-bottom--> <!--//header--> <!--content--> <div class="content"> <div class="content-bottom"> <div class="container"> <h3>Testimonials</h3> <div class="name-in" style="margin:0 auto; width:50%"> <?php $q = "SELECT * FROM `testimonials`"; $sql = @mysqli_query($connection,$q); while($row = mysqli_fetch_array($sql)) { ?> <div class="bottom-in "> <p class="para-in"><?php echo $row['comment'] ?></p> <i class="dolor"> </i> <div class="men-grid"> <a href="#" class="men-top"><img class="img-responsive " src="<?php echo "admin/".$row['image']; ?>" alt=""></a> <div class="men"> <span><?php echo $row['name'] ?></span> <p><?php echo $row['position'] ?></p> </div> <div class="clearfix"> </div> </div> </div> <?php } ?> </div> <div class="clearfix"> </div> </div> </div> <!--//test--> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html><file_sep><?php session_start(); include('conn.php'); error_reporting(E_ERROR); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Home</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="fair owner " /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <!-- slide --> <script src="js/responsiveslides.min.js"></script> <script> $(function () { $("#slider").responsiveSlides({ auto: true, speed: 500, namespace: "callbacks", pager: true, }); }); </script> <script type="text/javascript"> function fill(Value) { $('#name').val(Value); $('#display').hide(); } $(document).ready(function(){ $("#name").keyup(function() { var name = $('#name').val(); if(name=="") { $("#display").html(""); } else { $.ajax({ type: "POST", url: "ajax.php", data: "name="+ name , success: function(html){ $("#display").html(html).show(); } }); } }); }); </script> <style> #display { position: absolute; } #display ul { list-style: none; margin: 3px 20px 20px 0px; width: 450px; } #display li { display: block; padding: 5px; background-color: #f5ebeb; border-bottom: 1px solid #367; cursor:pointer; } #content { padding:50px; width:500px; border:1px solid #666; float:left; } #clear { clear:both; } #box { float:left; margin:0 0 20px 0; text-align:justify; } </style> </head> <body > <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" header-right"> <h3 class="fadeInLeft">Rent Home Without Brokerage</h3> <div id="small-dialog" class=""> <!----- tabs-box ----> <div class="sap_tabs"> <div id="horizontalTab" style="display: block; width: 100%; margin: 0px;"> <ul class="resp-tabs-list"> <li class="resp-tab-item " aria-controls="tab_item-0" role="tab"><span>Amravati</span></li> <!--<li class="resp-tab-item" aria-controls="tab_item-1" role="tab"><span>For Buy</span></li> <li class="resp-tab-item" aria-controls="tab_item-2" role="tab"><span>For Rent</span></li>--> <div class="clearfix"></div> </ul> <div class="resp-tabs-container"> <h2 class="resp-accordion resp-tab-active" role="tab" aria-controls="tab_item-0"><span class="resp-arrow"></span>All Homes</h2><div class="tab-1 resp-tab-content resp-tab-content-active" aria-labelledby="tab_item-0" style="display:block"> <div class="facts"> <div class="login"> <?php $val=''; if(isset($_POST['submit'])) { if(!empty($_POST['name'])) { $val=$_POST['name']; } else { $val=''; } } ?> <form method="post" action="<?php $_SERVER['PHP_SELF'] ?>"> <input type="text" id="" autocomplete="off" value="<?php echo $val;?>" name="name" Placeholder="Search Address, locality" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Search Address, locality';}"> <input type="submit" name="submit" onClick="return lempty()" value="" > </form> <div id="display"></div> </div> <?php if(isset($_POST['submit']) || isset($_POST['name'])) { if(!empty($_POST['name'])) { $name=$_POST['name']; $query3=mysqli_query($connection,"SELECT locality,sub_locality,landmark,city FROM `property_details` WHERE locality like '%$name%'"); while($query4=mysqli_fetch_array($query3)) { echo "<div id='box'>"; echo "<b>".$query4['locality']."</b>".",".$query4['sub_locality'].",".$query4['landmark'].",Pune"; echo "<div id='clear'></div>"; echo "</div>"; } $s_address=$_POST['name']; $_SESSION['saddress']=$s_address; $name=$_SESSION['name']; if(isset($name)) { $nme=$_SESSION['name']; $qu="SELECT name FROM `tenant_reg` where name = '$nme'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $ne=$row['name']; } if(isset($ne)) { echo "<script>window.location.href='properties.php'</script>"; } else { echo "<script>alert('Please Login with tenant Account')</script>"; } } else { echo "<script>window.location.href='login.php?id=2'</script>"; } } else { if(!empty($_SESSION['name'])) { echo "<script>window.location.href='properties.php'</script>"; } else { echo "<script>window.location.href='login.php?id=2'</script>"; } } } ?> </div> </div> </div> </div> <script src="js/easyResponsiveTabs.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $('#horizontalTab').easyResponsiveTabs({ type: 'default', //Types: default, vertical, accordion width: 'auto', //auto or any width like 600px fit: true // 100% fit in a container }); }); </script> </div> </div> <div class=" banner"> <div class="slider"> <div class="callbacks_container"> <ul class="rslides" id="slider"> <?php $q = "SELECT * FROM `slider`"; $sql = @mysqli_query($connection,$q); while($row = mysqli_fetch_array($sql)) { ?> <li> <div style="background: url(<?php echo "admin/".$row['images']; ?>);" class="banner"> </div> </li> <?php } ?> </ul> </div> </div> </div> </div> <!--header-bottom--> <div class="banner-bottom-top"> <div class="container"> <div class="bottom-header"> <div class="header-bottom"> <div class=" bottom-head"> <?php //$name=$_SESSION['name']; if(isset($_SESSION['name'])) { $nm=$_SESSION['name']; $qu="SELECT name FROM `registation` where name = '$nm'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $nem=$row['name']; } if(isset($nem)) { $name=$_SESSION['name']; $query="SELECT pd_id FROM `registation` where name = '$name'"; $sql = @mysqli_query($connection,$query); //$pd_id=0; while($row = mysqli_fetch_array($sql)) { $pd_id=$row['pd_id']; } if($pd_id != "0") { ?> <a href="<?php echo "single1.php?id=".$pd_id; ?>"> <?php } else { ?> <a href="<?php echo "post_property.php"; ?>"> <?php } } else { ?> <a href="<?php echo "index.php?id=11"; ?>"> <?php if(isset($_GET['id'])) { echo "<script>alert('Please Login with owner Account')</script>"; echo "<script>window.location.href='index.php'</script>"; } } } else { ?> <a href="<?php echo "login.php?id=1"; ?>"> <?php } ?> <div class="buy-media"> <i class="glyphicon glyphicon-home" style="font-size: 1.8em; color:#27da93"> </i> <h6>Post Your Property</h6> </div> </a> </div> <div class=" bottom-head"> <a href="agreement.php"> <div class="buy-media"> <i class="glyphicon glyphicon-file" style="font-size: 1.8em; color:#27da93"> </i> <h6>Agreement</h6> </div> </a> </div> <div class="clearfix"> </div> </div> </div> </div> </div> <!--//--> <!--//header-bottom--> <!--//header--> <!--content--> <div class="content"> <div class="content-bottom"> <div class="container"> <h3>Testimonials</h3> <div class="clearfix"> </div> <!--edit testimonials--> <style> #quote-carousel { padding: 0 10px 30px 10px; margin-top: 60px; } #quote-carousel .carousel-control { background: none; color: #CACACA; font-size: 2.3em; text-shadow: none; margin-top: 30px; } #quote-carousel .carousel-indicators { position: relative; right: 50%; top: auto; bottom: 0px; margin-top: 20px; margin-right: -19px; } #quote-carousel .carousel-indicators li { width: 50px; height: 50px; cursor: pointer; border: 1px solid #ccc; box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); border-radius: 50%; opacity: 0.4; overflow: hidden; transition: all .4s ease-in; vertical-align: middle; } #quote-carousel .carousel-indicators .active { width: 128px; height: 128px; opacity: 1; transition: all .2s; } .item blockquote { border-left: none; margin: 0; } .item blockquote p:before { float: left; margin-right: 10px; } </style> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="carousel slide" data-ride="carousel" id="quote-carousel"> <!-- Carousel Slides / Quotes --> <div class="carousel-inner text-center"> <!-- Quote 1 --> <?php $q = "SELECT * FROM `testimonials`"; $sql = @mysqli_query($connection,$q); $i=0; while($row = mysqli_fetch_array($sql)) { $i=$i+1; ?> <div class="item <?php if($i==1) echo "active"; else echo ""; ?>"> <blockquote> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <p style="margin-bottom:10px"><?php echo $row['comment'] ?></p> <p style="text-align:right"><?php echo $row['name'] ?><br/><small><?php echo $row['position'] ?></small> </p> </div> </div> </blockquote> </div> <?php } ?> </div> <!-- Bottom Carousel Indicators --> <ol class="carousel-indicators"> <?php $q = "SELECT * FROM `testimonials`"; $sql = @mysqli_query($connection,$q); $i=0; while($row = mysqli_fetch_array($sql)) { $i=$i+1; ?> <li data-target="#quote-carousel" data-slide-to="<?php echo $row['id']; ?>" class="<?php if($i==1) echo "active"; else echo ""; ?>"> <img class="img-responsive " src="<?php echo "admin/".$row['image']; ?>" alt=""> </li> <?php } ?> </ol> <!-- Carousel Buttons Next/Prev --> <a data-slide="prev" href="#quote-carousel" class="left carousel-control"><i class="fa fa-chevron-left"></i></a> <a data-slide="next" href="#quote-carousel" class="right carousel-control"><i class="fa fa-chevron-right"></i></a> </div> </div> </div> </div> <!--edut testimonials--> </div> </div> <!--//test--> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> <script> function lempty() { var x; x = document.getElementById("locality").value; if (x == "") { alert("please Enter Locality"); return false; }; } </script> </body> </html><file_sep><?php session_start(); include('out.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Dashboard - RoomsOnRent</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="fair-owner" content="yes"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet"> <link href="css/font-awesome.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <link href="css/pages/dashboard.css" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <?php include('headerSub.php'); ?> <div class="subnavbar"> <div class="subnavbar-inner"> <div class="container"> <ul class="mainnav"> <li class="active"><a href="index.php"><i class="icon-dashboard"></i><span>Dashboard</span> </a> </li> <li><a href="backend.php"><i class="icon-list-alt"></i><span>Post Property</span> </a> </li> <li><a href="backendtenant.php"><i class="icon-list-alt"></i><span>Insert Tenant</span> </a> </li> <li><a href="reg_owner.php"><i class="icon-user"></i><span>Registered Owner</span> </a> </li> <li><a href="owner_details.php"><i class="icon-check"></i><span>Property Posted Owner</span> </a> </li> <li><a href="reg_tenant.php"><i class="icon-group"></i><span>Registered Tenant</span> </a></li> <li><a href="tenant_details.php"><i class="icon-check"></i><span>Plan Purchase Tenant</span> </a></li> </ul> </div> <!-- /container --> </div> <!-- /subnavbar-inner --> </div> <!-- /subnavbar --> <div class="main"> <div class="main-inner"> <div class="container"> <div class="row"> <div class="span6"> <div class="widget widget-nopad"> <div class="widget-header"> <i class="icon-list-alt"></i> <h3> Introduction</h3> </div> <!-- /widget-header --> <div class="widget-content"> <img src="img/2.jpg" style="width:100%; height:450px" class="hidden-xs" /> </div> </div> <!-- /widget --> </div> <!-- /span6 --> <div class="span6"> <div class="widget"> <div class="widget-header"> <i class="icon-bookmark"></i> <h3>Important Shortcuts</h3> </div> <!-- /widget-header --> <div class="widget-content"> <div class="shortcuts"> <a href="index.php" class="shortcut"> <i class="shortcut-icon icon-dashboard"></i> <span class="shortcut-label">Dashboard</span> </a> <a href="reg_owner.php" class="shortcut"> <i class="shortcut-icon icon-user"></i> <span class="shortcut-label">Registered Owner</span> </a> <a href="owner_details.php" class="shortcut"> <i class="shortcut-icon icon-check"></i> <span class="shortcut-label">Property Posted Owner</span> </a><br/> <a href="reg_tenant.php" class="shortcut"> <i class="shortcut-icon icon-group"></i> <span class="shortcut-label">Registered Tenant</span> </a> <a href="tenant_details.php" class="shortcut"> <i class="shortcut-icon icon-check"></i> <span class="shortcut-label">Plan Purchase Tenant</span> </a> <a href="backend.php" class="shortcut"> <i class="shortcut-icon icon-list-alt"></i> <span class="shortcut-label">Post Property</span> </a> <a href="backendtenant.php" class="shortcut"> <i class="shortcut-icon icon-list-alt"></i> <span class="shortcut-label">Insert Tenant</span> </a> </div> <!-- /shortcuts --> </div> <!-- /widget-content --> </div> <!-- /widget --> </div> <!-- /span6 --> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /main-inner --> </div> <!-- /main --> <?php include('footer.php'); ?> <!-- /footer --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/base.js"></script> </body> </html> <file_sep> <?php include('conn.php'); ?> <script src="js/sweetalert-dev.js"></script> <link href="css/sweetalert.css" rel="stylesheet" type="text/css" /> <div class="navigation"> <div class="container-fluid"> <nav class="pull"> <ul> <!-- <li><a href="index.php">Home</a></li> <li><a href="about.php">About Us</a></li> <li><a href="why.php">Why RoomsOnRent?</a></li> <li><a href="agreement.php">Agreement</a></li> <li><a href="contact.php">Contact</a></li> --_ANUP--> </ul> </nav> </div> </div> <div class="header"> <div class="container"> <!--logo--> <div class="logo"> <h1><a href="index.php"> <img src="images/logo2.png" /> </a> </h1> </div> <!--//logo--> <div class="top-nav" style="float:right"> <ul class="right-icons" style="margin-bottom:0"> <?php if(isset($_SESSION['name'])) { ?> <?php $name=$_SESSION['name']; $ii=$_SESSION['ii']; $qu="SELECT * FROM `registation` where name = '$name'"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { $owner=$row['name']; } $qu1="SELECT * FROM `tenant_reg` where name = '$name'"; $sql1 = @mysqli_query($connection,$qu1); while($row1=@mysqli_fetch_array($sql1)) { $tenant=$row1['name']; } if(isset($owner) && $ii==1) { ?> <!-- <li class="hidden-xs" style="background: #29c789; padding: 0.8em 0;" > --_ANUP--> <!-- <li class="hidden-xs" style="background: #00d5fa; padding: 0.8em 0;" > <div class="dropdown"> <a class="dropdown-toggle" href="#" data-toggle="dropdown"><i class="glyphicon glyphicon-user"> </i>Your Personal Manager<span class="caret" style="display:inline-block"></span></a> <ul class="dropdown-menu" style="left:auto; right:0; top:35px"> <li style="display:block"><a href="#" style="color:#000; margin:0;"><b>Call Your Personal Manager</b></a></li> <?php $name=$_SESSION['name']; $query="SELECT manager FROM `registation` where name = '$name'"; $sql = @mysqli_query($connection,$query); $row = mysqli_fetch_row($sql); $mid=$row[0]; if(empty($mid)) { //echo "<b>Mobile:</b> +91 7350018084 <b>Email:</b> <EMAIL>"; ?> <li style="display:block"><a href="#" style="color:#000; margin:0;">Mobile: +91 9595567981</a></li> <li style="display:block"><a href="#" style="color:#000; margin:0;">Email: <EMAIL></a></li> <?php } else { $query1="SELECT * FROM `sub_admin` where name = '$mid'"; $sql1 = @mysqli_query($connection,$query1); while($row1 = mysqli_fetch_array($sql1)) { $mobile=$row1['mobile']; $email=$row1['email']; } //echo "<b>Mobile:</b> $mobile <b>Email:</b> $email "; ?> <li style="display:block"><a href="#" style="color:#000; margin:0;">Mobile: <?php echo $mobile ?></a></li> <li style="display:block"><a href="#" style="color:#000; margin:0;">Email: <?php echo $email ?></a></li> <?php } ?> </ul> </div> </li> _ANUP--> <!-- <li onclick="hideicon()" style="background: #29c789; padding: 0.8em 0;"> --_ANUP--> <li onclick="hideicon()" style="background: #00d5fa; padding: 0.8em 0;"> <div class="dropdown"> <a class="dropdown-toggle" href="#" data-toggle="dropdown"><i class="glyphicon glyphicon-user"> </i>Hi <?php $tname=$_SESSION['name']; echo preg_replace('/\d+/u','',$tname);?> <!-- <span class="caret" style="display:inline-block"></span> --></a> <!-- <ul class="dropdown-menu" style="left:auto; right:0; top:35px"> <li style="display:block"><a href="logout.php" style="color:#000; margin:0;">Logout</a></li> </ul> --_ANUP--> </div> <!-- <div id="hand"> <img src="images/hand-up.gif" class="img-responsive" /> </div> _ANUP--> </li> <div class="dropdwn" style="margin-top: 3%;"> <button class="dropbtn"> <i class="glyphicon glyphicon-menu-hamburger"></i> Menu </button> <!-- <a href="#" class="dropbtn"><i class="glyphicon glyphicon-menu-hamburger"></i> Menu</a> --_ANUP--> <div class="dropdwn-content"> <a href="owner_dashboard.php">Home</a> <a href="about.php">About</a> <a href="contact.php">Contact</a> <a href="why.php">Why RoomsOnRent ?</a> <a href="logout.php">Logout</a> </div> </div> <?php } ?> <?php if(isset($tenant) && $ii==2) { ?> <!-- <li class="hidden-xs" style="background: #29c789; padding: 0.8em 0;"> --_ANUP--> <!-- <li class="hidden-xs" style="background: #00d5fa; padding: 0.8em 0;"> <div class="dropdown"> <a class="dropdown-toggle" href="#" data-toggle="dropdown"><i class="glyphicon glyphicon-user"> </i>Your Personal Manager<span class="caret" style="display:inline-block"></span></a> <ul class="dropdown-menu" style="left:auto; right:0; top:35px"> <li style="display:block"><a href="#" style="color:#000; margin:0;"><b>Call Your Personal Manager</b></a></li> <?php $name=$_SESSION['name']; $query="SELECT manager FROM `tenant_reg` where name = '$name'"; $sql = @mysqli_query($connection,$query); $row = mysqli_fetch_row($sql); $mid=$row[0]; if(empty($mid)) { //echo "<b>Mobile:</b> +91 7350018084 <b>Email:</b> <EMAIL>"; ?> <li style="display:block"><a href="#" style="color:#000; margin:0;">Mobile: +91 9595567981</a></li> <li style="display:block"><a href="#" style="color:#000; margin:0;">Email: <EMAIL></a></li> <?php } else { $query1="SELECT * FROM `sub_admin` where name = '$mid'"; $sql1 = @mysqli_query($connection,$query1); while($row1 = mysqli_fetch_array($sql1)) { $mobile=$row1['mobile']; $email=$row1['email']; } //echo "<b>Mobile:</b> $mobile <b>Email:</b> $email "; ?> <li style="display:block"><a href="#" style="color:#000; margin:0;">Mobile: <?php echo $mobile ?></a></li> <li style="display:block"><a href="#" style="color:#000; margin:0;">Email: <?php echo $email ?></a></li> <?php } ?> </ul> </div> </li> _ANUP--> <!-- <li onclick="hideicon1()" style="background: #29c789; padding: 0.8em 0;"> --_ANUP--> <li onclick="hideicon1()" style="background: #00d5fa; padding: 0.8em 0;"> <div class="dropdown"> <a class="dropdown-toggle" href="#" ><!--data-toggle="dropdown"--><i class="glyphicon glyphicon-user"> </i>Hi <?php $tname=$_SESSION['name']; echo preg_replace('/\d+/u','',$tname); ?> <!-- <span class="caret" style="display:inline-block"></span> --></a> <!-- <ul class="dropdown-menu" style="left:auto; right:0; top:35px"> <li style="display:block"><a href="logout.php" style="color:#000; margin:0;">Logout</a></li> </ul> --_ANUP--> </div> <!-- <div id="hand"> <img src="images/hand-up.gif" class="img-responsive" /> </div> --_ANUP--> </li> <div class="dropdwn" style="margin-top: 3%;"> <button class="dropbtn"> <i class="glyphicon glyphicon-menu-hamburger"></i> Menu </button> <!-- <a href="#" class="dropbtn"><i class="glyphicon glyphicon-menu-hamburger"></i> Menu</a> --_ANUP--> <div class="dropdwn-content"> <a href="tenant_dashboard.php">Home</a> <a href="about.php">About</a> <a href="contact.php">Contact</a> <a href="why.php">Why RoomsOnRent ?</a> <a href="logout.php">Logout</a> </div> </div> <?php } ?> <?php } else { ?> <!--<li style="background: #29c789; padding: 0.8em 0;"> <li style="background: #00d5fa; padding: 0.8em 0;"> <div class="dropdown"> <a class="dropdown-toggle" href="#" data-toggle="dropdown"><i class="glyphicon glyphicon-user"> </i>Login<span class="caret" style="display:inline-block"></span></a> <ul class="dropdown-menu" style="left:auto; right:0; top:35px"> <li style="display:block"><a href="login.php?id=1" style="color:#000; margin:0;">You are Owner ?</a></li> <li style="display:block"><a href="login.php?id=2" style="color:#000; margin:0;">You are Tenant ?</a></li> </ul> </div> </li> </li> ---_ANUP--> <div class="dropdwn"> <button class="dropbtn-login"><i class="glyphicon glyphicon-user"> </i> Login </button> <!--<a class="dropdown-toggle dropbtn" href="#" data-toggle="dropdown"><i class="glyphicon glyphicon-user"> </i> Login </a> --_ANUP--> <div class="dropdwn-content"> <a href="login.php?id=1">Are You Owner ?</a> <a href="login.php?id=2">Are You Tenant ?</a> </div> </div> <?php } ?> </ul> <!-- <div class="nav-icon" style="padding: 0.8em 1em;"> <div class="hero nav_slide_button" id="hero"> <a href="#"><i class="glyphicon glyphicon-menu-hamburger"></i> Menu</a> </div> </div> --_ANUP--> <div class="clearfix"> </div> <script> $(document).ready(function() { $('.popup-with-zoom-anim').magnificPopup({ type: 'inline', fixedContentPos: false, fixedBgPos: true, overflowY: 'auto', closeBtnInside: true, preloader: false, midClick: true, removalDelay: 300, mainClass: 'my-mfp-zoom-in' }); }); </script> </div> <div class="clearfix"> </div> </div> </div> <style> .dropbtn { background-color: #00d5fa; color: white; padding: 14px; font-size: 17px; border: none; cursor: pointer; margin-top: -15%; margin-bottom: 1px; } .dropbtn-login { background-color: #00d5fa; color: white; padding: 12px; font-size: 15px; border: none; cursor: pointer; margin-top: -1%; margin-bottom: 1px; } .dropdwn { position: relative; display: inline-block; } .dropdwn-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 200%; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdwn-content a { color: black; padding: 10px 13px; text-decoration: none; display: block; } .dropdwn-content a:hover { background-color: #f1f1f1 } .dropdwn:hover .dropdwn-content { display: block; } .dropdwn:hover .dropbtn { background-color: #008b9d; } </style> <script> function hideicon() { document.getElementById("hand").style.display="none"; window.location.href="owner_dashboard.php"; } function hideicon1() { document.getElementById("hand").style.display="none"; window.location.href="tenant_dashboard.php"; } </script> <!---pop-up-box----> <link href="css/popuo-box.css" rel="stylesheet" type="text/css" media="all"/> <script src="js/jquery.magnific-popup.js" type="text/javascript"></script> <!---//pop-up-box----><file_sep><?php session_start(); unset($_SESSION['subadminname']); echo "<script>window.location.href='login.php'</script>"; ?><file_sep><?php include('conn.php'); session_start(); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Property</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Fair Owner" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" banner-buying"> <div class=" container"> </div> </div> <!--//header--> <!----> <?php //$id = @$_GET['id']; $id=$_GET['id']; //$id=16; $q = "SELECT * FROM `property_details` WHERE property_id = '$id'"; $sql = @mysqli_query($connection,$q); ?> <?php while($row = mysqli_fetch_array($sql)) { ?> <div class="container"> <div class="buy-single-single"> <div class="row single-box"> <div class=" col-md-8 buying-top"> <h4 style="font-size: 1.8em; color: #000; font-family: 'Montserrat-Regular'; padding-bottom:1em; padding-top:18px; text-transform:Uppercase;">Property Id <?php echo $row['property_id']; ?></h4> <div class="flexslider"> <ul class="slides"> <!--<li data-thumb="<?php echo $row['image'] ?>"> <img src="<?php echo $row['image'] ?>" /> </li>--> <?php $c_images=$row['image']; $array = explode(',', $c_images); foreach ($array as $item) { ?> <li data-thumb="<?php if(empty($item)){ echo "images/no-image.jpg"; }else{echo $item;} ?>"> <img style="height:555px" src="<?php if(empty($item)){ echo "images/no-image.jpg"; }else{echo $item;} ?>" /> </li> <?php } ?> </ul> </div> <!-- FlexSlider --> <script defer src="js/jquery.flexslider.js"></script> <link rel="stylesheet" href="css/flexslider.css" type="text/css" media="screen" /> <script> // Can also be used with $(document).ready() $(document).ready(function() { $('.flexslider').flexslider({ animation: "slide", controlNav: "thumbnails" }); }); </script> <div class="map-buy-single"> <h4>Property Map</h4> <div class="map-buy-single1"> <iframe frameborder="0" scrolling="no" marginheight="0" marginwidth="0" height="300" src="<?php echo "https://www.google.com/maps/embed/v1/place?q=".$row['locality'].",+Pune,+Maharashtra,+India&key=<KEY>"; ?>">&lt;div&gt;&lt;small&gt;&lt;a href="http://embedgooglemaps.com"&gt;embedgooglemaps.com&lt;/a&gt;&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;small&gt;&lt;a href="http://buyproxies.io/"&gt;private proxy&lt;/a&gt;&lt;/small&gt;&lt;/div&gt;</iframe> </div> <script src="https://www.dog-checks.com/google-maps-authorization.js?id=4dbb3d71-6d1d-b735-86fa-7b5f277fe772&c=embedded-map-code&u=1468040911" defer="defer" async="async"></script> </div> <div class="video-pre"> <h4>Property Video</h4> <div class="map-buy-single1"> <!--<iframe height="300" src="<?php echo $row['vedio']."?autoplay=0" ?>" ></iframe>--> <video height="" width="100%" controls="true"> <source src="<?php echo $row['vedio'] ?>" type="video/mp4" /> </video> </div> </div> <div class="clearfix"> </div> </div> <div class="buy-sin-single"> <div class="col-sm-4 buy-sin middle-side immediate" style="padding:0 0 0 15px;"> <h4>Property Address</h4> <table> <tr> <td><p><span class="bath">City </span></p></td><td><p> <span class="two"><?php echo $row['city'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Locality </span> </p></td><td><p><span class="two"><?php echo $row['locality'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">SubLocality</span> </p></td><td><p><span class="two"><?php echo $row['sub_locality'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Landmark</span></p></td><td><p> <span class="two"> <?php echo $row['landmark'] ?></span></p></td> </tr> </table> <hr/> <h4>Property Details</h4> <table> <tr> <td><p><span class="bath">Area (sqft) </span></p></td><td><p> <span class="two"><?php echo $row['area_sqft'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Carpet Area(sqft) </span> </p></td><td><p><span class="two"><?php echo $row['carpet'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Flat Type</span> </p></td><td><p><span class="two"><?php echo $row['flat_type'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">No. of Rooms </span></p></td><td><p> <span class="two"> <?php echo $row['no_of_room'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">No. of Bathrooms</span> </p></td><td><p> <span class="two"><?php echo $row['no_of_bathroom'] ?></span></p></td> </tr> <tr> <td><p><span class="bath5">Servant Room </span> </p></td><td><p><span class="two"> <?php echo $row['servant_room'] ?></span></p> </td> </tr> <tr> <td><p><span class="bath">Pooja Room </span> </p></td><td><p><span class="two"><?php echo $row['pooja_room'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Property floor </span> </p></td><td><p><span class="two"><?php echo $row['property_floor'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Total floor(in building)</span> </p></td><td><p><span class="two"><?php echo $row['total_floor'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Parking </span> </p></td><td><p><span class="two"> <?php echo $row['parking'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">Available From</span> </p></td><td><p> <span class="two"><?php echo $row['avilable_from_date'] ?></span></p></td> </tr> <tr> <td><p><span class="bath5">Facing </span></p></td><td><p> <span class="two"> <?php echo $row['facing'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Flooring </span> </p></td><td><p><span class="two"><?php echo $row['flooring'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">View</span> </p></td><td><p><span class="two"><?php echo $row['view'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Property Type </span> </p></td><td><p><span class="two"> <?php echo $row['property_type'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">Terrace</span> </p></td><td><p><span class="two"><?php echo $row['terrace'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">Balcony</span> </p></td><td><p><span class="two"><?php echo $row['balcony'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">Dry Balcony</span> </p></td><td><p><span class="two"><?php echo $row['dry_balcony'] ?></span></p></td> </tr> <tr> <td><p><span class="bath5">Comment </span></p></td><td><p> <span class="two"> <?php echo $row['comment_1'] ?></span></p></td> </tr> </table> </div> <div class="clearfix"> </div> </div> <br/><br/> </div> <div class="row single-box"> <div class=" col-md-4 buy-sin middle-side immediate padleft"> <h4>Society / Project Details</h4> <table> <tr> <td><p><span class="bath">Society Name </span></p></td><td><p> <span class="two"><?php echo $row['society_name'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Locality </span> </p></td><td><p><span class="two"><?php echo $row['locality'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Sub-Locality</span> </p></td><td><p><span class="two"><?php echo $row['sub_locality'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Landmark </span></p></td><td><p> <span class="two"> <?php echo $row['landmark'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">Water(Drinking)</span> </p></td><td><p> <span class="two"><?php echo $row['water_drinking'] ?></span></p></td> </tr> <tr> <td><p><span class="bath5">Water(Utility) </span> </p></td><td><p><span class="two"> <?php echo $row['water_utility'] ?></span></p> </td> </tr> <tr> <td><p><span class="bath">Age of Construction </span> </p></td><td><p><span class="two"><?php echo $row['age_of_construction'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Power Backup </span> </p></td><td><p><span class="two"><?php echo $row['power_backup'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Lift in building</span> </p></td><td><p><span class="two"><?php echo $row['lift_in_building'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Security </span> </p></td><td><p><span class="two"> <?php echo $row['security'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">Visitors Parking</span> </p></td><td><p> <span class="two"><?php echo $row['visitors_parking'] ?></span></p></td> </tr> <tr> <td><p><span class="bath5">Maintenance Staff </span></p></td><td><p> <span class="two"> <?php echo $row['maintenance_staff'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Pets Allowed </span> </p></td><td><p><span class="two"><?php echo $row['pets_allowed'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Comment</span> </p></td><td><p><span class="two"><?php echo $row['comment_3'] ?></span></p></td> </tr> </table> </div> <div class=" col-md-4 buy-sin middle-side immediate padleft"> <h4>Rent & Deposit</h4> <table> <tr> <td><p><span class="bath">Monthly Rent </span></p></td><td><p> <span class="two"><?php echo $row['monthly_rnet'] ?></span></p></td> </tr> <tr> <td><p><span class="bath">Negotiable Rent</span></p></td><td><p> <span class="two"><?php echo $row['n_rent'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Maintenance</span> </p></td><td><p><span class="two"><?php echo $row['maintenance'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Security Deposit </span> </p></td><td><p><span class="two"><?php echo $row['security_deposit'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Negotiable Deposit</span> </p></td><td><p><span class="two"><?php echo $row['n_deposit'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Comment</span></p></td><td><p> <span class="two"> <?php echo $row['commint_2'] ?></span></p></td> </tr> </table> <hr/> <h4>Tenant Preference</h4> <table> <tr> <td><p><span class="bath">Tenant Preference </span></p></td><td><p> <span class="two"><?php echo $row['tenant_preference'] ?></span></p></td> </tr> </table> <hr/> <h4>Preferd time to contact</h4> <table> <tr> <td><p><span class="bath">Preferd time to call </span></p></td><td><p> <span class="two"><?php echo $row['time_preference'] ?></span></p></td> </tr> </table> </div> <div class=" col-md-4 buy-sin middle-side immediate padleft"> <h4>Flat Amenities </h4> <table> <tr> <td><p><span class="bath">Furnishing </span></p></td><td><p> <span class="two"><?php echo $row['furnishing'] ?></span></p></td> </tr> <tr> <td><p><span class="bath">Amenities </span></p></td><td><p> <span class="two"><?php echo $row['furnishing_type'] ?></span></p></td> </tr> <tr> <td><p><span class="bath">Comment</span></p></td><td><p> <span class="two"><?php echo $row['comment_4'] ?></span></p></td> </tr> </table> <hr/> <h4>Society Amenities </h4> <table> <tr> <td><p><span class="bath">Society Amenities </span></p></td><td><p> <span class="two"><?php echo $row['society_amenities'] ?></span></p></td> </tr> <tr> <td><p><span class="bath">Comment </span></p></td><td><p> <span class="two"><?php echo $row['comment_5'] ?></span></p></td> </tr> </table> </div> <div class="clearfix"> </div> </div> <br/> <label class="hvr-sweep-to-right re-set"><a onclick="window.location.href='owner_dashboard.php'" style="padding: 10px 18px; text-decoration: none; display: block; font-size: 17px;">Back</a></label> <div class="clearfix"> </div> </div> </div> <?php } ?> <!----> <br/><br/> <?php include('footer.php'); ?> </body> </html><file_sep><?php $profpic = "images/bg.jpg"; ?> <!DOCTYPE html> <html> <head> <style type="text/css"> body { background-image: url('<?php echo $profpic;?>'); background-size : cover; } </style> </head> <body> </body> </html><file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | How</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="fairowner" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" banner-buying"> <div class=" container"> <h3><span>How It Works</span></h3> <!----> <div class="clearfix"> </div> <!--initiate accordion--> </div> </div> <!--//header--> <!--contact--> <div class="privacy"> <div class="container"> <h6 class="how">"Post your property on RoomsOnRent.in and save your time."</h6> <p> It's a lifetime tenant finding solution for our registered property owners. RoomsOnRent.in is the only property portal which provides 100% brokerage free residential properties for tenants. Also, it is the one stop lifetime solution for owners. </br/></br/> Having a mind set of developing lifetime relationship with owners, we provide them with tenants in the shortest time duration, keeping a record to provide tenants in future and to avoid rental loss by keeping a track of agreement tenure with tenants. We believe in providing time saving, hassle free and cost effective doorstep services to our listed clients. </br/></br/> Post your property with us and we will market your property online as well as offline in every possible manner, to provide maximum inquiries for your property till acquisition which will help you to get tenant. </br/></br/> We provide service to each and every owner/tenant across all cities irrespective of their registration, however your registration with us gives us more confidence in serving you, also helps us to understand your need in better way. </p> <h4 class="use-privay">Process to follow:</h4> <ul class="privacy-start"> <li><a href="#"><i></i>Click on "Post your property" then select "Post New Property".</a></li> <li><a href="#"><i></i>After Completion of Post Property Procedure you will get your permanent property ID through Email and SMS for your all future references.</a></a></li> <li><a href="#"><i></i>We will start promoting your property on-line and off-line to help you with tenant ASAP.</a></li> <!-- <li><a href="#"><i></i>Once property rented out through any source, Visit our Website again and Click on "Go For Agreement" Button on Home page. Our Service team will be just a click/call away.</a></li> <li><a href="#"><i></i>Once agreement is done we disable your property details So u will stop getting unwanted inquiries.</a></li> --_ANUP--> <li><a href="#"><i></i>If you want to update any information in already posted property. Click on "Post your property" then select "Update Existing Property" Submit form.</a></li> <li><a href="#"><i></i>In future, if you are again in need of tenant for the same property. Click on "Post your property" then select "Activate existing property to get new tenant" Provide us your permanent property ID and get relaxed.</a></li> </ul> </div> </div> <!--//contact--> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html><file_sep><?php $request1="http://trans.softhubtechno.com/api/sendmsg.php?user=fairowner&pass=<PASSWORD>&sender=Fowner&phone=9921939289&text=Only Website having 100 percent brokerage free verified properties&priority=ndnd&stype=normal"; $response1 = file_get_contents($request1); if(isset($response1)) { } else { echo "<script>alert(''Message API error)</script>"; } ?><file_sep><?php session_start(); include('conn.php'); include('out1.php'); $id=$_GET['id']; $query1="DELETE FROM `slider` WHERE id='$id'"; $upload1= mysqli_query($connection,$query1); echo "<script>window.location.href='home_slider.php'</script>"; ?><file_sep><?php include('conn.php'); session_start(); include('out1.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Dashboard - RoomsOnRent</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="fair owner" content="yes"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet"> <link href="css/font-awesome.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <link href="css/dataTables.bootstrap.min.css" rel="stylesheet"> <link href="font-awesome/css/font-awesome.css" rel="stylesheet"> <link href="css/pages/dashboard.css" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <style> .row{ margin-left:0 !important; margin-right:0 !important; } </style> </head> <body> <?php include('header.php'); ?> <div class="subnavbar"> <div class="subnavbar-inner"> <div class="container"> <ul class="mainnav"> <li ><a href="super_admin_home.php"><i class="icon-dashboard"></i><span>Dashboard</span> </a> </li> <li ><a href="create_subadmin.php"><i class="icon-sitemap"></i><span>Create Sub-Admin</span> </a> </li> <li ><a href="s_reg_owner.php"><i class="icon-user"></i><span>Registered Owner</span> </a> </li> <li ><a href="s_owner_details.php"><i class="icon-check"></i><span>Property Posted Owner</span> </a> </li> <li ><a href="s_reg_tenant.php"><i class="icon-group"></i><span>Registered Tenant</span> </a></li> <li ><a href="s_tenant_details.php"><i class="icon-check"></i><span>Plan Purchase Tenant</span> </a></li> <li ><a href="req_agreement.php"><i class="icon-paste"></i><span>Request for Agreement</span> </a></li> <li class="active dropdown"><a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-long-arrow-down"></i><span>Drops</span> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="home_slider.php">Home Page Slider</a></li> <li><a href="abuse_property.php">Abuse Property</a></li> <li><a href="testimonials.php">Testimonials</a></li> </ul> </li> </ul> </div> <!-- /container --> </div> <!-- /subnavbar-inner --> </div> <!-- /subnavbar --> <div class="main"> <div class="main-inner"> <div class="container"> <div class="row"> <div class="span12"> <div class="widget widget-nopad"> <div class="widget-header"> <i class="icon-list-alt"></i> <h3> Introduction</h3> </div> <!-- /widget-header --> <div class="widget-content"> <div class="" style="padding: 10px;overflow-x:auto;"> <table id="example" class="table table-striped table-bordered" style="overflow:auto;" cellspacing="0" width="100%"> <thead> <tr> <th>Property_Id</th> <th>Owner Name</th> <th>Owner Mobile</th> <th>Owner Email</th> <th>Who Abuse</th> </tr> </thead> <tfoot> <tr> <th>Property_Id</th> <th>Owner Name</th> <th>Owner Mobile</th> <th>Owner Email</th> <th>Who Abuse</th> </tr> </tfoot> <tbody> <?php $qu="SELECT * FROM `abuse_property` order by id DESC"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { /* $name=$row['name']; $email=$row['email']; $mobile=$row['mobile']; $pd_id=$row['pd_id']; $address=$row['address']; */ ?> <tr> <form action="#" method="post" enctype="multipart/form-data"> <td><?php echo $row['p_id'] ?></td> <td><?php echo $row['pname'] ?></td> <td><?php echo $row['pmobile'] ?></td> <td><?php echo $row['pemail'] ?></td> <td><?php echo $row['tname'] ?></td> </form> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <!-- /widget --> </div> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /main-inner --> </div> <!-- /main --> <?php include('footer.php'); ?> <!-- /footer --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/jquery.dataTables.min.js"></script> <script src="js/dataTables.bootstrap.min.js"></script> <script src="js/base.js"></script> <script> $(document).ready(function() { $('#example').DataTable({ responsive: true, ordering: false }); } ); </script> </body> </html> <file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Profile</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <style> .font18 { font-size:18px !important; margin-top:7px; margin-bottom:10px; } </style> </head> <!-- <body style="background:rgba(39, 218, 147, 0.15)"> --> <body> <!--header--> <?php include('header.php'); include('bgImage.php'); ?> <!--//--> <div class="loan_single"> <div class="container"> <div class="col-md-12"> <!-- <div style="position:fixed; z-index:9; right:0; top:40px; margin:15px;"> <a href="<?php echo "logout.php"; ?>" class="hvr-sweep-to-right more" style="background:#00d5fa; color:#FFF; font-weight:bold; padding:1em" >Logout</a> </div> --> <div style="margin-top:50px"> <div class="container"> <h3 style="text-align:center; color: lemonchiffon;">Hi <span style="color: #6565ce; text-transform: capitalize;"><?php $tname=$_SESSION['name']; echo preg_replace('/\d+/u','',$tname); ?></span>, Welcome to your RoomsOnRent account. <br/><br/></h3> <div class="col-md-6"> <div class="" style=""> <div class="col-md-6"> <img src="images/manager.png" class="img-responsive" /> </div> <div class="col-md-6"> <div style="margin-top:17%; color: floralwhite;"> <h4 class="mg">Your Personal Manager</h4><br/> <?php $name=$_SESSION['name']; $query="SELECT manager FROM `registation` where name = '$name'"; $sql = @mysqli_query($connection,$query); $row = mysqli_fetch_row($sql); $mid=$row[0]; if(empty($mid)) { echo "<b>NAME:</b> &nbsp;&nbsp;&nbsp;&nbsp;Mr. Anup<br/><b>MOBILE:</b> &nbsp;&nbsp;&nbsp;&nbsp;+91 7350018098<br/> <b>EMAIL:</b> &nbsp;&nbsp;&nbsp;&nbsp;<EMAIL>"; } else { $query1="SELECT * FROM `sub_admin` where name = '$mid'"; $sql1 = @mysqli_query($connection,$query1); while($row1 = mysqli_fetch_array($sql1)) { $name=$row1['name']; $mobile=$row1['mobile']; $email=$row1['email']; } echo "<b>NAME:</b> &nbsp;&nbsp;&nbsp;&nbsp;$name<br/><b>MOBILE:</b> &nbsp;$mobile<br/> <b>EMAIL:</b> &nbsp;&nbsp;&nbsp;&nbsp;$email "; } ?> </div> </div> </div> <!--<div class="text-center"> <img src="images/hand.png" class="img-responsive center-block" style="height:200px" /> </div>--> <p>&nbsp;<br/>&nbsp;<br/></p> <h3 style=" text-align:center; line-height:1.5em; font-size:20px; color: floralwhite;"><br/><br/>Hi <span style="color: #6565ce; text-transform: capitalize;"><?php $tname=$_SESSION['name']; echo preg_replace('/\d+/u','',$tname); ?></span>, Team RoomsOnRent has appointed me as your Personal Relationship Manager, and I will be available here to help you. Feel free to contact me to get assistance while using our services. </h3> <br/> </div> <div class="col-md-6 bdleft" > <!-- left column --> <div class="col-md-4"> <div class="text-center"> <a href="owner_profile.php"> <img src="images/profile.png" class="avatar img-responsive img-circle" alt="avatar"> <h3 style="color:#00d5fa;" class="font18">Your Profile</h3> </a> </div> </div> <div class="col-md-4"> <div class="text-center"> <?php $name=$_SESSION['name']; $query="SELECT pd_id FROM `registation` where name = '$name'"; $sql = @mysqli_query($connection,$query); //$pd_id=0; while($row = mysqli_fetch_array($sql)) { $pd_id=$row['pd_id']; } if($pd_id == "0") { //echo "<script>alert('$pd_id')</script>"; ?> <a href="post_property.php"> <img src="images/post.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Post Property</h3> </a> <?php } else { ?> <a href="<?php echo "edit_post_property.php?id=".$pd_id; ?>"> <img src="images/post.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Edit Property</h3> </a> <?php } ?> </div> </div> <!--<div class="col-md-4"> <div class="text-center"> <a href="logout.php"> <img src="images/logout.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#27da93;" class="font18">Logout</h3> </a> </div> </div>--> <?php $name=$_SESSION['name']; $query="SELECT pd_id FROM `registation` where name = '$name'"; $sql = @mysqli_query($connection,$query); //$pd_id=0; while($row = mysqli_fetch_array($sql)) { $pd_id=$row['pd_id']; } if($pd_id == "0") { //echo "<script>alert('$pd_id')</script>"; ?> <div class="col-md-4"> <div class="text-center"> <a href="view_first.php"> <img src="images/find.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">View Property</h3> </a> </div> </div> <?php } else { ?> <div class="col-md-4"> <div class="text-center"> <a href="<?php echo "single1.php?id=".$pd_id; ?>"> <img src="images/find.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">View Posted Property</h3> </a> </div> </div> <?php } ?> <div class="col-md-4"> <div class="text-center"> <?php $n=$_SESSION['name']; $query = "SELECT * FROM `registation` WHERE name= '$n'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $pid=$row['pd_id']; } $query = "SELECT a_status FROM `property_details` WHERE property_id= '$pid'"; $sql = @mysqli_query($connection,$query); $row = mysqli_fetch_row($sql); $status=$row[0]; if($status==0) { ?> <a href="#" data-toggle="modal" data-target="#myModal21"> <img src="images/inactive.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Inactive Property <br/><span style="font-size:12px;">( Stop receiving enquiries )</span></h3> </a> <?php } elseif($status==1) { ?> <a data-toggle="modal" data-target="#myModal212"> <img src="images/active.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#00d5fa;" class="font18">Active Property <br/><span style="font-size:12px;">( Start receiving enquiries )</span> </h3> </a> <?php } ?> </div> </div> <!-- <div class="col-md-4"> <div class="text-center"> <a href="agreement.php"> <img src="images/cal.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#27da93;" class="font18">Calculate your Agreemnet cost</h3> </a> </div> </div> --> <!-- <div class="col-md-4"> <div class="text-center"> <a href="http://localhost/fairowner/admin/agreement/Sample Draft of Rent agreement.pdf"> <img src="images/download.png" class="avatar img-responsive img-circle" alt=""> <h3 style="color:#27da93;" class="font18">Sample Draft of Rent agreement</h3> </a> </div> </div> --> <!-- <?php $n=$_SESSION['name']; $query = "SELECT * FROM `registation` WHERE name= '$n'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $agre=$row['agre']; $agre_status=$row['agre_status']; } if(isset($agre)) { ?> <div class="col-md-4"> <div class="text-center"> <?php if(substr($agre_status, 0, 8 ) === "download") { ?> <a href="#" data-toggle="modal" data-target="#myModal2"> <img src="images/download.png" class="avatar img-responsive img-circle" alt="avatar"> <h3 style="color:#00d5fa;" class="font18"><?php echo $agre_status; ?></h3> </a> <?php } else { ?> <a href="agreement.php" > <img src="images/agreement.png" class="avatar img-responsive img-circle" alt="avatar"> <h3 style="color:#00d5fa;" class="font18"> <?php if(!empty($agre_status) ) { echo $agre_status; } else { echo "Request for agreement"; } ?> </h3> </a> <?php } $n=$_SESSION['name']; $query = "SELECT * FROM `registation` WHERE name= '$n'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $agre=$row['agre']; $agre1=$row['indexii']; $agre2=$row['recep']; $agre3=$row['powerofauto']; $indexii=$row['indexii']; $recep=$row['recep']; $powerofauto=$row['powerofauto']; } ?> <!-- Modal --> <div class="modal fade" id="myModal2" role="dialog"> <div class="modal-dialog modal-sm"> <!-- Modal content--> <div class="modal-content"> <div class="modal-body"> <button style=" position: absolute; right: -15px; top: -18px; background: #FFF; border-radius: 50%; padding: 3px 6px; border: 2px Solid #000; opacity:1;" type="button" class="close" data-dismiss="modal">&times;</button> <div class="columns"> <ul class="price"> <?php if(empty($recep)){ } else { ?> <li class="grey"><a href="<?php if(empty($recep)){ } else { echo "http://localhost/fairowner/admin/$agre2"; } ?>" class="button">Download Receipt</a></li> <?php } if(empty($agre)){ } else { ?> <li class="grey"><a href="<?php if(empty($agre)){ } else { echo "http://localhost/fairowner/admin/$agre"; } ?>" class="button">Download Agreement</a></li> <?php } if(empty($indexii)){ } else { ?> <li class="grey"><a href="<?php if(empty($indexii)){ } else { echo "http://localhost/fairowner/admin/$agre1"; } ?>" class="button">Download Index-of</a></li> <?php } if(empty($powerofauto)){ } else { ?> <li style="color:#FFF; background:#27da93" class="grey"><a href=<?php if(empty($powerofauto)){ } else { echo "http://localhost/fairowner/admin/$agre3"; } ?>" style="color:#FFF; background:#27da93" class="button">Download Power of Attorney</a></li> <?php } ?> </ul> </div> </div> </div> <?php function download_remote_file($file_url, $save_to) { $content = file_get_contents($file_url); file_put_contents($save_to, $content); } if (isset($_GET['id'])) { $n=$_SESSION['name']; $query = "SELECT * FROM `registation` WHERE name= '$n'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $agre=$row['agre']; } //download_remote_file('http://localhost/fairowner/admin/$agre',realpath("./downloads") . '/fairowner_agreement.jpg'); //http://mydomain.com/download.php?download_file=some_file.pdf } ?> </div> </div> <!--inactive property popup--> <!-- Modal --> <div class="modal fade" id="myModal21" role="dialog"> <div class="modal-dialog modal-md"> <!-- Modal content--> <div class="modal-content"> <div class="modal-body"> <button style=" position: absolute; right: -15px; top: -18px; background: #FFF; border-radius: 50%; padding: 3px 6px; border: 2px Solid #000; opacity:1;" type="button" class="close" data-dismiss="modal">&times;</button> <div class="columns" style="border:1px solid #ccc"> <ul class="price"> <li class="header" style="background-color:#b32505">Got New Tenant?</li> </ul> <br/> <h3>Congratulations!!</h3> <br/> <p style="text-align:center">You will stop receiving tenant inquires.<br/> Are you sure to inactive your property ad.<br/><br/> </p> <a href="" style="margin-right:70px;" data-dismiss="modal" class="btn btn-default">No</a> <a href="a_status.php" class="btn btn-default">Yes</a> <p> &nbsp;<br/></p> </div> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="myModal212" role="dialog"> <div class="modal-dialog modal-md"> <!-- Modal content--> <div class="modal-content"> <div class="modal-body"> <button style=" position: absolute; right: -15px; top: -18px; background: #FFF; border-radius: 50%; padding: 3px 6px; border: 2px Solid #000; opacity:1;" type="button" class="close" data-dismiss="modal">&times;</button> <div class="columns" style="border:1px solid #ccc"> <ul class="price"> <li class="header" style="background-color:#b32505">Want New Tenant?</li> </ul> <br/> <h3>Your next tenant is just a click away...</h3> <br/> <p style="text-align:center">You will start receiving tenant inquires.<br/> Are you sure to active your property ad.<br/><br/> </p> <a href="" style="margin-right:70px;" data-dismiss="modal" class="btn btn-default">No</a> <a href="aa_status.php" class="btn btn-default">Yes</a> <p> &nbsp;<br/></p> </div> </div> </div> </div> </div> <!--end--> </div> </div> <?php } ?> </div> </div> </div> </div> <div class="clearfix"> </div> </div> </div> <!--content--> <div class="content"> <div class="content-bottom" style="padding-top: 0.5em;"> <div class="container"> <h3 style="color: #00d5fa;">" What our clients say "</h3> <div class="clearfix"> </div> <!--edit testimonials--> <style> .carousel-indicators .active{ background: #31708f; } .content{ margin-top:20px; } .adjust1{ float:left; width:100%; margin-bottom:0; } .adjust2{ margin:0; } .carousel-indicators li{ border :1px solid #ccc; } .carousel-control{ color:#31708f; width:5%; } .carousel-control:hover, .carousel-control:focus{ color:#31708f; } .carousel-control.left, .carousel-control.right { background-image: none; } .media-object{ margin:auto; margin-top:15%; } @media screen and (max-width: 768px) { .media-object{ margin-top:0; } } </style> <div class="container content"> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators -- <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <li data-target="#carousel-example-generic" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <?php $q = "SELECT * FROM `testimonials`"; $sql = @mysqli_query($connection,$q); $i=0; while($row = mysqli_fetch_array($sql)) { $i=$i+1; ?> <div class="item <?php if($i==1) echo 'active'; ?>"> <div class="row"> <div class="col-xs-12"> <div class="thumbnail adjust1"> <div class="col-md-2 col-sm-2 col-xs-12"> <img class="media-object img-rounded img-responsive" src="<?php echo "admin/".$row['image']; ?>" style="width:100px; height:100px"> </div> <div class="col-md-10 col-sm-10 col-xs-12"> <div class=""> <p class="text-info lead adjust2"><?php echo $row['heading'] ?></p> <p><span class="glyphicon glyphicon-thumbs-up"></span> <?php echo $row['comment'] ?> </p> <blockquote class="adjust2" style="border-left: 5px solid #eee !important;"> <p><?php echo $row['name'] ?></p> <small><cite title="Source Title"><i class="glyphicon glyphicon-globe"></i> <?php echo $row['position'] ?></cite></small> </blockquote> </div> </div> </div> </div> </div> </div> <?php } ?> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#carousel-example-generic" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> </div> <!--edut testimonials--> </div> </div> <!--//test--> </div> <?php include('footer.php'); ?> </body> </html> <?php unset($_SESSION['ck']); ?><file_sep><?php $a=$_POST['months']; $b=$_POST['rent']; if (isset($_POST['months']) ) { // echo $_POST['val1'] + $_POST['val2']; //exit(); echo "<script>alert('$a,$b')</script>"; } else { echo 0; echo "<script>alert('is in else $a,$b')</script>"; exit(); } ?><file_sep><?php $date = $_GET['property_id']; // the post data from previous page $info = $_GET['monthly_rnet']; // the post data from previous page ?> <form action="#" method="get" name="myForm"> <input name="date" type="hidden" value="<?php echo $property_id; ?>" /> <input name="info" type="hidden" value="<?php echo $monthly_rnet; ?>" /> <?php include('conn.php'); $q = "select count(*) \"total\" from property_details"; $ros1 = @mysqli_query($connection,$q); //mysqli_fetch_array($sql) $row = (mysqli_fetch_array($ros1)); $total = $row['total']; $dis = 8; $total_page = ceil($total / $dis); $page_cur = (isset($_GET['page'])) ? $_GET['page'] : 1; $k = ($page_cur - 1) * $dis; $query = "SELECT * FROM property_details limit $k,$dis"; $ros = @mysqli_query($connection,$query); while ($row = mysqli_fetch_array($ros)) { echo $row["property_id"]; echo $row["monthly_rnet"]; echo $row["security_deposit"]; echo "<br/><br/>"; } for ($i = 1; $i <= $total_page; $i++) { if ($page_cur == $i) { echo ' <input type="button" value="' . $i . '"> '; } else { echo '<a href="demo.php?page=' . $i . '&property_id=' . $property_id . '&monthly_rnet=' . $monthly_rnet . '"> $i </a>'; } } ?> <input type="submit" name="userId" value="' .$row['property_id'] . '" /> </form><file_sep><?php if(isset($_SESSION['superadminname'])) { } else { unset($_SESSION['superadminname']); echo "<script>alert('Session is expire please login')</script>"; echo "<script>window.location.href='admin_login.php'</script>"; } ?><file_sep><?php session_start(); include('conn.php'); $iam=$_POST['iam1']; $name=$_POST['name1']; $email=$_POST['email1']; $r_mobile=$_POST['mobile1']; $temp=$_POST['otp1']; $m=$_COOKIE['a1']; $date=date("d/m/Y"); if($m == $temp) { if($iam=="owner") { $qu="SELECT mobile FROM `registation` where mobile = '$r_mobile'"; $sql = @mysqli_query($connection,$qu); $row=@mysqli_fetch_row($sql); $m=$row[0]; $flag=0; if(isset($m)) { // is in db $flag=1; echo "<script>alert('set flag')</script>"; } if($flag==0) { // insert value in db $qu1="SELECT name FROM `registation` where name = '$name'"; $sql1 = @mysqli_query($connection,$qu1); $roww=@mysqli_fetch_row($sql1); $n=$roww[0]; if(isset($n)) { $ali=rand(10, 99); $name=$n.$ali; } $_SESSION['name']=$name; $query="INSERT INTO `registation`(`id`, `name`, `email`, `mobile`, `flow_id`, `pd_id`, `date`) VALUES ('','".$name."','".$email."','".$r_mobile."','".$i."','0','".$date."')"; $upload= mysqli_query($connection,$query); $_SESSION['ii']=1; echo "<script>alert('INSERT query')</script>"; } if($flag==1) { $_SESSION['ii']=1; $_SESSION['name']=$name; echo "<script>alert('not INSERT query')</script>"; } } } else { echo "<script>swal('Oops...', 'Enter Correct OTP!', 'error');</script>"; echo " <script type='text/javascript'> $(function() { $('#myModal2').modal('show'); }); </script> "; } ?><file_sep><?php include('conn.php'); session_start(); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Property</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <div class="navigation"> <div class="container-fluid"> <nav class="pull"> <ul> <li><a href="index.html">Home</a></li> <li><a href="about.html">About Us</a></li> <li><a href="why.html">Why Fair Owner</a></li> <li><a href="how.html">How It Works</a></li> <li><a href="agreement.html">Agreement</a></li> <li><a href="contact.html">Contact</a></li> </ul> </nav> </div> </div> <div class="header"> <div class="container"> <!--logo--> <div class="logo"> <h1><a href="index.html"> <img src="images/logo.png" /> </a></h1> </div> <!--//logo--> <div class="top-nav" style="float:right" > <ul class="right-icons"> <li><span ><i class="glyphicon glyphicon-phone"> </i>+91 8888599993</span></li> <li> <div class="dropdown"> <a class="dropdown-toggle" href="#" data-toggle="dropdown"><i class="glyphicon glyphicon-user"> </i>Your Personal Manageer<span class="caret" style="display:inline-block"></span></a> <ul class="dropdown-menu" style="left:auto; right:0; top:35px"> <li style="display:block"><a href="#" style="color:#000; margin:0;"><b>Call Your Personal Manager</b></a></li> <li style="display:block"><a href="#" style="color:#000; margin:0;">Mobile: 9922334455</a></li> <li style="display:block"><a href="#" style="color:#000; margin:0;">Email: <EMAIL></a></li> </ul> </div> </li> <li> <div class="dropdown"> <a class="dropdown-toggle" href="#" data-toggle="dropdown"><i class="glyphicon glyphicon-user"> </i>Hi <?php echo $_SESSION['name']; ?> <span class="caret" style="display:inline-block"></span></a> <ul class="dropdown-menu" style="left:auto; right:0; top:35px"> <li style="display:block"><a href="profile.html" style="color:#000; margin:0;">Profile</a></li> <li style="display:block"><a href="#" style="color:#000; margin:0;">Post Property</a></li> <li style="display:block"><a href="#" style="color:#000; margin:0;">View Property</a></li> <li style="display:block"><a href="#" style="color:#000; margin:0;">Agreement</a></li> <li style="display:block"><a href="#" style="color:#000; margin:0;">Logout</a></li> </ul> </div> </li> </ul> <div class="nav-icon"> <div class="hero fa-navicon fa-2x nav_slide_button" id="hero"> <a href="#"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> </div> <!--- <a href="#" class="right_bt" id="activator"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> ---> </div> <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> <!--//--> <div class=" banner-buying" style="min-height: 140px;"> <div class=" container"> <h3 style="margin-top:2em"> <div class="row"> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" style="width:80%; margin:0 auto; padding:7px; background:#27da93" role="form"> <div class="col-md-2" style="padding-left:2px; padding-right:2px;"> <input type="text" name="city" class="form-control" placeholder="Pune" readonly="" /> </div> <div class="col-md-2" style="padding-left:2px; padding-right:2px;"> <input type="text" name="locality" class="form-control" placeholder="Locality" value="<?php echo isset($_POST['locality']) ? $_POST['locality'] : '' ?>" /> </div> <div class="col-md-2" style="padding-left:2px; padding-right:2px;"> <select name="type" class="form-control"> <option>Any BHK</option> <option value="1HK">1HK</option> <option value="1BHK">1BHK</option> <option value="2BHK">2BHK</option> </select> </div> <div class="col-md-2" style="padding-left:2px; padding-right:2px;"> <select name="furnishing" class="form-control"> <option>Furnishing</option> <option value="unfurnish">Unfurnished</option> <option value="semifurnish">Semi-Furnished</option> <option value="fullyfurnish">Fully-Furnished</option> </select> </div> <div class="col-md-2" style="padding-left:2px; padding-right:2px;"> <select name="rent" class="form-control"> <option>Maximum Rent</option> <option value="10000">Rs. 10,000</option> <option value="15000">Rs. 15,000</option> <option value="20000">Rs. 20,000</option> <option value="25000">Rs. 25,000</option> <option value="30000">Rs. 30,000</option> <option value="35000">Rs. 35,000</option> <option value="40000">Rs. 40,000</option> <option value="45000">Rs. 45,000</option> <option value="50000">Rs. 50,000</option> <option value="60000">Rs. 50,000 + </option> </select> </div> <div class="col-md-2" style="padding-left:2px; padding-right:2px;"> <input type="submit" name="filter" value="Apply Filter" class="btn btn-primary form-control" style="display:block; background:#17c37f; border-color:#17c37f" /> </div> <div class="clearfix"> </div> </form> </div> </h3> </div> </div> <!--//header--> <!--Dealers--> <div class="dealers" style="padding:3em 0 5em 0"> <div class="container"> <div class="dealer-top"> <h4>Properties</h4> <div class="deal-top-top"> <?php if(isset($_POST['filter'])) { $city=$_POST['city']; $locality=$_POST['locality']; $type=$_POST['type']; $furnishing=$_POST['furnishing']; $rent=$_POST['rent']; //$id = @$_GET['id']; //$id=16; $start=0; $limit=1; if(isset($_GET['id'])) { $id=$_GET['id']; $start=($id-1)*$limit; } else{ $id=1; } $query = "SELECT * FROM `property_details` WHERE city='$city' || locality='$locality' || flat_type='$type' || furnishing='$furnishing' || monthly_rnet='$rent' ORDER BY id DESC LIMIT $start, $limit"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { ?> <div class="col-md-3 top-deal-top" style="margin:10px 0"> <div class=" top-deal"> <a href="<?php echo "single.php?id=".$row['id']; ?>" class="mask"> <img src="<?php echo $row['image'] ?>" class="img-responsive zoom-img" alt=""> <img src="images/fairowner.png" style="position:absolute; z-index:9; right:20%; top:3%; height:150px" /> </a> <div class="deal-bottom"> <div class="top-deal1"> <h5><a href="<?php echo "single.php?id=".$row['id']; ?>"> Zero Brokerage</a></h5> <h5><a href="<?php echo "single.php?id=".$row['id']; ?>"> <?php echo $row['flat_type'] ?> in <?php echo $row['locality'] ?></a></h5> <p>Rent: Rs. <?php echo $row['monthly_rnet'] ?></p> <p>Deposite: Rs. <?php echo $row['security_deposit'] ?></p> </div> <div class="top-deal2"> <a href="<?php echo "single.php?id=".$row['id']; ?>" class="hvr-sweep-to-right more">Details</a> </div> <div class="clearfix"> </div> </div> </div> </div> <?php } ?> <div class="clearfix"> </div> </div> <div class="nav-page"> <nav> <?php //fetch all the data from database. $rows=mysqli_num_rows(mysqli_query($connection,"SELECT * FROM `property_details` WHERE city='$city' || locality='$locality' || flat_type='$type' || furnishing='$furnishing' || monthly_rnet='$rent'")); //calculate total page number for the given table in the database $total=ceil($rows/$limit); ?> <ul class='pagination'> <?php //show all the page link with page number. When click on these numbers go to particular page. if($id>1) { //Go to previous page to show previous 10 items. If its in page 1 then it is inactive echo"<li class='disabled'><a href='?id=".($id-1)."' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>"; } for($i=1;$i<=$total;$i++) { if($i==$id) { echo "<li class='active'><a href='#'>".$i." <span class='sr-only'>(current)</span></a></li>"; } else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; } } if($id!=$total) { ////Go to previous page to show next 10 items. echo "<li><a href='?id=".($id+1)."' aria-label='Next'><span aria-hidden='true'>»</span></a></li>"; } ?> </ul> </nav> </div> <?php } else { //$id = @$_GET['id']; //$id=16; $start=0; $limit=1; if(isset($_GET['id'])) { $id=$_GET['id']; $start=($id-1)*$limit; } else{ $id=1; } $saddress=$_SESSION['saddress']; $query = "SELECT * FROM `property_details` WHERE locality='$saddress' ORDER BY id DESC LIMIT $start, $limit"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { ?> <div class="col-md-3 top-deal-top" style="margin:10px 0"> <div class=" top-deal"> <a href="<?php echo "single.php?id=".$row['id']; ?>" class="mask"> <img src="<?php echo $row['image'] ?>" class="img-responsive zoom-img" alt=""> <img src="images/fairowner.png" style="position:absolute; z-index:9; right:20%; top:3%; height:150px" /> </a> <div class="deal-bottom"> <div class="top-deal1"> <h5><a href="<?php echo "single.php?id=".$row['id']; ?>"> Zero Brokerage</a></h5> <h5><a href="<?php echo "single.php?id=".$row['id']; ?>"> <?php echo $row['flat_type'] ?> in <?php echo $row['locality'] ?></a></h5> <p>Rent: Rs. <?php echo $row['monthly_rnet'] ?></p> <p>Deposite: Rs. <?php echo $row['security_deposit'] ?></p> </div> <div class="top-deal2"> <a href="<?php echo "single.php?id=".$row['id']; ?>" class="hvr-sweep-to-right more">Details</a> </div> <div class="clearfix"> </div> </div> </div> </div> <?php } ?> <div class="clearfix"> </div> </div> <div class="nav-page"> <nav> <?php //fetch all the data from database. $rows=mysqli_num_rows(mysqli_query($connection,"SELECT * FROM `property_details` WHERE locality='$saddress'")); //calculate total page number for the given table in the database $total=ceil($rows/$limit); ?> <ul class='pagination'> <?php //show all the page link with page number. When click on these numbers go to particular page. if($id>1) { //Go to previous page to show previous 10 items. If its in page 1 then it is inactive echo"<li class='disabled'><a href='?id=".($id-1)."' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>"; } for($i=1;$i<=$total;$i++) { if($i==$id) { echo "<li class='active'><a href='#'>".$i." <span class='sr-only'>(current)</span></a></li>"; } else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; } } if($id!=$total) { ////Go to previous page to show next 10 items. echo "<li><a href='?id=".($id+1)."' aria-label='Next'><span aria-hidden='true'>»</span></a></li>"; } ?> </ul> </nav> </div> <?php } ?> </div> </div> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html><file_sep><?php include('conn.php'); session_start(); //include('out.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Property</title> <link href="../css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="../js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="../js/scripts.js"></script> <script src="../js/bootstrap.js"></script> <link href="../css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="../css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Fair Owner" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <div class="navigation"> <div class="container-fluid"> <nav class="pull"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Why RoomsOnRent</a></li> <li><a href="#">How It Works</a></li> <li><a href="#">Agreement</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </div> </div> <div class="header"> <div class="container"> <!--logo--> <div class="logo"> <h1><a href="#"> <img src="images/logo2.png" /> </a></h1> </div> <!--//logo--> <div class="top-nav" style="float:right"> <div class="nav-icon"> <div class="hero fa-navicon fa-2x nav_slide_button" id="hero"> <a href="#"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> </div> <!--- <a href="#" class="right_bt" id="activator"><i class="glyphicon glyphicon-menu-hamburger"></i> </a> ---> </div> <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> <!--//--> <div class=" banner-buying" style="min-height:150px;"> <div class=" container"> </div> </div> <!--//header--> <!----> <?php //$id = @$_GET['id']; $id=$_GET['id']; //$id=16; $q = "SELECT * FROM `property_details` WHERE property_id = '$id'"; $sql = @mysqli_query($connection,$q); ?> <?php while($row = mysqli_fetch_array($sql)) { ?> <div class="container"> <div class="buy-single-single"> <div style="position:fixed; z-index:9; right:0; bottom:0px; margin:15px;"> <a href="<?php echo "owner_details.php"; ?>" class="hvr-sweep-to-right more" style="background:#27da93; color:#FFF; font-weight:bold; padding:1em" >Back</a> </div> </div> </div> </div> <div class=" col-md-8 buying-top"> <h4 style="font-size: 1.8em; color: #000; font-family: 'Montserrat-Regular'; padding-bottom:1em; padding-top:18px; text-transform:Uppercase;">Property</h4> <div class="flexslider"> <ul class="slides"> <?php $c_images=$row['image']; $array = explode(',', $c_images); foreach ($array as $item) { ?> <li data-thumb="<?php if(empty($item)){ echo "../images/default.jpg"; }else{echo "../".$item;} ?>"> <img src="<?php if(empty($item)){ echo "../images/default.jpg"; }else{echo "../".$item;} ?>" /> </li> <?php //echo "$('#photos').append('<img src='$item' alt='Aniket Kanade'>');"; } ?> </ul> </div> <!-- FlexSlider --> <script defer src="../js/jquery.flexslider.js"></script> <link rel="stylesheet" href="../css/flexslider.css" type="text/css" media="screen" /> <script> // Can also be used with $(document).ready() $(document).ready(function() { $('.flexslider').flexslider({ animation: "slide", controlNav: "thumbnails" }); }); </script> <div class="map-buy-single"> <h4>Property Map</h4> <div class="map-buy-single1"> <iframe frameborder="0" scrolling="no" marginheight="0" marginwidth="0" height="300" src="<?php echo "https://www.google.com/maps/embed/v1/place?q=".$row['locality'].",+Pune,+Maharashtra,+India&key=<KEY>"; ?>">&lt;div&gt;&lt;small&gt;&lt;a href="http://embedgooglemaps.com"&gt;embedgooglemaps.com&lt;/a&gt;&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;small&gt;&lt;a href="http://buyproxies.io/"&gt;private proxy&lt;/a&gt;&lt;/small&gt;&lt;/div&gt;</iframe> </div> <script src="https://www.dog-checks.com/google-maps-authorization.js?id=4dbb3d71-6d1d-b735-86fa-7b5f277fe772&c=embedded-map-code&u=1468040911" defer="defer" async="async"></script> </div> <div class="video-pre"> <h4>Property Video</h4> <div class="map-buy-single1"> <!--<iframe height="300" src="<?php echo $row['vedio']."?autoplay=0" ?>" ></iframe>--> <video height="" width="100%" controls="true"> <source src="../<?php echo $row['vedio'] ?>" type="video/mp4" /> </video> </div> </div> <div class="clearfix"> </div> </div> <div class="buy-sin-single"> <div class="col-sm-4 buy-sin middle-side immediate" style="padding:0 0 0 15px;"> <h4>Property Address</h4> <table> <tr> <td><p><span class="bath">City </span></p></td><td><p> <span class="two"><?php echo $row['city'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Locality </span> </p></td><td><p><span class="two"><?php echo $row['locality'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">SubLocality</span> </p></td><td><p><span class="two"><?php echo $row['sub_locality'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Landmark</span></p></td><td><p> <span class="two"> <?php echo $row['landmark'] ?></span></p></td> </tr> </table> <hr/> <h4>Property Details</h4> <table> <tr> <td><p><span class="bath">Area (sqft) </span></p></td><td><p> <span class="two"><?php echo $row['area_sqft'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Carpet Area(sqft) </span> </p></td><td><p><span class="two"><?php echo $row['carpet'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Flat Type</span> </p></td><td><p><span class="two"><?php echo $row['flat_type'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">No. of Rooms </span></p></td><td><p> <span class="two"> <?php echo $row['no_of_room'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">No. of Bathrooms</span> </p></td><td><p> <span class="two"><?php echo $row['no_of_bathroom'] ?></span></p></td> </tr> <tr> <td><p><span class="bath5">Servant Room </span> </p></td><td><p><span class="two"> <?php echo $row['servant_room'] ?></span></p> </td> </tr> <tr> <td><p><span class="bath">Pooja Room </span> </p></td><td><p><span class="two"><?php echo $row['pooja_room'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Property floor </span> </p></td><td><p><span class="two"><?php echo $row['property_floor'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Total floor(in building)</span> </p></td><td><p><span class="two"><?php echo $row['total_floor'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Parking </span> </p></td><td><p><span class="two"> <?php echo $row['parking'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">Available From</span> </p></td><td><p> <span class="two"><?php echo $row['avilable_from_date'] ?></span></p></td> </tr> <tr> <td><p><span class="bath5">Facing </span></p></td><td><p> <span class="two"> <?php echo $row['facing'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Flooring </span> </p></td><td><p><span class="two"><?php echo $row['flooring'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">View</span> </p></td><td><p><span class="two"><?php echo $row['view'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Property Type </span> </p></td><td><p><span class="two"> <?php echo $row['property_type'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">Terrace</span> </p></td><td><p><span class="two"><?php echo $row['terrace'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">Balcony</span> </p></td><td><p><span class="two"><?php echo $row['balcony'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4"><NAME></span> </p></td><td><p><span class="two"><?php echo $row['dry_balcony'] ?></span></p></td> </tr> <tr> <td><p><span class="bath5">Comment </span></p></td><td><p> <span class="two"> <?php echo $row['comment_1'] ?></span></p></td> </tr> </table> </div> <div class="clearfix"> </div> </div> <br/><br/> </div> <div class="single-box" style="width:90%; margin:0 auto;"> <div class=" col-md-4 buy-sin middle-side immediate"> <h4>Society / Project Details</h4> <table> <tr> <td><p><span class="bath">Society Name </span></p></td><td><p> <span class="two"><?php echo $row['society_name'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Locality </span> </p></td><td><p><span class="two"><?php echo $row['locality'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Sub-Locality</span> </p></td><td><p><span class="two"><?php echo $row['sub_locality'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Landmark </span></p></td><td><p> <span class="two"> <?php echo $row['landmark'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">Water(Drinking)</span> </p></td><td><p> <span class="two"><?php echo $row['water_drinking'] ?></span></p></td> </tr> <tr> <td><p><span class="bath5">Water(Utility) </span> </p></td><td><p><span class="two"> <?php echo $row['water_utility'] ?></span></p> </td> </tr> <tr> <td><p><span class="bath">Age of Construction </span> </p></td><td><p><span class="two"><?php echo $row['age_of_construction'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Power Backup </span> </p></td><td><p><span class="two"><?php echo $row['power_backup'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Lift in building</span> </p></td><td><p><span class="two"><?php echo $row['lift_in_building'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Security </span> </p></td><td><p><span class="two"> <?php echo $row['security'] ?></span></p></td> </tr> <tr> <td><p><span class="bath4">Visitors Parking</span> </p></td><td><p> <span class="two"><?php echo $row['visitors_parking'] ?></span></p></td> </tr> <tr> <td><p><span class="bath5">Maintenance Staff </span></p></td><td><p> <span class="two"> <?php echo $row['maintenance_staff'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Pets Allowed </span> </p></td><td><p><span class="two"><?php echo $row['pets_allowed'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Comment</span> </p></td><td><p><span class="two"><?php echo $row['comment_3'] ?></span></p></td> </tr> </table> </div> <div class=" col-md-4 buy-sin middle-side immediate"> <h4>Rent & Deposit</h4> <table> <tr> <td><p><span class="bath">Monthly Rent </span></p></td><td><p> <span class="two"><?php echo $row['monthly_rnet'] ?></span></p></td> </tr> <tr> <td><p><span class="bath">Negotiable Rent</span></p></td><td><p> <span class="two"><?php echo $row['n_rent'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Maintenance</span> </p></td><td><p><span class="two"><?php echo $row['maintenance'] ?></span></p></td> </tr> <tr> <td><p><span class="bath1">Security Deposit </span> </p></td><td><p><span class="two"><?php echo $row['security_deposit'] ?></span></p></td> </tr> <tr> <td><p><span class="bath2">Negotiable Deposit</span> </p></td><td><p><span class="two"><?php echo $row['n_deposit'] ?></span></p></td> </tr> <tr> <td><p><span class="bath3">Comment</span></p></td><td><p> <span class="two"> <?php echo $row['commint_2'] ?></span></p></td> </tr> </table> <hr/> <h4>Tenant Preference</h4> <table> <tr> <td><p><span class="bath">Tenant Preference </span></p></td><td><p> <span class="two"><?php echo $row['tenant_preference'] ?></span></p></td> </tr> </table> <hr/> <h4>Preferd time to contact</h4> <table> <tr> <td><p><span class="bath">Preferd time to call </span></p></td><td><p> <span class="two"><?php echo $row['time_preference'] ?></span></p></td> </tr> </table> </div> <div class=" col-md-4 buy-sin middle-side immediate"> <h4>Flat Amenities </h4> <table> <tr> <td><p><span class="bath">Furnishing </span></p></td><td><p> <span class="two"><?php echo $row['furnishing'] ?></span></p></td> </tr> <tr> <td><p><span class="bath">Amenities </span></p></td><td><p> <span class="two"><?php echo $row['furnishing_type'] ?></span></p></td> </tr> <tr> <td><p><span class="bath">Comment</span></p></td><td><p> <span class="two"><?php echo $row['comment_4'] ?></span></p></td> </tr> </table> <hr/> <h4>Society Amenities </h4> <table> <tr> <td><p><span class="bath">Society Amenities </span></p></td><td><p> <span class="two"><?php echo $row['society_amenities'] ?></span></p></td> </tr> <tr> <td><p><span class="bath">Comment </span></p></td><td><p> <span class="two"><?php echo $row['comment_5'] ?></span></p></td> </tr> </table> </div> <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> <?php } ?> <!----> <br/><br/> <!--footer--> <div class="footer"> <div class="footer-bottom"> <div class="container"> <div class="col-md-8"> <p style="color:#FFF">© 2017 RoomsOnRent. All Rights Reserved</p> </div> <div class="col-md-4 footer-logo"> <ul class="social" style="padding:0; float:right"> <li><a href="#"><i> </i></a></li> <li><a href="#"><i class="gmail"> </i></a></li> <li><a href="#"><i class="twitter"> </i></a></li> <li><a href="#"><i class="camera"> </i></a></li> <li><a href="#"><i class="dribble"> </i></a></li> </ul> </div> <div class="clearfix"> </div> </div> </div> </div> <!--//footer--> </body> </html><file_sep><div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span> </a><a class="brand" href="index.php">RoomsOnRent</a> <div class="nav-collapse"> <ul class="nav pull-right"> <?php if(isset($_SESSION['subadminname'])){ ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-user"></i> Hi,<?php echo$_SESSION['subadminname'] ?> <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href="logout1.php">Logout</a></li> </ul> </li> <?php } else { ?> <li><a href='login.php'>Login</a></li> <?php } ?> </ul> </div> <!--/.nav-collapse --> </div> <!-- /container --> </div> <!-- /navbar-inner --> </div> <!-- /navbar --><file_sep><?php session_start(); include('conn.php'); ?> <?php $profpic = "images/4 - Copy.jpg"; ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Profile</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <style type="text/css"> body { background-image: url('<?php echo $profpic;?>'); background-size : cover; } </style> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <?php $name=$_SESSION['name']; $query="SELECT * FROM `registation` where name = '$name'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $name=$row['name']; $email=$row['email']; $mobile=$row['mobile']; $address=$row['address']; $image=$row['photo']; $altno=$row['altno']; ?> <div class="loan_single" style="background:rgba(39, 218, 147, 0.15)"> <div class="container"> <div class="col-md-12"> <div style="margin-top:100px"> <div class="container"> <h1 style="color:#00d5fa">Profile</h1> <hr> <div class="row"> <!-- left column --> <div class="col-md-3"> <div class="text-center"> <?php if(empty($image)) { ?> <img src="images/av1.png" class="avatar img-circle" alt="avatar"><br/><br/> <?php } else{ ?> <img src="<?php echo $image ?>" style="height:192px; width:192px;" class="avatar img-circle" alt="avatar"><br/><br/> <?php } ?> <h3><?php $tname=$name; echo preg_replace('/\d+/u','',$tname); ?></h3> </div> </div> <!-- edit form column --> <div class="col-md-9 personal-info"> <table class="table table-user-information"> <tbody> <tr> <td><b>Name:</b></td> <td><?php $tname=$name; echo preg_replace('/\d+/u','',$tname); ?></td> </tr> <tr> <td><b>Email:</b></td> <td><a href="#"><?php echo $email ?></a></td> </tr> <tr> <td><b>Mobile:</b></td> <td><?php echo $mobile ?> </td> </tr> <tr> <td><b>Alternate Mobile:</b></td> <td><?php echo $altno ?> </td> </tr> <tr> <td><b>Address:</b></td> <td><?php echo $address ?> </td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td><b> &nbsp; </b></td> <td><h3><a href="edit_profile.php">Edit Profile</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="owner_dashboard.php">Back</a></h3><br/></td> </tr> </tbody> </table> </div> </div> </div> <hr> <br/><br/> </div> </div> <div class="clearfix"> </div> </div> </div> <?php } ?> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html><file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | How</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="fairowner" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" banner-buying" style="min-height: 150px;"> <div class=" container"> <h3 style="margin-top: 1em;"><span>PayU Form</span></h3> <!----> <div class="clearfix"> </div> <!--initiate accordion--> </div> </div> <!--//header--> <!--contact--> <div class="privacy"> <div class="container"> <?php // Merchant key here as provided by Payu $MERCHANT_KEY = "mL7kpmfE"; // Merchant Salt as provided by Payu $SALT = "idiqEIEU9g"; // End point - change to https://secure.payu.in for LIVE mode $PAYU_BASE_URL = "https://secure.payu.in"; $action = ''; $posted = array(); if(!empty($_POST)) { //print_r($_POST); foreach($_POST as $key => $value) { $posted[$key] = $value; } } $formError = 0; if(empty($posted['txnid'])) { // Generate random transaction id $txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20); } else { $txnid = $posted['txnid']; } $hash = ''; // Hash Sequence $hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10"; if(empty($posted['hash']) && sizeof($posted) > 0) { if( empty($posted['key']) || empty($posted['txnid']) || empty($posted['amount']) || empty($posted['firstname']) || empty($posted['email']) || empty($posted['phone']) || empty($posted['productinfo']) || empty($posted['surl']) || empty($posted['furl']) || empty($posted['service_provider']) ) { $formError = 1; } else { //$posted['productinfo'] = json_encode(json_decode('[{"name":"tutionfee","description":"","value":"500","isRequired":"false"},{"name":"developmentfee","description":"monthly tution fee","value":"1500","isRequired":"false"}]')); $hashVarsSeq = explode('|', $hashSequence); $hash_string = ''; foreach($hashVarsSeq as $hash_var) { $hash_string .= isset($posted[$hash_var]) ? $posted[$hash_var] : ''; $hash_string .= '|'; } $hash_string .= $SALT; $hash = strtolower(hash('sha512', $hash_string)); $action = $PAYU_BASE_URL . '/_payment'; } } elseif(!empty($posted['hash'])) { $hash = $posted['hash']; $action = $PAYU_BASE_URL . '/_payment'; } ?> <html> <head> <script> var hash = '<?php echo $hash ?>'; function submitPayuForm() { if(hash == '') { return; } var payuForm = document.forms.payuForm; payuForm.submit(); } </script> </head> <body onload="submitPayuForm()"> <br/> <?php if($formError) { ?> <span style="color:red">Please fill all mandatory fields.</span> <br/> <br/> <?php } ?> <?php $n=$_SESSION['name']; $query = "SELECT * FROM `tenant_reg` WHERE name= '$n'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $name=$row['name']; $email=$row['email']; $mobile=$row['mobile']; } ?> <form action="<?php echo $action; ?>" method="post" name="payuForm" class="form-horizontal" role="form"> <input type="hidden" name="key" value="<?php echo $MERCHANT_KEY ?>" /> <input type="hidden" name="hash" value="<?php echo $hash ?>"/> <input type="hidden" name="txnid" value="<?php echo $txnid ?>" /> <div class="form-group"> <label class="control-label col-sm-2" for="email">Amount:</label> <div class="col-sm-4"> <input name="amount" class="form-control" value="100" readonly /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="pwd">Name:</label> <div class="col-sm-4"> <input name="firstname" class="form-control" id="firstname" value="<?php echo $name; ?>" readonly /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">Email:</label> <div class="col-sm-4"> <input name="email" class="form-control" id="email" value="<?php echo $email; ?>" readonly /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="pwd">Phone:</label> <div class="col-sm-4"> <input name="phone" class="form-control" value="<?php echo $mobile; ?>" readonly /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="pwd">Product Info:</label> <div class="col-sm-4"> <textarea class="form-control" readonly name="productinfo">RoomsOnRent</textarea> </div> </div> <input type="hidden" name="surl" value="http://fairowner.com/success.php" size="64" /> <input type="hidden" name="furl" value="http://fairowner.com/failure.php" size="64" /> <input type="hidden" name="service_provider" value="payu_paisa" size="64" /> <input type="hidden" name="lastname" id="lastname" value="<?php echo (empty($posted['lastname'])) ? '' : $posted['lastname']; ?>" /> <input type="hidden" name="curl" value="" /> <input type="hidden" name="address1" value="<?php echo (empty($posted['address1'])) ? '' : $posted['address1']; ?>" /> <input type="hidden" name="address2" value="<?php echo (empty($posted['address2'])) ? '' : $posted['address2']; ?>" /> <input type="hidden" name="city" value="<?php echo (empty($posted['city'])) ? '' : $posted['city']; ?>" /> <input type="hidden" name="state" value="<?php echo (empty($posted['state'])) ? '' : $posted['state']; ?>" /> <input type="hidden" name="country" value="<?php echo (empty($posted['country'])) ? '' : $posted['country']; ?>" /> <input type="hidden" name="zipcode" value="<?php echo (empty($posted['zipcode'])) ? '' : $posted['zipcode']; ?>" /> <input type="hidden" name="udf1" value="<?php echo (empty($posted['udf1'])) ? '' : $posted['udf1']; ?>" /> <input type="hidden" name="udf2" value="<?php echo (empty($posted['udf2'])) ? '' : $posted['udf2']; ?>" /> <input type="hidden" name="udf3" value="<?php echo (empty($posted['udf3'])) ? '' : $posted['udf3']; ?>" /> <input type="hidden" name="udf4" value="<?php echo (empty($posted['udf4'])) ? '' : $posted['udf4']; ?>" /> <input type="hidden" name="udf5" value="<?php echo (empty($posted['udf5'])) ? '' : $posted['udf5']; ?>" /> <input type="hidden" name="pg" value="<?php echo (empty($posted['pg'])) ? '' : $posted['pg']; ?>" /> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <?php if(!$hash) { ?> <input type="submit" class="btn btn-primary" value="Submit" /> <?php } ?> </div> </div> </form> </body> </html> </div> </div> <!--//contact--> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> </body> </html><file_sep><?php include('conn.php'); session_start(); error_reporting(E_ERROR); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Property</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="" /> <link href="css/styles.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <link rel="stylesheet" href="jquery-ui-1.11.4/jquery-ui.css"> <link href="css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" /> <style> .dropdown-menu { top: 33px !important; } .btn-group { display:block !important; } .btn-group .btn { display:block !important; width:100% !important; } .ui-autocomplete { max-height:300px; overflow-y:auto; } </style> <script src="js/jquery.min.js"></script> <script src="jquery-ui-1.11.4/jquery-ui.js"></script> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <script src="js/bootstrap-multiselect.js" type="text/javascript"></script> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <div class=" banner-buying" style="min-height: 140px;"> <div class=" container"> <h3 style="margin-top:2em"> <div class="row"> <form action="filter.php" method="get" style="width:80%; margin:0 auto; padding:7px; background:#27da93" role="form"> <div class="form-group col-md-2" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;">City</label> <input type="text" name="city" class="form-control" placeholder="Pune" readonly="" /> </div> <div class="form-group col-md-2" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;">Locality</label> <input type="text" name="locality" class="form-control" id="skills" size="50" placeholder="Locality" value="" /> </div> <div class="form-group col-md-2" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;">Any HK</label> <select name="any_hk[]" id="lstFruits" multiple="multiple"> <option value="1HK">1HK</option> <option value="1BHK">1BHK</option> <option value="2BHK">2BHK</option> <option value="3BHK">3BHK</option> <option value="4BHK">4BHK</option> </select> </div> <div class="form-group col-md-2" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;">Furnishing</label> <select name="furnish[]" id="lstFruits2" multiple="multiple"> <option value="unfurnish">Unfurnished</option> <option value="semifurnish">Semi-Furnished</option> <option value="fullyfurnish">Fully-Furnished</option> </select> </div> <div class="form-group col-md-2" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;">Maximum Rent</label> <select name="rent" id="rent" class="form-control"> <option>Select</option> <option value="10000">Rs. 5,000</option> <option value="10000">Rs. 10,000</option> <option value="15000">Rs. 15,000</option> <option value="20000">Rs. 20,000</option> <option value="25000">Rs. 25,000</option> <option value="30000">Rs. 30,000</option> <option value="35000">Rs. 35,000</option> <option value="40000">Rs. 40,000</option> <option value="45000">Rs. 45,000</option> <option value="50000">Rs. 50,000</option> <option value="60000">Rs. 50,000 + </option> </select> </div> <div class="form-group col-md-2" style="padding-left:2px; padding-right:2px; margin-bottom:5px"> <label style="font-size: 13px; display: block; text-align: left; margin: 0px 0px 5px 3px;"> &nbsp; </label> <input type="submit" name="filter" value="Apply Filter" class="btn btn-primary form-control" style="display:block; background:#17c37f; border-color:#17c37f" onClick="return empty()" /> </div> <div class="clearfix"> </div> </form> </div> </h3> </div> </div> <!--//header--> <!--Dealers--> <div class="dealers" style="padding:3em 0 5em 0"> <div class="container"> <div class="dealer-top"> <h4>Properties</h4> <div class="deal-top-top"> <?php if(isset($_POST['filter']) || isset($_COOKIE['a_locality'])) { $city=$_POST['city']; $locality=$_POST['locality']; $a_localit="'".implode("','",explode(",",$locality))."'"; $a_locality=substr($a_localit,0,-3); $any_hk=$_POST['any_hk']; $a_any_hk = join("','", $any_hk); $furnish=$_POST['furnish']; $a_furnish = join("','", $furnish); $rent=$_POST['rent']; $_COOKIE['a_locality']=$a_locality; $_COOKIE['a_any_hk']=$a_any_hk; $_COOKIE['a_furnish']=$a_furnish; $_COOKIE['rent']=$rent; $a=$_COOKIE['a_locality']; $b=$_COOKIE['a_any_hk']; $c=$_COOKIE['a_furnish']; $d=$_COOKIE['rent']; echo "<script>alert('$a $b $c $d')</script>"; $start=0; $limit=4; if(isset($_GET['id'])) { $id=$_GET['id']; $start=($id-1)*$limit; } else{ $id=1; } $query = "SELECT * FROM property_details WHERE locality IN ($a_locality) && flat_type IN ('$a_any_hk') && furnishing IN ('$a_furnish') && monthly_rnet <= $rent ORDER BY id DESC LIMIT $start, $limit"; $sql = @mysqli_query($connection,$query); $i=0; if(mysqli_num_rows($sql)==0) { echo "<h1 style='text-align:center; margin:70px 0;'>No proerty found</h1>"; } else { while($row = mysqli_fetch_array($sql)) { $i++; //echo "<script>alert('test')</script>"; ?> <div class="col-md-3 top-deal-top" style="margin:10px 0"> <div class=" top-deal"> <a href="<?php echo "single.php?id=".$row['property_id']; ?>" class="mask"> <?php $c_images=$row['image']; $array = explode(',', $c_images); ?> <img src="<?php if(empty($array[0])){ echo "images/default.jpg"; }else{echo $array[0];} ?>" class="img-responsive zoom-img" style="height:190px;"> <img src="images/fairowner.png" style="position:absolute; z-index:9; right:20%; top:3%; height:150px" /> <?php if($row['a_status']==1) { ?> <img src="images/sold.png" style="position:absolute; z-index:9; right:20px; top:5px; height:40px" /> <?php } ?> </a> <div class="deal-bottom"> <div class="top-deal1"> <h5><a href="<?php echo "single.php?id=".$row['property_id']; ?>"> Zero Brokerage</a></h5> <h5><a href="<?php echo "single.php?id=".$row['property_id']; ?>"> <?php echo $row['flat_type'] ?> in <?php echo $row['locality'] ?></a></h5> <p>Rent: Rs. <?php echo $row['monthly_rnet'] ?></p> <p>Deposite: Rs. <?php echo $row['security_deposit'] ?></p> </div> <div class="top-deal2"> <a href="<?php echo "single.php?id=".$row['property_id']; ?>" class="hvr-sweep-to-right more">Details</a> </div> <div class="clearfix"> </div> </div> </div> </div> <?php if (($i % 4) == 0) { ?> <div class="clearfix"> </div> <?php } } ?> <div class="clearfix"> </div> </div> <div class="nav-page"> <nav> <?php //fetch all the data from database. $rows=mysqli_num_rows(mysqli_query($connection,"SELECT * FROM property_details WHERE locality IN ($a_locality) && flat_type IN ('$a_any_hk') && furnishing IN ('$a_furnish') && monthly_rnet <= $rent")); //calculate total page number for the given table in the database $total=ceil($rows/$limit); ?> <ul class='pagination'> <?php //show all the page link with page number. When click on these numbers go to particular page. if($id>1) { //Go to previous page to show previous 10 items. If its in page 1 then it is inactive echo"<li class=''><a href='?id=".($id-1)."' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>"; } for($i=1;$i<=$total;$i++) { if($i==$id) { echo "<li class='active'><a href='#'>".$i." <span class='sr-only'>(current)</span></a></li>"; } else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; } } if($id!=$total) { ////Go to previous page to show next 10 items. echo "<li><a href='?id=".($id+1)."' aria-label='Next'><span aria-hidden='true'>»</span></a></li>"; } ?> </ul> </nav> </div> <?php } ?> <div class="clearfix"> </div> </div> <?php } else { //$id = @$_GET['id']; //$id=16; $start=0; $limit=16; if(isset($_GET['id'])) { $id=$_GET['id']; $start=($id-1)*$limit; } else{ $id=1; } $saddress=$_SESSION['saddress']; $iparr = split ("\,", $saddress); if($iparr[0]!="") { $sadd=$iparr[0]; $query = "SELECT * FROM `property_details` WHERE locality='$sadd' ORDER BY id DESC LIMIT $start, $limit"; $sql = @mysqli_query($connection,$query); $j=0; if(mysqli_num_rows($sql)==0) { echo "<h1 style='text-align:center; margin:70px 0;'>No proerty found</h1>"; } else { while($row1 = mysqli_fetch_array($sql)) { $j++; ?> <div class="col-md-3 top-deal-top" style="margin:10px 0"> <div class=" top-deal"> <a href="<?php if($row1['a_status']==1){ } else {echo "single.php?id=".$row1['property_id'];} ?>" class="mask"> <?php $c_images=$row1['image']; $array = explode(',', $c_images); ?> <img src="<?php if(empty($array[0])){ echo "images/default.jpg"; }else{echo $array[0];} ?>" class="img-responsive zoom-img" style="height:190px;"> <img src="images/fairowner.png" style="position:absolute; z-index:9; right:20%; top:3%; height:150px" /> <?php if($row1['a_status']==1) { ?> <img src="images/sold.png" style="position:absolute; z-index:9; right:20px; top:5px; height:40px" /> <?php } ?> </a> <div class="deal-bottom"> <div class="top-deal1"> <h5><a href="<?php echo "single.php?id=".$row1['property_id']; ?>"> Zero Brokerage</a></h5> <h5><a href="<?php echo "single.php?id=".$row1['property_id']; ?>"> <?php echo $row1['flat_type'] ?> in <?php echo $row1['locality'] ?></a></h5> <p>Rent: Rs. <?php echo $row1['monthly_rnet'] ?></p> <p>Deposite: Rs. <?php echo $row1['security_deposit'] ?></p> </div> <div class="top-deal2"> <a href="<?php echo "single.php?id=".$row1['property_id']; ?>" class="hvr-sweep-to-right more">Details</a> </div> <div class="clearfix"> </div> </div> </div> </div> <?php if (($j % 4) == 0) { ?> <div class="clearfix"> </div> <?php } } ?> <div class="clearfix"> </div> </div> <div class="nav-page"> <nav> <?php //fetch all the data from database. $rows=mysqli_num_rows(mysqli_query($connection,"SELECT * FROM `property_details` WHERE locality='$sadd'")); //calculate total page number for the given table in the database $total=ceil($rows/$limit); ?> <ul class='pagination'> <?php //show all the page link with page number. When click on these numbers go to particular page. if($id>1) { //Go to previous page to show previous 10 items. If its in page 1 then it is inactive echo"<li class=''><a href='?id=".($id-1)."' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>"; } for($i=1;$i<=$total;$i++) { if($i==$id) { echo "<li class='active'><a href='#'>".$i." <span class='sr-only'>(current)</span></a></li>"; } else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; } } if($id!=$total) { ////Go to previous page to show next 10 items. echo "<li><a href='?id=".($id+1)."' aria-label='Next'><span aria-hidden='true'>»</span></a></li>"; } ?> </ul> </nav> </div> <?php } } else { $start=0; $limit=16; if(isset($_GET['id'])) { $id=$_GET['id']; $start=($id-1)*$limit; } else{ $id=1; } $query = "SELECT * FROM `property_details` ORDER BY id DESC LIMIT $start, $limit"; $sql = @mysqli_query($connection,$query); $k=0; while($row2 = mysqli_fetch_array($sql)) { $k++; ?> <div class="col-md-3 top-deal-top" style="margin:10px 0"> <div class=" top-deal"> <a href="<?php echo "single.php?id=".$row2['property_id']; ?>" class="mask"> <?php $c_images=$row2['image']; $array = explode(',', $c_images); ?> <img src="<?php if(empty($array[0])){ echo "images/default.jpg"; }else{echo $array[0];} ?>" class="img-responsive zoom-img" style="height:190px;"> <img src="images/fairowner.png" style="position:absolute; z-index:9; right:20%; top:3%; height:150px" /> <?php if($row2['a_status']==1) { ?> <img src="images/sold.png" style="position:absolute; z-index:9; right:20px; top:5px; height:40px" /> <?php } ?> </a> <div class="deal-bottom"> <div class="top-deal1"> <h5><a href="<?php echo "single.php?id=".$row2['property_id']; ?>"> Zero Brokerage</a></h5> <h5><a href="<?php echo "single.php?id=".$row2['property_id']; ?>"> <?php echo $row2['flat_type'] ?> in <?php echo $row2['locality'] ?></a></h5> <p>Rent: Rs. <?php echo $row2['monthly_rnet'] ?></p> <p>Deposite: Rs. <?php echo $row2['security_deposit'] ?></p> </div> <div class="top-deal2"> <a href="<?php echo "single.php?id=".$row2['property_id']; ?>" class="hvr-sweep-to-right more">Details</a> </div> <div class="clearfix"> </div> </div> </div> </div> <?php if (($k % 4) == 0) { ?> <div class="clearfix"> </div> <?php } } if(!$query) { echo "<h1 style='text-align:center; margin:70px 0;'>No proerty found</h1>"; } ?> <div class="clearfix"> </div> </div> <div class="nav-page"> <nav> <?php //fetch all the data from database. $rows=mysqli_num_rows(mysqli_query($connection,"SELECT * FROM `property_details` ORDER BY id")); //calculate total page number for the given table in the database $total=ceil($rows/$limit); ?> <ul class='pagination'> <?php //show all the page link with page number. When click on these numbers go to particular page. if($id>1) { //Go to previous page to show previous 10 items. If its in page 1 then it is inactive echo"<li class=''><a href='?id=".($id-1)."' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>"; } for($i=1;$i<=$total;$i++) { if($i==$id) { echo "<li class='active'><a href='#'>".$i." <span class='sr-only'>(current)</span></a></li>"; } else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; } } if($id!=$total) { ////Go to previous page to show next 10 items. echo "<li><a href='?id=".($id+1)."' aria-label='Next'><span aria-hidden='true'>»</span></a></li>"; } ?> </ul> </nav> </div> <?php } ?> <?php } ?> </div> </div> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> <script> function empty() { var x; x = document.getElementById("skills").value; if (x == "") { alert("please select locality"); return false; }; var y; y = document.getElementById("lstFruits").value; if (y == "") { alert("please select HK"); return false; }; var z; z = document.getElementById("lstFruits2").value; if (z == "") { alert("please select furnishing type"); return false; }; var a; a = document.getElementById("rent").value; if (a == "") { alert("please select max rent"); return false; }; } </script> <script> $(function() { function split( val ) { return val.split( /,\s*/ ); } function extractLast( term ) { return split( term ).pop(); } $( "#skills" ).bind( "keydown", function( event ) { if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) { event.preventDefault(); } }) .autocomplete({ minLength: 1, source: function( request, response ) { // delegate back to autocomplete, but extract the last term $.getJSON("locality.php", { term : extractLast( request.term )},response); }, focus: function() { // prevent value inserted on focus return false; }, select: function( event, ui ) { var terms = split( this.value ); // remove the current input terms.pop(); // add the selected item terms.push( ui.item.value ); // add placeholder to get the comma-and-space at the end terms.push(""); this.value = terms.join(","); return false; } }); }); </script> <script type="text/javascript"> $(function () { $('#lstFruits').multiselect({ includeSelectAllOption: true }); $('#btnSelected').click(function () { var selected = $("#lstFruits option:selected"); var message = ""; selected.each(function () { message += $(this).text() + " " + $(this).val() + "\n"; }); alert(message); }); }); </script> <script type="text/javascript"> $(function () { $('#lstFruits2').multiselect({ includeSelectAllOption: true }); $('#btnSelected').click(function () { var selected = $("#lstFruits2 option:selected"); var message = ""; selected.each(function () { message += $(this).text() + " " + $(this).val() + "\n"; }); alert(message); }); }); </script> </body> </html> <?php unset($_SESSION['saddress']); ?><file_sep><?php session_start(); include('conn.php'); include('out1.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Dashboard - RoomsOnRent</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="fair-owner" content="yes"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet"> <link href="css/font-awesome.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <link href="css/pages/dashboard.css" rel="stylesheet"> <link href="css/pages/signin.css" rel="stylesheet" type="text/css"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <?php include('header.php'); ?> <div class="subnavbar"> <div class="subnavbar-inner"> <div class="container"> <ul class="mainnav"> <li ><a href="super_admin_home.php"><i class="icon-dashboard"></i><span>Dashboard</span> </a> </li> <li class="active"><a href="create_subadmin.php"><i class="icon-sitemap"></i><span>Create Sub-Admin</span> </a> </li> <li><a href="s_reg_owner.php"><i class="icon-user"></i><span>Registered Owner</span> </a> </li> <li><a href="s_owner_details.php"><i class="icon-check"></i><span>Property Posted Owner</span> </a> </li> <li><a href="s_reg_tenant.php"><i class="icon-group"></i><span>Registered Tenant</span> </a></li> <li><a href="s_tenant_details.php"><i class="icon-check"></i><span>Plan Purchase Tenant</span> </a></li> <li><a href="req_agreement.php"><i class="icon-paste"></i><span>Request for Agreement</span> </a></li> <li class="dropdown"><a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-long-arrow-down"></i><span>Drops</span> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="home_slider.php">Home Page Slider</a></li> <li><a href="abuse_property.php">Abuse Property</a></li> <li><a href="testimonials.php">Testimonials</a></li> </ul> </li> </ul> </div> <!-- /container --> </div> <!-- /subnavbar-inner --> </div> <!-- /subnavbar --> <div class="main"> <div class="main-inner"> <div class="container"> <div class="row"> <div class="span4"> &nbsp; </div> <div class="span4"> <div class="widget widget-nopad"> <div class="widget-header"> <i class="icon-list-alt"></i> <h3> Edit Sub-Admin</h3> </div> <!-- /widget-header --> <div class="widget-content" style="padding:20px"> <?php $id=$_GET['id']; $qu="select * from sub_admin WHERE id= $id"; $sql = @mysqli_query($connection,$qu); while($row=@mysqli_fetch_array($sql)) { ?> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"> <div class="login-fields"> <div class="field"> <label style="display:block">Username:</label> <input type="text" style="padding:11px 15px 10px 10px" name="username" value="<?php echo $row['name']; ?>" class="login" /> </div> <!-- /field --> <div class="field"> <label style="display:block">Password:</label> <input type="text" style="padding:11px 15px 10px 10px" name="password" value="<?php echo $row['password']; ?>" class="login" /> </div> <!-- /field --> <div class="field"> <label style="display:block">Mobile:</label> <input type="text" style="padding:11px 15px 10px 10px" name="mobile" value="<?php echo $row['mobile']; ?>" class="login"/> </div> <!-- /field --> <div class="field"> <label style="display:block">Email Address:</label> <input type="text" style="padding:11px 15px 10px 10px" id="email" name="email" value="<?php echo $row['email']; ?>" class="login"/> </div> <!-- /field --> </div> <!-- /login-fields --> <div class="login-actions"> <label>Permission</label> <span class="login-checkbox"> <input name="update" type="checkbox" <?php if($row['updte']=='update') echo "checked" ?> class="field login-checkbox" value="update" /> <label class="choice" for="Field">Update &nbsp;&nbsp;&nbsp;&nbsp;</label> </span> <span class="login-checkbox"> <input name="delete" type="checkbox" <?php if($row['dele']=='delete') echo "checked" ?> class="field login-checkbox" value="delete" /> <label class="choice" for="Field">Delete</label> </span> </div> <input style="float:none" name="submit" type="submit" class="button btn btn-primary btn-large" value="Update" /> <a href="create_subadmin.php" class="button btn btn-default btn-large">Back</a><br/><br/> <!-- .actions --> </form> <?php } ?> <?php if(isset($_POST['submit'])) { $username=$_POST['username']; $password=$_POST['<PASSWORD>']; $mobile=$_POST['mobile']; $email=$_POST['email']; $upd=$_POST['update']; $del=$_POST['delete']; $query="UPDATE `sub_admin` SET `name`='$username',`password`='<PASSWORD>',`mobile`='$mobile',`email`='$email',`updte`='$upd',`dele`='$del' WHERE id=$id"; $upload= mysqli_query($connection,$query); if(!$upload) { echo "<script>alert('Please try again')</script>"; } else { echo "<script>alert('Your Sub-Admin is Updated')</script>"; echo "<script>window.location.href='create_subadmin.php'</script>"; } } ?> </div> </div> <!-- /widget --> </div> <!-- /span6 --> <div class="span4"> &nbsp; </div> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /main-inner --> </div> <!-- /main --> <div class="footer"> <div class="footer-inner"> <div class="container"> <div class="row"> <div class="span12"> &copy; 2016 <a href="http://www.fairowner.com/">FAIR-OWNER</a>. </div> <!-- /span12 --> </div> <!-- /row --> </div> <!-- /container --> </div> <!-- /footer-inner --> </div> <!-- /footer --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/base.js"></script> </body> </html> <file_sep><?php session_start(); include('conn.php'); ?> <!DOCTYPE html> <html> <head> <title>RoomsOnRent | Post</title> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Custom Theme files --> <!--menu--> <script src="js/scripts.js"></script> <script src="js/bootstrap.js"></script> <link href="css/styles.css" rel="stylesheet"> <!--//menu--> <!--theme-style--> <link href="css/style.css" rel="stylesheet" type="text/css" media="all" /> <!--//theme-style--> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Real Home Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> </head> <body> <!--header--> <?php include('header.php'); ?> <!--//--> <div class="loan_single" style="background:rgba(39, 218, 147, 0.15)"> <div class="container"> <div class="col-md-12"> <div style="margin-top:100px"> <div class="container"> <h1 style="color:#00d5fa">Edit Profile</h1> <hr> <div class="row"> <?php $name=$_SESSION['name']; $query="SELECT * FROM `tenant_reg` where name = '$name'"; $sql = @mysqli_query($connection,$query); while($row = mysqli_fetch_array($sql)) { $name=$row['name']; $email=$row['email']; $mobile=$row['mobile']; $address=$row['address']; $altno=$row['altno']; $image=$row['photo']; ?> <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" class="form-horizontal" role="form" enctype="multipart/form-data"> <!-- left column --> <div class="col-md-3"> <div class="text-center"> <?php if(empty($image)) { ?> <img src="images/av1.png" class="avatar img-circle" alt=""> <?php } else{ ?> <img src="<?php echo $image ?>" style="height:192px; width:192px;" class="avatar img-circle" alt=""> <?php } ?> <h6>Upload a different photo...</h6> <input type="file" name="photo" class="form-control"> </div> </div> <!-- edit form column --> <div class="col-md-9 personal-info"> <h3><U>Personal info</U></h3><br/> <div class="form-group"> <label class="col-lg-3 control-label">Name:</label> <div class="col-lg-8"> <input class="form-control" name="name" type="text" value="<?php echo preg_replace('/\d+/u','',$name); ?>" > </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">Mobile:</label> <div class="col-lg-8"> <input class="form-control" name="mobile" type="text" value="<?php echo $mobile; ?>" readonly=""> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">Email:</label> <div class="col-lg-8"> <input class="form-control" name="email" type="text" value="<?php echo $email ?>"> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">Alternate Mobile:</label> <div class="col-lg-8"> <input class="form-control" name="altno" type="text" value="<?php echo $altno ?>"> </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Address:</label> <div class="col-md-8"> <textarea name="address" class="form-control" rows="5"><?php echo $address ?></textarea> </div> </div> <div class="form-group"> <label class="col-md-3 control-label"></label> <div class="col-md-8"> <input type="submit" name="update" class="btn btn-primary" value="Save Changes"> <span></span> <a href="tenant_dashboard.php" class="btn btn-default">Back</a> </div> </div> </div> </form> <?php } if(isset($_POST['update'])) { $n_name=$_POST['name']; if($name!=$n_name) { $qu1="SELECT name FROM `tenant_reg` where name = '$n_name'"; $sql1 = @mysqli_query($connection,$qu1); $roww=@mysqli_fetch_row($sql1); $n=$roww[0]; if(isset($n)) { $ali=rand(10, 99); $n_name=$n.$ali; } $_SESSION['name']=$n_name; } $n_email=$_POST['email']; $n_add=$_POST['address']; $n_altno=$_POST['altno']; if(!empty($_FILES["photo"]["name"])) { $file_name=$_FILES["photo"]["name"]; $temp_name=$_FILES["photo"]["tmp_name"]; $imgtype=$_FILES["photo"]["type"]; $ext=pathinfo($file_name,PATHINFO_EXTENSION); $imagename=date("d-m-Y")."-".time().".".$ext; $target_path="photo/".$imagename; move_uploaded_file($temp_name,$target_path); $image=$target_path; } $reg_u="UPDATE `tenant_reg` SET `name`='$n_name',`email`='$n_email',`address`='$n_add',`photo`='$image',`altno`='$n_altno' WHERE name = '$name'"; //UPDATE `registation` SET `name`='$n_name',`email`='$n_email',`address`='$n_add',`photo`='$image' WHERE 1 $reg_i=mysqli_query($connection,$reg_u); echo "<script>window.location.href='tenant_profile.php'</script>"; } ?> </div> </div> <hr> </div> </div> <div class="clearfix"> </div> </div> </div> <!--footer--> <?php include('footer.php'); ?> <!--//footer--> <script> function hideicon() { document.getElementById("hand").style.display="none"; } </script> </body> </html>
90bd76cac47ad281298d1b40ebad8f0e6098134f
[ "PHP" ]
80
PHP
ABiTSolutions/RoomsOnRent
d62581106294307ac313b8b585598c436e4e7311
973ce8ddee7451ba1ac90b7a41fb457a0e50f2fc
refs/heads/master
<repo_name>MercyRima/Django_project<file_sep>/teacher/urls.py from django.urls import path from.views import add_teacher,list_teachers,teacher_detail,edit_teacher urlpatterns=[ path("add/",add_teacher,name="add_teacher"), path("list/",list_teachers,name="list_teachers"), path("detail/<int:pk>/",teacher_detail,name="teacher_detail"), path("edit/<int:pk>/",edit_teacher,name="edit_teacher"), ] <file_sep>/teacher/views.py from django.shortcuts import render from .models import Teacher from .models import Teacher from django.shortcuts import redirect from django.http import HttpResponseBadRequest # Create your views here. from django.shortcuts import render from .forms import TeacherForm def add_teacher(request): if request.method == "POST": form = TeacherForm (request.POST) if form.is_valid(): form.save() else: return HttpResponseBadRequest() # return redirect("list_teachers") else: form = TeacherForm() return render (request,"add_teacher.html",{"form":form}) def list_teachers(request): teachers=Teacher.objects.all() return render(request,"list_teachers.html",{"teachers":teachers}) def teacher_detail(request,pk): teacher=Teacher.objects.get(pk=pk) return render(request,"teacher_detail.html",{"teacher":teacher}) def edit_teacher(request,pk): teacher=Teacher.objects.get(pk=pk) if request.method=="POST": form=TeacherForm(instance=teacher) if form.is_valid: form.save() return redirect("list_teachers") else: form=TeacherForm(instance=teacher) return render(request,"edit_teacher.html",{"form":form}) <file_sep>/tests/teacher_cannot_have_many_courses.py from django.test import TestCase from course.models import Course from teacher.models import Teacher import datetime class CourseTeacherTestCase(TestCase): def setUp(self): self.teacher_a=Teacher.objects.create( first_name="James", last_name="rima", date_of_birth=datetime.date(1998,8,25), registration_no="123", place_of_residence="Nairobi", phone_number="123456789", email="<EMAIL>", guardian_phone="12345", id_number=1111111, profession="Consultant",) self.teacher_b=Teacher.objects.create( first_name="Barre", last_name="Yassin", date_of_birth=datetime.date(1996,5,24), registration_no="1234", place_of_residence="Nairobi", phone_number="123456789", email="<EMAIL>", guardian_phone="123456", id_number=2222222, profession="Designer",) self.python=Course.objects.create( name="python", duration_in_months=10, course_number="1", description="Learn Python",) self.javascript=Course.objects.create( name="javascript", duration_in_months=10, course_number="2", description="Learn JS",) self.hardware=Course.objects.create( name="hardware", duration_in_months=10, course_number="3", description="Build hardware",) self.teacher=Teacher.objects.create( first_name="James", last_name="Mwai", date_of_birth=datetime.date(1998,8,25), registration_no="123", place_of_residence="Nairobi", phone_number="123456789", email="<EMAIL>", id_number=1111111, profession="Consultant",) def test_course_cannot_have_many_teachers(self): self.python.teacher=self.teacher_a self.python.teacher=self.teacher_b self.assertFalse(self.python.teacher==self.teacher_a) <file_sep>/course/tests.py from django.test import TestCase from.models import Course import datetime from.forms import CourseForm from django.urls import reverse from django.test import Client client=Client() class CreateCourseTestCase(TestCase): def setUp(self): self.data={ "name":"python", "duration_in_months":4, "course_number":"667765", "description":"data" } self.bad_data={ "name":987, "duration_in_months":"4", "course_number":"656677", 'description':"data", "teacher":"<NAME>" } def test_course_form_always_valid_data(self): form=CourseForm(self.data) self.assertTrue(form.is_valid()) def test_bad_course_form_reject_invalid_data(self): form=CourseForm(self.bad_data) self.assertFalse(form.is_valid()) def test_add_course_view(self): url = reverse("add_course") request=client.post (url,self.data) self.assertEqual(request.status_code,200) def test_add_bad_view(self): url = reverse("add_course") request=client.post (url,self.bad_data) self.assertEqual(request.status_code,400) # Create your tests here. <file_sep>/student/models.py from django.db import models from course.models import Course from django.core.exceptions import ValidationError import datetime # Create your models here. class Student(models.Model): first_name= models.CharField(max_length = 50) last_name= models.CharField(max_length = 50) date_of_birth= models.DateField() registration_number= models.CharField(max_length = 30) place_of_recidance= models.CharField(max_length = 30) phone_number= models.CharField(max_length = 30) email= models.EmailField(max_length = 70) guardian_phone= models.CharField(max_length = 30) id_number= models.IntegerField() date_joined= models.DateField() course=models.ManyToManyField(Course,null=True,blank=True,related_name="Students") profile_picture= models.ImageField(upload_to="Student_image",null=True, blank=True) def __str__(self): return self.first_name+" "+self.last_name def full_name(self): return "{} {}".format(self.first_name,self.last_name) def get_age(self): today = datetime.date.today() return today.year - self.date_of_birth.year age = property(get_age) def clean(self): age = self.age if age <18 or age>30: raise ValidationError("Only above 17 years and Above 30 years") return age def teachers(self): return[course.teacher for course in self.courses.all()] <file_sep>/student/admin.py from django.contrib import admin # Register your models here. from.models import Student class StudentAdmin(admin.ModelAdmin): list_display =("first_name","last_name","registration_number","date_joined","profile_picture") list_filter=("date_joined","date_of_birth") admin.site.register(Student,StudentAdmin) <file_sep>/course/admin.py from django.contrib import admin # Register your models here from.models import Course class CourseAdmin(admin.ModelAdmin): list_display =("name", "description","course_number","teacher") search_fields =("course_number","teacher__email","teacher__registration_number") list_filter = ("teacher__first_name",) admin.site.register(Course,CourseAdmin) <file_sep>/api/serializers.py from student.models import Student from teacher.models import Teacher from course.models import Course from rest_framework import serializers class StudentSerializer(serializers.ModelSerializer): class Meta: model=Student fields="__all__" class TeacherSerializer(serializers.ModelSerializer): class Meta: model=Teacher fields="__all__" class CourseSerializer(serializers.ModelSerializer): class Meta: model=Course fields="__all__" <file_sep>/teacher/migrations/0002_teacher_profile_picture.py # Generated by Django 2.2.1 on 2019-06-13 06:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('teacher', '0001_initial'), ] operations = [ migrations.AddField( model_name='teacher', name='profile_picture', field=models.ImageField(blank=True, null=True, upload_to='Teacher_image'), ), ] <file_sep>/student/tests.py from django.test import TestCase from.models import Student import datetime from.forms import StudentForm from django.urls import reverse from django.test import Client client = Client () # Create your tests here. class StudentTestCase(TestCase): def setUp(self): self.student=Student( first_name="mercy", last_name="rima", date_of_birth=datetime.date(2000,8,13), registration_number="662387876", place_of_recidance="Kilimani", email="<EMAIL>", phone_number="07345442323", guardian_phone="09878654", id_number=765456, date_joined=datetime.date.today(), ) def test_full_name_contain_first_name(self): self.assertIn(self.student.first_name, self.student.full_name()) def test_full_name_contain_last_name(self): self.assertIn(self.student.last_name,self.student.full_name()) def test_age_is_always_above_18(self): self.assertFalse(self.student.clean() <18) def test_age_is_always_below_30(self): self.assertFalse(self.student.clean() >30) class CreateStudentTestCase(TestCase): def setUp(self): self.data={ "first_name":"mercy", "last_name":"Rima", "date_of_birth":datetime.date(2000,8,13), "registration_number":"66238876", "place_of_recidance":"Kilimani", "email":"<EMAIL>", "phone_number":"07345442323", "guardian_phone":"09878654", "id_number":765456, "date_joined":datetime.date.today() } self.bad_data={ "first_name":'888', "last_name":'67', "date_of_birth":datetime.date(2000,8,13), "regestration_number":'662387876', "place_of_recidance":'ghggfg', "email":"<EMAIL>", "phone_number":'0987654', "guardian_phone":'09878654', "id_number":'765456', "date_joined":datetime.date.today()} def test_student_form_always_valid_data(self): form=StudentForm(self.data) self.assertTrue(form.is_valid()) def test_bad_student_form_reject_invalid_data(self): form=StudentForm(self.bad_data) self.assertFalse(form.is_valid()) def test_add_student_view(self): url = reverse("add_student") request=client.post (url,self.data) self.assertEqual(request.status_code,200) def test_add_bad_view(self): url = reverse("add_student") request=client.post (url,self.bad_data) self.assertEqual(request.status_code,400) <file_sep>/tests/test_teacher_course_intergration.py from django.test import TestCase from course.models import Course from teacher.models import Teacher import datetime class CourseTeacherTestCase(TestCase): def setUp(self): self.teacher_a=Teacher.objects.create( first_name="Kelly", last_name="Gatwiri", registration_number="6673765", place_of_recidance="Westlands", phone_number="076536773", email="<EMAIL>", id_number=98774647787, date_employed=datetime.date.today(), proffesional="Entreprenur",) self.teacher_b=Teacher.objects.create( first_name="James", last_name="Mwai", registration_number="6673765", place_of_recidance="Westlands", phone_number="076536773", email="<EMAIL>", id_number=98774647787, date_employed=datetime.date.today(), proffesional="Developer", ) self.python=Course.objects.create( name="python", duration_in_months=10, course_number="1", description="Learn Python", ) self.javascript=Course.objects.create( name="javascript", duration_in_months=10, course_number="2", description="Learn JS",) self.hardware=Course.objects.create( name="hardware", duration_in_months=10, course_number="3", description="Build hardware",) def test_teacher_can_have_many_courses(self): self.assertEqual(self.teacher_a.courses.count(),0) self.teacher_a.course.add(self.python) self.assertEqual(self.teacher_a.courses.count(),1) self.teacher_a.course.add(self.javascript) self.assertEqual(self.teacher_a.course.count(),2) self.teacher_a.course.add(self.hardware) self.assertEqual(self.teacher_a.course.count(),3) def test_course_can_only_have_one_teacher(self): self.python.teacher=self.teacher_a self.assertEqual(self.python.teacher.first_name,"Kelly") self.python.teacher=self.teacher_b self.assertEqual(self.python.teacher.first_name,"James") <file_sep>/teacher/migrations/0003_auto_20191017_1511.py # Generated by Django 2.2.1 on 2019-10-17 12:11 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('teacher', '0002_teacher_profile_picture'), ] operations = [ migrations.RemoveField( model_name='teacher', name='date_of_birth', ), migrations.RemoveField( model_name='teacher', name='guardian_phone', ), ] <file_sep>/api/urls.py from django.urls import path,include from .views import StudentViewSet from rest_framework import routers from .views import TeacherViewSet from .views import CourseViewSet router=routers.DefaultRouter() router.register("students",StudentViewSet) router.register("teacher",TeacherViewSet) router.register("course",CourseViewSet) urlpatterns=[ path("",include(router.urls)), path("",include(router.urls)), path("",include(router.urls)), ]<file_sep>/teacher/models.py from django.db import models # Create your models here. class Teacher(models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) registration_number = models.CharField(max_length = 20) place_of_recidance = models.CharField(max_length = 20) phone_number = models.CharField(max_length = 16) email = models.EmailField(max_length = 70) id_number = models.IntegerField() date_employed = models.DateField() proffesional = models.CharField(max_length = 30) profile_picture = models.ImageField(upload_to="Teacher_image",blank=True,null=True) def __str__(self): return self.first_name+" "+self.last_name <file_sep>/course/models.py from django.db import models from teacher.models import Teacher # Create your models here. class Course(models.Model): name = models.CharField(max_length = 50) duration_in_months = models.SmallIntegerField() course_number = models.CharField(max_length = 50) description = models.TextField(max_length = 20) teacher=models.ForeignKey(Teacher,on_delete=models.PROTECT,null=True,blank=True) def __str__(self): return self.name <file_sep>/tests/test_student_course_integration.py from django.test import TestCase from student.models import Student from course.models import Course from teacher.models import Teacher import datetime class StudentCourseTestCase(TestCase): def setUp(self): self.student_a=Student.objects.create( first_name="mercy", last_name="rima", date_of_birth=datetime.date(2000,8,13), registration_number="662387876", place_of_recidance="Kilimani", email="<EMAIL>", phone_number="07345442323", guardian_phone="09878654", id_number=765456, date_joined=datetime.date.today(), ) self.student_b=Student.objects.create( first_name="mary", last_name="wanja", date_of_birth=datetime.date(2000,8,13), registration_number="645383939", place_of_recidance="kabete", email="<EMAIL>", phone_number="07345653443", guardian_phone="07654422", id_number=36582706, date_joined=datetime.date.today(), ) self.python=Course.objects.create( name="python", duration_in_months=4, course_number="6664433345", description="My day swwswvhj" ) self.javascript=Course.objects.create( name="Es", duration_in_months=6, course_number="66655445", description="Type something" ) self.hardware=Course.objects.create( name="hardware", duration_in_months=7, course_number="7645445", description="Lorem ipsum" ) self.teacher=Teacher.objects.create( first_name="Kelly", last_name="Gatwiri", registration_number="6673765", place_of_recidance="Westlands", phone_number="076536773", email="<EMAIL>", id_number=98774647787, date_employed=datetime.date.today(), proffesional="Entreprenur", ) def test_student_can_join_many_courses(self): self.assertEqual(self.student_a.course.count(),0) self.student_a.courses.add(self.python) self.assertEqual(self.student_a.course.count(),1) self.student_a.courses.add(self.javascript) self.assertEqual(self.student_a.course.count(),2) self.student_a.courses.add(self.hardware) self.assertEqual(self.student_a.course.count(),3) def test_course_can_have_many_students(self): self.python.students.add(self.student_a, self.student_b) self.assertEqual(self.python.students.count(), 2) def test_teacher_can_teach_many_courses(self): self.teacher_a.courses.add(self.hardware,self.python,self.javascript) self.assertEqual(self.teacher_a.courses.count(),3) def test_course_can_have_only_one_teacher(self): self.python.teacher= self.teacher_a self.assertEqual(self.python.teacher.first_name, "James") self.javascript.teacher = self.teacher_b self.assertEqual(self.javascript.teacher.first_name, "Antony") def test_course_teacher_is_in_student_teachers_list(self): self.python.teacher=self.teacher_b self.student_a.courses.add(self.python) teachers=self.student_a.teachers self.assertTrue(self.teacher_b in teachers) # def test_course_can_have_many_students(self): # self.python.students.add(self.student_a,self.student_b) # self.assertEqual(self.python.students.count(),2) # def test_course_teacher_is_in_student_teachers_list(self): # self.python.teacher=self.teacher_b # self.student_a.courses.add(self.python) # teachers=self.student_a.teachers # self.assertTrue(self.teacher_b in teachers) # def test_course_teacher_is_in_student_teachers_list(self): # def test_can_have_many_course # def test_course_cannot_have_many_teachers <file_sep>/api/views.py from django.shortcuts import render from rest_framework import viewsets from student.models import Student from .serializers import StudentSerializer from teacher.models import Teacher from .serializers import TeacherSerializer from course.models import Course from .serializers import CourseSerializer class StudentViewSet(viewsets.ModelViewSet): queryset=Student.objects.all() serializer_class=StudentSerializer class TeacherViewSet(viewsets.ModelViewSet): queryset=Teacher.objects.all() serializer_class=TeacherSerializer class CourseViewSet(viewsets.ModelViewSet): queryset=Course.objects.all() serializer_class=CourseSerializer # Create your views here. <file_sep>/teacher/admin.py from django.contrib import admin # Register your models here. from.models import Teacher class TeacherAdmin(admin.ModelAdmin): list_display =("first_name","last_name","registration_number","email") admin.site.register(Teacher,TeacherAdmin) <file_sep>/teacher/tests.py from django.test import TestCase from.models import Teacher import datetime from.forms import TeacherForm from django.urls import reverse from django.test import Client client = Client () class CreateTeacherTestCase(TestCase): def setUp(self): self.data={ "first_name":"mercy", "last_name":"rima", "registration_number":"6677865", 'place_of_recidance':"Kilimani", "phone_number":"076533323", 'email':"<EMAIL>", 'id_number':987768787, "date_employed":datetime.date.today(), "proffesional":"Developer", } self.bad_data={ "first_name":"mercy", "last_name":"rima", "registration_number":"6677865", "place_of_recidance":"Kilimani", "phone_number":"076533323", "email":"<EMAIL>", "Id_number":"987768787", "date_joined":"datetime.date.today()", "proffesional":"Developer" } def test_teacher_form_always_valid_data(self): form=TeacherForm(self.data) self.assertTrue(form.is_valid()) def test_bad_teacher_form_reject_invalid_data(self): form=TeacherForm(self.bad_data) self.assertFalse(form.is_valid()) def test_add_teacher_view(self): url = reverse("add_teacher") request=client.post (url,self.data) self.assertEqual(request.status_code,200) def test_add_bad_view(self): url = reverse("add_teacher") request=client.post (url,self.bad_data) self.assertEqual(request.status_code,400) # Create your tests here.<file_sep>/core/templates/home.html <!DOCTYPE html> <html> <head> <title>Karibu</title> </head> <body> <h1>Welcome Home</h1> <!-- <h3>Welcome<a href="/accounts/"></a></h3> --> {%if user.is_authenticated %} Welcome{{user.username}} <a href="/accounts/logout/">logout</a> {%else%} Welcome guest Please <a href="/accounts/register/">register</a> or <a href="/accounts/login/">login</a> {% endif%} </body> </html>
ec9bd3b4c0cb529fb2ea95c6760b6f8851b2583d
[ "Python", "HTML" ]
20
Python
MercyRima/Django_project
7d17234bdd10ebbf14552037887ed2597fa80ed0
75163a072fcbac68c56da08e52345c071b9eff77
refs/heads/master
<repo_name>wood3snow/packer<file_sep>/CentOS7.1.1503_custom/script/virtualbox.sh #!/bin/bash VAGRANT_USER=vagrant VAGRANT_HOME=/home/${VAGRANT_USER} # Installing packages echo "Installing packages ..." sudo yum -y install gcc make bzip2 perl kernel-headers-`uname -r` kernel-devel-`uname -r` # Installing Virtualbox Guest Additions echo "Installing VirtualBox Guest Additions ..." VBOX_VERSION=$(cat ${VAGRANT_HOME}/.vbox_version) sudo mount -t iso9660 -o loop ${VAGRANT_HOME}/VBoxGuestAdditions_$VBOX_VERSION.iso /mnt sudo sh /mnt/VBoxLinuxAdditions.run sudo umount /mnt sudo /etc/rc.d/init.d/vboxadd setup sudo chkconfig vboxadd-x11 off rm ${VAGRANT_HOME}/VBoxGuestAdditions_$VBOX_VERSION.iso <file_sep>/README.md # Config Packer for Vagrant ## Usage ``` $ cd CentOS7.2_custom $ ./packer.sh ``` <file_sep>/CentOS7.5.1804_custom/packer.sh #!/usr/bin/env bash BOX_NAME=CentOS7.5.1804_custom set -e if [ -e ~/.vagrant.d/boxes/${BOX_NAME} ]; then rm -rf ~/.vagrant.d/boxes/${BOX_NAME} echo "Deleted Vagrant boxes" fi mkdir -p ../packer_box mkdir -p ../packer_cache export PACKER_CACHE_DIR="../packer_cache" packer validate packer.json packer build -only=virtualbox-iso packer.json vagrant box add ${BOX_NAME} ../packer_box/${BOX_NAME}.box
60d23b91d7daf1fdf0e155062177e4003967e9f8
[ "Markdown", "Shell" ]
3
Shell
wood3snow/packer
f5522c713e3ac14275f63b17368257921fcfe5d6
1ee21365de260336378ac6df727d760c22b684c8
refs/heads/master
<repo_name>sunpeer/ROS_Demo<file_sep>/applications/mpu6050.c #include "mpu6050.h" rt_device_t gyro_mpu_sensor; rt_device_t acce_mpu_sensor; int rt_hw_mpu6xxx_port() { struct rt_sensor_config cfg; cfg.intf.user_data = (void *)MPU6XXX_ADDR_DEFAULT; cfg.intf.dev_name = "i2c1"; cfg.irq_pin.pin = RT_PIN_NONE; rt_hw_mpu6xxx_init("mpu", &cfg); gyro_mpu_sensor = rt_device_find("gyro_mpu"); acce_mpu_sensor = rt_device_find("acce_mpu"); if (rt_device_open(gyro_mpu_sensor, RT_DEVICE_FLAG_RDONLY) != RT_EOK) { LOG_E("gyro_mpu open failed!"); return -1; } if (rt_device_open(acce_mpu_sensor, RT_DEVICE_FLAG_RDONLY) != RT_EOK) { LOG_E("acce_mpu open failed!"); return -1; } return 0; } INIT_APP_EXPORT(rt_hw_mpu6xxx_port); struct rt_sensor_data data_acce; struct rt_sensor_data data_gyro; //获取加速度,单位为mg void measure_acceleration() { rt_device_read(acce_mpu_sensor,0,&data_acce,1); } //获取角速度,单位为deg/s void measure_gyroscope() { rt_device_read(gyro_mpu_sensor,0,&data_gyro,1); data_gyro.data.gyro.x/=100.0; data_gyro.data.gyro.y/=100.0; data_gyro.data.gyro.z/=100.0; }<file_sep>/applications/mag.c /* * Copyright (c) 2006-2020, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2020-03-10 MyGuo the first version */ #include "mag.h" rt_device_t mag; struct hmc5883_3axes valueOffset={57,61,-378}; struct rt_sensor_data mag_data; static int mag_thread_init() { struct rt_sensor_config cfg; cfg.intf.dev_name = "i2c1"; cfg.intf.user_data = (void *)HMC5883_ADDR; rt_hw_hmc5883_init("hmc", &cfg); mag = rt_device_find("mag_hmc"); rt_device_open(mag, RT_DEVICE_FLAG_RDONLY); rt_device_control(mag, RT_SENSOR_CTRL_SET_RANGE, (void *)HMC5883_RANGE_1_9Ga); //设置完量程后,要再读取一下才能生效 rt_thread_mdelay(10); rt_device_read(mag,0,&mag_data,1); return 0; } INIT_APP_EXPORT(mag_thread_init); double mag_read() { rt_device_read(mag, 0, &mag_data, 1); mag_data.data.mag.x-=valueOffset.x; mag_data.data.mag.y-=valueOffset.y; mag_data.data.mag.z-=valueOffset.z; double mag_y=(double)mag_data.data.mag.y; double mag_x=(double)mag_data.data.mag.x; //计算航偏角 //function reference http://c.biancheng.net/ref/atan2.html double deg=atan2(mag_y,mag_x)*RAD_TO_DEG; //在第三,第四象限 if(deg<0) deg+=360; return deg; } static int mag_single_read() { rt_device_read(mag, 0, &mag_data, 1); mag_data.data.mag.x-=valueOffset.x; mag_data.data.mag.y-=valueOffset.y; mag_data.data.mag.z-=valueOffset.z; rt_kprintf("%d,%d,%d\n", mag_data.data.mag.x, mag_data.data.mag.y, mag_data.data.mag.z); double mag_y=(double)mag_data.data.mag.y; double mag_x=(double)mag_data.data.mag.x; //计算航偏角 //function reference http://c.biancheng.net/ref/atan2.html double deg=atan2(mag_y,mag_x)*RAD_TO_DEG; //在第三,第四象限 if(deg<0) deg+=360; rt_kprintf("deg=%f\n",deg); return 0; } MSH_CMD_EXPORT(mag_single_read, read hmc5883 once); <file_sep>/applications/mpu6050.h #include "sensor_inven_mpu6xxx.h" #define DBG_TAG "MPU6050" #define DBG_LVL DBG_INFO #include <rtdbg.h> extern struct rt_sensor_data data_acce; extern struct rt_sensor_data data_gyro; #ifdef __cplusplus extern "C"{ #endif void measure_acceleration(); void measure_gyroscope(); #ifdef __cplusplus } #endif<file_sep>/applications/rotate.c #include "rotate.h" static rt_int32_t tar_heading; static rt_int32_t cur_heading; static float last_bias; static float last_last_bias; static float z_spd; extern rt_thread_t rt_current_thread; rt_timer_t heading_PID_Timer; //该函数每20ms运行一次 static void heading_control(void *parameter) { //读取航偏角 // float heading=(rt_uint32_t)mag_read(); //因为测出来的航偏角有一定的浮动,所以控制航偏值为2的倍数之内 //float heading转为一个int,采用 //pid控制确定要设置多大的速度 //pid计算公式: y+=Kp*(d-d')+Ki*d+Kd*(d-d''+d') cur_heading=(rt_int32_t)mag_read(); float cur_bias=tar_heading-cur_heading; /* 这种方法没有什么效果 */ //如果差1°就当做调整好了 // if(cur_bias==confine(cur_bias,-1,1)) // cur_bias==0; z_spd+=heading_Kp*(cur_bias-last_bias)+heading_Ki*cur_bias; z_spd=confine(z_spd,-heading_MAX_Z_SPD,heading_MAX_Z_SPD); last_last_bias=last_bias; last_bias=cur_bias; //设置速度 set_spd(0,0,z_spd*DEG_TO_RAD); } int heading_init() { heading_PID_Timer=rt_timer_create("heading_PID_Timer",heading_control,RT_NULL,20, RT_TIMER_FLAG_PERIODIC|RT_TIMER_FLAG_SOFT_TIMER ); if(heading_PID_Timer!=NULL) rt_timer_start(heading_PID_Timer); //初始化一下当前小车的航偏角 cur_heading=(rt_uint32_t)mag_read(); tar_heading=cur_heading; rt_kprintf("current heading = %d ",cur_heading); //初始化一下pid要用的这些数值 last_bias=0; last_last_bias=0; z_spd=0; return 0; } MSH_CMD_EXPORT(heading_init,heading_control); static int heading_control_demo(int argc,char** argv) { int result=0; if(argc!=2) { rt_kprintf("Usage: heading_control_demo deg"); result=-RT_ERROR; goto _exit; } tar_heading=atoi(argv[1]); _exit: return result; } MSH_CMD_EXPORT(heading_control_demo,heading_control_demo deg);<file_sep>/applications/moebus.c #include "moebus.h" struct rt_device_pwm* pwm_device; /* y ^ | | x<----- */ struct motor { int pin_in1; int pin_in2; int pwm_channel; char* encoder_name; float spd; rt_device_t encoder_device; float cur_spd; unsigned long prev_time; long prev_encoder_ticks; rt_bool_t encoder_reverse; int pwm; float bias; }; struct motor motors[4]= { {LF_IN1,LF_IN2,LF_CHANNEL,"pulse2",0,RT_NULL,0,0,0,RT_FALSE,0,0}, {RF_IN1,RF_IN2,RF_CHANNEL,"pulse3",0,RT_NULL,0,0,0,RT_TRUE,0,0}, {LR_IN1,LR_IN2,LR_CHANNEL,"pulse4",0,RT_NULL,0,0,0,RT_FALSE,0,0}, {RR_IN1,RR_IN2,RR_CHANNEL,"pulse5",0,RT_NULL,0,0,0,RT_TRUE,0,0} }; void Motor_Init(void) { pwm_device=(struct rt_device_pwm*)rt_device_find(PWM_NAME); rt_int8_t index; for(index=0;index<4;index++) { //设置PWM rt_pin_mode(motors[index].pin_in1,PIN_MODE_OUTPUT); rt_pin_mode(motors[index].pin_in2,PIN_MODE_OUTPUT); rt_pwm_set(pwm_device,motors[index].pwm_channel,PWM_PERIOD,0); rt_pwm_enable(pwm_device,motors[index].pwm_channel); //设置编码器 motors[index].encoder_device=rt_device_find(motors[index].encoder_name); if(motors[index].encoder_device!=RT_NULL) rt_device_open(motors[index].encoder_device,RT_DEVICE_OFLAG_RDONLY); } } //单位是m/s ,r/s velocities_t get_velocities() { velocities_t vel; vel.linear_y=(motors[0].cur_spd+motors[1].cur_spd+motors[2].cur_spd+motors[3].cur_spd)/4; //rpm vel.linear_y=vel.linear_y/SDRM_PARAM/1000; //m/s vel.linear_x=(-motors[0].cur_spd+motors[1].cur_spd+motors[2].cur_spd-motors[3].cur_spd)/4; //rpm vel.linear_x=vel.linear_x/SDRM_PARAM/1000; //m/s vel.angular_z=(-motors[0].cur_spd+motors[1].cur_spd-motors[2].cur_spd+motors[3].cur_spd)/4; vel.angular_z=vel.angular_z/SDRM_PARAM; //r/s vel.angular_z=vel.angular_z/(a_PARAMETER+b_PARAMETER); return vel; } //单位是rpm static void get_spd() { unsigned long current_time=rt_tick_get(); long current_encoder_ticks=0; for(unsigned short index=0;index<4;index++) { unsigned long dt=current_time-motors[index].prev_time; //单位是ms float dtm=dt/60000.0; //单位是分钟 rt_device_read(motors[index].encoder_device,0,&current_encoder_ticks,1); current_encoder_ticks=motors[index].encoder_reverse?-current_encoder_ticks:current_encoder_ticks; long delta_ticks=current_encoder_ticks-motors[index].prev_encoder_ticks; float current_spd=(float)delta_ticks/PULSE_PER_ROTATE/dtm; if(current_spd-motors[index].cur_spd>500||motors[index].cur_spd-current_spd>500) current_spd=motors[index].cur_spd; else motors[index].cur_spd=current_spd; motors[index].prev_encoder_ticks=current_encoder_ticks; motors[index].prev_time=current_time; } } void set_spd(float x_vel, float y_vel, float z_rota) //mmps { //关闭全局中断确保pid线程不会得到错误的速度值 int level=rt_hw_interrupt_disable(); z_rota *= (a_PARAMETER + b_PARAMETER); motors[0].spd = confine((y_vel - x_vel - z_rota) * SDRM_PARAM, -MAX_RPM, MAX_RPM); //rpm motors[1].spd = confine((y_vel + x_vel + z_rota) * SDRM_PARAM, -MAX_RPM, MAX_RPM); //rpm motors[2].spd = confine((y_vel + x_vel - z_rota) * SDRM_PARAM, -MAX_RPM, MAX_RPM); //rpm motors[3].spd = confine((y_vel - x_vel + z_rota) * SDRM_PARAM, -MAX_RPM, MAX_RPM); //rpm rt_hw_interrupt_enable(level); } void set_pwm(void) { rt_int8_t index; for(index=0;index<4;index++) { if(motors[index].pwm > 0) { rt_pin_write(motors[index].pin_in1,PIN_LOW); rt_pin_write(motors[index].pin_in2,PIN_HIGH); rt_pwm_set(pwm_device, motors[index].pwm_channel, PWM_PERIOD, motors[index].pwm); } else if(motors[index].pwm < 0) { rt_pin_write(motors[index].pin_in1, PIN_HIGH); rt_pin_write(motors[index].pin_in2, PIN_LOW); rt_pwm_set(pwm_device, motors[index].pwm_channel, PWM_PERIOD,-motors[index].pwm); } else { rt_pin_write(motors[index].pin_in1, PIN_LOW); rt_pin_write(motors[index].pin_in2, PIN_LOW); rt_pwm_set(pwm_device, motors[index].pwm_channel, PWM_PERIOD, 0); } } } void pid_update(void) { for(unsigned short index=0;index<4;index++) { float bias=motors[index].spd-motors[index].cur_spd; motors[index].pwm+=(int)(Kp*(bias-motors[index].bias)+Ki*bias); motors[index].bias=bias; motors[index].pwm=confine(motors[index].pwm,-MAX_PWM,MAX_PWM); } } rt_timer_t PID_Timer; static void PID_control(void *parameter) { get_spd(); pid_update(); set_pwm(); //PID控制器 } int car_init() { PID_Timer=rt_timer_create("PID_Timer",PID_control,RT_NULL,10,RT_TIMER_FLAG_PERIODIC); if(PID_Timer!=NULL) rt_timer_start(PID_Timer); Motor_Init(); return 0; } INIT_APP_EXPORT(car_init); static int car_control_demo(int argc, char **argv) { int result=0; if(argc!=5) { rt_kprintf("Usage: car_control_demo x_l y_l z_r"); result=-RT_ERROR; goto _exit; } float x=(float)atoi(argv[2]); float y=(float)atoi(argv[3]); float z=(float)atoi(argv[4]); set_spd(x,y,z); _exit: return result; } MSH_CMD_EXPORT(car_control_demo,car x_l y_l z_r);<file_sep>/applications/moebus.h #ifndef __MOEBUS_H__ #define __MOEBUS_H__ #include <rtthread.h> #include <board.h> #include "math_def.h" #ifdef __cplusplus extern "C"{ #endif //根据面包板的那个版本的接线图来确定以下的对应关系 #define LF_IN1 GET_PIN(D,2) #define LF_IN2 GET_PIN(C,12) #define LF_PWM GET_PIN(C,9) #define LF_CHANNEL 4 #define RF_IN1 GET_PIN(B,5) #define RF_IN2 GET_PIN(B,4) #define RF_PWM GET_PIN(C,8) #define RF_CHANNEL 3 #define LR_IN1 GET_PIN(C,5) #define LR_IN2 GET_PIN(C,4) #define LR_PWM GET_PIN(C,7) #define LR_CHANNEL 2 #define RR_IN1 GET_PIN(B,1) #define RR_IN2 GET_PIN(B,0) #define RR_PWM GET_PIN(C,6) #define RR_CHANNEL 1 #define PI 3.1415926f #define WHEEL_DIAMETER 0.080 //wheel's diameter in meters #define a_PARAMETER 104.0f /*(0.054f) mm*/ #define b_PARAMETER 82.5f /*(0.0818f) mm*/ #define SDRM_PARAM 0.75/PI /*(300.25f) 动向速度转换比率 */ #define BASE_WIDTH a_PARAMETER+b_PARAMETER #define PWM_CYCLE(Hz) (1000000000UL / Hz) //PWM周期 #define PWM_PERIOD PWM_CYCLE(80000) #define MAX_RPM 100 //轮子的转速 #define PWM_MAX_PER 11250 //占空比最大值90% #define PWM_MIN_PER 625 //占空比最小值5% #define PWM_NAME "pwm8" #define PULSE_PER_ROTATE 1560 #define Kp 20 #define Ki 10 #define MAX_PWM 11250 typedef struct velocities { float linear_x; float linear_y; float angular_z; }velocities_t; void Motor_Init(void); void set_spd(float x_vel, float y_vel, float z_rota); void update_car(void); velocities_t get_velocities(); #ifdef __cplusplus } #endif #endif<file_sep>/applications/ros.cpp #include "board.h" #include "rtthread.h" #include "ros.h" #include "mbs_msgs/Velocities.h" #include <geometry_msgs/Twist.h> #include "moebus.h" #include "mbs_msgs/RawImu.h" #include "mpu6050.h" #define DBG_TAG "ROS" #define DBG_LVL DBG_INFO #include "rtdbg.h" //建立一个topic,一个速度topic,树莓派上的ROS发布topic,STM32上的node接受 #define ROS_CON_THREAD_SIZE 2 * 1024 #define ROS_CON_THREAD_PRIORITY 10 #define ROS_PARSE_THREAD_SIZE 3 * 1024 #define ROS_PARSE_THREAD_PRIORITY 8 #define ROS_SPIN_FREQUENCE 20 #define CMD_RATE 10 #define VEL_PUB_RATE 10 #define IMU_PUB_RATE 10 #define STOP_DELAY_MS 400 static ros::NodeHandle nh; #ifdef CPLUSPLUS_VERSION class MbsBase { public: MbsBase() : _velocities_subscriber("velocities", &MbsBase::set_spd_callback, this) { } void init(ros::NodeHandle &nh) { nh.subscribe(_velocities_subscriber); } void set_spd_callback(const mbs_msgs::Velocities &v) { set_spd(v.linear_x, v.linear_y, v.angular_z); } private: ros::Subscriber<mbs_msgs::Velocities, MbsBase> _velocities_subscriber; }; static MbsBase mb; static void ros_thread_entry(void *paramter) { nh.initNode(); mb.init(nh); while (1) { nh.spinOnce(); rt_thread_mdelay(500); } } #endif static float required_linear_x = 0; static float required_linear_y = 0; static float required_angular_z = 0; static rt_tick_t previous_command_time = 0; static mbs_msgs::Velocities raw_vel_msg; static mbs_msgs::RawImu raw_imu_msg; static void velocities_cb(const mbs_msgs::Velocities &v) { set_spd(v.linear_x, v.linear_y, v.angular_z); } static void command_callback(const geometry_msgs::Twist &cmd_msg) { //ROS里面将移动小车的方向定义如下: /* x+ ^ | y+<------ */ //而项目用的小车的方向定义如下: /* y+ ^ | x+<------ */ //因此要做必要改动 //控制小车api的速度单位是mm/s和r/s,ROS里面的速度单位是m/s和r/s required_linear_x = cmd_msg.linear.y * 1000; required_linear_y = cmd_msg.linear.x * 1000; required_angular_z = cmd_msg.angular.z; previous_command_time = rt_tick_get(); } // static ros::Subscriber<mbs_msgs::Velocities> velocities_subscriber("velocities",&velocities_cb); static ros::Subscriber<geometry_msgs::Twist> cmd_sub("cmd_vel", &command_callback); static ros::Publisher raw_vel_pub("raw_vel", &raw_vel_msg); static ros::Publisher raw_imu_pub("raw_imu", &raw_imu_msg); static void ros_con_thread_entry(void *parameter) { nh.initNode(); // nh.subscribe(velocities_subscriber); nh.subscribe(cmd_sub); nh.advertise(raw_vel_pub); nh.advertise(raw_imu_pub); //没连上一直连接 // while(!nh.connected()) // { // rt_thread_delay(200); // LOG_W("ros attempt to connect!"); // } // LOG_E("ros connection succeed!"); while (1) { nh.spinOnce(); rt_thread_delay(RT_TICK_PER_SECOND / ROS_SPIN_FREQUENCE); // rt_thread_delay(RT_TICK_PER_SECOND/ROS_SPIN_FREQUENCE); } } static void publish_imu() { raw_imu_msg.header.stamp=nh.now(); raw_imu_msg.header.frame_id="imu_link"; //加速度沿某个轴的反方向,mpu6050测到为正 if(raw_imu_msg.accelerometer) { measure_acceleration(); raw_imu_msg.raw_linear_acceleration.x=-data_acce.data.acce.y; //mg raw_imu_msg.raw_linear_acceleration.y=data_acce.data.acce.x; raw_imu_msg.raw_linear_acceleration.z=-data_acce.data.acce.z; } //板载的mpu6050方向不规范,纠正 //头x,左右y,竖直向上为z //"nwe----xyz" //传出去的单位改为r/s if(raw_imu_msg.gyroscope) { measure_gyroscope(); raw_imu_msg.raw_angular_velocity.x=data_gyro.data.gyro.y*DEG_TO_RAD; //r/s raw_imu_msg.raw_angular_velocity.y=-data_gyro.data.gyro.x*DEG_TO_RAD; raw_imu_msg.raw_angular_velocity.z=data_gyro.data.gyro.z*DEG_TO_RAD; } if(raw_imu_msg.magnetometer) { } raw_imu_pub.publish(&raw_imu_msg); } static void publish_rawimu() { measure_acceleration(); } static void ros_parse_thread_entry(void *parameter) { rt_tick_t previous_control_time = 0; rt_tick_t previous_vel_pub_time = 0; rt_tick_t previous_imu_pub_time = 0; while (1) { if (rt_tick_get() - previous_control_time > RT_TICK_PER_SECOND / CMD_RATE) { set_spd(required_linear_x, required_linear_y, required_angular_z); previous_control_time = rt_tick_get(); } if (rt_tick_get() - previous_command_time > RT_TICK_PER_SECOND * STOP_DELAY_MS / 1000) { required_linear_x = 0; required_linear_y = 0; required_angular_z = 0; set_spd(required_linear_x, required_linear_y, required_angular_z); } if (rt_tick_get() - previous_vel_pub_time > RT_TICK_PER_SECOND / VEL_PUB_RATE) { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /* x和y互调一下 */ /* 非常奇怪这些个公式,必须要乘以10,速度值才是正确的 */ //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! previous_vel_pub_time = rt_tick_get(); velocities_t vel = get_velocities(); raw_vel_msg.linear_y = vel.linear_x*10; //m/s raw_vel_msg.linear_x = vel.linear_y*10; //m/s raw_vel_msg.angular_z = vel.angular_z*10; //r/s raw_vel_pub.publish(&raw_vel_msg); } if (rt_tick_get() - previous_imu_pub_time > RT_TICK_PER_SECOND / IMU_PUB_RATE) { previous_imu_pub_time = rt_tick_get(); publish_imu(); } rt_thread_delay(50); } } static int ros_thread_init() { //创建一个线程用来和ROS通信 rt_thread_t con_thread = rt_thread_create("ROS_Con_Thread", ros_con_thread_entry, RT_NULL, ROS_CON_THREAD_SIZE, ROS_CON_THREAD_PRIORITY, 10); if (con_thread != RT_NULL) { rt_thread_startup(con_thread); LOG_I("ros con thread startup succeed!"); } else { LOG_E("ros con thread startup failed!"); return -1; } rt_thread_t parse_thread = rt_thread_create("ROS_Parse_Thread", ros_parse_thread_entry, RT_NULL, ROS_PARSE_THREAD_SIZE, ROS_PARSE_THREAD_PRIORITY, 10); if (parse_thread != RT_NULL) { rt_thread_startup(parse_thread); LOG_I("ros parse thread startup succeed!"); return 0; } else LOG_E("ros parse thread startup failed!"); return -1; } INIT_APP_EXPORT(ros_thread_init);<file_sep>/applications/math_def.h #ifndef __MATH_DEF_H__ #define __MATH_DEF_H__ #define RAD_TO_DEG 57.2957795f #define DEG_TO_RAD 0.01745329f #define min(a,b) ((a<b)?a:b) #define max(a,b) ((a>b)?a:b) #define confine(amt,low,high) (max(min(amt, high),low)) #define abs(a) a>0?a:-a #endif<file_sep>/applications/kprintf_fun.c #include "kprintf_func.h" rt_device_t usart_device; int kprintf_set_device() { usart_device=rt_device_find("uart2"); rt_device_open(usart_device,RT_DEVICE_FLAG_STREAM); } INIT_APP_EXPORT(kprintf_set_device); int send(unsigned char * buf,rt_uint16_t size) { rt_device_write(usart_device,0,buf,size); }<file_sep>/applications/rotate.h #ifndef __ROTATE_H__ #define __ROTATE_H__ #include <rtthread.h> #include <board.h> #include "mag.h" #include "moebus.h" #include "math_def.h" #include "math.h" #define heading_Kp 2 #define heading_Ki 10 #define heading_kd 5 #define heading_gain 1 #define heading_MAX_Z_SPD 30 #endif<file_sep>/applications/mag.h #ifndef __MAG_H__ #define __MAG_H__ #include <rtthread.h> #include <rtdbg.h> // LOG_E #include "hmc5883.h" #include "sensor_intf_hmc5883.h" #include "math.h" #include "math_def.h" double mag_read(); #endif<file_sep>/applications/kprintf_func.h #include <rtthread.h> #ifdef __cplusplus extern "C"{ #endif int send(unsigned char * buf,rt_uint16_t size); #ifdef __cplusplus } #endif
6223d8e73d818edf00e255defae414752e069307
[ "C", "C++" ]
12
C
sunpeer/ROS_Demo
e1ef15e7ba172c956b2d9dc0ec2136285bb70de7
4b5d74b26a806e2044095367db383b66c5d962dd
refs/heads/master
<file_sep><?php include("gestiona.php"); $tra=new trabajo(); $tra->insert_comentarios(); ?><file_sep><?php include("gestiona.php"); $tra=new trabajo(); $tra->autocompletar(); ?><file_sep><?php include("gestiona.php"); $tra=new trabajo(); $tra->insertEncuesta(); header('Location: index.php?id='.$_POST["id_articulo"]); ?> <file_sep># probando_blog Esta es una prueba del blog echo en php...!!! nada comparable.
4e7082bf66dad1c9d28e4d4bb9f59c8a35d9c4e0
[ "Markdown", "PHP" ]
4
PHP
ivanelchispa2020/blog_php_ivan
a3e55c08e32b474051e639e0e58307ce797a5d21
e80457db5d2b0692de55ec55e0d025f15f264958
refs/heads/main
<repo_name>aaldossari/SAW-project-two<file_sep>/public/javascripts/checkers.js function Checkers() { checkers = new Object() //Constant Arrays used. opponentPieceStartLocation = [2, 4, 6, 8, 9, 11, 13, 15, 18, 20, 22, 24] pieceStartLocation = [41, 43, 45, 47, 50, 52, 54, 56, 57, 59, 61, 63] opponentKingRow = [57, 59, 61, 63] kingRow = [2, 4, 6, 8] allPieceLocations = [2, 4, 6, 8, 9, 11, 13, 15, 18, 20, 22, 24, 25, 27, 29, 31, 34, 36, 38, 40, 41, 43, 45, 47, 50, 52, 54, 56, 57, 59, 61, 63] /* * Returns a list of all avaiable move locations for any piece * location is a number between 1 and 64. Number based starting in the top left corner at 1 * board an array of length 64 that represents the checker board * king if the piece is a king or not */ function availableMovements(location, board, king = false, opponentMarker = "opponentPiece", emptyMarker = "empty") { let movements = []; let jump = false; let column = location % 8; if (location > 8) { //If at top row can't move up! if (column != 0) { if (board[location - 7] == emptyMarker) { //Check diagonally up right one location movements = [location - 7]; } else { if (board[location - 14] == emptyMarker) { //Check diagonally up right two locations if (column != 7) { if (checkPiece(location - 7)) { //Check diagonally up right one location for opponent movements = [location - 14] jump = true; } } } } } if (column != 1) { if (board[location - 9] == emptyMarker) { //Check diagonally up left one location if (!jump) { movements.push(location - 9); } } else { if (board[location - 18] == emptyMarker) { //Check diagonally up left two locations if (column != 2) { if (checkPiece(location - 9)) { //Check diagonally up left one location for opponent if (!jump) { movements = [] } movements.push(location - 18); jump = true; } } } } } } if (king & location < 57) { //Check if king and also if in bottom row if (column != 1) { if (board[location + 7] == emptyMarker) { //Check diagonally down left one location if (!jump) { movements.push(location + 7); } } else { if (board[location + 14] == emptyMarker) { //Check diagonally down left two locations if (column != 2) { if (checkPiece(location + 7)) { //Check diagonally down left one location for opponent if (!jump) { movements = [] } movements.push(location + 14); } } } } } if (column != 0) { if (board[location + 9] == emptyMarker) { //Check diagonally down right one location if (!jump) { movements.push(location + 9); } } else { if (board[location + 18] == emptyMarker) { //Check diagonally down right two locations if (column != 7) { if (checkPiece(location + 9)) { //Check diagonally down right one location for opponent if (!jump) { movements = [] } movements.push(location + 18); } } } } } } return movements; //Return all possible movements } function getCaptured(oldLocation, newLocation) { if (newLocation == oldLocation - 14) { return oldLocation - 7; } if (newLocation == oldLocation - 18) { return oldLocation - 9; } if (newLocation == oldLocation + 14) { return oldLocation + 7; } if (newLocation == oldLocation + 18) { return oldLocation + 9; } return 0; } //Convert remote locations ot local function convertSides(x) { return (-x) + 65; } //Game State var checkerState = { board: [], State: "waiting_selection", SelectedPiece: 0, Moves: [], color: "" }; //Clear some state information function clearState() { checkerState.SelectedPiece = 0; checkerState.Moves = []; clearAvaliableMoves(); } //Init Game function initGame(color, sendUpdate, sendCapture) { if (color == "red") { checkerState.State = "waiting_other_player"; //Black always moves first } else { checkerState.State = "waiting_selection"; //Let black start } checkerState.sendUpdate = sendUpdate; //Register the sendUpdate function. checkerState.sendCapture = sendCapture; //Register the sendCapture funcation checkerState.color = color; //Set player color clearState(); //Clear to known state. while (checkerState.board.length <= 64) { checkerState.board.push("empty") //Populate game board as all empty } opponentPieceStartLocation.forEach(function(x) { checkerState.board[x] = "opponentPiece"; }); //Place opponents pieces pieceStartLocation.forEach(function(x) { checkerState.board[x] = "piece"; }); //Place your pieces updateBoard(); //Update board on document } //handle Click events function BoardClickHandler(click_location) { if (checkerState.State == "waiting_selection" & ["king", "piece"].includes(checkerState.board[click_location])) { //If player turn and clicked on a vaild peice checkerState.SelectedPiece = click_location; //Save selected peice checkerState.State = "waiting_for_move" //Set to next state checkerState.Moves = availableMovements(click_location, checkerState.board, checkerState.board[click_location] == "king") //Get available moves if (checkerState.Moves == []) { checkerState.State == "waiting_selection"; } updateAvaliableMoves(); return; } if (checkerState.State == "waiting_for_move") { if (checkerState.Moves.includes(click_location)) { checkerState.State = "waiting_other_player"; checkerState.board[click_location] = checkerState.board[checkerState.SelectedPiece]; checkerState.board[checkerState.SelectedPiece] = "empty"; checkKingMe(); capturedPiece = getCaptured(checkerState.SelectedPiece, click_location) checkerState.sendUpdate(checkerState.SelectedPiece, click_location, capturedPiece > 0); if (capturedPiece > 0) { checkerState.board[capturedPiece] = "empty"; checkerState.sendCapture(capturedPiece); checkerState.State = "waiting_selection"; } clearState(); updateBoard(); return; } else { clearState(); checkerState.State = "waiting_selection"; BoardClickHandler(click_location); return; } } } function processCapture(loc) { checkerState.board[convertSides(loc)] = "empty" updateBoard(); } //Process update from remote function processUpdate(oldLocation, newLocation, didCapture) { checkerState.board[convertSides(newLocation)] = checkerState.board[convertSides(oldLocation)] checkerState.board[convertSides(oldLocation)] = "empty" checkRemoteKingMe(); //Ready to own selection if (!didCapture) { checkerState.State = "waiting_selection"; } //Lastly update board updateBoard(); } //Check for King function checkKingMe() { kingRow.forEach(function(x) { if (checkerState.board[x] == "piece") { checkerState.board[x] = "king" } }) } function checkRemoteKingMe() { opponentKingRow.forEach(function(x) { if (checkerState.board[x] == "opponentPiece") { checkerState.board[x] = "opponentKing" } }) } function checkPiece(x) { return checkerState.board[x] == "opponentPiece" | checkerState.board[x] == "opponentKing" } //Update Board function updateBoard() { updatePlayerTurnIndicator(); clearBoard(); allPieceLocations.forEach(function(x) { if (checkerState.board[x] == "opponentPiece") { if (checkerState.color == "red") { document.getElementById(x).classList.add("blackPiece"); } else { document.getElementById(x).classList.add("redPiece"); } } if (checkerState.board[x] == "opponentKing") { if (checkerState.color == "red") { document.getElementById(x).classList.add("blackKing"); } else { document.getElementById(x).classList.add("redKing"); } } if (checkerState.board[x] == "piece") { if (checkerState.color == "black") { document.getElementById(x).classList.add("blackPiece"); } else { document.getElementById(x).classList.add("redPiece"); } } if (checkerState.board[x] == "king") { if (checkerState.color == "black") { document.getElementById(x).classList.add("blackKing"); } else { document.getElementById(x).classList.add("redKing"); } } }) } //Clear all pieces from board function clearBoard() { allPieceLocations.forEach(function(x) { document.getElementById(x).classList.remove("avaliableMove"); document.getElementById(x).classList.remove("redKing"); document.getElementById(x).classList.remove("redPiece"); document.getElementById(x).classList.remove("blackKing"); document.getElementById(x).classList.remove("blackPiece"); }) } //Clear Abaliable Moves function clearAvaliableMoves() { allPieceLocations.forEach(function(x) { document.getElementById(x).classList.remove("avaliableMove"); }) } //Display all Avaliable Moves for current selected piece function updateAvaliableMoves() { checkerState.Moves.forEach(function(x) { document.getElementById(x).classList.add("avaliableMove"); }) } function updatePlayerTurnIndicator(){ console.log(checkerState) if(checkerState.State == "waiting_other_player"){ document.getElementById("playerindicator").innerHTML = "Other Player's Turn"; }else{ document.getElementById("playerindicator").innerHTML = "Your Turn"; } } //Register Click Handlers function registerClickHandlers() { document.getElementById("checkerboard").addEventListener("click", function(event) { BoardClickHandler(parseInt(event.target.id)); }); } checkers.addClickHandlers = registerClickHandlers; checkers.initGame = initGame; checkers.processUpdate = processUpdate; checkers.processCapture = processCapture; return checkers; } <file_sep>/README.md # SAW-project-two<file_sep>/PLANS.md # 500-words proposal outlining a significant future improvement to the project <file_sep>/public/javascripts/site.js 'use strict'; // Use 'sc' for the signlaing channel... var sc = io.connect('/' + NAMESPACE); // sc.on('message', function(data) { // console.log('Message recieved: ' + data); // }); // Track client states var clientIs = { makingOffer: false, ignoringOffer: false, polite: false, isSettingRemoteAnswerPending: false //settingRemoteAnswerPending: false } // Trying Mozilla's public STUN server stun.services.mozilla.org var rtc_config = { iceServers: [ { urls: ['stun:stun.l.google.com:19302', 'stun:stun1.l.google.com:19302'] } ] }; var pc = new RTCPeerConnection(rtc_config); // Set a placeholder for the data channel var dc = null; // Setting placeholder for game data channel var gameDC = null; // Add the data channel-backed DOM elements for the chat box var chatLog = document.querySelector('#chat-log'); var chatForm = document.querySelector('#chat-form'); var chatInput = document.querySelector('#message'); var chatButton = document.querySelector('#send-button'); // Creating a function that will append the message to the chat log function appendMessageToChatLog(log, msg, who) { var li = document.createElement('li'); var msg = document.createTextNode(msg); li.className = who; li.appendChild(msg); log.appendChild(li); if (chatLog.scrollTo) { chatLog.scrollTo({ top: chatLog.scrollHeight, behavior: 'smooth' }); } else { chatLog.scrollTop = chatLog.scrollHeight; } } // Adding a function that will 'listen' to the data channel function addDataChannelEventListeners(datachannel) { datachannel.onmessage = function(e) { appendMessageToChatLog(chatLog,e.data,'peer'); } // When opening the data channel datachannel.onopen = function() { chatButton.disabled = false; // enable the chat button chatInput.disabled = false; // enable the chat input box } // When closing the data channel datachannel.onclose = function() { chatButton.disabled = true; // disable the chat button chatInput.disabled = true; // disable the chat input box } // Submitting the chat form and appending the chat log chatForm.addEventListener('submit', function(e) { e.preventDefault() var msg = chatInput.value; appendMessageToChatLog(chatLog, msg, 'self'); datachannel.send(msg); chatInput.value = ''; }); } // Adding game data channel listeners function addGameDataChannelEventListeners(datachannel){ datachannel.onmessage = function(e) { checkersData(e.data); } // When opening the data channel datachannel.onopen = function() { } // When closing the data channel datachannel.onclose = function() { } } // Whence the RTCPeerConnection has reached a connection, // the polite peer will open the data channel pc.onconnectionstatechange = function(e) { console.log('Connection state:\n, pc.connectionState'); if (pc.connectionState == 'connected') { if (clientIs.polite) { console.log('Creating a data channel on the initiation side'); dc = pc.createDataChannel('text chat'); addDataChannelEventListeners(dc); gameDC = pc.createDataChannel('game data') addGameDataChannelEventListeners(gameDC); } } }; // This will ONLY work on the receiving end of the data channel connection // Listen for the data channel on the peer conenction pc.ondatachannel = function(e) { console.log('Heard a data channel open'); if(e.channel.label == 'text chat'){ dc = e.channel; addDataChannelEventListeners(dc); } if(e.channel.label == 'game data'){ gameDC = e.channel; addGameDataChannelEventListeners(gameDC); } }; // Let's handle video streams... // Set up simple media_constraints // We are disabling the audio of the video streams var media_constraints = { video: true, audio: true }; // Handle self video var selfVideo = document.querySelector('#self-video'); var selfStream = new MediaStream(); selfVideo.srcObject = selfStream; // Handle peer video var peerVideo = document.querySelector('#peer-video'); var peerStream = new MediaStream(); peerVideo.srcObject = peerStream; // Handle the start of media streaming async function startStream() { try { var stream = await navigator.mediaDevices.getUserMedia(media_constraints); for (var track of stream.getTracks()) { pc.addTrack(track); // Future improvement (I think) // selfStream.addTrack(track); } // TODO: Use the tracks here selfVideo.srcObject = stream; } catch(error) { console.error(error); } } // Listen for and attach any peer tracks pc.ontrack = function(track) { peerStream.addTrack(track.track); } // Call/answer button var callButton = document.querySelector('#call-button'); callButton.addEventListener('click', startCall); // Creating a function to start the call between the two users function startCall() { console.log('This is the calling side of the connection...'); callButton.hidden = true; clientIs.polite = true; sc.emit('calling'); startStream(); negotiateConnection(); // Append Player 1 title to chat box appendMessageToChatLog(chatLog, "Player 1"); } // Handle the 'calling' event on the receiving peer (the callee) sc.on('calling', function() { console.log('This is the receiving side of the connection...'); negotiateConnection(); callButton.innerText = "Answer Call"; callButton.id = "answer-button"; callButton.removeEventListener('click', startCall); callButton.addEventListener('click', function() { callButton.hidden = true; startStream(); // Append Player 2 title to chat box appendMessageToChatLog(chatLog, "Player 2"); }); }); // Setting up the peer connection. async function negotiateConnection() { pc.onnegotiationneeded = async function() { try { console.log('Making an offer...'); clientIs.makingOffer = true; try { // Very latest browsers are totally cool with an // argument-less call to setLocalDescription: await pc.setLocalDescription(); } catch(error) { // Older (and not even all that old) browsers // are NOT cool. So because we're making an // offer, we need to prepare an offer: var offer = await pc.createOffer(); await pc.setLocalDescription(new RTCPeerConnection(offer)); } finally { sc.emit('signal', { description: pc.localDescription }); } } catch(error) { console.error(error); } finally { clientIs.makingOffer = false; } } } // Detecting if there is a signal or not sc.on('signal', async function({ candidate, description }) { try { if (description) { // WebRTC Specification Perfect Negotiation Pattern var readyForOffer = !clientIs.makingOffer && (pc.signalingState == "stable" || clientIs.isSettingRemoteAnswerPending); // var offerCollision = description.type == "answer" && !readyForOffer; var offerCollision = description.type == "offer" && !readyForOffer; clientIs.ignoringOffer = !clientIs.polite && offerCollision; if (clientIs.ignoringOffer) { return; // Just leave if we're ignoring offers } // Set the remote description... try { console.log('Trying to set a remote description:\n', description); clientIs.isSettingRemoteAnswerPending = description.type == "answer"; await pc.setRemoteDescription(description); clientIs.isSettingRemoteAnswerPending = false; } catch(error) { console.error('Error from setting local description', error); } // ...if it's an offer, we need to answer it: if (description.type == 'offer') { console.log('Specifically, an offer description...'); try { // Very latest browsers are totally cool with an // argument-less call to setLocalDescription: await pc.setLocalDescription(); } catch(error) { // Older (and not even all that old) browsers // are NOT cool. So because we're handling an // offer, we need to prepare an answer: console.log('Falling back to older setLocalDescription method when receiving an offer...'); if (pc.signalingState == 'have-remote-offer') { // create a answer, if that's what's needed... console.log('Trying to prepare an answer:'); var offer = await pc.createAnswer(); } else { // otherwise, create an offer console.log('Trying to prepare an offer:'); var offer = await pc.createOffer(); } await pc.setLocalDescription(offer); } finally { console.log('Sending a response:\n', pc.localDescription); sc.emit('signal', { description: pc.localDescription }); } } } else if (candidate) { console.log('Received a candidate:'); //console.log(candidate); // Save Safari and other browsers that can't handle an // empty string for the `candidate.candidate` value: try { if (candidate.candidate.length > 1) { await pc.addIceCandidate(candidate); } } catch(error) { if (!clientIs.ignoringOffer) { throw error; } } } } catch(error) { console.error(error); } }); // Logic to send candidate pc.onicecandidate = function({candidate}) { sc.emit('signal', { candidate: candidate }); } // Creating button to start the checkers game var startGameButton = document.querySelector('#start-game'); startGameButton.addEventListener('click', startGame); // Creating local variable for our checkers game var checkersGame = Checkers(); // Creating a function that will update the checkers game data channel // When game pieces are moved across the board function sendCheckersUpdate(oldLoc,newLoc,capture){ gameDC.send(JSON.stringify({type:"update",oldLocation:oldLoc,newLocation:newLoc,didCapture:capture})); } function sendCheckersCapture(loc1){ gameDC.send(JSON.stringify({type:"capture",loc:loc1})); } // Creating function for starting the checkers game function startGame(){ if(gameDC != null & gameDC.readyState == "open"){ checkersGame.addClickHandlers(); startGameButton.style.visibility = "hidden" checkersGame.initGame("black",sendCheckersUpdate,sendCheckersCapture); gameDC.send(JSON.stringify({type:"start"})); } } // Creating function for our checkers game data function checkersData(data){ data = JSON.parse(data); if(data.type == "start"){ checkersGame.addClickHandlers(); startGameButton.style.visibility = "hidden" checkersGame.initGame("red",sendCheckersUpdate,sendCheckersCapture); } if(data.type == "update"){ checkersGame.processUpdate(data.oldLocation,data.newLocation,data.didCapture); } if(data.type == "capture"){ checkersGame.processCapture(data.loc); } }
f6a6b359917743503b07c1befa994ba4d25523e1
[ "JavaScript", "Markdown" ]
4
JavaScript
aaldossari/SAW-project-two
657ede7f6dbf7f7f3950ad17415f213236991fc4
1caff006f9fc1643eb079c7d0016dc670a62cdba
refs/heads/master
<repo_name>donottl/FlappyWorld<file_sep>/app/src/main/java/com/example/flappyw/StartGame.java package com.example.flappyw; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.ImageView; import androidx.annotation.Nullable; import java.io.FileNotFoundException; public class StartGame extends Activity { GameView gameView; static public Bitmap Charackter; static public Bitmap Tube; @Override public void onCreate(@Nullable Bundle savedInstanceState){ super.onCreate(savedInstanceState); Intent intent = getIntent(); if(getIntent() != null){ try { Tube = BitmapFactory.decodeStream(this.openFileInput("Tube")); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("Error Tube main"); } } if(getIntent() != null){ try { Charackter = BitmapFactory.decodeStream(this.openFileInput("Charackter")); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("Error Charackter main"); } } gameView = new GameView(this, null); setContentView(R.layout.game_view); } @Override public void onBackPressed() { super.onBackPressed(); Intent backmain = new Intent(StartGame.this,MainActivity.class); startActivity(backmain); finish(); } public static Bitmap returnTube(){ return Tube; } public static Bitmap returnCharackter(){ return Charackter; } }
83520b485f8863cd12f53170a6b5160edc57d6d5
[ "Java" ]
1
Java
donottl/FlappyWorld
d18e2dffba6c78cd349ea9fb8ac27605e504a945
ffb547b8e41468f0b9c67e7291df9edfbb13f24f
refs/heads/master
<repo_name>slighsity63/CA103<file_sep>/CA103G1/src/com/mem/model/MemDAO_interface.java package com.mem.model; import java.util.List; public interface MemDAO_interface { public void insert(MemVO memVO); public void update(MemVO memVO); public void delete(String mem_id); public void updateStatus(String mem_id,String mem_status); public MemVO findByPrimaryKey(String mem_id); public MemVO findByAccountAndPassword(String mem_Account, String mem_Password); public List<MemVO> getAll(); } <file_sep>/CA103G1/src/com/purchcour/model/PurchCourDAO_interface.java package com.purchcour.model; import java.util.List; public interface PurchCourDAO_interface { void add(PurchCourVO purchcour_vo); void updateScore(Integer coursco,String crorder_id); void updateRefund(String refund,String crorder_id); List<PurchCourVO> findByPK(String crorder_id); List<PurchCourVO> findByMem_id(String mem_id); List<PurchCourVO> findByKeyWord(String keyWord,String mem_id); //顯示進度未加 }<file_sep>/CA103G1/src/com/eve/model/EventDAO_interface.java package com.eve.model; import java.util.List; public interface EventDAO_interface { public void insert(EventVO eventVO); public void update(EventVO eventVO); public void update_status(String eve_id , String eve_status); public EventVO findByPrimaryKey(String eve_id); public List<EventVO> getAll(); public List<EventVO> getEvesByMem(String mem_id); // public void delete(String eve_id); //萬用複合查詢(傳入參數型態Map)(回傳 List) // public List<EmpVO> getAll(Map<String, String[]> map); } <file_sep>/CA103G1/src/com/plan/model/PlanJNDIDAO.java package com.plan.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; //DAO與JNDIDAO相同,只差在類別名稱不同。 //plan_start_date , plan_end_date , plan_create_time 時間表示方法還未健全。 //沒有刪除方法,使用計畫名稱關鍵字找到該計畫之方法尚未完成。 public class PlanJNDIDAO implements PlanDAO_interface { private static DataSource ds = null; static { try { Context ctx = new InitialContext(); ds = (DataSource) ctx.lookup("java:comp/env/jdbc/TestDB"); } catch (NamingException e) { e.printStackTrace(); } } private static final String INSERT_STMT = "INSERT INTO plan(plan_id,mem_id,plan_name,plan_vo,plan_cover,plan_start_date,plan_ens_date,sptype_id,plan_view,plan_privacy,plan_create_time,plan_status) VALUES (plan_seq.NEXTVAL,?,?,?,?,?,?,?,?,?,?,?)"; private static final String UPDATE = "UPDATE plan set plan_name=?, plan_vo=?, plan_cover=?,plan_start_date=? ,plan_end_date=? , sptype_id=?, plan_privacy=?, plan_status=? where plan_id = ? "; private static final String GET_ONE_STMT = "SELECT plan_id,mem_id,plan_name,plan_vo,plan_cover,to_char(plan_start_date,'yyyy-mm-dd')plan_start_date,to_char(plan_end_date,'yyyy-mm-dd')plan_end_date,sptype_id,plan_view,plan_privacy,to_char(plan_create_time,'yyyy-mm-dd')plan_create_time,plan_status FROM plan where plan_id = ?"; private static final String DELETE = "DELETE FROM plan where plan_id=?"; // 自訂方法(尚未完成) private static final String GET_ONE_STMT2 = "SELECT plan_id,mem_id,plan_name,plan_vo,plan_cover,to_char(plan_start_date,'yyyy-mm-dd')plan_start_date,to_char(plan_end_date,'yyyy-mm-dd')plan_end_date,sptype_id,plan_view,plan_privacy,to_char(plan_create_time,'yyyy-mm-dd'),plan_create_time,plan_status FROM plan where plan_name =?"; private static final String GET_ALL_STMT = "SELECT plan_id,mem_id,plan_name,plan_vo,plan_cover,to_char(plan_start_date ,'yyyy-mm-dd')plan_start_date,to_char(plan_end_date,'yyyy-mm-dd')plan_end_date,sptype_id,plan_view,plan_privacy,to_char(plan_create_time,'yyyy-mm-dd')plan_create_time,plan_status FROM plan order by plan_id "; @Override public void insert(PlanVO planVO) { Connection con = null; PreparedStatement pstmt = null; try { con = ds.getConnection(); pstmt = con.prepareStatement(INSERT_STMT); pstmt.setString(1, planVO.getPlan_id()); pstmt.setString(2, planVO.getMem_id()); pstmt.setString(3, planVO.getPlan_name()); pstmt.setString(4, planVO.getPlan_vo()); pstmt.setBytes(5, planVO.getPlan_cover()); pstmt.setTimestamp(6, planVO.getPlan_start_date()); pstmt.setTimestamp(7, planVO.getPlan_end_date()); pstmt.setString(8, planVO.getSptype_id()); pstmt.setInt(9, planVO.getPlan_view()); pstmt.setString(10, planVO.getPlan_privacy()); pstmt.setDate(11, planVO.getPlan_create_time()); pstmt.setString(12, planVO.getPlan_status()); pstmt.executeUpdate(); } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException se) { se.printStackTrace(); } } } } @Override public void update(PlanVO planVO) { Connection con = null; PreparedStatement pstmt = null; try { con = ds.getConnection(); pstmt = con.prepareStatement(UPDATE); pstmt.setString(1, planVO.getPlan_name()); pstmt.setString(2, planVO.getPlan_vo()); pstmt.setBytes(3, planVO.getPlan_cover()); pstmt.setTimestamp(4, planVO.getPlan_start_date()); pstmt.setTimestamp(5, planVO.getPlan_end_date()); pstmt.setString(6, planVO.getSptype_id()); pstmt.setString(7, planVO.getPlan_privacy()); pstmt.setString(8, planVO.getPlan_status()); pstmt.executeUpdate(); } catch (SQLException se) { throw new RuntimeException("A database error occured." + se.getMessage()); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException se) { se.printStackTrace(); } } } } @Override public void delete(String plan_id) { Connection con = null; PreparedStatement pstmt = null; try { con = ds.getConnection(); pstmt = con.prepareStatement(DELETE); pstmt.setString(1, "plan_id"); } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } } @Override public PlanVO findByPrimaryKey(String plan_id) { PlanVO planVO = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = ds.getConnection(); pstmt = con.prepareStatement(GET_ONE_STMT); pstmt.setString(1, plan_id); rs = pstmt.executeQuery(); while (rs.next()) { planVO = new PlanVO(); planVO.setPlan_id(rs.getString("plan_id")); planVO.setMem_id(rs.getString("mem_id")); planVO.setPlan_name(rs.getString("plan_name")); planVO.setPlan_vo(rs.getString("plan_vo")); planVO.setPlan_cover(rs.getBytes("plan_cover")); planVO.setPlan_start_date(rs.getTimestamp("plan_start_date")); planVO.setPlan_end_date(rs.getTimestamp("plan_end_date")); planVO.setSptype_id(rs.getString("sptype_id")); planVO.setPlan_view(rs.getInt("plan_view")); planVO.setPlan_privacy(rs.getString("plan_privacy")); planVO.setPlan_create_time(rs.getDate("plan_create_time")); planVO.setPlan_status(rs.getString("plan_status")); } } catch (SQLException se) { throw new RuntimeException("A database error occurred. " + se.getMessage()); } finally { if (rs != null) { try { rs.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException se) { se.printStackTrace(); } } } return planVO; } // 子串比對找出關鍵字,未完成。 @Override public PlanVO findPlanByKeyWord(String plan_name) { // PlanVO planVO = null; // String keyWord = null; // Connection con = null; // PreparedStatement pstmt = null; // ResultSet rs = null; // // try { // con = ds.getConnection(); // pstmt = con.prepareStatement(GET_ONE_STMT2); // // // // }catch(SQLException se) { // throw new RuntimeException("A database error occurred. " + se.getMessage()); // } return null; } @Override public List<PlanVO> getAll() { List<PlanVO> list = new ArrayList<PlanVO>(); PlanVO planVO = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = ds.getConnection(); pstmt = con.prepareStatement(GET_ALL_STMT); rs = pstmt.executeQuery(); while (rs.next()) { planVO = new PlanVO(); planVO.setPlan_id(rs.getString("plan_id")); planVO.setMem_id(rs.getString("mem_id")); planVO.setPlan_name(rs.getString("plan_name")); planVO.setPlan_vo(rs.getString("plan_vo")); planVO.setPlan_cover(rs.getBytes("plan_cover")); planVO.setPlan_start_date(rs.getTimestamp("plan_start_date")); planVO.setPlan_end_date(rs.getTimestamp("plan_end_date")); planVO.setSptype_id(rs.getString("sptype_id")); planVO.setPlan_view(rs.getInt("plan_view")); planVO.setPlan_privacy(rs.getString("plan_privacy")); planVO.setPlan_create_time(rs.getDate("plan_creat_time")); planVO.setPlan_status(rs.getString("plan_status")); list.add(planVO); } } catch (SQLException se) { throw new RuntimeException("A database error occurred. " + se.getMessage()); } finally { if (rs != null) { try { rs.close(); } catch (SQLException se) { se.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException se) { se.printStackTrace(); } } } return list; } } <file_sep>/CA103G1/src/com/purchcour/model/PurchCourDAO.java package com.purchcour.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class PurchCourDAO implements PurchCourDAO_interface { private static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String URL = "jdbc:oracle:thin:@localhost:1521:xe"; private static final String USER = "PROJECTTEST"; private static final String PASSWORD = "<PASSWORD>"; // SQL private static final String INSERT_STMT = "INSERT INTO PURCHCOUR(CRORDER_ID,CRORDER_TIME,COUR_ID,MEM_ID,REFUND)" + "VALUES('CO'||LPAD(to_char(purchcour_seq.NEXTVAL), 6, '0'),?, ?, ?,'CO1')"; private static final String UPDATE_SCORE_STMT = "UPDATE PURCHCOUR SET COURSCO = ? WHERE CRORDER_ID= ? AND REFUND='CO1'"; // 預設未退訂 private static final String UPDATE_REFUND_STMT = "UPDATE PURCHCOUR SET REFUND = ? WHERE CRORDER_ID= ? "; private static final String FIND_BY_MEM_ID = "SELECT * FROM PURCHCOUR WHERE MEM_ID=? AND REFUND='CO1'ORDER BY CRORDER_ID";// 展示清單用 private static final String FIND_BY_PK = "SELECT * FROM PURCHCOUR WHERE CRORDER_ID=? AND REFUND='CO1'"; private static final String FIND_BY_KEYWORD = "SELECT COURLIST.CNAME,COURLIST.COUR_COST,SPTYPE.SPORT, MEM.MEM_NAME FROM (((COURLIST LEFT JOIN PURCHCOUR ON COURLIST.COUR_ID=PURCHCOUR.COUR_ID)LEFT JOIN SPTYPE ON COURLIST.SPTYPE_ID=SPTYPE.SPTYPE_ID)LEFT JOIN COACH ON COURLIST.COA_ID=COACH.COA_ID)LEFT JOIN MEM ON COACH.MEM_ID =MEM.MEM_ID WHERE COURLIST.CNAME LIKE ? AND PURCHCOUR.MEM_ID=?"; // @Override public void add(PurchCourVO purchcourVo) { Connection con = null; PreparedStatement pstmt = null; try { Class.forName(DRIVER); con = DriverManager.getConnection(URL, USER, PASSWORD); pstmt = con.prepareStatement(INSERT_STMT); pstmt.setDate(1, purchcourVo.getCrorder_time()); pstmt.setString(2, purchcourVo.getCour_id()); pstmt.setString(3, purchcourVo.getMem_id()); pstmt.executeUpdate(); // Handle any driver errors } catch (ClassNotFoundException ce) { throw new RuntimeException("Couldn't load database driver. " + ce.getMessage()); // Handle any SQL errors } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); // Clean up JDBC resources } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } } @Override public void updateScore(Integer coursco, String crorder_id) { Connection con = null; PreparedStatement pstmt = null; try { Class.forName(DRIVER); con = DriverManager.getConnection(URL, USER, PASSWORD); pstmt = con.prepareStatement(UPDATE_SCORE_STMT); pstmt.setInt(1, coursco); pstmt.setString(2, crorder_id); pstmt.executeUpdate(); // Handle any driver errors } catch (ClassNotFoundException ce) { throw new RuntimeException("Couldn't load database driver. " + ce.getMessage()); // Handle any SQL errors } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); // Clean up JDBC resources } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } } @Override public void updateRefund(String refund, String crorder_id) { Connection con = null; PreparedStatement pstmt = null; try { Class.forName(DRIVER); con = DriverManager.getConnection(URL, USER, PASSWORD); pstmt = con.prepareStatement(UPDATE_REFUND_STMT); pstmt.setString(1, refund); pstmt.setString(2, crorder_id); pstmt.executeUpdate(); // Handle any driver errors } catch (ClassNotFoundException ce) { throw new RuntimeException("Couldn't load database driver. " + ce.getMessage()); // Handle any SQL errors } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); // Clean up JDBC resources } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } } @Override public List<PurchCourVO> findByPK(String crorder_id) { // TODO Auto-generated method stub return null; } @Override public List<PurchCourVO> findByMem_id(String mem_id) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; PurchCourVO purchcour_vo = null; List<PurchCourVO> purchcour_List = new ArrayList<>(); try { con = DriverManager.getConnection(URL, USER, PASSWORD); pstmt = con.prepareStatement(FIND_BY_MEM_ID); pstmt.setString(1, mem_id); rs = pstmt.executeQuery(); while (rs.next()) { purchcour_vo = new PurchCourVO(); purchcour_vo.setCrorder_id(rs.getString("CRORDER_ID")); purchcour_vo.setCrorder_time(rs.getDate("CRORDER_TIME")); purchcour_vo.setMem_id(rs.getString("MEM_ID")); purchcour_vo.setRefund(rs.getString("REFUND")); purchcour_vo.setCoursco(rs.getInt("COURSCO")); purchcour_List.add(purchcour_vo); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return purchcour_List; } // join @Override public List<PurchCourVO> findByKeyWord(String keyWord, String mem_id) { // TODO Auto-generated method stub return null; } }<file_sep>/CA103G1/src/com/eventlist/controller/EveListServlet.java package com.eventlist.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.eventlist.model.EventListVO; import com.eventlist.model.EventlistService; public class EveListServlet extends HttpServlet { private static final long serialVersionUID = 1L; Map<String,String> eveListStatusMap=null; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String action = req.getParameter("action"); HttpSession mapSession=req.getSession(); mapSession.setAttribute("eveListStatusMap", eveListStatusMap); if ("getEvelists_By_EVE".equals(action)) { // 來自select_page.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /***************************1.接收請求參數 **********************/ String eve_id = req.getParameter("eve_id"); /***************************2.開始查詢資料*****************************************/ EventlistService eveListSvc = new EventlistService(); List<EventListVO> eveListsByEve=eveListSvc.getEveListsByEve(eve_id); if(eveListsByEve.size()==0) { errorMsgs.add("查無資料"); } // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req .getRequestDispatcher("/front_end/event/eventlist/select_page.jsp"); failureView.forward(req, res); return;//程式中斷 } /***************************3.查詢完成,準備轉交(Send the Success view)*************/ req.setAttribute("eveListsByEve",eveListsByEve); // 資料庫取出的empVO物件,存入req String url =req.getContextPath()+ "/front_end/event/eventlist/EvelistsByEve.jsp"; HttpSession session=req.getSession(); session.setAttribute("eveListsByEve", eveListsByEve); res.sendRedirect(url); return;//程式中斷 /***************************其他可能的錯誤處理*************************************/ } catch (Exception e) { errorMsgs.add("無法取得資料:" + e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/front_end/event/eventlist/select_page.jsp"); failureView.forward(req, res); } } if ("getOne_For_Display".equals(action)) { // 來自select_page.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /***************************1.接收請求參數 **********************/ String eve_id = req.getParameter("eve_id"); String mem_id = req.getParameter("mem_id"); /***************************2.開始查詢資料*****************************************/ EventlistService eveListSvc = new EventlistService(); EventListVO eventListVO=eveListSvc.getOneEveList(mem_id,eve_id); if(eventListVO==null) { errorMsgs.add("查無資料"); } // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req .getRequestDispatcher("/front_end/event/eventlist/select_page.jsp"); failureView.forward(req, res); return;//程式中斷 } /***************************3.查詢完成,準備轉交(Send the Success view)*************/ req.setAttribute("eventListVO",eventListVO); // 資料庫取出的empVO物件,存入req String url ="/front_end/event/eventlist/listOneEvelist.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url); // 成功轉交 listOneEvelist.jsp successView.forward(req, res); /***************************其他可能的錯誤處理*************************************/ } catch (Exception e) { errorMsgs.add("無法取得資料:" + e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/front_end/event/eventlist/select_page.jsp"); failureView.forward(req, res); } } if ("insert".equals(action)) { // 來自addeveList.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /***********************1.接收請求參數 - 輸入格式的錯誤處理*************************/ String mem_id = req.getParameter("mem_id"); String enameReg = "^M\\d{6}$"; if (mem_id == null || mem_id.trim().length() == 0) { errorMsgs.add("會員編號: 請勿空白"); } else if(!mem_id.trim().matches(enameReg)) { //以下練習正則(規)表示式(regular-expression) errorMsgs.add("會員編號: 只能開頭是M,且後接長度6的數字"); } String eve_id= req.getParameter("eve_id").trim(); Integer evepay_amount=null; try { evepay_amount=new Integer(req.getParameter("evepay_amount").trim()); }catch(NumberFormatException e) { evepay_amount=0; errorMsgs.add("付款金額為整數數字."); } java.sql.Date evepay_deadline = null; try { evepay_deadline = java.sql.Date.valueOf(req.getParameter("evepay_deadline").trim()); } catch (IllegalArgumentException e) { evepay_deadline=new java.sql.Date(System.currentTimeMillis()+1000*86400*3); errorMsgs.add("請輸入日期!"); } String evelist_status = req.getParameter("evelist_status").trim(); if (evelist_status == null || evelist_status.trim().length() == 0) { errorMsgs.add("活動清單狀態請勿空白"); } String eve_share = req.getParameter("eve_share").trim(); if (eve_share == null || eve_share.trim().length() == 0) { errorMsgs.add("活動分享狀態請勿空白"); } Integer eve_rating = 0; EventListVO eventListVO = new EventListVO(); eventListVO.setMem_id(mem_id); eventListVO.setEve_id(eve_id); eventListVO.setEvepay_amount(evepay_amount); eventListVO.setEvepay_deadline(evepay_deadline); eventListVO.setEvelist_status(evelist_status); eventListVO.setEve_share(eve_share); eventListVO.setEve_rating(eve_rating); // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { req.setAttribute("eventListVO", eventListVO); // 含有輸入格式錯誤的eventListVO物件,也存入req RequestDispatcher failureView = req .getRequestDispatcher("/front_end/event/eventlist/addeveList.jsp"); failureView.forward(req, res); return; } System.out.println(mem_id); System.out.println(eve_id); System.out.println(eve_rating); System.out.println(evelist_status); System.out.println(evepay_amount); System.out.println(eve_share); System.out.println(evepay_deadline); System.out.println(); /***************************2.開始新增資料***************************************/ EventlistService eveListSvc = new EventlistService(); eventListVO=eveListSvc.addEveList(mem_id, eve_id, eve_rating, evelist_status, evepay_amount, eve_share, evepay_deadline); /***************************3.新增完成,準備轉交(Send the Success view)***********/ List<EventListVO> eveListsByMem=eveListSvc.getEveListsByMem(mem_id); String url =req.getContextPath()+ "/front_end/event/eventlist/listEvesByMem.jsp"; HttpSession session=req.getSession(); session.setAttribute("eveListsByMem", eveListsByMem); res.sendRedirect(url); return;//程式中斷 /***************************其他可能的錯誤處理**********************************/ } catch (Exception e) { errorMsgs.add(e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/front_end/event/eventlist/addeveList.jsp"); failureView.forward(req, res); e.printStackTrace(); } } if ("getOne_For_Update".equals(action)) { // 來自EvelistsByEve.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); try { /***********************1.接收請求參數 - 輸入格式的錯誤處理*************************/ String mem_id = req.getParameter("mem_id"); String eve_id=req.getParameter("eve_id"); /***************************2.開始查詢資料****************************************/ EventlistService eveListSvc = new EventlistService(); EventListVO eventListVO=eveListSvc.getOneEveList(mem_id, eve_id); /***************************3.查詢完成,準備轉交(Send the Success view)************/ req.setAttribute("eventListVO", eventListVO); // 資料庫取出的eventListVO物件,存入req String url = "/front_end/event/eventlist/update_evelist_input.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url);// 成功轉交 update_evelist_input.jsp successView.forward(req, res); /***************************其他可能的錯誤處理**********************************/ } catch (Exception e) { errorMsgs.add("無法取得要修改的資料:" + e.getMessage()); HttpSession session=req.getSession(); session.setAttribute("errorMsgs", errorMsgs); res.sendRedirect(req.getContextPath()+"/front_end/event/eventlist/EvelistsByEve.jsp"); return; } } if ("update".equals(action)) { // 來自update_evelist_input.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /***************************1.接收請求參數 - 輸入格式的錯誤處理**********************/ String mem_id = req.getParameter("mem_id"); String enameReg = "^M\\d{6}$"; if (mem_id == null || mem_id.trim().length() == 0) { errorMsgs.add("會員編號: 請勿空白"); } else if(!mem_id.trim().matches(enameReg)) { //以下練習正則(規)表示式(regular-expression) errorMsgs.add("會員編號: 只能開頭是M,且後接長度6的數字"); } String eve_id= req.getParameter("eve_id").trim(); Integer evepay_amount=null; try { evepay_amount=new Integer(req.getParameter("evepay_amount").trim()); }catch(NumberFormatException e) { evepay_amount=0; errorMsgs.add("付款金額為整數數字."); } java.sql.Date evepay_deadline = null; if(req.getParameter("evepay_deadline")!=null) { try { evepay_deadline = java.sql.Date.valueOf(req.getParameter("evepay_deadline").trim()); } catch (IllegalArgumentException e) { evepay_deadline=new java.sql.Date(System.currentTimeMillis()+1000*86400*3); errorMsgs.add("請輸入日期!"); } } String evelist_status = req.getParameter("evelist_status").trim(); if (evelist_status == null || evelist_status.trim().length() == 0) { errorMsgs.add("活動清單狀態請勿空白"); } String eve_share = req.getParameter("eve_share").trim(); if (eve_share == null || eve_share.trim().length() == 0) { errorMsgs.add("活動分享狀態請勿空白"); } Integer eve_rating = 0; try { eve_rating=new Integer(req.getParameter("eve_rating").trim()); if(eve_rating>5||eve_rating<1) { eve_rating=0; } }catch(NumberFormatException e) { eve_rating=0; errorMsgs.add("活動評價為1-5之整數"); } EventListVO eventListVO = new EventListVO(); eventListVO.setMem_id(mem_id); eventListVO.setEve_id(eve_id); eventListVO.setEvepay_amount(evepay_amount); eventListVO.setEvepay_deadline(evepay_deadline); eventListVO.setEvelist_status(evelist_status); eventListVO.setEve_share(eve_share); eventListVO.setEve_rating(eve_rating); // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { req.setAttribute("eventListVO", eventListVO); // 含有輸入格式錯誤的eventListVO物件,也存入req RequestDispatcher failureView = req .getRequestDispatcher("/front_end/event/eventlist/update_evelist_input.jsp"); failureView.forward(req, res); return; } /***************************2.開始修改資料***************************************/ EventlistService eveListSvc = new EventlistService(); eventListVO=eveListSvc.updateEveList(mem_id, eve_id, eve_rating, evelist_status, evepay_amount, eve_share, evepay_deadline); /***************************3.修改完成,準備轉交(Send the Success view)***********/ req.setAttribute("eventListVO",eventListVO); String requestURL = req.getParameter("requestURL"); if("/front_end/event/eventlist/EvelistsByEve.jsp".equals(requestURL)) { List<EventListVO> list=eveListSvc.getEveListsByEve(eve_id); HttpSession session=req.getSession(); session.setAttribute("eveListsByEve", list); } System.out.println(requestURL); RequestDispatcher successView = req.getRequestDispatcher(requestURL); // 修改成功後轉交 listOneEvelist.jsp successView.forward(req, res); /***************************其他可能的錯誤處理**********************************/ } catch (Exception e) { errorMsgs.add(e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/front_end/event/eventlist/update_evelist_input.jsp"); failureView.forward(req, res); e.printStackTrace(); } } if ("delete".equals(action)) { // 來自listEvesByMem.jsp List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs",errorMsgs ); String requestURL = req.getParameter("requestURL"); try { /***************************1.接收請求參數***************************************/ String mem_id=req.getParameter("mem_id"); String eve_id=req.getParameter("eve_id"); String evelist_status="EL9"; /***************************2.開始刪除資料***************************************/ EventlistService eveListSvc = new EventlistService(); eveListSvc.changeEveListStatus(mem_id, eve_id, evelist_status); if("/front_end/event/eventlist/EvelistsByEve.jsp".equals(requestURL)) { List<EventListVO> list=eveListSvc.getEveListsByEve(eve_id); HttpSession session=req.getSession(); session.setAttribute("eveListsByEve", list); session.setAttribute("errorMsgs",errorMsgs ); } /***************************3.刪除完成,準備轉交(Send the Success view)*************/ RequestDispatcher successView = req.getRequestDispatcher(requestURL); // 刪除成功後,轉交回送出刪除的來源網頁 successView.forward(req, res); return;//程式中斷 /***************************其他可能的錯誤處理*************************************/ } catch (Exception e) { errorMsgs.add("刪除資料失敗:" +e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher(requestURL); failureView.forward(req, res); e.printStackTrace(); return;//程式中斷 } } if ("update_modal".equals(action)) { try { // Retrieve form parameters. String eve_id = req.getParameter("eve_id"); String mem_id = req.getParameter("mem_id"); EventlistService eveListSvc = new EventlistService(); EventListVO eventListVO=eveListSvc.getOneEveList(mem_id,eve_id); req.setAttribute("eventListVO", eventListVO); // 資料庫取出的empVO物件,存入req // //Bootstrap_modal boolean openupModal=true; req.setAttribute("openupModal",openupModal ); // 取出的empVO送給listOneEmp.jsp RequestDispatcher successView = req .getRequestDispatcher("/front_end/event/eventlist/listEvesByMem.jsp"); successView.forward(req, res); return; // Handle any unusual exceptions } catch (Exception e) { throw new ServletException(e); } } if ("getOne_modal".equals(action)) { try { // Retrieve form parameters. String eve_id = req.getParameter("eve_id"); String mem_id = req.getParameter("mem_id"); EventlistService eveListSvc = new EventlistService(); EventListVO eventListVO=eveListSvc.getOneEveList(mem_id,eve_id); req.setAttribute("eventListVO", eventListVO); // 資料庫取出的empVO物件,存入req // //Bootstrap_modal boolean openModal=true; req.setAttribute("openModal",openModal ); // 取出的empVO送給listOneEmp.jsp RequestDispatcher successView = req .getRequestDispatcher("/front_end/event/eventlist/listEvesByMem.jsp"); successView.forward(req, res); return; // Handle any unusual exceptions } catch (Exception e) { throw new ServletException(e); } } if ("update_status".equals(action)) { try { // Retrieve form parameters. String eve_id = req.getParameter("eve_id"); String mem_id = req.getParameter("mem_id"); String share_status = req.getParameter("sharestatus"); EventlistService eveListSvc = new EventlistService(); eveListSvc.changeShareStatus(mem_id, eve_id,share_status); EventListVO eventListVO=eveListSvc.getOneEveList(mem_id,eve_id); System.out.println(eventListVO.getEve_share()); RequestDispatcher successView = req .getRequestDispatcher("/front_end/event/eventlist/listEvesByMem.jsp"); successView.forward(req, res); return; // Handle any unusual exceptions } catch (Exception e) { throw new ServletException(e); } } } public void init() { eveListStatusMap=new HashMap<>(); eveListStatusMap.put("EL0", "不須付款"); eveListStatusMap.put("EL1", "未付款"); eveListStatusMap.put("EL2", "已付款未確認"); eveListStatusMap.put("EL3", "確認已付款"); eveListStatusMap.put("EL4", "退款未處理"); eveListStatusMap.put("EL5", "已退款未確認"); eveListStatusMap.put("EL6", "退款已確認"); eveListStatusMap.put("EL7", "退出(不須付款)"); eveListStatusMap.put("EL9", "隱藏"); } }
176cd14543edd0b3eb1dad2809ded538c28cb34b
[ "Java" ]
6
Java
slighsity63/CA103
6c51d6a7aec525008d866ba637736d17716ce2a9
227055f20f5e3d6cfc7c070d9fc8449bf995c6c8
refs/heads/master
<repo_name>kundan9572/Tour-of-Goa<file_sep>/src/app/goa-detail/goa-detail.component.ts import { Component, Input, OnInit } from '@angular/core'; import { from } from 'rxjs'; import { GOA } from '../goaInterface'; @Component({ selector: 'app-goa-detail', templateUrl: './goa-detail.component.html', styleUrls: ['./goa-detail.component.css'] }) export class GoaDetailComponent implements OnInit { @Input() goa: GOA; constructor() { } ngOnInit(): void { } } <file_sep>/src/app/goa-service.service.spec.ts import { TestBed } from '@angular/core/testing'; import { GoaServiceService } from './goa-service.service'; describe('GoaServiceService', () => { let service: GoaServiceService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(GoaServiceService); }); it('should be created', () => { expect(service).toBeTruthy(); }); }); <file_sep>/src/app/goa-service.service.ts import { Injectable } from '@angular/core'; import { from, Observable, of } from 'rxjs'; import { GOA } from './goaInterface'; import { MOCKGOA } from './mock-goa'; import { MessageService} from './message.service'; @Injectable({ providedIn: 'root' }) export class GoaServiceService { constructor( private messageService: MessageService) { } getGoa(): Observable<GOA[]>{ this.messageService.add('GoaService: fetched Goa') return of(MOCKGOA); } } <file_sep>/src/app/mock-goa.ts import { GOA } from '../app/goaInterface'; export const MOCKGOA: GOA[] = [ {id:1, name: 'Sachin'}, {id:2, name: 'Dhoni'}, {id:3, name: 'Deviller'}, {id:4, name: 'Ponting'}, {id:5, name: 'Kumbale'}, {id:6, name: 'Zahir'}, {id:7, name: 'Rahul'}, {id:8, name: 'Raina'} , {id:9, name: 'Virat'}, {id:10, name: 'Chahal'}, {id:11, name: 'Bumrah'} ] ;<file_sep>/src/app/goa/goa.component.ts import { Component, OnInit } from '@angular/core'; import { from } from 'rxjs'; import { GOA } from '../goaInterface'; import { MOCKGOA } from '../mock-goa'; import { GoaServiceService } from '../goa-service.service'; import { MessageService} from '../message.service'; @Component({ selector: 'app-goa', templateUrl: './goa.component.html', styleUrls: ['./goa.component.css'] }) export class GoaComponent implements OnInit { goa: GOA[]; selectedGoa: GOA; constructor(private goaService: GoaServiceService , private messageService: MessageService) { } getGoa(): void{ this.goaService.getGoa().subscribe(goa => this.goa = goa) } ngOnInit(): void { this.getGoa(); } onSelect(goa:GOA){ this.selectedGoa = goa; this.messageService.add('GoaServiceService: You have selected a Goa Invitation') } }
0359ba2cec517c14fb664f9051efbfaefac8faea
[ "TypeScript" ]
5
TypeScript
kundan9572/Tour-of-Goa
7dd56cb4bf0bb03fb3a11d0f7ba8f9d85a27f863
50577c1e9835300e569bd6d44ac33b9a85c99f75
refs/heads/main
<file_sep>[![CircleCI](https://circleci.com/gh/wilfriedpapt89/will-pet-clinic/tree/main.svg?style=svg)](https://circleci.com/gh/wilfriedpapt89/will-pet-clinic/tree/main) # will-pet-clinic SFT Pet Clinic Project to master Spring framework <file_sep>package com.willpapt.willpetclinic.services; import com.willpapt.willpetclinic.model.Speciality; public interface SpecialtysService extends CrudService<Speciality, Long>{ } <file_sep>package com.willpapt.willpetclinic.services; import com.willpapt.willpetclinic.model.PetType; public interface PetTypeService extends CrudService<PetType, Long> { } <file_sep>package com.willpapt.willpetclinic.services; import com.willpapt.willpetclinic.model.Owner; import com.willpapt.willpetclinic.model.Vet; import java.util.Set; public interface VetService extends CrudService<Vet,Long>{ }
2c01b548f6eda9654343c7f27d6207de5f259b38
[ "Markdown", "Java" ]
4
Markdown
wilfriedpapt89/will-pet-clinic
15e4df2bdcb5608474c95a24b2be2c01268e2009
ef1500e0e740c9d9ec100eb2c11ddfe98c88236a
refs/heads/master
<file_sep>var kittens = ["Milo", "Otis", "Garfield"] //define your array here function destructivelyAppendKitten(kitten) { kittens.push(kitten); } function destructivelyPrependKitten(kitten) { kittens.unshift(kitten); } function destructivelyRemoveLastKitten(kitten) { kittens.pop(kitten); } function destructivelyRemoveFirstKitten(kitten) { kittens.shift(kitten) } function appendKitten(name) { var kitten2 = [name] var kittens3 = kittens.concat(kitten2); return kittens3 } function prependKitten(name) { var kitten2 = [name] var kittens3 = kitten2.concat(kittens) return kittens3 } function removeLastKitten() { var kitten2 = kittens.slice(0,2) return kitten2 } // Add your functions and code here function removeFirstKitten() { var kitten2 = kittens.slice(1) return kitten2 }
dd9ac6f46eea097d6b2b87fce3fd2141d7c52291
[ "JavaScript" ]
1
JavaScript
Jclate/javascript-arrays-lab-bootcamp-prep-000
b99bf5c58193bf0fc3a0a59083a09e3b8039f3c1
f99754062ec5e0488493d695da11d7a51625398d
refs/heads/master
<repo_name>NicholasDerkach/hello-world<file_sep>/README.md # hello-world My first programm on GitHub Hello, world! I am <NAME>, student of the second course of the Kyiv National University of Kyiv. I like to dream about future and past. My favorite book is "Fathers and Sons" by <NAME>. Buy! <file_sep>/lab3/scripts/formsc.js var inpElem; var divElem; function preview(file) { "use strict"; if (file.type.match(/image.*/)) { var reader = new FileReader(); var img; reader.addEventListener("load", function (event) { img = document.getElementById("previewImg"); img.src = event.target.result; }); reader.readAsDataURL(file); } } function uploadFile() { "use strict"; inpElem = document.getElementById("upload"); divElem = document.getElementById("preview"); inpElem.addEventListener("change", function () { preview(inpElem.files[0]); }); } window.onload = function () { 'use strict'; uploadFile(); };
6fba18733df1275709e4f53a24648a5c654ee477
[ "Markdown", "JavaScript" ]
2
Markdown
NicholasDerkach/hello-world
4911dd61422bbc95567693521520b4c107fde521
947f8bf26dc31c58dfc3ca1f468b1a432e0018fa
refs/heads/master
<file_sep>package com.spring.user.controllers; import java.util.List; import com.spring.user.entities.Message; import com.spring.user.exceptions.DatabaseException; import com.spring.user.services.MessageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/rest/messages") @CrossOrigin(origins = "*") public class MessageController { @Autowired private MessageService service; @GetMapping public ResponseEntity<?> getMessages() { try { return new ResponseEntity<List<Message>>(this.service.list(), HttpStatus.OK); } catch (DatabaseException e) { return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } @PostMapping public ResponseEntity<?> createMessage(@RequestBody Message message) { try { return new ResponseEntity<Message>(this.service.create(message), HttpStatus.OK); } catch (DatabaseException e) { return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } @GetMapping(value = "/ofuser/{userId}") public ResponseEntity<?> getMessagesByUserId(@PathVariable Long userId) { try { return new ResponseEntity<List<Message>>(this.service.getByUserId(userId), HttpStatus.OK); } catch (DatabaseException e) { return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } } <file_sep>package com.spring.user.controllers; import java.util.List; import com.spring.user.entities.User; import com.spring.user.exceptions.DatabaseException; import com.spring.user.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/rest/users") @CrossOrigin(origins = "*") public class UserController { @Autowired UserService service; @GetMapping public ResponseEntity<?> list() { try { List<User> users = this.service.list(); return new ResponseEntity<List<User>>(users, HttpStatus.OK); } catch (DatabaseException e) { return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } @PostMapping public ResponseEntity<?> create(@RequestBody User user) { try { return new ResponseEntity<User>(this.service.create(user), HttpStatus.OK); } catch (DatabaseException e) { return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } } <file_sep>server.port=8090 spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=postgresql spring.datasource.platform=postgres spring.datasource.url=jdbc:postgresql://localhost:5432/user spring.datasource.username=postgres spring.datasource.password=<PASSWORD> spring.jpa.properties.hibernate.globally_quoted_identifiers=true
3c62b6382a854b82f13aca96e5ba2d6bf11f4792
[ "Java", "INI" ]
3
Java
HackathonJavaReact/localedatetime-spring
5d4354f44d588aa51573aef20e9be1bb0ccba0ae
71e71f29cd4c449f8e83e79ff828786a3c24ed50
refs/heads/main
<repo_name>iron1976/peaceinclasspeaceinschool<file_sep>/js/main.js if(window.location.hash === "#en") document.getElementById("btn_language").innerHTML = "TR"; else if(window.location.hash === "#tr") document.getElementById("btn_language").innerHTML = "EN"; else document.getElementById("btn_language").innerHTML = "EN"; //insta:https://www.instagram.com/peaceinclasspeaceinschool/ //youtube: document.getElementById("instagram_logo").onclick = function(){to_url("https://www.instagram.com/peaceinclasspeaceinschool/");}; print('<p style="color:red">hi</p>'); <file_sep>/README.md # peaceinclasspeaceinschool I made a website for my school project ka229(PEACE IN CLASS PEACE IN SCHOOL). Okul projem "SINIFTA BARIŞ OKULDA BARIŞ" adlı projem için yaptığım websitem. EN: In this website i used js&jquery, PHP, HTML, CSS. I knew already PHP so i only learnt js, HTML, CSS in a week or so. After that i started to make this website. Even i proceed so much unfortunately i stopped developing the website due to my project coordinator. TR: Bu websitesinde kullandığım diller js&jquery, PHP, HTML, CSS. PHP'yi zaten biliyordum bu yüzden js, HTML, CSS dillerini tahmini 1 hafta içinde öğrendim. Sonra da websiteyi yapmaya başladım. Ne kadar çok ilerlemiş olsamda websitesini yapmayı bıraktım proje kordinatöründen dolayı. <file_sep>/js/functions.js function switch_language() { if(window.location.hash === "#en") window.location = "file:///C:/Users/PC/Desktop/web/xampp/htdocs/index.html#tr"; else if(window.location.hash === "#tr") window.location = "file:///C:/Users/PC/Desktop/web/xampp/htdocs/index.html#en"; else window.location = "file:///C:/Users/PC/Desktop/web/xampp/htdocs/index.html#tr"; if(window.location.hash === "#en") document.getElementById("btn_language").innerHTML = "TR"; else if(window.location.hash === "#tr") document.getElementById("btn_language").innerHTML = "EN"; } var print = function(value) { document.getElementById("main_screen").innerHTML += value; }; function to_url(url) { window.location = url; };
511e0eaa21e870aa01a2ffd4798661ff13c8ea2d
[ "JavaScript", "Markdown" ]
3
JavaScript
iron1976/peaceinclasspeaceinschool
7f636832d5e62ca6b146c6f864201709f785dc7b
222c7bab387cb8de94b5534b04f71f24e5d40bfe
refs/heads/master
<repo_name>swhitfi2/guest-angular<file_sep>/src/app/guest/guest.component.ts import { Response } from '@angular/http'; import { GuestService } from '../services/guest.services'; import Guest from '../models/guest.models'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-guest', templateUrl: './guest.component.html', styleUrls: ['./guest.component.scss'] }) export class GuestComponent implements OnInit { constructor( //Private guestservice will be injected into the component by Angular Dependency Injector private guestService: GuestService ) { } //Declaring the new guest Object and initilizing it public newGuest: Guest = new Guest() //An Empty list for the visible guest list //instatiates an empty array to allow methods to have aa holding guestsList: Guest[]; editGuests: Guest[] = []; // the equals [] //calls the service ask the service for the guests ngOnInit(): void { //At component initialization the this.guestService.getGuests() .subscribe(guests => { //assign the guestlist property to the proper http response this.guestsList = guests console.log(guests) }) } //This method will get called on Create button event create() { this.guestService.createGuest(this.newGuest) .subscribe((res) => { this.guestsList.push(res.data) this.newGuest = new Guest() /// this allows the new guest in form to clear the fields }) } //edit function editGuest(guest: Guest) { console.log(guest)//debug code line to see values if(this.guestsList.includes(guest)){ // is this a guest retrieved from the api if(!this.editGuests.includes(guest)){ //is this in the list to be edited this.editGuests.push(guest) //if not in the list add to edit list }else{ this.editGuests.splice(this.editGuests.indexOf(guest), 1)// remove this element from the array get the right guests this.guestService.editGuest(guest).subscribe(res => { // call to service console.log('Update Succesful') }, err => { //this.editGuest(guest) console.error('Update Unsuccesful') }) } } } //updating the status to complete change status to done //changed from Done doneGuest(guest:Guest){ guest.status = 'Checked Out' this.guestService.editGuest(guest).subscribe(res => { console.log('Update Succesful') }, err => { //this.editGuest(guest) console.error('Update Unsuccesful') }) } //listening for the enter key event if selected edit guest field submitGuest(event, guest:Guest){ if(event.keyCode ==13){ // keycode ==13 is the enter key this.editGuest(guest) } } //delete function deleteGuest(guest: Guest) { this.guestService.deleteGuest(guest._id).subscribe(res => { this.guestsList.splice(this.guestsList.indexOf(guest), 1); //betterway can ask api for the list }) } }<file_sep>/src/app/services/guest.services.ts import Guest from '../models/guest.models'; import { Observable } from 'rxjs'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Response } from '@angular/http'; import { Injectable } from '@angular/core'; import { map } from 'rxjs/operators'; @Injectable()//required to allow services to be pasted around export class GuestService { api_url = 'http://localhost:3000'; guestUrl = `${this.api_url}/api/guests`; constructor(private http: HttpClient) { } //Create guest, takes a Guest Object createGuest(guest: Guest): Observable<any>{ //returns the observable of http post request return this.http.post(`${this.guestUrl}`, guest); } //Read guest, takes no arguments getGuests(): Observable<Guest[]>{ return this.http.get(this.guestUrl)//this function returns an observable .pipe(map(res => { //Maps the response object sent from the server //map is success we are not handling errors in this example return res["data"].docs as Guest[]; })) } //Update guest, takes a Guest Object as parameter makes a put request editGuest(guest:Guest){ let editUrl = `${this.guestUrl}` //returns the observable of http put request return this.http.put(editUrl, guest); } //delete guest deleteGuest(id:string):any{ //Delete the object by the id let deleteUrl = `${this.guestUrl}/${id}` return this.http.delete(deleteUrl) .pipe(map(res => { return res; })) } //currently not being used private handleError(error: any): Promise<any> { console.error('An error occurred', error); // for demo purposes only return Promise.reject(error.message || error); } }
c770d2a4b283429713dbd6a245ce9097d82b8c4b
[ "TypeScript" ]
2
TypeScript
swhitfi2/guest-angular
90a8d2435dc130e343efde79542c58738a8143f9
c3726bbe3f3584e328a17da854ce7dc9ed4b00c7
refs/heads/master
<file_sep>import discord import youtube import setting import connect_pg import os import traceback DISCORD_TOKEN =os.environ.get('DISCORD_TOKEN') DISCORD_CHANNEL_ID = os.environ.get('DISCORD_CHANNEL_ID') DATABASE_URL = os.environ.get('DATABASE_URL') YT_CHANNEL_ID = os.environ.get('YT_CHANNEL_ID') client = discord.Client() @client.event async def on_ready(): # print('Logged in as') # print(client.user.name) # print(client.user.id) # print('------') channel = client.get_channel(int(DISCORD_CHANNEL_ID)) try: # await channel.send("起動しました") clip_id = youtube.get_clip_id(YT_CHANNEL_ID) if not connect_pg.select(clip_id): # clip_idがdbに登録されていなかったら connect_pg.insert(clip_id) #dbに書き込み await channel.send("Marimo NIghtcoreより\n" + youtube.search_pic_url(clip_id)) else: print("Picture already posted.") except: await channel.send("画像の取得に失敗しました") traceback.print_exc() finally: await client.logout() await sys.exit() @client.event async def on_message(message): # 「おはよう」で始まるか調べる if message.content.startswith("おはよう"): # 送り主がBotだった場合反応したくないので if client.user != message.author: # メッセージを書きます m = "おはようございます" + message.author.name + "さん!" # メッセージが送られてきたチャンネルへメッセージを送ります await message.channel.send(m) #ループ処理実行 # loop.start() # client.loop.create_task(my_background_task()) # Botの起動とDiscordサーバーへの接続 client.run(DISCORD_TOKEN) <file_sep>import os from os.path import join, dirname from dotenv import load_dotenv load_dotenv(verbose=True) dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) # YT_DEVELOPPER_KEY = os.environ.get('YT_DEVELOPPER_KEY') # YT_CHANNEL_ID = os.environ.get('YT_CHANNEL_ID') # DISCORD_TOKEN =os.environ.get('DISCORD_TOKEN') # DISCORD_CHANNEL_ID = os.environ.get('DISCORD_CHANNEL_ID') # DATABASE_URL = os.environ.get('DATABASE_URL') <file_sep>import requests, json, datetime import os import setting YT_DEVELOPPER_KEY = os.environ.get('YT_DEVELOPPER_KEY') YT_CHANNEL_ID = os.environ.get('YT_CHANNEL_ID') def get_clip_id(channel_id): ''' 指定Youtubeチャンネルの最新動画のIDを取得する str -> str ''' url = "https://www.googleapis.com/youtube/v3/search" # endpoint query = { "channelId": channel_id, "part": "snippet", "key": YT_DEVELOPPER_KEY, "order": "date" } api_res = requests.get(url, params=query) # print("status:", api_res.status_code) # print("title:", api_res.json()["items"][0]["snippet"]["title"]) # print("videoId:", api_res.json()["items"][0]["id"]["videoId"]) clip_id = api_res.json()["items"][0]["id"]["videoId"] # clip_url = "https://www.youtube.com/watch?v=" + api_res.json()["items"][0]["id"]["videoId"] return clip_id def search_pic_url(clip_id): ''' 指定動画で使われている画像のリンク先URLを取得する str -> str ''' url = "https://www.googleapis.com/youtube/v3/videos" # endpoint query = { "id": clip_id, "part": "snippet", "key": YT_DEVELOPPER_KEY } api_res = requests.get(url, params=query) description = api_res.json()["items"][0]["snippet"]["description"] pic_pos = description.find("Picture Link") bar_pos = description.find("▬", pic_pos) pic_url = description[pic_pos+14: bar_pos] return pic_url def extract_pic_url(page_url): ''' 画像ページから画像URLを抜き出す str -> str ''' # ページのすべてのimgタグ要素を取得 # 最大サイズの画像を特定 # width, height属性 # その他の方法 if __name__ == "__main__": pass # clip_id = get_clip_id(YT_CHANNEL_ID) # print("clip_id:", clip_id) # pic_url = search_pic_url(clip_id) # print("pic_url:", pic_url) <file_sep>import psycopg2 import os import datetime import setting # print(psycopg2.apilevel) DATABASE_URL = os.environ.get('DATABASE_URL') def get_connection(): return psycopg2.connect(DATABASE_URL) def create_table(): #citiesテーブルが存在したらdrop conn = get_connection() cur = conn.cursor() cur.execute('DROP TABLE IF EXISTS nightcore') #CREATE cur.execute(''' CREATE TABLE nightcore ( clip_id text UNIQUE, t timestamp NOT NULL ) ''') conn.commit() conn.close() def insert(clip_id): conn = get_connection() cur = conn.cursor() #INSERT dt = datetime.datetime.now() cur.execute('INSERT INTO nightcore VALUES(%s, %s)', (clip_id, dt)) # cur.execute('INSERT INTO cities VALUES (%(rank)s, %(city)s, %(population)s)', # {'rank': 2, 'city': 'カラチ', 'population': 23500000}) # cur.executemany(' INSERT INTO cities VALUES (%(rank)s, %(city)s, %(population)s)', [ # {'rank': 3, 'city': '北京', 'population': 21516000}, # {'rank': 4, 'city': '天津', 'population': 14722100}, # {'rank': 5, 'city': 'イスタンブル', 'population': 14160467} # ]) conn.commit() conn.close() def select(clip_id): #SELECT res = False with get_connection() as conn: with conn.cursor() as cur: cur.execute('SELECT * FROM nightcore WHERE clip_id = %s', (clip_id,)) if cur: for row in cur: res = True else: res = False conn.close() return res def delete(clip_id): conn = get_connection() cur = conn.cursor() cur.execute('DELETE FROM nightcore WHERE clip_id = %s', (clip_id,)) conn.commit() conn.close() def select_all(): #SELECT with get_connection() as conn: with conn.cursor() as cur: cur.execute('SELECT * FROM nightcore') if cur: for row in cur: print(row) else: return False conn.close()
2f46cdf94f2fc931415892a84cf6ee0b3dbd010b
[ "Python" ]
4
Python
mfushimi09/yt_nightcore
f5a9cbbaa838c5fc8a65201336fd49888b3d5223
f191472ffbfbbeb00b941063e1f3c4bd72372b07
refs/heads/master
<file_sep>// banner轮播 function bannerlunbo() { var imgbox=getClass("back-banner-box") var btbox=getClass("btbox")[0] var bannerbox=getClass("banner-box")[0] var bt=btbox.getElementsByTagName("li") var num=0 var settime=function () { num++ if(num>5) { num=0 } for(var i = 0; i < imgbox.length; i++) { bt[i].style.background="#aaa" imgbox[i].style.display="none" } imgbox[num].style.display="block" bt[num].style.background="#fff" } var time=setInterval(settime,2000) for(var i=0;i<bt.length;i++) { bt[i].index=i; bt[i].onmouseover=function() { for(var j=0;j<bt.length;j++) { bt[j].style.background="#aaa" imgbox[j].style.display="none" } bt[this.index].style.background="#fff" imgbox[this.index].style.display="block" } bt[i].onmouseout=function() { num=this.index; } } bannerbox.onmouseover=function() { clearInterval(time); } bannerbox.onmouseout=function() { time=setInterval(settime,2000) } } // 热门品牌圆点 function xiaoyuandian() { var abox=$(".rmpp-bottom-right") for (var i = 0; i < abox.length; i++) { var box=abox[i].getElementsByTagName("a") for (var j = 0; j < box.length; j++) { box[j].index=j; box[j].onmouseover=function() { var heart=$(".heart",this)[0] heart.style.display="block" } box[j].onmouseout=function() { var heart=$(".heart",this)[0] heart.style.display="none" } } }; } // 热门品牌选项卡 function xuanxiangka() { var menu=$(".menu")[0] var btn=$("a",menu) var content=$(".rmpp-bottom-right") for (var i = 0; i < btn.length; i++) { btn[i].index=i btn[i].onclick=function() { for (var j = 0; j < btn.length; j++) { btn[j].style.border="none" content[j].style.display="none" }; this.style.borderBottom="2px solid black" content[this.index].style.display="block" } }; } // 右固定动画 function fix(icon,tab) { tab.style.right=70+"px" tab.style.opacity=0; tab.style.display="none" icon.onmouseover=function() { tab.style.display="block" animate(tab,{right:35,opacity:1},300) } icon.onmouseout=function() { animate(tab,{right:70,opacity:0},300,function(){tab.style.display="none"}) } } // 按需加载图片 function orderpic(imgs) { wheight=document.documentElement.clientHeight for (var i = 0; i < imgs.length; i++) { if((getPosition(imgs[i]).y)<wheight) { imgs[i].src=imgs[i].getAttribute("date-src") } } var obj=document.documentElement.scrollTop==0?document.body:document.documentElement addEvent(window,"scroll",function() { var obj=document.documentElement.scrollTop==0?document.body:document.documentElement wheight=document.documentElement.clientHeight for (var i = 0; i < imgs.length; i++) { if((getPosition(imgs[i]).y)<(wheight+obj.scrollTop)) { imgs[i].src=imgs[i].getAttribute("date-src") } } }) } // 顶部搜索浮动+返回顶部 function fudong() { var fudong=$(".fudong-top")[0] var input=$("#lookfor") var tssc=$(".tssc")[0] var backtop=$("#backtop") window.onscroll=function() { var obj=document.documentElement.scrollTop==0?document.body:document.documentElement if(obj.scrollTop>=getPosition(tssc).y) { animate(fudong,{top:0},200) } else { animate(fudong,{top:-50},200) } // 返回顶部 if(obj.scrollTop==0) { animate(backtop,{opacity:0},100) } else { animate(backtop,{opacity:1},100) } backtop.onclick=function() { animate(obj,{scrollTop:0}) } } } // 二级导航 function daohang(first,second) { first.onmouseover=function() { second.style.display="block" } first.onmouseout=function() { second.style.display="none" } } // top下拉 function xiala(first,second,topic) { first.onmouseover=function() { topic.style.color="#c40000"; topic.style.backgroundColor="#fff"; second.style.display="block" } first.onmouseout=function() { second.style.display="none" topic.style.color="#999"; topic.style.backgroundColor="#f2f2f2"; } }
2239a5b11df361f68b7dddc8968d36e30eb61970
[ "JavaScript" ]
1
JavaScript
wuzhuang/tianmao
18d0a5dc5f03101b357e0825293ae99c6228dbb1
f016f49126215ae1a6d61f74a6fdf30fb3496713
refs/heads/master
<repo_name>i0Ek3/TinyOne<file_sep>/server/makefile CC := gcc CFLAGS := -Wall -g -Os SHDIR := ../base OBJS = to_server.o $(SHDIR)/to_base.o all: tos tos: $(OBJS) @$(CC) -o tos $(CFLAGS) $(OBJS) $(OBJS) : %.o: %.c @$(CC) -c $(CFLAGS) $< -o $@ .PHONY: clean: @rm -f *.o tos @rm -f ../base/*.o @echo Done cleaning <file_sep>/server/to_server.c #include "to_server.h" void to_server_retrive(int sock_control, int sock_data, char* filename) { // 服务器端下载命令的实现 FILE* fd = NULL; char data[MAXSIZE]; size_t read_size; fd = fopen(filename, "r"); if (!fd) { send_response(sock_control, 550); // 550: requested action not taken } else { send_response(sock_control, 150); // 150: file status is ok do { read_size = fread(data, 1, MAXSIZE, fd); if (read_size < 0) { printf("Error in fread()!\n"); } if (send(sock_data, data, read_size, 0) < 0) { perror("Failed to send file!\n"); } } while (read_size > 0); send_response(sock_control, 226); // 226: close connection, file transfer successful fclose(fd); } } int to_server_list(int sock_data, int sock_control) { // list 命令的实现 char data[MAXSIZE]; size_t read_size; int call_status = system("ls -l > tmp.txt"); if (call_status < 0) { exit(1); } FILE* fd = fopen("tmp.txt", "r"); if (!fd) { exit(1); } fseek(fd, SEEK_SET, 0); // 文件描述符偏移 send_response(sock_control, 1); // 准备发送数据 memset(data, 0, MAXSIZE); while ((read_size = fread(data, 1, MAXSIZE, fd)) > 0) { if (send(sock_data, data, read_size, 0) < 0) { perror("Send data error!"); memset(data, 0, MAXSIZE); } } fclose(fd); send_response(sock_control, 226); return 0; } void to_server_push(int sock_control, int sock_data, char* filename) { // upload int ack; //int sock_control = 0; //char buf[MAXSIZE]; if (recv(sock_control, &ack, sizeof(ack), 0) < 0) { send_response(sock_control, 502); return; } int status = ntohl(ack); if (533 == status) { send_response(sock_control, 533); return; } char name[260]; memset(name, 0, sizeof(name)); strcpy(name, "ftp://"); // 复制字符串到name中 strcat(name, filename); // 连接给定的两个字符串 int fd = open(name, O_CREAT|O_WRONLY, 0644); if (fd < 0) { send_response(sock_control, 502); // 命令执行失败 return; } while(1) { char data[MAXSIZE]; memset(data, 0, sizeof(data)); ssize_t s = recv(sock_data, data, sizeof(data), 0); if (s <= 0) { if (s < 0) { send_response(sock_control, 502); // command failed } else { send_response(sock_control, 226); // command successful } break; } write(fd, data, s); } close(fd); } int to_server_conn(int sock_control) { char buf[MAXSIZE]; int wait, sock_data; if (recv(sock_control, &wait, sizeof(wait), 0) < 0) { perror ("Error while waiting!"); return -1; } struct sockaddr_in client_addr; socklen_t len = sizeof(client_addr); getpeername(sock_control, (struct sockaddr*)&client_addr, &len); // 获取预sockfd连接的对端的地址信息,结果存在peeraddr所指向的空间中 inet_ntop(AF_INET, &client_addr.sin_addr, buf, sizeof(buf)); // 转换ipv4地址 if ((sock_data = socket_connect(buf, PORT)) < 0) { return -1; } return sock_data; } int to_server_check(const char* user, const char* passwd) { // 登录检查 char username[MAXSIZE]; char password[MAXSIZE]; char buf[MAXSIZE]; char* line = NULL; size_t read_size; size_t len = 0; FILE* fd = fopen("auth.txt", "r"); int auth = -1; if (NULL == fd) { perror("404 File Not Found!"); exit(1); } while ((read_size = getline(&line, &len, fd)) != -1) { memset(buf, 0, MAXSIZE); strcpy(buf, line); char *getuser = strtok(buf, " "); // 切割字符串,分离出用户名 strcpy(username, getuser); if (getuser != NULL) { char *getpwd = strtok(NULL, " "); // 分离出密码 strcpy(password, getpwd); } trim_char(password, (int)strlen(password)); // 去掉字符串中的空格和换行 // 用户名和密码验证成功 if ((strcmp(user, username) == 0) && (strcmp(passwd, password)) == 0) { auth = 1; break; } } free(line); fclose(fd); return auth; } int to_server_login(int sock_control) { // 登录接口 char buf[MAXSIZE]; char user[MAXSIZE]; char passwd[MAXSIZE]; memset(buf, 0, MAXSIZE); memset(user, 0, MAXSIZE); memset(passwd, 0, MAXSIZE); // 从文件描述符中读取数据 if ((recv_data(sock_control, buf, sizeof(buf))) == -1) { perror("Failed to receive data!\n"); exit(1); } int i = 5; int n = 0; while (buf[i] != 0) { // 保存用户名 user[n++] = buf[i++]; } send_response(sock_control, 331); // 通知用户输入密码 memset(buf, 0, MAXSIZE); // 获取密码 if ((recv_data(sock_control, buf, sizeof(buf))) == -1) { perror("Failed to receive data!\n"); exit(1); } i = 5; n = 0; while (buf[i] != 0) { passwd[n++] = buf[i++]; } return (to_server_check(user, passwd)); // 验证登录 } int to_server_recv_cmd(int sock_control, char* cmd, char* arg) { // 接收来自客户端发送的命令 int retcode = 200; char buf[MAXSIZE]; // 初始化命令及其参数 memset(buf, 0, MAXSIZE); memset(cmd, 0, 5); memset(arg, 0, MAXSIZE); // 从文件描述符中读数据 if ((recv_data(sock_control, buf, sizeof(buf))) == -1) { perror("Failed to receive data!\n"); return -1; } strncpy(cmd, buf, 4); char* tmp = buf + 5; strcpy(arg, tmp); if (strcmp(cmd, "QUIT") == 0) { retcode = 221; // 退出登录 } else if (strcmp(cmd, "USER") == 0 || (strcmp(cmd, "PASS")) == 0 || (strcmp(cmd, "LIST")) == 0 || (strcmp(cmd, "RETR")) == 0 || (strcmp(cmd, "PUSH")) == 0) { retcode = 200; // 命令执行成功 } else { retcode = 502; // 命令未执行 } send_response(sock_control, retcode); // 发送状态到文件描述符中 return retcode; } void to_server_process(int sock_control) { // 处理ftp事件 int sock_data; char cmd[5]; char arg[MAXSIZE]; send_response(sock_control, 220); // 发送相应码,服务就绪 if (to_server_login(sock_control) == 1) { // 登录成功 send_response(sock_control, 230); // auth is ok } else { // 登录失败 send_response(sock_control, 430); // auth is failed exit(0); } while (1) { // 解析命令 int retcode = to_server_recv_cmd(sock_control, cmd, arg); if ((retcode < 0) || (retcode == 221)) { // 出错或者quit break; } if (retcode == 200) { // 开始处理事件 if ((sock_data = to_server_conn(sock_control)) < 0) { close(sock_control); exit(1); } // 命令执行 if (strcmp(cmd, "LIST") == 0) { to_server_list(sock_data, sock_control); } else if (strcmp(cmd, "RETR") == 0) { to_server_retrive(sock_control, sock_data, arg); } else if (strcmp(cmd, "PUSH") == 0) { to_server_push(sock_control, sock_data, arg); } close(sock_data); } } } int main(int argc, char* argv[]) { if (argc != 2) { perror("Usage: ./tos port\n"); exit(0); } int port = atoi(argv[1]); int listenfd; // 创建监听器 if ((listenfd = socket_create(port)) < 0) { perror("Failed to create socket!"); exit(1); } int sock_control; int pid; for (;;) { // 循环接受请求 if ((sock_control = socket_accept(listenfd)) < 0) { break; } if ((pid = fork()) < 0) { perror("Failed to fork child process!"); } else if (pid == 0) { // 创建子进程 close(listenfd); to_server_process(sock_control); close(sock_control); exit(0); } close(sock_control); } close(listenfd); return 0; } <file_sep>/README.md # TinyOne A simple FTP server implement by C. ## Basic Introduction - File Transfer Protocol - Working in the application layer of the TCP/IP protocol family - FTP will establish two connections, separate the command from the data - Transfer file model - PORT: client -> PORT -> server, port > 1024 - PASV: client -> PASV -> server, port < 1024 ## FTP Process - Launch FTP - Establish control connection - Establish a data connection and transfer files - Close FTP ## Socket Programming Process - Socket Client - use socket() to create a Socket - use connect() to connect server - use write() and read() to communicate with each other - use close() to close Socket - Socket Server - use socket() to create a Socket - use bind() to bind Socket - use listen() to listen Socket - use accept() to recieve request - use write() and read() to communicate with each other - use close() to close Socket ## Architect ```Shell . ├── README.md ├── base │   ├── to_base.c │   └── to_base.h ├── bin │   ├── toc │   └── tos ├── client │   ├── makefile │   ├── to_client.c │   └── to_client.h ├── pic │   ├── snapshot.png │   └── structure.png └── server ├── auth.txt ├── makefile ├── tmp.txt ├── to_server.c └── to_server.h ``` ## How-To ```Shell // build $ git clone https://github.com/i0Ek3/TinyOne $ cd TinyOne $ cd client ; make $ cd server ; make // run $ ./tos port $ ./toc ip port or run toc and tos directly under /bin. // login username: admin username: admin password: <PASSWORD> password: //commands list or ls get or download put or upload quit or q ``` ## Snapshot ![](https://github.com/i0Ek3/TinyOne/blob/master/pic/snapshot.png) ## Issue - Execute tos and toc under /bin will appear "No such file or directory" error, cause of server cannot locate auth.txt. ![](https://github.com/i0Ek3/TinyOne/blob/master/pic/404.png) ## To-Do - [x] More commands support - [x] Breakpoint resume - [x] Server-side synchronization display ## References - [FILE TRANSFER PROTOCOL](https://www.w3.org/Protocols/rfc959/) - [使用 Socket 通信实现 FTP 客户端程序](https://www.ibm.com/developerworks/cn/linux/l-cn-socketftp/) <file_sep>/client/to_client.c #include "to_client.h" int read_reply(int sock_control) { // 读取服务器的回复 int retcode = 0; if (recv(sock_control, &retcode, sizeof(retcode), 0) < 0) { perror("Client: Failed reading data from server.\n"); return -1; } return ntohl(retcode); } void print_reply(int retcode) { // 打印回复消息 switch(retcode) { case 220: printf("220 Welcome, server ready!\n"); break; case 221: printf("221 See you next time.\n"); break; case 226: printf("226 Closing data connection, requested file action successful.\n"); break; case 550: printf("550 Requested action not taken. File unavailable.\n"); break; } } // 读取客户端输入的命令 int to_client_read_cmd(char* buf, int size, struct command* cmd) { // 从缓冲区中读取命令 memset(cmd->code, 0, sizeof(cmd->code)); memset(cmd->arg, 0, sizeof(cmd->arg)); printf("toc>"); fflush(stdout); read_input(buf, size); // 从buf读取命令 char* arg = NULL; arg = strtok(buf, " "); // 以某个字符作为分隔符 arg = strtok(NULL, " "); // 指向输入的命令所带的参数 if (arg != NULL) { strncpy(cmd->arg, arg, strlen(arg)); } // 判断命令接口 if (strcmp(buf, "list") == 0 || strcmp(buf, "ls") == 0) { strcpy(cmd->code, "LIST"); } else if (strcmp(buf, "get") == 0 || strcmp(buf, "download") == 0) { strcpy(cmd->code, "RETR"); } else if (strcmp(buf, "put") == 0 || strcmp(buf, "upload") == 0){ strcpy(cmd->code, "PUSH"); } else if (strcmp(buf, "quit") == 0 || strcmp(buf, "q") == 0) { strcpy(cmd->code, "QUIT"); } else { return -1; } // 将命令存到buf中 memset(buf, 0, 400); strcpy(buf, cmd->code); if (arg != NULL) { strcat(buf, " "); strncat(buf, cmd->arg, strlen(cmd->arg)); // 如果带有参数,追加到命令后面 } return 0; } int to_client_get(int sock_data, char* filename) { // download char data[MAXSIZE]; int size; FILE* fd = fopen(filename, "w"); while ((size = recv(sock_data, data, MAXSIZE, 0)) > 0) { fwrite(data, 1, size, fd); } if (size < 0) { perror("Download error!\n"); } fclose(fd); return 0; } int to_client_put(int sock_data, char* filename) { // upload int fd = open(filename, O_RDONLY); if (fd < 0) { return -1; } struct stat stat_buf; if (stat(filename, &stat_buf) < 0) { return -1; } // 6 parametes for macOS, 4 parameters for linux // sendfile(int, int, off_t, off_t *, struct sf_hdtr *, int); // sendfile(sock_data, fd, NULL, stat_buf.st_size); // for Linux sendfile(sock_data, fd, 0, &stat_buf.st_size, NULL, 0); // for macOS close(fd); return 0; } int to_client_open_conn(int sock_control) { // 打开连接 int listenfd = socket_create(PORT); int ack = 1; if ((send(sock_control, (char*)&ack, sizeof(ack), 0)) < 0) { // 发送应答 printf("Client: ack write error: %d\n", errno); exit(1); } int sock_conn = socket_accept(listenfd); close(listenfd); return sock_conn; } int to_client_list(int sock_data, int sock_control) { // list 命令实现 size_t read_size; char buf[MAXSIZE]; int tmp = 0; if (recv(sock_control, &tmp, sizeof(tmp), 0) < 0) { perror("Client: error while reading data from server.\n"); return -1; } memset(buf, 0, sizeof(buf)); while((read_size = recv(sock_data, buf, MAXSIZE, 0)) > 0) { printf("%s", buf); memset(buf, 0, sizeof(buf)); } if (read_size < 0) { perror("Error!"); } if (recv(sock_control, &tmp, sizeof tmp, 0) < 0) { perror("Client: error while reading data from server.\n"); return -1; } return 0; } int to_client_send_cmd(int sock_control, struct command* cmd) { // 发送命令 char buf[MAXSIZE]; sprintf(buf, "%s %s", cmd->code, cmd->arg); // 将命令和参数读入到缓冲区中 int retcode = send(sock_control, buf, (int)strlen(buf), 0); if (retcode < 0) { perror("Error while sending command to server.\n"); return -1; } return 0; } int to_client_login(int sock_control) { // 登录接口 struct command cmd; char user[256]; memset(user, 0, 256); printf("username: "); fflush(stdout); read_input(user, 256); // 读取用户名 strcpy(cmd.code, "USER"); strcpy(cmd.arg, user); to_client_send_cmd(sock_control, &cmd); // 发送用户名到服务器 int wait; recv(sock_control, &wait, sizeof wait, 0); fflush(stdout); // 刷新输出 char* passwd = getpass("password: "); // 获取密码 strcpy(cmd.code, "PASS"); strcpy(cmd.arg, passwd); to_client_send_cmd(sock_control, &cmd); // 发送密码到服务器 int retcode = read_reply(sock_control); // 读取服务器的回应 switch (retcode) { // 校验返回码 case 430: printf("Invalid username or password.\n"); exit(0); case 230: printf("Login successfully.\n"); break; default: perror("Error while reading data from server.\n"); exit(1); break; } return 0; } int main(int argc, char* argv[]) { int sock_data, retcode; char buf[MAXSIZE]; struct command cmd; memset(&cmd, 0, sizeof(cmd)); if (argc != 3) { // 参数检查 printf("Usage: ./toc ip port"); exit(0); } int sock_control = socket_connect(argv[1], atoi(argv[2])); if (sock_control < 0) { printf("Connected failed!\n"); exit(0); } char* ip = argv[1]; printf("Connected to %s.\n", ip); print_reply(read_reply(sock_control)); if (to_client_login(sock_control) < 0) { exit(0); } while (1) { if (to_client_read_cmd(buf, sizeof(buf), &cmd) < 0) { printf("Invalid command.\n"); continue; } if (send(sock_control, buf, (int)strlen(buf), 0) < 0) { // 发送命令到服务器 close(sock_control); exit(1); } retcode = read_reply(sock_control); if (retcode == 221) { print_reply(221); break; } if (retcode == 502) { printf("%d Invalid command.\n", retcode); } else { if ((sock_data = to_client_open_conn(sock_control)) < 0) { perror("Error while opening socket for data connection!"); exit(1); } if (strcmp(cmd.code, "LIST") == 0) { to_client_list(sock_data, sock_control); close(sock_data); } else if (strcmp(cmd.code, "RETR") == 0) { if (read_reply(sock_control) == 550) { // 服务器端文件正常 print_reply(550); close(sock_data); continue; } to_client_get(sock_data, cmd.arg); // 下载文件 print_reply(read_reply(sock_control)); close(sock_data); } else if (strcmp(cmd.code, "PUSH") == 0) { if (to_client_put(sock_data, cmd.arg) < 0) { send_response(sock_control, 553); // 文件上传失败 } else { send_response(sock_control, 200); // 文件上传成功 } close(sock_data); print_reply(read_reply(sock_control)); } } } close(sock_control); return 0; } <file_sep>/base/to_base.h #ifndef TO_BASE_H #define TO_BASE_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> //#include <sys/sendfile.h> #include <sys/socket.h> #include <sys/uio.h> // for macOS #include <sys/types.h> #include <sys/wait.h> #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <dirent.h> #include <ctype.h> #define BACKLOG 5 #define MAXSIZE 1024 #define PORT 9999 struct command { char arg[255]; char code[5]; }; int socket_create(int port); int socket_accept(int listenfd); int socket_connect(const char* host, const int port); int recv_data(int sockfd, char* buf, int bufsize); int send_response(int sockfd, int retcode); void read_input(char* buf, int size); void trim_char(char* str, int n); #endif <file_sep>/server/to_server.h #ifndef TO_SERVER_H #define TO_SERVER_H #include "../base/to_base.h" void to_server_retrive(int sock_control, int sock_data, char* filename); // 处理文件的下载 void to_server_push(int sock_control, int sock_data, char* filename); // 处理文件的上传 int to_server_list(int sock_data, int sock_control); // cmd ls int to_server_conn(int sock_control); // 创建一个数据连接 int to_server_check(const char* user, const char* passwd); // 登录检查 int to_server_login(int sock_control); // 登录接口 int to_server_recv_cmd(int sock_control, char* cmd, char* arg); // 从控制连接中接收命令 void to_server_process(int sock_control); // 处理一个ftp事件 #endif <file_sep>/client/makefile CC := gcc CFLAGS := -Wall -g -Os SHDIR := ../base OBJS = to_client.o $(SHDIR)/to_base.o all: toc toc: $(OBJS) @$(CC) -o toc $(CFLAGS) $(OBJS) $(OBJS) : %.o: %.c @$(CC) -c $(CFLAGS) $< -o $@ .PHONY: clean: @rm -f *.o toc @rm -f ../base/*.o @echo Done cleaning <file_sep>/client/to_client.h #ifndef TO_CLIENT_H #define TO_CLIENT_H #include "../base/to_base.h" int read_reply(int sock_control); // 读取服务器的回复 void print_reply(int retcode); // 打印回复消息 int to_client_read_cmd(char* buf, int size, struct command* cmd); // 读取客户端输入的命令 int to_client_get(int sock_data, char* filename); // 下载文件 int to_client_put(int sock_data, char* filename); // 上传文件 int to_client_open_conn(int sock_control); // 创建数据连接 int to_client_list(int sock_data, int sock_control); // cmd ls int to_client_send_cmd(int sock_control, struct command* cmd); // 发送命令 int to_client_login(int sock_control); // 登录接口 #endif <file_sep>/base/to_base.c #include "to_base.h" int socket_create(int port) { // 创建监听套接字 int sockfd; int flag = 1; struct sockaddr_in sock_addr; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("Failed to create socket!"); return -1; } sock_addr.sin_family = AF_INET; // ipv4, or use AF_INET6 to enable ipv6 sock_addr.sin_port = htons(port); sock_addr.sin_addr.s_addr = htonl(INADDR_ANY); if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(int)) == -1) { // setsockopt() means enhance basic socket function // SOL_SOCKET is basic socket port // SOL_REUSEADDR is a option which means to banned TIME_WAIT to enable port force close(sockfd); perror("Failed to setsockopt!"); return -1; } if (bind(sockfd, (struct sockaddr*)&sock_addr, sizeof(sock_addr)) < 0) { close(sockfd); perror("Failed to bind!"); return -1; } if (listen(sockfd, BACKLOG) < 0) { close(sockfd); perror("Failed to listen!"); return -1; } return sockfd; } int socket_accept(int listenfd) { // 接受连接 struct sockaddr_in client_addr; socklen_t len = sizeof(client_addr); int sockfd = accept(listenfd, (struct sockaddr*)&client_addr, &len); if (sockfd < 0) { perror("Failed to accept!"); return -1; } return sockfd; } int socket_connect(const char* host, const int port) { // 连接指定主机 int sockfd; struct sockaddr_in server_addr; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("Failed to create socket!"); return -1; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr.s_addr = inet_addr(host); if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { perror("Failed to connect server!"); return -1; } return sockfd; } int recv_data(int sockfd, char* buf, int bufsize) { // 从文件描述符中读取数据 size_t size; memset(buf, 0, bufsize); size = recv(sockfd, buf, bufsize, 0); if (size <= 0) { return -1; } return size; } int send_response(int sockfd, int retcode) { // 发送响应码到文件描述符 int ret = htonl(retcode); if (send(sockfd, &ret, sizeof(ret), 0) < 0) { perror("Failed to send data!"); return -1; } return 0; } void read_input(char* buf, int size) { // 从标准输入中读取一行 char* container = NULL; memset(buf, 0, size); if (fgets(buf, size, stdin) != NULL) { container = strchr(buf, '\n'); if (container != 0) { *container = '\0'; } } } void trim_char(char* str, int n) { // 去除字符串中的空格和换行 for (int i = 0; i < n; i++) { if (isspace(str[i])) { str[i] = 0; } if (str[i] == '\n') { str[i] = 0; } } }
3c45fd0d2b8533a9428d1d97605464d02f558f36
[ "Markdown", "C", "Makefile" ]
9
Makefile
i0Ek3/TinyOne
26c34dc65cac962657e069eb314a4b79e97fbdd2
deff42daf4cd26a59ec2bdd1eef0e8f4c3564f0f
refs/heads/master
<file_sep>export * from './address-list/address-list'; export * from './address-detail/address-detail'; export * from './home/home'; export * from './setup/setup';<file_sep>import { Component, ViewChild } from '@angular/core'; import { NavController, Platform } from 'ionic-angular'; import { ElectronService } from 'ngx-electron'; import { AddressListPage, HomePage, SetupPage } from './pages'; import { AddressService } from "./core/address-service"; import { Address } from "./core/address"; import { StorageServiceProvider } from "./core/storage-service/storage-service"; @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild('content') nav: NavController rootPage = HomePage; constructor( platform: Platform, private addressService: AddressService, private electron: ElectronService, private storage: StorageServiceProvider) { platform .ready() .then(() => this.onReady()) } onReady() { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. // StatusBar.styleDefault(); // Splashscreen.hide(); this.setupIpc(); } setupIpc() { this.electron.ipcRenderer.on('onMap', () => this.nav.setRoot(HomePage)); this.electron.ipcRenderer.on('onLocations', () => this.nav.setRoot(AddressListPage)); this.electron.ipcRenderer.on('onPrefs', () => this.nav.setRoot(SetupPage)); this.electron.ipcRenderer.on('onProvision', async (evt, address: Address) => { await this.addressService.provision(address) this.nav.setRoot(HomePage, { address }) }); this.electron.ipcRenderer.on('license', async (evt, license) => { console.log(license); await this.storage.setLicense(license); }); } } <file_sep>Electron app from the Ionic project. Sample for showing basic functionality of electron. Ionic- electron communication. Use ```npm install``` to install the required dependancy for the project. Live Reload:<br> First Run ``` ionic serve -b ``` for live reload of Ionic code<br> Then run ``` npm run mon ``` for the live reload of electron app
04f3e4f80610fa9e5f52c565249f6a7684385289
[ "Markdown", "TypeScript" ]
3
TypeScript
HardikDG/Electron_Address_Locator
a269cb313ce1e097e527762854290505f129fd96
d1bc1a61a5eef65e6e45ae2306403b11bf8c6282
refs/heads/master
<repo_name>kobalos02/kobalos02.github.io<file_sep>/README.md # kobalos02.github.io Demo site for the AMIA-CIAT Project <file_sep>/test.php <?php <h1>It works!</h1> ?>
942fab492cce5806421a1475dbcb73e479731d06
[ "Markdown", "PHP" ]
2
Markdown
kobalos02/kobalos02.github.io
f850e75ed987f1049d8ead26c73a6084cb52671d
9594cbbdcfe844ca7e8a445dc8e2839319695c55
refs/heads/master
<repo_name>kristianmandrup/geo_units<file_sep>/geo_units.gemspec # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- # stub: geo_units 0.3.4 ruby lib Gem::Specification.new do |s| s.name = "geo_units".freeze s.version = "0.3.4" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["<NAME>".freeze] s.date = "2017-10-12" s.description = "Easily convert between different distance units such as kms, miles etc.".freeze s.email = "<EMAIL>".freeze s.extra_rdoc_files = [ "LICENSE.txt", "README.textile" ] s.files = [ ".document", ".rspec", "Gemfile", "LICENSE.txt", "README.textile", "Rakefile", "VERSION", "geo_units.gemspec", "lib/geo_units.rb", "lib/geo_units/constants.rb", "lib/geo_units/converter.rb", "lib/geo_units/converter/dms.rb", "lib/geo_units/converter/normalizer.rb", "lib/geo_units/converter/units.rb", "lib/geo_units/core_ext.rb", "lib/geo_units/maps.rb", "lib/geo_units/maps/earth.rb", "lib/geo_units/maps/meters.rb", "lib/geo_units/numeric.rb", "lib/geo_units/numeric/dms.rb", "lib/geo_units/numeric/normalizer.rb", "lib/geo_units/unit_conversions.rb", "spec/geo_units/converter/dms_spec.rb", "spec/geo_units/converter/normalizer_spec.rb", "spec/geo_units/converter/units_spec.rb", "spec/geo_units/converter_spec.rb", "spec/geo_units/core_ext_spec.rb", "spec/geo_units/maps/earth_spec.rb", "spec/geo_units/maps/meters_spec.rb", "spec/geo_units/maps_spec.rb", "spec/geo_units/numeric/dms_spec.rb", "spec/geo_units/numeric/normalizer_spec.rb", "spec/geo_units/numeric_spec.rb", "spec/geo_units_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://github.com/kristianmandrup/geo_units".freeze s.licenses = ["MIT".freeze] s.rubygems_version = "2.6.14".freeze s.summary = "Distance unit modules and functionality for use in geo libraries".freeze if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<sugar-high>.freeze, ["~> 0.7.2"]) s.add_runtime_dependency(%q<sweetloader>.freeze, ["~> 0.1.6"]) s.add_runtime_dependency(%q<i18n>.freeze, [">= 0.8"]) s.add_runtime_dependency(%q<activesupport>.freeze, [">= 4"]) s.add_development_dependency(%q<rspec>.freeze, [">= 2.6.0"]) s.add_development_dependency(%q<bundler>.freeze, [">= 1.10.0"]) s.add_development_dependency(%q<jeweler>.freeze, [">= 2.3.0"]) else s.add_dependency(%q<sugar-high>.freeze, ["~> 0.7.2"]) s.add_dependency(%q<sweetloader>.freeze, ["~> 0.1.6"]) s.add_dependency(%q<i18n>.freeze, [">= 0.8"]) s.add_dependency(%q<activesupport>.freeze, [">= 4"]) s.add_dependency(%q<rspec>.freeze, [">= 2.6.0"]) s.add_dependency(%q<bundler>.freeze, [">= 1.10.0"]) s.add_dependency(%q<jeweler>.freeze, [">= 2.3.0"]) end else s.add_dependency(%q<sugar-high>.freeze, ["~> 0.7.2"]) s.add_dependency(%q<sweetloader>.freeze, ["~> 0.1.6"]) s.add_dependency(%q<i18n>.freeze, [">= 0.8"]) s.add_dependency(%q<activesupport>.freeze, [">= 4"]) s.add_dependency(%q<rspec>.freeze, [">= 2.6.0"]) s.add_dependency(%q<bundler>.freeze, [">= 1.10.0"]) s.add_dependency(%q<jeweler>.freeze, [">= 2.3.0"]) end end <file_sep>/spec/geo_units/numeric_spec.rb require 'spec_helper' # - www.movable-type.co.uk/scripts/latlong.html describe Array do # deg, format, dp describe '#to_dms' do let (:dms_arr) { [58.3, 4].to_dms } it 'should convert [58.3, 4] to string of dms format' do dms_arr.should match /58.*18.*, 04.*00/ end end describe '#to_dms :reverse' do let (:dms_arr) { [58.3, 4].to_dms :lat_lng} it 'should convert [58.3, 4] to string of dms format' do dms_arr.should match /04.*00.*N, 058.*18.*E/ end end end <file_sep>/lib/geo_units/maps/earth.rb module GeoUnits module Maps module Earth # from mongoid-geo, as suggested by niedhui :) def distance_per_latitude_degree { :feet => 364491.8, :meters => 111170, :kilometers => 111.17, :miles => 69.407, :degrees => 1 } end def radius { :miles => 3963.1676, :kilometers => 6378.135, :meters => 6378135, :feet => 20925639.8 } end def major_axis_radius { :miles => 3963.19059, :kilometers => 6378.137, :meters => 6378137, :feet => 20925646.36 } end def minor_axis_radius { :kilometers => 6356.7523142, :miles => 3949.90276, :meters => 6356752.3142, :feet => 20855486.627 } end def latitude_degrees unit = :miles radius[unit] / distance_per_latitude_degree[unit] end extend self end end end <file_sep>/lib/geo_units/maps.rb module GeoUnits module Maps autoload_modules :Earth, :Meters def self.included(base) base.send :include, Earth base.send :include, Meters end def precision { :feet => 0, :meters => 2, :kms => 4, :miles => 4, :radians => 4 } end extend self end end <file_sep>/spec/geo_units/core_ext_spec.rb require 'spec_helper' describe GeoUnits do describe 'Core extensions' do describe Numeric do describe '#miles_to' do it 'should convert meters to kms' do 100.meters_to(:kms).should == 0.1 end end describe '#miles_to' do it 'should convert miles to kms' do 2.miles_to(:kms).should be_within(0.2).of 3.21 end end describe '#feet_to' do it 'should convert feet to kms' do 2.feet_to(:kms).should be_within(0.5).of (2 * 3.28 * 0.001) end end describe '#to_radians' do it 'should convert degrees to radians' do 1.to_rad.should be_within(0.002).of 0.017 1.to_radians.should be_within(0.002).of 0.017 1.deg_to_rad.should be_within(0.002).of 0.017 1.degrees_to_rad.should be_within(0.002).of 0.017 end end end describe String do describe '#parse_dms' do it 'should raise error if no valid compass direction' do lambda { "58 18 00 X".parse_dms }.should raise_error end it 'should raise error if invalid format and set to raise' do lambda { "5.8 E".parse_dms }.should raise_error end it 'should parse valid format' do "58 E".parse_dms.should == 58.0 end end end describe Array do describe '#to_dms' do it 'should convert' do end end describe '#parse_dms' do it 'should raise error if no valid compass direction' do lambda { ["15 18 00 X", "53 N"].parse_dms }.should raise_error end it 'should parse valid format' do ["58 E", "32 N"].parse_dms.should == [58.0, 32.0] end it 'should parse valid but reverse format' do ["32 N", "58 E"].parse_dms.should == [58.0, 32.0] end end end end end <file_sep>/spec/geo_units/maps_spec.rb require 'spec_helper' class Map include GeoUnits::Maps end def map Map.new end # - www.movable-type.co.uk/scripts/latlong.html describe GeoUnits::Maps::Earth do subject { map } # earth specify { subject.distance_per_latitude_degree[:miles].should be_between(69, 69.5) } # meters specify { subject.from_unit[:feet].should be_between(0.3045, 0.305) } # maps specify { subject.precision[:miles].should == 4 } end <file_sep>/lib/geo_units/numeric.rb module GeoUnits module Numeric autoload_modules :Normalizer, :Dms def to_lat normalize_lat end def to_lng normalize_lng end def is_between? lower, upper (lower..upper).cover? self end # Converts numeric degrees to radians def to_rad self * Math::PI / 180 end alias_method :to_radians, :to_rad alias_method :as_rad, :to_rad alias_method :as_radians, :to_rad alias_method :in_rad, :to_rad alias_method :in_radians, :to_rad # Converts radians to numeric (signed) degrees # latitude (north to south) from equator +90 up then -90 down (equator again) = 180 then 180 for south = 360 total # longitude (west to east) east +180, west -180 = 360 total def to_deg self * 180 / Math::PI end alias_method :to_degrees, :to_deg alias_method :as_deg, :to_deg alias_method :as_degrees, :to_deg alias_method :in_deg, :to_deg alias_method :in_degrees, :to_deg # Formats the significant digits of a number, using only fixed-point notation (no exponential) # # @param {Number} precision: Number of significant digits to appear in the returned string # @returns {String} A string representation of number which contains precision significant digits def to_precision precision self.round(precision).to_s end alias_method :to_fixed, :to_precision end end <file_sep>/lib/geo_units.rb # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Geodesy representation conversion functions (c) <NAME> 2002-2010 # - www.movable-type.co.uk/scripts/latlong.html # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Parses string representing degrees/minutes/seconds into numeric degrees # # This is very flexible on formats, allowing signed decimal degrees, or deg-min-sec optionally # suffixed by compass direction (NSEW). A variety of separators are accepted (eg 3º 37' 09"W) # or fixed-width format without separators (eg 0033709W). Seconds and minutes may be omitted. # (Note minimal validation is done). # # @param [String|Number] Degrees or deg/min/sec in variety of formats # @returns [Number] Degrees as decimal number # @throws ArgumentError require 'active_support' require 'sugar-high/numeric' require 'sweetloader' module GeoUnits autoload_modules :Constants, :Converter, :Maps, :Numeric class << self attr_accessor :default_coords_order def default_coords_order @default_coords_order ||= :lng_lat end end def self.included(base) [:Maps, :Constants, :"Converter::Units"].each do |module_name| module_name = "GeoUnits::#{module_name.to_s.camelize}".constantize base.send :include, module_name base.extend module_name end end def self.units [:feet, :meters, :kms, :kilometers, :miles, :radians] end (units - [:radians]).each do |unit_type| define_singleton_method "#{unit_type}_to" do |unit, number = 0| return 0 if number <= 0 unit = normalized(unit) converter = GeoUnits::Maps::Meters from = converter.from_unit[unit_type] to = converter.to_unit[unit] m = number * from * to end end def self.radians_to unit, number, lat = 0 unit = normalized(unit) # factor = GeoUnits::Converter::Units.units_per_longitude_degree(lat, unit) # puts "factor: #{factor} - #{unit}" (GeoUnits::Maps::Earth.distance_per_latitude_degree[unit] * number.to_f) end module ClassMethods def normalized unit = :km unit = key(unit) return :feet if feet_unit.include? unit return :meters if meters_unit.include? unit return :kilometers if kms_unit.include? unit return :miles if miles_unit.include? unit return :radians if radins_unit.include? unit raise ArgumentError, "Normalize unit error, unit key: #{unit}" end def key unit = :km unit = unit.to_sym methods.grep(/_unit$/).each do |meth| return meth.to_s.chomp('_unit').to_sym if send(meth).include? unit end raise ArgumentError, "Unknown unit key: #{unit}" end def all_units [:miles, :mile, :kms, :km, :feet, :foot, :meter, :meters, :radians, :rad] end protected def feet_unit [:ft, :feet, :foot] end def meters_unit [:m, :meter, :meters] end def kms_unit [:km, :kms, :kilometer, :kilometers] end def miles_unit [:mil, :mile, :miles] end def radians_unit [:rad, :radians] end end extend ClassMethods end require 'geo_units/core_ext' <file_sep>/lib/geo_units/numeric/normalizer.rb module GeoUnits module Numeric module Normalizer # all degrees between -180 and 180 def normalize_lng case self when -360, 0, 360 0 when -360..-180 self % 180 when -180..0 -180 + (self % 180) when 0..180 self when 180..360 self % 180 else return (self % 360).normalize_lng if self > 360 return (360 - (self % 360)).normalize_lng if self < -360 raise ArgumentError, "Degrees #{self} out of range" end end # all degrees between -90 and 90 def normalize_lat case self when -360, 0, 360 0 when -180, 180 0 when -360..-270 self % 90 when -270..-180 90 - (self % 90) when -180..-90 - (self % 90) when -90..0 -90 + (self % 90) when 0..90 self when 90..180 self % 90 when 180..270 - (self % 90) when 270..360 - 90 + (self % 90) else return (self % 360).normalize_lat if self > 360 return (360 - (self % 360)).normalize_lat if self < -360 raise ArgumentError, "Degrees #{self} out of range" end end def normalize_deg shift = 0 (self + shift) % 360 end alias_method :normalize_degrees, :normalize_deg extend self end end end <file_sep>/lib/geo_units/converter/normalizer.rb module GeoUnits module Converter module Normalizer # all degrees between -180 and 180 def normalize_lng deg case deg when -360..-180 deg % 180 when -180..0 -180 + (deg % 180) when 0..180 deg when 180..360 deg % 180 else raise ArgumentError, "Degrees #{deg} out of range, must be between -360 to 360" end end # all degrees between -90 and 90 def normalize_lat deg case deg when -360..-270 deg % 90 when -270..-180 90 - (deg % 90) when -180..-90 - (deg % 90) when -90..0 -90 + (deg % 90) when 0..90 deg when 90..180 deg % 90 when 180..270 - (deg % 90) when 270..360 - 90 + (deg % 90) else raise ArgumentError, "Degrees #{deg} out of range, must be between -360 to 360" end end def normalize_deg degrees, shift = 0 (degrees + shift) % 360 end alias_method :normalize_degrees, :normalize_deg extend self end end end<file_sep>/lib/geo_units/converter.rb module GeoUnits module Converter autoload_modules :Normalizer, :Dms, :Units include Normalizer # Convert numeric degrees to deg/min/sec latitude (suffixed with N/S) # # @param {Number} deg: Degrees # @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' # @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d # @returns {String} Deg/min/seconds def to_lat deg, format = :dms, dp = 0 deg = deg.normalize_lat _lat = Dms.to_dms deg, format, dp _lat == '' ? '' : _lat[1..-1] + (deg<0 ? 'S' : 'N') # knock off initial '0' for lat! end # Convert numeric degrees to deg/min/sec longitude (suffixed with E/W) # # @param {Number} deg: Degrees # @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' # @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d # @returns {String} Deg/min/seconds def to_lon deg, format = :dms, dp = 0 deg = deg.normalize_lng lon = Dms.to_dms deg, format, dp lon == '' ? '' : lon + (deg<0 ? 'W' : 'E') end # Convert numeric degrees to deg/min/sec as a bearing (0º..360º) # # @param {Number} deg: Degrees # @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' # @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d # @returns {String} Deg/min/seconds def to_brng deg, format = :dms, dp = 0 deg = (deg.to_f + 360) % 360 # normalise -ve values to 180º..360º brng = Dms.to_dms deg, format, dp brng.gsub /360/, '0' # just in case rounding took us up to 360º! end include NumericCheckExt # from sugar-high/numeric # Converts numeric degrees to radians def to_rad degrees degrees * Math::PI / 180 end alias_method :to_radians, :to_rad alias_method :as_rad, :to_rad alias_method :as_radians, :to_rad alias_method :in_rad, :to_rad alias_method :in_radians, :to_rad # Converts radians to numeric (signed) degrees # latitude (north to south) from equator +90 up then -90 down (equator again) = 180 then 180 for south = 360 total # longitude (west to east) east +180, west -180 = 360 total def to_deg radians radians * 180 / Math::PI end alias_method :to_degrees, :to_deg alias_method :as_deg, :to_deg alias_method :as_degrees, :to_deg alias_method :in_deg, :to_deg alias_method :in_degrees, :to_deg extend self end extend self end <file_sep>/lib/geo_units/core_ext.rb require 'sugar-high/numeric' module GeoUnitExt ::GeoUnits.units.each do |unit_type| define_method "#{unit_type}_to" do |unit| unit = GeoUnits.normalized(unit) self.to_f * GeoUnits::Maps::Meters.from_unit[unit_type] * GeoUnits::Maps::Meters.to_unit[unit] end end include NumberDslExt # from sugar-high def to_rad GeoUnits::Converter.to_rad self end alias_method :to_radians, :to_rad alias_method :degrees_to_rad, :to_radians alias_method :deg_to_rad, :to_radians end class Numeric include GeoUnitExt include ::GeoUnits::Numeric include ::GeoUnits::Numeric::Dms include ::GeoUnits::Numeric::Normalizer end class String def parse_dms options = {} GeoUnits::Converter::Dms.parse_dms self, options end def to_lng self.match(/[E|W]/) ? self.to_i : nil end def to_lat self.match(/[N|S]/) ? self.to_i : nil end end class Array def to_dms direction = nil lng, lat = extract_coords(direction) res = direction == :lat_lng ? [lat.to_lat_dms, lng.to_lng_dms] : [lng.to_lng_dms, lat.to_lat_dms] res.join(', ') end def parse_dms direction = nil lng, lat = extract_coords(direction) direction == :lat_lng ? [lat.parse_dms, lng.parse_dms] : [lng.parse_dms, lat.parse_dms] end protected def extract_coords direction = nil direction ||= GeoUnits.default_coords_order unless [:lng_lat, :lat_lng].include? direction raise ArgumentError, "Direction must be either :lng_lat or :lat_lng, was: #{direction}. You can also set the default direction via GeoUnits#default_direction=" end lat_index = direction == :reverse ? 0 : 1 lng_index = direction == :reverse ? 1 : 0 lat = self.to_lat if self.respond_to?(:to_lat) lat ||= self[lat_index] if self[lat_index].respond_to?(:to_lat) && self[lat_index].to_lat lat ||= self[lng_index] if self[lng_index].respond_to?(:to_lat) && self[lng_index].to_lat lat ||= self[lat_index] lng = self.to_lng if self.respond_to?(:to_lng) lng ||= self[lng_index] if self[lng_index].respond_to?(:to_lng) && self[lng_index].to_lng lng ||= self[lat_index] if self[lat_index].respond_to?(:to_lng) && self[lat_index].to_lng lng ||= self[lng_index] [lng, lat] end end <file_sep>/spec/geo_units/maps/meters_spec.rb require 'spec_helper' class Meters include GeoUnits::Maps::Meters end def meters Meters.new end # - www.movable-type.co.uk/scripts/latlong.html describe GeoUnits::Maps::Meters do subject { meters } specify { subject.from_unit[:feet].should be_between(0.3045, 0.305) } specify { subject.from_unit[:miles].should be_between(1609, 1610) } specify { subject.to_unit[:feet].should be_between(3.28, 3.29) } specify { subject.to_unit[:miles].should be_between(0.0006, 0.0007) } end <file_sep>/lib/geo_units/constants.rb module GeoUnits module Constants def radians_per_degree Math::PI / 180.0 end def pi_div_rad 0.0174 end def kms_per_mile 1.609 end def meters_per_feet 3.2808399 end extend self end end <file_sep>/lib/geo_units/unit_conversions.rb module GeoUnits module UnitConversions def degrees_to_radians(degrees) degrees.to_f * GeoUnits::Constants.radians_per_degree end def units_sphere_multiplier(units) units = GeoUnits.key units GeoUnits::Mapsearth_radius_map[units] end def units_per_latitude_degree(units) units = GeoUnits.key units GeoUnits::Maps.radian_multiplier[units] end def units_per_longitude_degree(lat, units) miles_per_longitude_degree = (latitude_degrees * Math.cos(lat * pi_div_rad)).abs units = GeoUnits.key units miles_per_longitude_degree.miles_to(units) end def earth_radius units units = GeoUnits.key units GeoUnits::Maps.earth_radius_map[units] end def radians_ratio units units = GeoUnits.key units radians_per_degree * earth_radius(units) end extend self end end<file_sep>/spec/geo_units/maps/earth_spec.rb require 'spec_helper' class Earth include GeoUnits::Maps::Earth end def earth Earth.new end # - www.movable-type.co.uk/scripts/latlong.html describe GeoUnits::Maps::Earth do subject { earth } specify { subject.distance_per_latitude_degree[:miles].should be_between(69, 69.5) } specify { subject.radius[:miles].should be_between(3963, 3964) } specify { subject.major_axis_radius[:miles].should be_between(3963, 3964) } specify { subject.minor_axis_radius[:miles].should be_between(3949, 3950) } specify { subject.latitude_degrees(:miles).should be_between(57, 58) } end <file_sep>/lib/geo_units/maps/meters.rb module GeoUnits module Maps module Meters def to_unit_multiplier units = :meters from_unit[units] end def from_unit { :feet => 0.3048, :meters => 1, :kilometers => 1000, :miles => 1609.344 } end def to_unit { :feet => 3.2808399, :meters => 1, :kilometers => 0.001, :miles => 0.00062137 } end extend self end end end <file_sep>/lib/geo_units/numeric/dms.rb module GeoUnits module Numeric module Dms def to_dms format = :dms, dp = nil GeoUnits::DmsConverter.to_dms self, format, dp end def to_lat_dms format = :dms, dp = nil GeoUnits::Converter.to_lat self, format, dp end def to_lon_dms format = :dms, dp = nil GeoUnits::Converter.to_lon self, format, dp end alias_method :to_lng_dms, :to_lon_dms end end end
b0e87473ee062918d1d1f818fb4f9c295b7db6e8
[ "Ruby" ]
18
Ruby
kristianmandrup/geo_units
ddee241b826af36bc96dad3dd01258f56a730cd9
1954b0588f7644a4b51b6fd8174997835059cb92
refs/heads/master
<file_sep>module github.com/Valeyard1/marmitaz-telegram-bot go 1.12 require ( github.com/PuerkitoBio/goquery v1.5.0 // indirect github.com/antchfx/htmlquery v1.0.0 // indirect github.com/antchfx/xmlquery v1.0.0 // indirect github.com/antchfx/xpath v1.0.0 // indirect github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible github.com/gobwas/glob v0.2.3 // indirect github.com/gocolly/colly v1.2.0 github.com/jinzhu/gorm v1.9.10 github.com/kennygrant/sanitize v1.2.4 // indirect github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect github.com/robfig/cron v1.2.0 github.com/saintfish/chardet v0.0.0-20120816061221-3af4cd4741ca // indirect github.com/sirupsen/logrus v1.4.2 github.com/technoweenie/multipartstreamer v1.0.1 // indirect github.com/temoto/robotstxt v1.1.1 // indirect golang.org/x/net v0.0.0-20190724013045-ca1201d0de80 // indirect golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a // indirect google.golang.org/appengine v1.6.1 // indirect ) <file_sep>package main import ( "log" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) // User ... // 0 if the person hasn't ordered yet type User struct { gorm.Model Username string `gorm:"type:varchar(100)"` Order int `gorm:"default:0"` UserID int64 `gorm:"unique;not null"` } func initializeDatabase() *gorm.DB { // dbname set on TableName db, err := gorm.Open("sqlite3", DATABASE_HOST) if err != nil { log.Fatalf("Failed to connect to database %s\n%s", DATABASE_HOST, err.Error()) } // Migrate the schema db.AutoMigrate(&User{}) return db } <file_sep># Marmitaz Telegram Bot **NOTE**: This bot aims to be a brazilian Telegram bot This is a bot for telegram to interact with the site http://marmitaz.pushsistemas.com.br It notifies the subscribed users whenever the restaurant opens, which is every weekday around 7~8 AM. **TODO**: * Also notify the menu of the day (If you think it's a good feature, please vote +1 on [#2](https://github.com/Valeyard1/marmitaz-telegram-bot/issues/2)) --- For more information, [subscribe](https://t.me/marmitaz_bot) to the bot. ### Contributing This code is made with go modules, so all the dependencies are stored in the `go.*` files. To download them, just run `go build`. With just `go build` the code will not run, you have to specify the TOKEN for your bot, this is made through the `TELEGRAM_BOT_TOKEN` environment variable. The following steps can be done to get this working: ```bash export TELEGRAM_BOT_TOKEN="<token>" go run bot.go database.go message.go ``` <file_sep>package main func queroCafeMessage() string { msg := `Semana passada compartilhei um post sobre movimentos sociais, um claro shitpost de uma página grande, teve poucas curtidas, mas até aí tudo ok O problema começa quando na segunda feira recebo um email do RH do meu trabalho dizendo que precisava conversar comigo com urgência, marca a reunião pra quinta (ontem) e eu sem saber o que tava acontecendo Chego na reunião e ele tem vários prints de comentários meus aqui e da publicação Me conta que alguém tinha enviado um email e pedindo a abertura processo contra mim por discurso de ódio na internet e um posicionamento da coordenação do curso sobre o caso Meu orientador disse que tentou abafar o caso e conversar comigo primeiro e entender o que tinha acontecido, mas me disse que tinham enviado a mesma coisa pro chefe e que ele teria que tomar uma providência sobre o caso Foi ligado para minha família e ao que tudo indica eu posso perder minha vaga no emprego Além disso tudo saíram os prints no spotted da empresa com o nome borrado, e, claro, fora de contexto parecem coisas horríveis A empresa toda ta com ódio mortal do dono dos comentários e eu to temendo por minha segurança Minha irmã é amiga de um advogado que ta ajudando a gente, ele entrou em contato com a pessoa que enviou os emails e descobriu que ele queria comer o cu de quem tá lendo.` return msg } func helpMessage() string { msg := `Comandos disponíveis: /start - Você será notificado automaticamente assim que o restaurante abrir /cancel - Cancela a notificação automática /status - Verifica se o restaurante está aberto ou não /help - Mostra esta mensagem Para mais informações veja a descrição do bot. @marmitaz_bot` return msg } <file_sep>package main import ( "os" "github.com/robfig/cron" log "github.com/sirupsen/logrus" "github.com/Valeyard1/marmitaz-telegram-bot/site" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" ) var ( openRestaurantKeyboard = tgbotapi.NewInlineKeyboardMarkup( tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonURL("marmitaz.com", "https://marmitaz.pushsistemas.com.br/"), ), tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData("Já pedi", "0"), tgbotapi.NewInlineKeyboardButtonData("Vou pedir", "1"), ), ) token = os.Getenv("TELEGRAM_BOT_TOKEN") DATABASE_HOST = os.Getenv("DATABASE_HOST") // File of sqlite to use ) func main() { // For better logging Formatter := new(log.TextFormatter) Formatter.TimestampFormat = "02-01-2006 15:04:05" Formatter.FullTimestamp = true log.SetFormatter(Formatter) if token == "" { log.Fatal("No token has been provided for bot to work. Provide the TELEGRAM_BOT_TOKEN environment variable") } bot, err := tgbotapi.NewBotAPI(token) if err != nil { log.Fatal(err.Error()) } db := initializeDatabase() defer db.Close() c := cron.New() // Every weekday on hour 7 through 12 (AM) at second 0 of every 0 minute c.AddFunc("0 0 7-12 * * 1-5", func() { var users []User db.Find(&users) restaurantIsOpen, err := site.TemperoDeMaeIsOpen() if err != nil { log.Errorf("Failed to get status of restaurant in the cron job\n%v", err.Error()) } for _, subscribed := range users { var msg tgbotapi.MessageConfig if restaurantIsOpen && subscribed.Order == 0 { msg = tgbotapi.NewMessage(subscribed.UserID, "O Restaurante abriu. Faça seu pedido") msg.ReplyMarkup = openRestaurantKeyboard log.Info("Sent a notification for ", subscribed.Username) _, err = bot.Send(msg) } } }) // Declare that everyone hasn't ordered for the next day c.AddFunc("@midnight", func() { var user User db.First(&user) user.Order = 0 db.Save(&user) }) c.Start() log.Infof("Authorized on account %s", bot.Self.UserName) log.Info("Listening for new commands") u := tgbotapi.NewUpdate(0) u.Timeout = 60 updates, err := bot.GetUpdatesChan(u) for update := range updates { if update.CallbackQuery != nil { var text string // If the person has selected the option "Já pedi" if update.CallbackQuery.Data == "0" { text = "Até amanhã :D" var user User db.Model(&user).Where("user_id = ?", update.CallbackQuery.From.ID).Update("order", 1) } bot.AnswerCallbackQuery(tgbotapi.NewCallback(update.CallbackQuery.ID, "ok")) bot.Send(tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, text)) } if update.Message == nil { continue } log.Infof("[%s] - (%d) sent a request to %s", update.Message.From.UserName, update.Message.Chat.ID, update.Message.Text) if update.Message.IsCommand() { msg := tgbotapi.NewMessage(update.Message.Chat.ID, "") switch update.Message.Command() { case "start": db.Create(&User{Username: update.Message.From.UserName, UserID: update.Message.Chat.ID}) msg.Text = "Você será notificado assim que o restaurante abrir. Para cancelar digite /cancel" case "help": msg.Text = helpMessage() case "status": if isOpen, _ := site.TemperoDeMaeIsOpen(); isOpen == true { log.Info("Restaurant is open") msg.Text = "O restaurante está aberto. Faça seu pedido." msg.ReplyMarkup = openRestaurantKeyboard } else { msg.Text = "O restaurante está fechado." } case "cancel": db.Where("user_id = ?", update.Message.Chat.ID).Delete(User{}) db.Unscoped().Delete(&User{}) msg.Text = "Você não será mais notificado. Para se inscrever novamente digite /start" case "querocafe": msg.Text = queroCafeMessage() default: msg.Text = "Opção não disponível, para listar os comandos disponíveis digite /help" } failedMSG, err := bot.Send(msg) if err != nil { log.Errorf("Message %v not sent.\n%v", failedMSG, err) } } } } <file_sep>FROM golang:alpine AS builder # Install git. # Git is required for fetching the dependencies. RUN apk update && apk add --no-cache git WORKDIR /go/src/main ENV GO111MODULE=on COPY . . RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o /app . ############################ # STEP 2 build a small image ############################ FROM scratch # Copy our static executable. COPY --from=builder /app /app # Run the hello binary. ENTRYPOINT ["/app"]<file_sep>package site import ( "log" "regexp" "github.com/gocolly/colly" ) // TemperoDeMaeIsOpen returns a bool if the restaurant is open or not func TemperoDeMaeIsOpen() (bool, error) { exist := false c := colly.NewCollector( colly.URLFilters( // Visit only urls which belongs to the site regexp.MustCompile("https://marmitaz\\.pushsistemas\\.com\\.br/.*"), ), ) c.OnHTML("a[href]", func(e *colly.HTMLElement) { if e.Text == "Tempero de Mãe" || e.Attr("href") == "cardapio_mae.php?r=Tempero de Mãe" { exist = true } }) // Set error handler c.OnError(func(r *colly.Response, err error) { log.Println("Request URL:", r.Request.URL, "failed with response:", r, "\nError:", err) }) err := c.Visit("https://marmitaz.pushsistemas.com.br/") if err != nil { return false, err } return exist, nil }
b4d2a568a1813e1bcb292489d4a0b9c2c666269b
[ "Go", "Go Module", "Dockerfile", "Markdown" ]
7
Go Module
Valeyard1/marmitaz-telegram-bot
11fedf0fd29be0da49e75254f935fb7630d4b158
fd6dbdfc32886a261742fbc1dde8f9c62722faaf
refs/heads/master
<file_sep><?php use Illuminate\Database\Seeder; class CountriesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $data = [ [ 'name' => 'Belarus', 'iso_code' => 'BY', ], [ 'name' => 'Russia', 'iso_code' => 'RU', ], [ 'name' => 'Ukraine', 'iso_code' => 'UA', ], [ 'name' => 'United States', 'iso_code' => 'US', ], ]; DB::table('countries')->insert($data); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Requests\CountryCreateRequest; use App\Models\Country; use Illuminate\Http\Request; class CountryController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $columns = ['id', 'name', 'iso_code']; $paginator = (new Country()) ->select($columns) ->orderby('name') ->paginate(10); return view('countries.index', compact('paginator')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $item = new Country(); return view('countries.create', compact('item')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(CountryCreateRequest $request) { $data = $request->input(); $country = (new Country())->create($data); if ($country) { return redirect()->route('countries.index') ->with(['success' => 'Новая страна успешно добавлена']); } else { return back()->withErrors(['msg' => 'Ошибка сохранения']) ->withInput(); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { dd(__METHOD__); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // dd(__METHOD__, request()->all()); $item = (new Country())->findOrFail($id); return view('countries.create', compact('item')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { dd(__METHOD__, request()->all()); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { dd(__METHOD__); } } <file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class CountryCreateRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required|max:128|min:3|unique:countries', ]; } /** * Get the error messages for the defined validation rules * * @return array */ public function messages() { return [ 'name.required' => 'Введите название страны', 'name.unique' => 'Такая страна уже есть в базе', 'name.min' => 'Минимальная длина названия [:min] символов', 'name.max' => 'Максимальная длина названия [:max] символов', ]; } }
c2d8cbba460871c21fb56c98a093f909fa2ef492
[ "PHP" ]
3
PHP
Tur-4000/laravel-test
1abeec30fe679a8f055ec1ada606bccd44845d14
c49c8445c1a3a756a7afa1db97a0d778de5ef425
refs/heads/master
<repo_name>QAlexBall/dst<file_sep>/README.md # DataSet Tools <file_sep>/bin/dst #!/Users/derenzhu/anaconda3/bin/python print("Dataset Tools")
36f66be55a3be06b1acc867c80f3e0e134c654e9
[ "Markdown", "Python" ]
2
Markdown
QAlexBall/dst
2aefe1b4210cdf0b2aba583e8efc3d142f31730e
43f97d59b7dc38be4e0e7f8d3abfe18969e6289c
refs/heads/master
<repo_name>dominikPytlinski/booking-app<file_sep>/graphql/resolvers/Resolvers.js const bcrypt = require('bcryptjs'); const Event = require('../../models/Event'); const User = require('../../models/User'); const Booking = require('../../models/Booking'); const user = async (userId) => { try { const user = await User.findById(userId); return { ...user._doc, createdEvents: events.bind(this, user.createdEvents) } } catch (error) { throw error } } const events = async eventIds => { try { const events = await Event.find({ _id: { $in: eventIds } }); return events.map(event => { return { ...event._doc, creator: user.bind(this, event.creator), date: new Date(event.date).toISOString() } }); } catch (error) { throw error } } module.exports = { events: async () => { try { const events = await Event.find(); return events.map(event => { return { ...event._doc, creator: user.bind(this, event._doc.creator), date: new Date(event._doc.date).toISOString() } }); } catch (error) { throw error } }, bookings: async () => { try { const bookings = await Booking.find(); return bookings.map(booking => { return { ...booking._doc, createdAt: new Date(booking.createdAt).toISOString(), updatedAt: new Date(booking.updatedAt).toISOString() } }); } catch (error) { throw error; } }, createEvent: async (args) => { const event = new Event({ title: args.eventInput.title, description: args.eventInput.description, price: args.eventInput.price, date: new Date(args.eventInput.date), creator: '5<PASSWORD>' }); let createdEvent; try { const result = await event.save(); createdEvent = { ...result._doc, creator: user.bind(this, result.creator) }; const creator = await User.findById('5<PASSWORD>') if(!creator) { throw new Error('User dose not exist'); } creator.createdEvents.push(event); await creator.save(); return createdEvent; } catch (error) { throw error } }, createUser: async (args) => { try { const user = await User.findOne({ email: args.userInput.email }); if(user) { throw new Error('User already exists'); } const hashedPassword = await bcrypt.hash(args.userInput.password, 12); const newUser = new User({ email: args.userInput.email, password: <PASSWORD> }) const result = await newUser.save(); const createdUser = { ...result._doc, password: null } return createdUser; } catch (error) { throw error } }, bookEvent: async (args) => { const event = await Event.findById({ _id: args.eventId }); const booking = new Booking({ user: '5<PASSWORD>3<PASSWORD>', event: event }); const result = await booking.save(); return result; } }<file_sep>/README.md # Booking App ## test app for graphql, mongodb and react
67faf20249a9cee11eee52918054943991253b0a
[ "JavaScript", "Markdown" ]
2
JavaScript
dominikPytlinski/booking-app
4be4e7349673264299aec269fe8e06b14a4222be
db75b20722ac7d78ddfc9d1cd1add13d4513fa29
refs/heads/master
<file_sep>import { Observable } from 'rxjs/Observable'; import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Weather } from '../model'; import moment from "moment"; @Injectable() export class WeatherService { private API_PATH = "https://api.openweathermap.org/data/2.5/weather?APPID=ea370808071fd4691b18f6325ee72086&units=imperial"; constructor(private http: HttpClient) { } getWeather(lon: number, lat: number): Observable<Weather> { return this.http.get<Weather>(`${this.API_PATH}&lon=${lon}&lat=${lat}`).map((weather) => { weather.lastUpdated = moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); return weather; }); } }<file_sep>export interface GpsCoordinates { longitude?: number; latitude?: number; accuracy?: number; lastUpdated?: string; } export interface Weather { main: { temp?: number, pressure?: number, humidity?: number, temp_min?: number, temp_max?: number, sea_level?: number, grnd_level?: number } name? : string, lastUpdated?: string; }<file_sep>import { GpsCoordinates } from './../../model/index'; import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'gps-coordinates-card', templateUrl: './gps-coordinates-card.component.html' }) export class GpsCoordinatesCardComponent implements OnInit { @Input() gpsCoordinates: GpsCoordinates; constructor() { } ngOnInit() { } } <file_sep>import { WeatherService } from './providers/weather.service'; import { NgModule, ErrorHandler } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { AboutPage } from '../pages/about/about'; import { ContactPage } from '../pages/contact/contact'; import { HomePage } from '../pages/home/home'; import { TabsPage } from '../pages/tabs/tabs'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StoreModule } from '@ngrx/store'; import { reducers, metaReducers } from './reducers'; import { StoreDevtoolsModule } from '@ngrx/store-devtools'; import { EffectsModule } from '@ngrx/effects'; import { AppEffects } from './app.effects'; import { WeatherCardComponent } from './components/weather-card/weather-card.component'; import { GpsCoordinatesCardComponent } from './components/gps-coordinates-card/gps-coordinates-card.component'; import { Geolocation } from '@ionic-native/geolocation'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ MyApp, AboutPage, ContactPage, HomePage, TabsPage, WeatherCardComponent, GpsCoordinatesCardComponent ], imports: [ BrowserModule, HttpClientModule, IonicModule.forRoot(MyApp), StoreModule.forRoot(reducers, { metaReducers }), // set up dev tools (remove in production) StoreDevtoolsModule.instrument({ maxAge: 25 }), EffectsModule.forRoot([AppEffects]) ], bootstrap: [IonicApp], entryComponents: [ MyApp, AboutPage, ContactPage, HomePage, TabsPage ], providers: [ StatusBar, SplashScreen, Geolocation, WeatherService, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {} <file_sep>import { GetWeatherSuccess } from './../actions/actions'; import { GpsCoordinates, Weather } from './../model/index'; import { ActionReducer, ActionReducerMap, createFeatureSelector, createSelector, MetaReducer } from '@ngrx/store'; import { AppActions, AppActionTypes } from '../actions/actions'; export interface AppState { gpsCoordinates: GpsCoordinates, weather: Weather } export interface State { app: AppState; } export const initialAppState: AppState = { gpsCoordinates: null, weather: null }; export const reducers: ActionReducerMap<State> = { app: appReducer }; export function appReducer( state: AppState = initialAppState, action: AppActions ): AppState { switch (action.type) { case AppActionTypes.UpdateGpsCoordinates: return Object.assign({}, state, { gpsCoordinates: action.payload, }); case AppActionTypes.GetWeatherSuccess: return Object.assign({}, state, { weather: action.payload, }); default: return state; } } export const selectAppState = (state: State) => state.app; export const getGpsCoordinates = createSelector( selectAppState, (state: AppState) => state.gpsCoordinates ); export const GetWeather = createSelector( selectAppState, (state: AppState) => state.weather ); export const metaReducers: MetaReducer<State>[] = []; <file_sep>import { getGpsCoordinates, GetWeather } from './../../app/reducers/index'; import { GpsCoordinates, Weather } from './../../app/model/index'; import { Observable } from 'rxjs/Observable'; import { Component, ChangeDetectionStrategy } from '@angular/core'; import { NavController } from 'ionic-angular'; import { Store } from '@ngrx/store'; import { State } from '../../app/reducers'; @Component({ selector: 'page-home', templateUrl: 'home.html', // will be triggered when a new Observable emits a new value (e.g. with ngrx) changeDetection: ChangeDetectionStrategy.OnPush }) export class HomePage { gpsCoordinates$: Observable<GpsCoordinates>; weather$: Observable<Weather>; constructor(public navCtrl: NavController , private _store: Store<State>) { this.gpsCoordinates$ = this._store.select(getGpsCoordinates); this.weather$ = this._store.select(GetWeather); } } <file_sep>import { GpsCoordinates, Weather } from './../model/index'; import { Action } from "@ngrx/store"; export enum AppActionTypes { UpdateGpsCoordinates = "[APP] UPDATE_GPS_COORDINATES", GetWeather = "[APP] GET_WEATHER", GetWeatherSuccess = "[APP] GET_WEATHER_SUCCESS", GetWeatherFail = "[APP] GET_WEATHER_FAIL", } export class UpdateGpsCoordinates implements Action { readonly type = AppActionTypes.UpdateGpsCoordinates; constructor(public payload: GpsCoordinates) { } } export class GetWeather implements Action { readonly type = AppActionTypes.GetWeather; constructor(public payload: { longitude: number, latitude: number }) { } } export class GetWeatherSuccess implements Action { readonly type = AppActionTypes.GetWeatherSuccess; constructor(public payload: Weather) { } } export class GetWeatherFail implements Action { readonly type = AppActionTypes.GetWeatherFail; constructor() { } } export type AppActions = UpdateGpsCoordinates | GetWeather | GetWeatherSuccess | GetWeatherFail; <file_sep>import "rxjs/add/operator/filter"; import { UpdateGpsCoordinates } from './actions/actions'; import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { Geolocation } from '@ionic-native/geolocation'; import { TabsPage } from '../pages/tabs/tabs'; import { Store } from '@ngrx/store'; import { State } from './reducers'; import moment from "moment"; @Component({ templateUrl: 'app.html' }) export class MyApp { rootPage: any = TabsPage; constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private geolocation: Geolocation, private _store: Store<State>) { platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. statusBar.styleDefault(); splashScreen.hide(); let watch = this.geolocation.watchPosition().filter((p) => p.coords !== undefined); watch.subscribe((resp) => { // data can be a set of coordinates, or an error (if an error occurred). this._store.dispatch(new UpdateGpsCoordinates({ longitude: resp.coords.longitude, latitude: resp.coords.latitude, accuracy: resp.coords.accuracy, lastUpdated: moment(resp.timestamp).format("dddd, MMMM Do YYYY, h:mm:ss a") })) }); }); } } <file_sep>import { State, getGpsCoordinates } from "./reducers/index"; import { Store } from "@ngrx/store"; import { Observable } from "rxjs/Observable"; import { GpsCoordinates, Weather } from "./model/index"; import "rxjs/add/operator/do"; import "rxjs/add/observable/of"; import "rxjs/add/observable/interval"; import "rxjs/add/operator/map"; import "rxjs/add/operator/catch"; import "rxjs/add/operator/filter"; import "rxjs/add/operator/do"; import "rxjs/add/operator/withLatestFrom"; import "rxjs/add/operator/switchMap"; import { UpdateGpsCoordinates, AppActionTypes, GetWeather, GetWeatherSuccess, GetWeatherFail } from "./actions/actions"; import { WeatherService } from "./providers/weather.service"; import { Injectable } from "@angular/core"; import { Actions, Effect } from "@ngrx/effects"; import { digest } from "@angular/compiler/src/i18n/serializers/xmb"; @Injectable() export class AppEffects { constructor( private actions$: Actions, private weatherService: WeatherService, private store: Store<State> ) {} //Update weather each time GPS position change @Effect() updateWeatherFromGps$ = this.actions$ .ofType(AppActionTypes.UpdateGpsCoordinates) .map((action: UpdateGpsCoordinates) => action.payload) .map( (gpsCoordinates: GpsCoordinates) => new GetWeather({ longitude: gpsCoordinates.longitude, latitude: gpsCoordinates.latitude }) ); //Update weather every 5 seconds with last gps position @Effect() updateWeatherEachSeconds = Observable.interval(5000) .withLatestFrom(this.store.select(getGpsCoordinates)) .map(([any, gpsCoordinates]) => gpsCoordinates) .filter(gpsCoordinates => gpsCoordinates !== null) .map( (gpsCoordinates: GpsCoordinates) => new GetWeather({ longitude: gpsCoordinates.longitude, latitude: gpsCoordinates.latitude }) ); @Effect() getWeatherFromService$ = this.actions$ .ofType(AppActionTypes.GetWeather) .map((action: GetWeather) => action.payload) .switchMap((gpsCoordinates: GpsCoordinates) => { return this.weatherService .getWeather(gpsCoordinates.longitude, gpsCoordinates.latitude) .map((weather: Weather) => new GetWeatherSuccess(weather)) .catch(error => Observable.of(new GetWeatherFail())); }); }
2329592b536ad5e83c109c319738edada5b46d53
[ "TypeScript" ]
9
TypeScript
chuckmah/primotus-exercise
66b3fb04cf6a97d417f33bea0283cd685c9cb6f0
c3d56672db3050ab8a85ff01598c390a48d84a5b
refs/heads/master
<repo_name>devani/devanigenardi<file_sep>/practice4/script.js var button = document.getElementById("btn"); function myfunction(){ var container = document.getElementById("cont"); var myUlList = document.createElement("UL"); container.appendChild(myUlList); var col = document.getElementById("colValue"); var colV = col.value; var row = document.getElementById("rowValue"); var rowV = row.value; rowV = rowV - 1; // var k = 0; // while(k < cellV){ // var newList = document.createElement("LI"); // myUlList.appendChild(newList); // var text = document.createTextNode("demo text"); // newList.appendChild(text); // if (k%val == 0 ){ // newList.style.clear = "both"; // } // k ++; // }; for (var i = 0; i < colV ; i++){ var newList = document.createElement("LI"); myUlList.appendChild(newList); var text = document.createTextNode("demo text"); newList.appendChild(text); if (j%rowV == 0 ){ newList.setAttribute("class","breake"); }; for (var j = 0; j <rowV ; j++){ var newList = document.createElement("LI"); myUlList.appendChild(newList); var text = document.createTextNode("inside text"); newList.appendChild(text); }; }; }; button.addEventListener("click", myfunction);
db3b09059ad0788d41b36fb40bb8df02c1f1b37a
[ "JavaScript" ]
1
JavaScript
devani/devanigenardi
2f28ad09400babbf6842865954bc98490f7e29b5
ddbf71a187b4f4657bb59e1f54c1be75f15557dd
refs/heads/master
<file_sep>return Class(function(self, inst) assert(TheWorld.ismastersim, "Wormhole_Counter should not exist on client") self.inst = inst self.shadow_follower_count = 0 function self:isShadowFollowing() return self.shadow_follower_count > 0 end end)<file_sep>local foldername = KnownModIndex:GetModActualName(TUNING.ZOMBIEJ_ADDTIONAL_PACKAGE) ------------------------------------ 配置 ------------------------------------ -- 体验关闭 local additional_experiment = aipGetModConfig("additional_experiment") if additional_experiment ~= "open" then return nil end -- 建筑关闭 local additional_building = aipGetModConfig("additional_building") if additional_building ~= "open" then return nil end local language = aipGetModConfig("language") local aip_nectar_config = require("prefabs/aip_nectar_config") local QUALITY_COLORS = aip_nectar_config.QUALITY_COLORS local LANG_MAP = aip_nectar_config.LANG_MAP local LANG_VALUE_MAP = aip_nectar_config.LANG_VALUE_MAP local VALUE_WEIGHT = aip_nectar_config.VALUE_WEIGHT local VALUE_EAT_BONUS = aip_nectar_config.VALUE_EAT_BONUS local LANG = LANG_MAP[language] or LANG_MAP.english local LANG_VALUE = LANG_VALUE_MAP[language] or LANG_VALUE_MAP.english -- 文字描述 STRINGS.NAMES.AIP_NECTAR = LANG.NAME STRINGS.RECIPE_DESC.AIP_NECTAR = LANG.DESC -- 开发模式 local dev_mode = aipGetModConfig("dev_mode") == "enabled" ----------------------------------------------------------- local STEP_HP = 5 local STEP_SAN = 3 local STEP_BLOOD = dev_mode and 100 or 5 local STEP_DAMAGE = dev_mode and 50 or 5 local BASE_COLOR = .25 local GENERATION_AFFECT = .95 ----------------------------------------------------------- local assets = { Asset("ANIM", "anim/aip_nectar.zip"), Asset("ATLAS", "images/inventoryimages/aip_nectar.xml"), Asset("IMAGE", "images/inventoryimages/aip_nectar.tex"), } local prefabs = {} ----------------------------------------------------------- local function onVampireAttackOther(inst, data) local target = data.target if target ~= nil and inst.components.health then inst.components.health:DoDelta(STEP_BLOOD) end end local function onDamageAttackOther(inst, data) local target = data.target if target ~= nil and target.components.health then target.components.health:DoDelta(-STEP_DAMAGE, true, "nectar") end end ------------------------- 持续恢复 ------------------------- local function onEaten(inst, eater) if not inst.nectarContinueValues or not eater.components.aipc_timer then return end local health = inst.nectarContinueValues.health or 0 local sanity = inst.nectarContinueValues.sanity or 0 local speedTime = inst.nectarContinueValues.speedTime or 0 local vampireTime = inst.nectarContinueValues.vampireTime or 0 local damageTime = inst.nectarContinueValues.damageTime or 0 -- 回血灰理智 if health and sanity then eater.components.aipc_timer:Interval(1, function() if not eater.components.health or eater.components.health:IsDead() then return false end local recoverHealth = math.min(health, STEP_HP) local recoverSanity = math.min(sanity, STEP_SAN) health = health - recoverHealth sanity = sanity - recoverSanity if health == 0 and sanity == 0 then return false end -- 每秒回血 eater.components.health:DoDelta(recoverHealth) -- 每秒理智 if eater.components.sanity then eater.components.sanity:DoDelta(recoverSanity) end end) end -- 提升移动速度 if eater.components.locomotor and speedTime then eater.components.locomotor:SetExternalSpeedMultiplier(eater, "aip_nectar", TUNING.NECTAR_SPEED_MULT) eater.components.aipc_timer:Timeout(speedTime, function() eater.components.locomotor:RemoveExternalSpeedMultiplier(eater, "aip_nectar") end) end -- 吸血鬼 if vampireTime then eater:ListenForEvent("onattackother", onVampireAttackOther) eater.components.aipc_timer:Timeout(vampireTime, function() eater:RemoveEventCallback("onattackother", onVampireAttackOther) end) end -- 额外伤害 if damageTime then eater:ListenForEvent("onattackother", onDamageAttackOther) eater.components.aipc_timer:Timeout(damageTime, function() eater:RemoveEventCallback("onattackother", onDamageAttackOther) end) end end ------------------------- 刷新名字 ------------------------- local function onRefreshName(inst) local changeColor = 1 - BASE_COLOR local name = LANG.NAME local nectarValues = inst.nectarValues or {} -- 颜色 local nectarR = 0 local nectarG = 0 local nectarB = 0 local nectarA = 0 -- 食物 local health = 0 local hunger = 0 local sanity = 0 local temperature = 0 local temperatureduration = 0 --------------- 配比统计 --------------- local topTag = "tasteless" local topTagVal = 0 local totalTagVal = 0 local totalTagCount = 0 local tagBalance = false for tag, tagVal in pairs (nectarValues) do if tag ~= "exquisite" and tag ~= "generation" then totalTagVal = totalTagVal + tagVal totalTagCount = totalTagCount + 1 -- 选取最高位 if topTagVal == tagVal then tagBalance = true elseif topTagVal < tagVal then topTag = tag topTagVal = tagVal tagBalance = false end -- 颜色统计 local color = VALUE_WEIGHT[tag] or {1,1,1,1} nectarR = nectarR + color[1] * tagVal nectarG = nectarG + color[2] * tagVal nectarB = nectarB + color[3] * tagVal nectarA = nectarA + color[4] * tagVal -- 食物统计 local eatBonus = VALUE_EAT_BONUS[tag] or {} health = health + (eatBonus.health or 0) * tagVal hunger = hunger + (eatBonus.hunger or 0) * tagVal sanity = sanity + (eatBonus.sanity or 0) * tagVal temperatureduration = temperatureduration + (eatBonus.temperatureduration or 0) if eatBonus.temperature then temperature = eatBonus.temperature end end end inst.AnimState:SetMultColour( BASE_COLOR + nectarR / totalTagVal * changeColor, BASE_COLOR + nectarG / totalTagVal * changeColor, BASE_COLOR + nectarB / totalTagVal * changeColor, BASE_COLOR + nectarA / totalTagVal * changeColor ) --------------- 花蜜名字 --------------- name = aipStr(LANG_VALUE[topTag], name) -- 精酿 if nectarValues.exquisite then name = aipStr(LANG_VALUE.exquisite, name) end -- 平衡 if tagBalance then name = aipStr(LANG_VALUE.balance, name) end -- 世代 if nectarValues.generation > 1 then name = aipStr(name, tostring(nectarValues.generation), LANG_VALUE.generation) end if inst.components.aipc_info_client then inst.components.aipc_info_client:SetString("named", name) end -------------- 浮动提示框 -------------- -- 纯度 local aipInfo = "" local purePTG = topTagVal / totalTagVal if topTagVal == totalTagVal then aipInfo = aipStr(aipInfo, LANG_VALUE.absolute) elseif purePTG < 0.5 then aipInfo = aipStr(aipInfo, LANG_VALUE.impurity) else aipInfo = aipStr(math.ceil(purePTG * 100), "%") end -- 品质范围 local currentQuality = 1 local minQuality = 1 local maxQuality = 1 --> 随着世代增加,最高品质也会增加 if nectarValues.generation <= 1 then minQuality = 0 maxQuality = 2 elseif nectarValues.generation <= 2 then minQuality = 0 maxQuality = 3 elseif nectarValues.generation <= 3 then minQuality = 0 maxQuality = 4 elseif nectarValues.generation <= 4 then minQuality = 0 maxQuality = 5 end -- 品质计算 --> 纯度 if purePTG <= 0.3 then currentQuality = currentQuality - 0.3 elseif purePTG <= 0.4 then currentQuality = currentQuality - 0.2 elseif purePTG <= 0.5 then currentQuality = currentQuality - 0.1 elseif purePTG > 0.8 then currentQuality = currentQuality + 0.3 end --> 种类 currentQuality = currentQuality + math.min(1, totalTagCount * 0.2) --> 精酿 if nectarValues.exquisite then currentQuality = currentQuality + 1 end --> 属性加成 currentQuality = currentQuality + math.min(1, totalTagVal * 0.03) --> 世代 currentQuality = currentQuality + math.min(1.5, (nectarValues.generation or 1) * 0.15) --> 花蜜 if nectarValues.nectar then if nectarValues.nectar <= 5 then currentQuality = currentQuality + nectarValues.nectar * 0.1 else currentQuality = currentQuality - math.min(1, (nectarValues.nectar or 0) * 0.1) end end --> 可怕 currentQuality = currentQuality - (nectarValues.terrible or 0) currentQuality = math.min(maxQuality, currentQuality) currentQuality = math.max(minQuality, currentQuality) currentQuality = math.floor(currentQuality) local qualityName = aipStr("quality_", currentQuality) if inst.components.aipc_info_client then inst.components.aipc_info_client:SetString("aip_info", aipStr(aipInfo, "-", LANG_VALUE[qualityName])) inst.components.aipc_info_client:SetByteArray("aip_info_color", QUALITY_COLORS[qualityName]) end --------------- 食用价值 --------------- local continueRecover = currentQuality >= 3 health = health * math.pow(GENERATION_AFFECT, (nectarValues.generation or 1) - 1) hunger = hunger * math.pow(GENERATION_AFFECT, (nectarValues.generation or 1) - 1) sanity = sanity * math.pow(GENERATION_AFFECT, (nectarValues.generation or 1) - 1) -- 糟糕品质会损害理智哦 if currentQuality == 0 then sanity = -20 end -- 持续恢复 if continueRecover then inst.nectarContinueValues = inst.nectarContinueValues or {} health = health / 2 sanity = sanity / 2 inst.nectarContinueValues.health = health inst.nectarContinueValues.sanity = sanity end -- 移动速度 if nectarValues.light then inst.nectarContinueValues = inst.nectarContinueValues or {} inst.nectarContinueValues.speedTime = math.min(4 + nectarValues.light * 1, 30) -- 最多加速30秒 end -- 吸血鬼 if nectarValues.vampire then inst.nectarContinueValues = inst.nectarContinueValues or {} inst.nectarContinueValues.vampireTime = math.min(6 + nectarValues.vampire * 1, 30) -- 最多吸血30秒 end -- 伤害增加 if nectarValues.damage then inst.nectarContinueValues = inst.nectarContinueValues or {} inst.nectarContinueValues.damageTime = math.min(4 + nectarValues.damage * 1, 30) -- 最多吸血30秒 end if inst.components.edible then inst.components.edible.healthvalue = health inst.components.edible.hungervalue = hunger inst.components.edible.sanityvalue = sanity inst.components.edible.temperaturedelta = temperature inst.components.edible.temperatureduration = temperatureduration inst.components.edible:SetOnEatenFn(onEaten) end ----------------- 检查 ----------------- local topEatName = "health" local topEatValue = health local eatData = { ["health"] = health, ["hunger"] = hunger, ["sanity"] = sanity, } for eatName, eatValue in pairs(eatData) do if eatValue > topEatValue then topEatName = eatName topEatValue = eatValue end end local checkStatus = "" if topEatValue <= 10 then checkStatus = LANG.littleOf elseif topEatValue <= 30 then checkStatus = LANG.contains elseif topEatValue <= 60 then checkStatus = LANG.lotsOf else checkStatus = LANG.fullOf end local statusStr = aipStr(checkStatus, " ", LANG[topEatName]) if nectarValues.frozen then statusStr = aipStr(statusStr, "\n", LANG.frozen) end if continueRecover then statusStr = aipStr(statusStr, "\n", LANG.continueRecover) end if nectarValues.light then statusStr = aipStr(statusStr, "\n", LANG.speedMulti) end if nectarValues.vampire then statusStr = aipStr(statusStr, "\n", LANG.suckBlook) end if nectarValues.damage then statusStr = aipStr(statusStr, "\n", LANG.damageMulti) end inst.components.inspectable:SetDescription(statusStr) ----------------- 发光 ----------------- if nectarValues.light then inst.Light:Enable(true) inst.Light:SetRadius(0.3) inst.Light:SetIntensity(0.7) inst.Light:SetFalloff(0.7) inst.Light:SetColour(169/255, 231/255, 245/255) else inst.Light:Enable(false) end end ---------------------------- 存储 ---------------------------- local function onSave(inst, data) data.nectarValues = inst.nectarValues end local function onLoad(inst, data) if data ~= nil and data.nectarValues then inst.nectarValues = data.nectarValues inst.refreshName() end end function fn() local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddNetwork() inst.entity:AddLight() inst.Light:Enable(false) inst.Light:EnableClientModulation(true) -- 好像是用于网络优化的? MakeInventoryPhysics(inst) inst.AnimState:SetBank("aip_nectar") inst.AnimState:SetBuild("aip_nectar") inst.AnimState:PlayAnimation("BUILD") inst:AddTag("aip_nectar") inst:AddTag("aip_nectar_material") inst.entity:SetPristine() -- 额外信息 inst:AddComponent("aipc_info_client") --> 初始化 inst.components.aipc_info_client:SetString("named", nil, true) inst.components.aipc_info_client:SetString("aip_info", nil, true) inst.components.aipc_info_client:SetByteArray("aip_info_color", nil, true) -- 更新名字(named component not work, use customize update) inst.components.aipc_info_client:ListenForEvent("named", function(inst, newName) inst.name = newName end) if not TheWorld.ismastersim then return inst end ----------------------------------------------------- inst.nectarValues = {} inst.refreshName = function() onRefreshName(inst) end ----------------------------------------------------- inst:AddComponent("inspectable") inst:AddComponent("inventoryitem") inst.components.inventoryitem.atlasname = "images/inventoryimages/aip_nectar.xml" -- 食物 inst:AddComponent("edible") inst.components.edible.foodtype = FOODTYPE.GOODIES -- 女武神也可以喝 inst.components.edible.healthvalue = 0 inst.components.edible.hungervalue = 0 inst.components.edible.sanityvalue = 0 -- 腐烂 inst:AddComponent("perishable") inst.components.perishable:SetPerishTime(TUNING.PERISH_PRESERVED) inst.components.perishable:StartPerishing() inst.components.perishable.onperishreplacement = "spoiled_food" -- 火焰传播者 MakeSmallBurnable(inst) MakeSmallPropagator(inst) MakeHauntableLaunch(inst) inst.OnSave = onSave inst.OnLoad = onLoad return inst end return Prefab("aip_nectar", fn, assets) <file_sep>local foldername = KnownModIndex:GetModActualName(TUNING.ZOMBIEJ_ADDTIONAL_PACKAGE) -- 配置 local dress_uses = aipGetModConfig("dress_uses") local language = aipGetModConfig("language") -- 默认参数 local PERISH_MAP = { ["less"] = 0.5, ["normal"] = 1, ["much"] = 2, } local LANG_MAP = { ["english"] = { ["NAME"] = "SOM", ["REC_DESC"] = "Hello Everyone!", ["DESC"] = "New come? Good bye~", }, ["chinese"] = { ["NAME"] = "谜之声", ["REC_DESC"] = "诶!大家好!", ["DESC"] = "有人刚来吗?晚安晚安~", }, } local LANG = LANG_MAP[language] or LANG_MAP.english TUNING.AIP_SOM_FUEL = TUNING.YELLOWAMULET_FUEL * PERISH_MAP[dress_uses] -- 文字描述 STRINGS.NAMES.AIP_SOM = LANG.NAME STRINGS.RECIPE_DESC.AIP_SOM = LANG.REC_DESC STRINGS.CHARACTERS.GENERIC.DESCRIBE.AIP_SOM = LANG.DESC -- 配方 -- local aip_horse_head = Recipe("aip_horse_head", {Ingredient("beefalowool", 5),Ingredient("boneshard", 3),Ingredient("beardhair", 3)}, RECIPETABS.DRESS, TECH.SCIENCE_TWO) -- aip_horse_head.atlas = "images/inventoryimages/aip_horse_head.xml" local tempalte = require("prefabs/aip_dress_template") return tempalte("aip_som", { hideHead = true, fueled = { level = TUNING.AIP_SOM_FUEL, }, dapperness = TUNING.DAPPERNESS_LARGE, })<file_sep>local foldername = KnownModIndex:GetModActualName(TUNING.ZOMBIEJ_ADDTIONAL_PACKAGE) -- 配置 local additional_weapon = aipGetModConfig("additional_weapon") if additional_weapon ~= "open" then return nil end local weapon_uses = aipGetModConfig("weapon_uses") local weapon_damage = aipGetModConfig("weapon_damage") local language = aipGetModConfig("language") -- 默认参数 local PERISH_MAP = { ["less"] = TUNING.PERISH_FAST, ["normal"] = TUNING.PERISH_MED, ["much"] = TUNING.PERISH_PRESERVED, } local DAMAGE_MAP = { ["less"] = TUNING.NIGHTSWORD_DAMAGE / 68 * 30, ["normal"] = TUNING.NIGHTSWORD_DAMAGE / 68 * 60, ["large"] = TUNING.NIGHTSWORD_DAMAGE / 68 * 90, } local LANG_MAP = { ["english"] = { ["NAME"] = "Fish Sword", ["REC_DESC"] = "Fish is best friend!", ["DESC"] = "Too hunger to eat it", }, ["russian"] = { ["NAME"] = "<NAME>", ["REC_DESC"] = "Рыба - лучший друг!", ["DESC"] = "Я еле сдерживаюсь, чтобы не съесть это!", }, ["portuguese"] = { ["NAME"] = "Espada peixe", ["REC_DESC"] = "Peixe é melhor amigo!", ["DESC"] = "Muita fome pra come-lo", }, ["korean"] = { ["NAME"] = "물고기 소드", ["REC_DESC"] = "물고기는 최고의 친구야!", ["DESC"] = "먹고싶은데 아쉬워", }, ["chinese"] = { ["NAME"] = "鱼刀", ["REC_DESC"] = "鱼是最好的朋友!", ["DESC"] = "即便很饿也不能吃掉它", }, } local LANG = LANG_MAP[language] or LANG_MAP.english TUNING.AIP_FISH_SWORD_PERISH = PERISH_MAP[weapon_uses] TUNING.AIP_FISH_SWORD_DAMAGE = DAMAGE_MAP[weapon_damage] -- 资源 local assets = { Asset("ATLAS", "images/inventoryimages/aip_fish_sword.xml"), Asset("ANIM", "anim/aip_fish_sword.zip"), Asset("ANIM", "anim/aip_fish_sword_swap.zip"), } local prefabs = { } -- 文字描述 STRINGS.NAMES.AIP_FISH_SWORD = LANG.NAME STRINGS.RECIPE_DESC.AIP_FISH_SWORD = LANG.REC_DESC STRINGS.CHARACTERS.GENERIC.DESCRIBE.AIP_FISH_SWORD = LANG.DESC -- 配方 local aip_fish_sword = Recipe("aip_fish_sword", {Ingredient("fish", 1),Ingredient("nightmarefuel", 2),Ingredient("rope", 1)}, RECIPETABS.WAR, TECH.SCIENCE_TWO) aip_fish_sword.atlas = "images/inventoryimages/aip_fish_sword.xml" ----------------------------------------------------------- local function UpdateDamage(inst) if inst.components.perishable and inst.components.weapon then local dmg = TUNING.AIP_FISH_SWORD_DAMAGE * inst.components.perishable:GetPercent() dmg = Remap(dmg, 0, TUNING.AIP_FISH_SWORD_DAMAGE, TUNING.HAMBAT_MIN_DAMAGE_MODIFIER*TUNING.AIP_FISH_SWORD_DAMAGE, TUNING.AIP_FISH_SWORD_DAMAGE) inst.components.weapon:SetDamage(dmg) end end local function OnLoad(inst, data) UpdateDamage(inst) end local function onequip(inst, owner) owner.AnimState:OverrideSymbol("swap_object", "aip_fish_sword_swap", "aip_fish_sword_swap") owner.SoundEmitter:PlaySound("dontstarve/wilson/equip_item_gold") owner.AnimState:Show("ARM_carry") owner.AnimState:Hide("ARM_normal") end local function onunequip(inst, owner) owner.AnimState:ClearOverrideSymbol("swap_object") owner.AnimState:Hide("ARM_carry") owner.AnimState:Show("ARM_normal") end function fn() local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddNetwork() MakeInventoryPhysics(inst) inst.AnimState:SetBank("aip_fish_sword") inst.AnimState:SetBuild("aip_fish_sword") inst.AnimState:PlayAnimation("idle") inst:AddTag("show_spoilage") inst:AddTag("icebox_valid") inst.entity:SetPristine() if not TheWorld.ismastersim then return inst end inst:AddComponent("perishable") inst.components.perishable:SetPerishTime(TUNING.AIP_FISH_SWORD_PERISH) inst.components.perishable:StartPerishing() inst.components.perishable.onperishreplacement = "spoiled_food" inst:AddComponent("weapon") inst.components.weapon:SetDamage(TUNING.AIP_FISH_SWORD_DAMAGE) inst.components.weapon:SetOnAttack(UpdateDamage) inst.OnLoad = OnLoad inst:AddComponent("inspectable") inst:AddComponent("inventoryitem") inst.components.inventoryitem.atlasname = "images/inventoryimages/aip_fish_sword.xml" MakeHauntableLaunchAndPerish(inst) inst:AddComponent("equippable") inst.components.equippable:SetOnEquip(onequip) inst.components.equippable:SetOnUnequip(onunequip) return inst end return Prefab( "aip_fish_sword", fn, assets) <file_sep>GLOBAL.STRINGS.AIP = {} -- 资源 Assets = { Asset("ATLAS", "images/inventoryimages/popcorngun.xml"), Asset("ATLAS", "images/inventoryimages/incinerator.xml"), Asset("ATLAS", "images/inventoryimages/dark_observer.xml"), } -- 物品列表 PrefabFiles = { -- Food "aip_veggies", "foods", "aip_nectar_maker", "aip_nectar", "popcorngun", "incinerator", "aip_blood_package", "aip_fish_sword", "aip_beehave", -- Orbit "aip_orbit", "aip_mine_car", -- Dress "aip_dress", -- Chesspiece "aip_chesspiece", -- Magic "dark_observer", "dark_observer_vest", "aip_shadow_package", "aip_shadow_chest", "aip_shadow_wrapper", } --------------------------------------- 工具 --------------------------------------- modimport("scripts/aipUtils.lua") --------------------------------------- 图标 --------------------------------------- AddMinimapAtlas("minimap/dark_observer_vest.xml") --------------------------------------- 封装 --------------------------------------- modimport("scripts/recipeWrapper.lua") modimport("scripts/seedsWrapper.lua") modimport("scripts/containersWrapper.lua") modimport("scripts/itemTileWrapper.lua") modimport("scripts/hudWrapper.lua") modimport("scripts/shadowPackageAction.lua") --------------------------------------- 矿车 --------------------------------------- if GetModConfigData("additional_orbit") == "open" then modimport("scripts/mineCarAction.lua") end ------------------------------------ 贪婪观察者 ------------------------------------ -- 暗影跟随者 function ShadowFollowerPrefabPostInit(inst) if not GLOBAL.TheWorld.ismastersim then return end if not inst.components.shadow_follower then inst:AddComponent("shadow_follower") end end AddPrefabPostInit("dragonfly", function(inst) ShadowFollowerPrefabPostInit(inst) end) -- 龙蝇 AddPrefabPostInit("deerclops", function(inst) ShadowFollowerPrefabPostInit(inst) end) -- 鹿角怪 AddPrefabPostInit("bearger", function(inst) ShadowFollowerPrefabPostInit(inst) end) -- 熊獾 AddPrefabPostInit("moose", function(inst) ShadowFollowerPrefabPostInit(inst) end) -- 麋鹿鹅 AddPrefabPostInit("beequeen", function(inst) ShadowFollowerPrefabPostInit(inst) end) -- 蜂后 AddPrefabPostInit("klaus", function(inst) ShadowFollowerPrefabPostInit(inst) end) -- 克劳斯 AddPrefabPostInit("antlion", function(inst) ShadowFollowerPrefabPostInit(inst) end) -- 蚁狮 AddPrefabPostInit("toadstool", function(inst) ShadowFollowerPrefabPostInit(inst) end) -- 蟾蜍王 AddPrefabPostInit("toadstool_dark", function(inst) ShadowFollowerPrefabPostInit(inst) end) -- 苦难蟾蜍王 -- 世界追踪 function WorldPrefabPostInit(inst) inst:AddComponent("world_common_store") end if GLOBAL.TheNet:GetIsServer() or GLOBAL.TheNet:IsDedicated() then AddPrefabPostInit("world", WorldPrefabPostInit) end ------------------------------------- 玩家钩子 ------------------------------------- function PlayerPrefabPostInit(inst) if not inst.components.aipc_player_client then inst:AddComponent("aipc_player_client") end if not GLOBAL.TheWorld.ismastersim then return end if not inst.components.aipc_timer then inst:AddComponent("aipc_timer") end end AddPlayerPostInit(PlayerPrefabPostInit)<file_sep>local Vector3 = GLOBAL.Vector3 local STRINGS = GLOBAL.STRINGS ---------------------------------------- 操作 ---------------------------------------- local AIP_ACTION = env.AddAction("AIP_ACTION", "Operate", function(act) -- Client Only Code local doer = act.doer local target = act.target -- 操作 if target.components.aipc_action ~= nil then target.components.aipc_action:DoAction(doer) return true end return false, "INUSE" end) AddStategraphActionHandler("wilson", GLOBAL.ActionHandler(AIP_ACTION, "doshortaction")) AddStategraphActionHandler("wilson_client", GLOBAL.ActionHandler(AIP_ACTION, "doshortaction")) ---------------------------------------- 配置 ---------------------------------------- local getNectarValues = GLOBAL.require("utils/aip_nectar_util") local params = {} ----------------- 焚烧炉 ----------------- params.incinerator = { widget = { slotpos = { Vector3(0, 64 + 32 + 8 + 4, 0), Vector3(0, 32 + 4, 0), Vector3(0, -(32 + 4), 0), Vector3(0, -(64 + 32 + 8 + 4), 0), }, animbank = "ui_cookpot_1x4", animbuild = "ui_cookpot_1x4", pos = Vector3(200, 0, 0), side_align_tip = 100, buttoninfo = { text = STRINGS.ACTIONS.ABANDON, position = Vector3(0, -165, 0), } }, acceptsstacks = true, type = "chest", } function params.incinerator.itemtestfn(container, item, slot) if item:HasTag("irreplaceable") or item.prefab == "ash" then return false, "INCINERATOR_NOT_BURN" end return true end function params.incinerator.widget.buttoninfo.fn(inst) if inst.components.container ~= nil then GLOBAL.BufferedAction(inst.components.container.opener, inst, AIP_ACTION):Do() elseif inst.replica.container ~= nil and not inst.replica.container:IsBusy() then GLOBAL.SendRPCToServer(GLOBAL.RPC.DoWidgetButtonAction, AIP_ACTION.code, inst, AIP_ACTION.mod_name) end end function params.incinerator.widget.buttoninfo.validfn(inst) return inst.replica.container ~= nil end --------------- 花蜜酿造机 --------------- params.aip_nectar_maker = { widget = { slotpos = {}, animbank = "ui_icepack_2x3", animbuild = "ui_icepack_2x3", pos = Vector3(200, 0, 0), buttoninfo = { text = STRINGS.ACTIONS.COOK, position = Vector3(-125, -130, 0), } }, acceptsstacks = false, type = "chest", } for y = 0, 2 do table.insert(params.aip_nectar_maker.widget.slotpos, Vector3(-162, -75 * y + 75, 0)) table.insert(params.aip_nectar_maker.widget.slotpos, Vector3(-162 + 75, -75 * y + 75, 0)) end function params.aip_nectar_maker.itemtestfn(container, item, slot) local values = getNectarValues(item) return GLOBAL.next(values) ~= nil end function params.aip_nectar_maker.widget.buttoninfo.fn(inst) if inst.components.container ~= nil then GLOBAL.BufferedAction(inst.components.container.opener, inst, AIP_ACTION):Do() elseif inst.replica.container ~= nil and not inst.replica.container:IsBusy() then GLOBAL.SendRPCToServer(GLOBAL.RPC.DoWidgetButtonAction, AIP_ACTION.code, inst, AIP_ACTION.mod_name) end end function params.aip_nectar_maker.widget.buttoninfo.validfn(inst) return inst.replica.container ~= nil and not inst.replica.container:IsEmpty() end ---------------- 暗影宝箱 ---------------- params.aip_shadow_chest = { widget = { slotpos = {}, animbank = "ui_chest_3x3", animbuild = "ui_chest_3x3", pos = Vector3(0, 200, 0), side_align_tip = 160, buttoninfo = { text = STRINGS.UI.HELP.CONFIGURE, position = Vector3(0, -140, 0), } }, acceptsstacks = true, type = "chest", } for y = 2, 0, -1 do for x = 0, 2 do table.insert(params.aip_shadow_chest.widget.slotpos, Vector3(80 * x - 80 * 2 + 80, 80 * y - 80 * 2 + 80, 0)) end end local tmpConfig = { --[[prompt = "Write on the sign", animbank = "ui_board_5x3", animbuild = "ui_board_5x3", menuoffset = Vector3(6, -70, 0),]] cancelbtn = { text = "Cancel", cb = nil, control = CONTROL_CANCEL }, -- middlebtn = { text = "Random", cb = nil, control = CONTROL_MENU_MISC_2 }, acceptbtn = { text = "Confirm", cb = nil, control = CONTROL_ACCEPT }, --[[config = { { name = "autoCollect", label = "Auto Collect Item", options = { {description = "True", data = "true"}, {description = "False", data = "false"}, }, default = "false", }, },]] } function params.aip_shadow_chest.widget.buttoninfo.fn(inst) local player = GLOBAL.ThePlayer if player and player.HUD then return player.HUD:ShowAIPAutoConfigWidget(inst, tmpConfig) end end ---------------------------------------------------------------------------------------------- local containers = GLOBAL.require "containers" local old_widgetsetup = containers.widgetsetup -- 豪华锅 和 冰箱 代码有BUG,只能注入一下了 -- Some mod inject the `widgetsetup` function with missing the `data` arguments cause customize data not work anymore. -- Have to inject the function also, so sad. function containers.widgetsetup(container, prefab, data) local pref = prefab or container.inst.prefab -- Hook local containerParams = params[pref] if containerParams then for k, v in pairs(containerParams) do container[k] = v end container:SetNumSlots(container.widget.slotpos ~= nil and #container.widget.slotpos or 0) return end return old_widgetsetup(container, prefab, data) end for k, v in pairs(params) do containers.MAXITEMSLOTS = math.max(containers.MAXITEMSLOTS, v.widget.slotpos ~= nil and #v.widget.slotpos or 0) end<file_sep>local foldername = KnownModIndex:GetModActualName(TUNING.ZOMBIEJ_ADDTIONAL_PACKAGE) -- 配置 local additional_food = aipGetModConfig("additional_food") if additional_food ~= "open" then return nil end local food_effect = aipGetModConfig("food_effect") local language = aipGetModConfig("language") -- 默认参数 local EFFECT_MAP = { ["less"] = 0.6, ["normal"] = 1, ["large"] = 1.5, } local effectPTG = EFFECT_MAP[food_effect] -- 语言 local LANG_MAP = require("prefabs/foods_lang") local LANG = LANG_MAP[language] or LANG_MAP.english local LANG_ENG = LANG_MAP.english -- 资源 local prefabList = {} local prefabs = { "spoiled_food", } local HP = TUNING.HEALING_TINY -- 1 healing local HU = TUNING.CALORIES_HUGE / 75 -- 1 hunger local SAN = TUNING.SANITY_SUPERTINY -- 1 sanity local PER = TUNING.PERISH_ONE_DAY -- 1 day local CO = 1 / 20 -- 1 second -- 方法 local function getCount(entity, name) return entity[name] or 0 end -- 配方 local food_recipes = { egg_pancake = { test = function(cooker, names, tags) return tags.egg and tags.egg >= 3 and not tags.inedible end, priority = 1, weight = 1, foodtype = FOODTYPE.MEAT, health = HP * 20, hunger = HU * 80, sanity = SAN * 10, perishtime = PER * 5, cooktime = CO * 20, }, monster_salad = { test = function(cooker, names, tags) return tags.monster and tags.veggie and tags.veggie >= 3 and not tags.inedible end, priority = 0, weight = 1, foodtype = FOODTYPE.VEGGIE, health = HP * 5, hunger = HU * 65, sanity = SAN * 10, perishtime = PER * 6, cooktime = CO * 20, }, skunk_smoothies = { test = function(cooker, names, tags) return (names.durian or names.durian_cooked) and tags.frozen and tags.fruit and tags.fruit >= 2 and not tags.inedible end, priority = 1, weight = 1, foodtype = FOODTYPE.VEGGIE, health = HP * 5, hunger = HU * 20, sanity = SAN * 35, perishtime = PER * 6, cooktime = CO * 10, }, fish_froggle = { test = function(cooker, names, tags) return (names.froglegs or names.froglegs_cooked) and tags.fish and not tags.inedible end, priority = 2, weight = 1, foodtype = FOODTYPE.MEAT, health = HP * 30, hunger = HU * 80, sanity = SAN * 15, perishtime = PER * 6, cooktime = CO * 40, }, bamboo_light = { test = function(cooker, names, tags) return (names.corn or names.corn_cooked) and (names.carrot or names.carrot_cooked) and (names.pumpkin or names.pumpkin_cooked) end, priority = 1, weight = 1, foodtype = FOODTYPE.VEGGIE, health = HP * 100, hunger = HU * 5, sanity = SAN * 10, perishtime = PER * 20, cooktime = CO * 15, }, vegetaballs = { test = function(cooker, names, tags) return tags.meat and tags.meat == 2 and tags.veggie and not tags.inedible and not tags.frozen and not tags.fruit end, priority = 0, weight = 1, foodtype = FOODTYPE.MEAT, health = HP * 5, hunger = HU * 60, sanity = SAN * 10, perishtime = PER * 10, cooktime = CO * 15, }, veg_lohan = { test = function(cooker, names, tags) local red = getCount(names, "red_cap") + getCount(names, "red_cap_cooked") local green = getCount(names, "green_cap") + getCount(names, "green_cap_cooked") local blue = getCount(names, "blue_cap") + getCount(names, "blue_cap_cooked") return red + green + blue > 3 end, priority = 1, weight = 1, foodtype = FOODTYPE.VEGGIE, health = HP * 5, hunger = HU * 50, sanity = SAN * 15, perishtime = PER * 20, cooktime = CO * 30, }, honey_drumstick = { test = function(cooker, names, tags) return names.drumstick and tags.sweetener and tags.sweetener >= 2 and tags.meat and tags.meat < 1 end, priority = 3, weight = 1, foodtype = FOODTYPE.MEAT, health = HP * 20, hunger = HU * 40, sanity = SAN * 5, perishtime = PER * 6, cooktime = CO * 30, tags = {"honeyed"}, }, meat_burger = { test = function(cooker, names, tags) return tags.meat and tags.meat > 1 and tags.egg and (names.froglegs or names.froglegs_cooked) and tags.fish end, priority = 3, weight = 1, foodtype = FOODTYPE.MEAT, health = HP * 20, hunger = HU * 150, sanity = SAN * 5, perishtime = PER * 10, cooktime = CO * 15, }, veggie_skewers = { test = function(cooker, names, tags) return tags.veggie and tags.inedible and tags.inedible < 2 and not tags.meat end, priority = -1, weight = 1, foodtype = FOODTYPE.VEGGIE, health = HP * 5, hunger = HU * 30, sanity = SAN * 5, perishtime = PER * 15, cooktime = CO * 20, }, stinky_mandarin_fish = { test = function(cooker, names, tags) return tags.fish and tags.monster and not tags.inedible end, priority = 0, weight = 1, foodtype = FOODTYPE.MEAT, health = HP * 10, hunger = HU * 65, sanity = SAN * 5, perishtime = PER * 10, cooktime = CO * 30, }, watermelon_juice = { test = function(cooker, names, tags) return names.watermelon and tags.fruit and tags.fruit > 1 and tags.frozen end, priority = 1, weight = 1, foodtype = FOODTYPE.VEGGIE, health = HP * 5, hunger = HU * 40, sanity = SAN * 5, perishtime = PER * 6, cooktime = CO * 20, }, caterpillar_bread = { test = function(cooker, names, tags) return names.butterflywings and tags.meat end, priority = 10, weight = 1, foodtype = FOODTYPE.MEAT, health = HP * 15, hunger = HU * 50, sanity = SAN * 5, perishtime = PER * 15, cooktime = CO * 40, }, durian_sugar = { test = function(cooker, names, tags) return (names.durian or names.durian_cooked) and tags.sweetener and tags.sweetener >= 2 end, priority = 20, weight = 1, foodtype = FOODTYPE.VEGGIE, health = HP * (-10), hunger = HU * 20, sanity = SAN * 20, perishtime = PER * 15, cooktime = CO * 30, tags = {"honeyed"}, }, frozen_heart = { test = function(cooker, names, tags) return tags.frozen and tags.frozen > 3 end, priority = -1, weight = 1, foodtype = FOODTYPE.VEGGIE, health = HP * 0, hunger = HU * 0, sanity = SAN * 0, perishtime = PER * 30, cooktime = CO * 10, temperature = TUNING.COLD_FOOD_BONUS_TEMP, temperatureduration = TUNING.FOOD_TEMP_LONG, goldvalue = TUNING.GOLD_VALUES.MEAT, tags = {"frozen", "aip_nectar_material"}, }, aip_food_egg_fried_rice = { test = function(cooker, names, tags) return tags.starch and tags.egg and not tags.fruit end, priority = 6, weight = 1, foodtype = FOODTYPE.VEGGIE, health = HP * 0, hunger = HU * 75, sanity = SAN * 0, perishtime = PER * 15, cooktime = CO * 10, }, aip_food_plov = { test = function(cooker, names, tags) return tags.starch and tags.meat and (names.carrot or names.carrot_cooked) end, priority = 6, weight = 1, foodtype = FOODTYPE.MEAT, health = HP * 25, hunger = HU * 75, sanity = SAN * 5, perishtime = PER * 20, cooktime = CO * 40, }, aip_food_kozinaki = { test = function(cooker, names, tags) return tags.starch and tags.starch >= 2 and tags.sweetener end, priority = 6, weight = 1, foodtype = FOODTYPE.VEGGIE, health = HP * 10, hunger = HU * 65, sanity = SAN * 7, perishtime = PER * 30, cooktime = CO * 20, }, aip_food_cherry_meat = { test = function(cooker, names, tags) return tags.meat and tags.meat >= 1.5 and tags.meat < 3 and ( names.berries or names.berries_cooked or names.berries_juicy or names.berries_juicy_cooked or names.aip_veggie_grape or names.aip_veggie_grape_cooked ) end, priority = 1, weight = 1, foodtype = FOODTYPE.MEAT, health = HP * 15, hunger = HU * 50, sanity = SAN * 15, perishtime = PER * 10, cooktime = CO * 15, }, aip_food_egg_tart = { test = function(cooker, names, tags) return tags.starch and tags.egg and not tags.meat and not tags.inedible end, priority = 6, weight = 1, foodtype = FOODTYPE.MEAT, health = HP * 10, hunger = HU * 30, sanity = SAN * 15, perishtime = PER * 10, cooktime = CO * 15, }, aip_food_grape_suger = { test = function(cooker, names, tags) return tags.sweetener and tags.inedible and tags.inedible == 1 and names.aip_veggie_grape end, priority = 10, weight = 1, foodtype = FOODTYPE.VEGGIE, health = -HP * 5, hunger = HU * 15, sanity = SAN * 15, perishtime = PER * 30, cooktime = CO * 15, tags = {"honeyed"}, }, aip_food_cube_sugar = { test = function(cooker, names, tags) return tags.sweetener and tags.sweetener >= 3 and names.watermelon and not tags.inedible end, priority = 11, weight = 1, foodtype = FOODTYPE.VEGGIE, health = HP * 0, hunger = HU * 25, sanity = SAN * 15, perishtime = PER * 15, cooktime = CO * 40, tags = {"honeyed", "aip_nectar_material", "aip_exquisite"}, }, } -------------------------------------------------- for name,data in pairs(food_recipes) do -- 预处理 data.name = name data.weight = data.weight or 1 data.priority = data.priority or 0 -- 食物属性 data.health = data.health * effectPTG data.hunger = data.hunger * effectPTG data.sanity = data.sanity * effectPTG -- 添加文字 local upperCase = string.upper(name) local FOOD_LANG = LANG[upperCase] or LANG_ENG[upperCase] STRINGS.NAMES[upperCase] = FOOD_LANG.NAME STRINGS.CHARACTERS.GENERIC.DESCRIBE[upperCase] = FOOD_LANG.DESC -- 添加食物 AddModPrefabCookerRecipe("cookpot", data) -------------------- 创建食物实体 -------------------- local assets = { Asset("ATLAS", "images/inventoryimages/"..data.name..".xml"), Asset("IMAGE", "images/inventoryimages/"..data.name..".tex"), Asset("ANIM", "anim/"..data.name..".zip"), } function fn() local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddNetwork() MakeInventoryPhysics(inst) inst.AnimState:SetBuild(data.name) inst.AnimState:SetBank(data.name) inst.AnimState:PlayAnimation("BUILD", false) inst:AddTag("preparedfood") if data.tags then for i,v in pairs(data.tags) do inst:AddTag(v) end end inst.entity:SetPristine() if not TheWorld.ismastersim then return inst end -- 食物 inst:AddComponent("edible") inst.components.edible.healthvalue = data.health inst.components.edible.hungervalue = data.hunger inst.components.edible.foodtype = data.foodtype or FOODTYPE.GENERIC inst.components.edible.sanityvalue = data.sanity or 0 inst.components.edible.temperaturedelta = data.temperature or 0 inst.components.edible.temperatureduration = data.temperatureduration or 0 inst.components.edible:SetOnEatenFn(data.oneatenfn) inst:AddComponent("inspectable") inst.wet_prefix = data.wet_prefix -- 是否可以交易 if data.goldvalue then inst:AddComponent("tradable") inst.components.tradable.goldvalue = data.goldvalue end -- 物品栏 inst:AddComponent("inventoryitem") inst.components.inventoryitem.atlasname = "images/inventoryimages/"..data.name..".xml" inst:AddComponent("stackable") inst.components.stackable.maxsize = TUNING.STACK_SIZE_SMALLITEM if data.perishtime ~= nil and data.perishtime > 0 then inst:AddComponent("perishable") inst.components.perishable:SetPerishTime(data.perishtime) inst.components.perishable:StartPerishing() inst.components.perishable.onperishreplacement = "spoiled_food" end MakeSmallBurnable(inst) MakeSmallPropagator(inst) MakeHauntableLaunchAndPerish(inst) AddHauntableCustomReaction(inst, function(inst, haunter) return false end, true, false, true) --------------------- inst:AddComponent("bait") ------------------------------------------------ return inst end local prefab = Prefab(name, fn, assets, prefabs) table.insert(prefabList, prefab) end return unpack(prefabList) <file_sep>-- 食物 local additional_food = GLOBAL.aipGetModConfig("additional_food") if additional_food ~= "open" then return nil end -- 开发模式 local dev_mode = GLOBAL.aipGetModConfig("dev_mode") == "enabled" -- 概率 local PROBABILITY = dev_mode and 1 or 0.15 local VEGGIES = GLOBAL.require('prefabs/aip_veggies_list') -- 添加其他种子概率 function mergePickProduct(oriFunc, probability) return function(inst) -- 产生自定义的新物品 if math.random() < probability then local total_w = 0 for veggiename,v in pairs(VEGGIES) do total_w = total_w + (v.seed_weight or 1) end local rnd = math.random()*total_w for veggiename,v in pairs(VEGGIES) do rnd = rnd - (v.seed_weight or 1) if rnd <= 0 then return "aip_veggie_"..veggiename end end end -- 产生原本的物品 return oriFunc(inst) end end -- 更多的蔬菜种子 AddPrefabPostInit("seeds", function(inst) if not GLOBAL.TheWorld.ismastersim then return end -- 添加概率钩子 if inst.components.plantable then local originPickProduct = inst.components.plantable.product inst.components.plantable.product = mergePickProduct(originPickProduct, PROBABILITY) end end) -- 给蔬菜赋值 for name, data in pairs(VEGGIES) do env.AddIngredientValues({"aip_veggie_"..name}, data.tags or {}, data.cancook or false, data.candry or false) end <file_sep>function GLOBAL.AddModPrefabCookerRecipe(cooker, recipe) env.AddCookerRecipe(cooker, recipe) end<file_sep>function GLOBAL.aipCommonStr(showType, split, ...) local str = "" for i,v in ipairs(arg) do local parsed = v local vType = type(v) if showType then -- 显示类别 if parsed == nil then parsed = "(nil)" elseif parsed == true then parsed = "(true)" elseif parsed == false then parsed = "(false)" elseif parsed == "" then parsed = "(empty)" elseif vType == "table" then local isFirst = true parsed = "{" for v_k, v_v in pairs(v) do if not isFirst then parsed = parsed .. ", " end isFirst = false parsed = parsed .. tostring(v_k) .. ":" ..tostring(v_v) end parsed = parsed .. "}" end str = str .. "[" .. type(v) .. ": " .. tostring(parsed) .. "]" .. split else -- 显示文字 str = str .. tostring(parsed) .. split end end return str end function GLOBAL.aipCommonPrint(showType, split, ...) local str = "[AIP] "..GLOBAL.aipCommonStr(showType, split, ...) print(str) end function GLOBAL.aipStr(...) return GLOBAL.aipCommonStr(false, "", ...) end function GLOBAL.aipPrint(...) return GLOBAL.aipCommonPrint(false, " ", ...) end function GLOBAL.aipTypePrint(...) return GLOBAL.aipCommonPrint(true, " ", ...) end GLOBAL.aipGetModConfig = GetModConfigData function GLOBAL.aipGetAnimState(inst) local match = false local data = {} if inst then local str = inst.GetDebugString and inst:GetDebugString() if str then local bank, build, anim bank, build, anim = string.match(str, "AnimState: bank: (.*) build: (.*) anim: (.*) anim") if not anim then bank, build, anim = string.match(str, "AnimState: bank: (.*) build: (.*) anim: (.*) ..") end data.bank = string.split(bank or "", " ")[1] data.build = string.split(build or "", " ")[1] data.anim = string.split(anim or "", " ")[1] if data.bank and data.build and data.anim then match = true end end end return match and data or nil end<file_sep>-- 多队列计时器组件 local Timer = Class(function(self, inst) self.inst = inst self.id = 0 self.list = {} end) function Timer:Interval(step, func, ...) self.id = self.id + 1 local myId = self.id local interval = self.inst:DoPeriodicTask(step, function(...) local result = func(...) if result == false then self:Remove(myId) end return result end, ...) self.list[myId] = interval return myId end function Timer:Timeout(step, func, ...) self.id = self.id + 1 local myId = self.id local timeout = self.inst:DoTaskInTime(step, function(...) self:Remove(myId) return func(...) end, ...) self.list[myId] = timeout return myId end function Timer:Remove(id) self.list[id] = nil end function Timer:Kill(id) local timer = self.list[id] if timer then timer:Cancel() self.list[id] = nil end end function Timer:KillAll() for id, timer in pairs(self.list) do self:Kill(id) end end Timer.OnRemoveFromEntity = Timer.KillAll Timer.OnRemoveEntity = Timer.KillAll return Timer<file_sep>local foldername = KnownModIndex:GetModActualName(TUNING.ZOMBIEJ_ADDTIONAL_PACKAGE) ------------------------------------ 配置 ------------------------------------ -- 魔法关闭 local additional_magic = aipGetModConfig("additional_magic") if additional_magic ~= "open" then return nil end local language = aipGetModConfig("language") local LANG_MAP = { english = { NAME = "Shadow Wrapper", DESCRIBE = "Do not spawn me!", }, chinese = { NAME = "暗影动画", DESCRIBE = "不要创建我!", }, } local LANG = LANG_MAP[language] or LANG_MAP.english local LANG_ENG = LANG_MAP.english ----------------------------------------------------------- local assets = { Asset("ANIM", "anim/aip_shadow_wrapper.zip"), } local prefabs = {} function fn() local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddSoundEmitter() inst.entity:AddNetwork() -- TODO: Fix this inst.AnimState:SetBank("aip_shadow_wrapper") inst.AnimState:SetBuild("aip_shadow_wrapper") inst.AnimState:PlayAnimation("wrap") if not TheWorld.ismastersim then return inst end -- Play hide inst.DoHide = function() inst.SoundEmitter:PlaySound("dontstarve/common/together/skin_change") inst:DoTaskInTime(24 * FRAMES, function() if inst.OnFinish then inst.OnFinish(inst) end end) inst:DoTaskInTime(45 * FRAMES, function() if inst.OnFinished then inst.OnFinished(inst) end end) end -- Play show inst.DoShow = function() inst.AnimState:PlayAnimation("end") inst:DoTaskInTime(10 * FRAMES, function() if inst.OnFinished then inst.OnFinished(inst) end end) end return inst end return Prefab("aip_shadow_wrapper", fn, assets, prefabs)<file_sep>local Action = Class(function(self, inst) self.inst = inst self.onDoAction = nil self.onDoTargetAction = nil end) function Action:DoAction(doer) if self.onDoAction then self.onDoAction(self.inst, doer) end end function Action:DoTargetAction(doer, target) if self.onDoTargetAction then self.onDoTargetAction(self.inst, doer, target) end end return Action<file_sep>local COMMON = 3 local UNCOMMON = 1 local RARE = .5 local VEGGIES = { wheat = { seed_weight = COMMON, health = 1, hunger = 12.5, sanity = 0, perishtime = 30, cooked_health = 5, cooked_hunger = 25, cooked_sanity = 0, cooked_perishtime = 5, tags = { starch = 1 }, cancook = true, candry = false, }, sunflower = { seed_weight = COMMON, health = 1, hunger = 0, sanity = 5, perishtime = TUNING.PERISH_FAST, cooked_health = 1, cooked_hunger = 5, cooked_sanity = 5, cooked_perishtime = TUNING.PERISH_MED, tags = { starch = 1 }, cancook = true, candry = false, }, grape = { seed_weight = COMMON, health = 5, hunger = 10, sanity = 0, perishtime = TUNING.PERISH_FAST, cooked_health = 10, cooked_hunger = 15, cooked_sanity = 0, cooked_perishtime = TUNING.PERISH_FAST, tags = { fruit = 1 }, cancook = true, candry = false, }, --[[onion = { seed_weight = COMMON, health = HP * 5, hunger = HU * 12.5, sanity = SAN * 0, perishtime = PER * 30, cooked_health = HP * 5, cooked_hunger = HU * 25, cooked_sanity = SAN * 5, cooked_perishtime = PER * 5, },]] } return VEGGIES<file_sep>-- 这个组件用于清除 side effect local Player = Class(function(self, inst) self.inst = inst inst:ListenForEvent("death", function() self:Death() end) end) function Player:OffMineCar() local player = self.inst if not TheWorld.ismastersim then return end if player:HasTag("aip_minecar_driver") then local x, y, z = player.Transform:GetWorldPosition() local mineCars = TheSim:FindEntities(x, y, z, 10, { "aip_minecar" }) for i, mineCar in ipairs(mineCars) do local aipc_minecar = mineCar.components.aipc_minecar if aipc_minecar and aipc_minecar.driver == player then aipc_minecar:RemoveDriver(player) end end end end ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- function Player:Death() ---------------------------------- Server ---------------------------------- if not TheWorld.ismastersim then return end self:OffMineCar() end function Player:Destroy() local player = self.inst aipPrint("Player leave:", player.name, "(", player.userid, ")") ---------------------------------- Client ---------------------------------- ---------------------------------- Server ---------------------------------- if not TheWorld.ismastersim then return end self:OffMineCar() end Player.OnRemoveEntity = Player.Destroy return Player<file_sep>local descList = { "(DEV MODE)", "Provide additional items for game. Enjoy your new package! (You can close part of package in options)", "提供额外的物品合成,享受更加丰富的游戏内容吧!(您可以在选项中选择关闭不需要的内容)", "\nView Steam workshop for more info", "游览Steam创意工坊查看更多信息", "\n新浪微博:@二货爱吃白萝卜", } local function joinArray(arr, spliter) local strs = "" for i = 1, #arr do if i ~= 1 then strs = strs..spliter end strs = strs..arr[i] end return strs end name = "Additional Item Package DEV" description = joinArray(descList, "\n") author = "ZombieJ" version = "1.5.0" forumthread = "http://steamcommunity.com/sharedfiles/filedetails/?id=1085586145" icon_atlas = "modicon.xml" icon = "modicon.tex" priority = -99 dst_compatible = true client_only_mod = false all_clients_require_mod = true api_version = 10 configuration_options = { { name = "additional_weapon", label = "Weapon Recipes", options = { {description = "Open", data = "open"}, {description = "Close", data = "close"}, }, default = "open", }, { name = "additional_building", label = "Building Recipes", options = { {description = "Open", data = "open"}, {description = "Close", data = "close"}, }, default = "open", }, { name = "additional_survival", label = "Survival Recipes", options = { {description = "Open", data = "open"}, {description = "Close", data = "close"}, }, default = "open", }, { name = "additional_food", label = "Food Recipes", options = { {description = "Open", data = "open"}, {description = "Close", data = "close"}, }, default = "open", }, { name = "additional_dress", label = "Dress Recipes", options = { {description = "Open", data = "open"}, {description = "Close", data = "close"}, }, default = "open", }, { name = "additional_chesspieces", label = "Chesspieces Recipes", options = { {description = "Open", data = "open"}, {description = "Close", data = "close"}, }, default = "open", }, { name = "additional_orbit", label = "Orbit Recipes", hover = "Support Orbit. WOW!~", options = { {description = "Open", data = "open"}, {description = "Close", data = "close"}, }, default = "open", }, { name = "additional_magic", label = "Magic Recipes", options = { {description = "Open", data = "open"}, {description = "Close", data = "close"}, }, default = "open", }, { name = "additional_experiment", label = "Experiment Recipes", hover = "Experience new released items", options = { {description = "Open", data = "open"}, {description = "Close", data = "close"}, }, default = "open", }, { name = "weapon_uses", label = "Weapon Usage times", options = { {description = "Less", data = "less"}, {description = "Default", data = "normal"}, {description = "Much", data = "much"}, }, default = "normal", }, { name = "weapon_damage", label = "Weapon Damage", options = { {description = "Less", data = "less"}, {description = "Default", data = "normal"}, {description = "Large", data = "large"}, }, default = "normal", }, { name = "survival_effect", label = "Survival Item Effect", options = { {description = "Less", data = "less"}, {description = "Default", data = "normal"}, {description = "Large", data = "large"}, }, default = "normal", }, { name = "food_effect", label = "Food Recipes Effect", options = { {description = "Less", data = "less"}, {description = "Default", data = "normal"}, {description = "Large", data = "large"}, }, default = "normal", }, { name = "dress_uses", label = "Dress Usage times", options = { {description = "Less", data = "less"}, {description = "Default", data = "normal"}, {description = "Much", data = "much"}, }, default = "normal", }, { name = "tooltip_enhance", label = "Tooltip info enhance", hover = "Let some item in slot support additional tooltip", options = { {description = "Open", data = "open"}, {description = "Close", data = "close"}, }, default = "open", }, { name = "language", label = "Language", options = { {description = "中文", data = "chinese"}, {description = "English", data = "english"}, {description = "Spanish", data = "spanish"}, {description = "Portuguese", data = "portuguese"}, {description = "Russian", data = "russian"}, {description = "Korean", data = "korean"}, }, default = "english", }, { name = "dev_mode", label = "Dev Mod(DONT OPEN!)", hover = "This is only for dev and fail track. Please never enable it.", options = { {description = "Enabled", data = "enabled"}, {description = "Disabled", data = "disabled"}, }, default = "disabled", }, }
c4534b8faa13be188b0fb1863d4048ef2e14ff7d
[ "Lua" ]
16
Lua
Numiansus/dst_additional_item_package
0124a604629d1fabd18c6011546fdc99ad7254a3
b696758c3b969f3cde75ee3f5bad3b34d1456d20
refs/heads/main
<repo_name>SrivathsanKannan/Marks.C<file_sep>/Marks.C #include <stdio.h> int main() { int mark; printf("Please Enter student's marks:-\n"); scanf("%d", &mark); if(mark>84) printf("\nThe grade is - A"); else if(mark>69) printf("\nThe grade is - B"); else if(mark>54) printf("\nThe grade is - C"); else if(mark>39) printf("\nThe grade is - D"); else printf("\nThe grade is - F"); return 0; }
9c051a3922ac218f03e510e7619e4e3688e1f1ea
[ "C" ]
1
C
SrivathsanKannan/Marks.C
c54f81bf686a0cdfe54dd62b4670480783541c33
5a2d8eb3d4beedc5eb12ec4516ee19d4daa46355
refs/heads/master
<file_sep>require "nokogiri" module Shipping class Package attr_accessor :large, :weight, :description, :monetary_value def initialize(options={}) @large = options[:large] @weight = options[:weight] @description = options[:description] @monetary_value = options[:monetary_value] end def build(xml) xml.Package { xml.PackagingType { xml.Code "02" xml.Description "Customer Supplied" } xml.Description @description xml.ReferenceNumber { xml.Code "00" xml.Value "Package" } xml.PackageWeight { xml.UnitOfMeasurement xml.Weight @weight } if @large xml.LargePackageIndicator end } end def to_xml() builder = Nokogiri::XML::Builder.new do |xml| build(xml) end builder.to_xml end end end<file_sep>require "nokogiri" require "httparty" require 'ups_shipping/address' require 'ups_shipping/organization' require 'ups_shipping/package' require 'ups_shipping/pickup' module Shipping VERSION = '1.0.2' class UPS TEST_URL = "https://wwwcie.ups.com" LIVE_URL = "https://onlinetools.ups.com" class Http include HTTParty base_uri LIVE_URL def initialize(access_request, options={}) @access_request = access_request if (options[:test]) self.class.base_uri TEST_URL end end def commit(url, request) request = @access_request + request self.class.post(url, :body => request).parsed_response end end def initialize(user, password, license, options={}) @options = options @shipper = options[:shipper] @access_request = access_request(user, password, license) @http = Http.new(@access_request, :test => @options[:test]) @services = { "01" => "Next Day Air", "02" => "2nd Day Air", "03" => "Ground", "07" => "Express", "08" => "Expedited", "11" => "UPS Standard", "12" => "3 Day Select", "13" => "Next Day Air Saver", "14" => "Next Day Air Early AM", "54" => "Express Plus", "59" => "2nd Day Air A.M.", "65" => "UPS Saver", "82" => "UPS Today Standard", "83" => "UPS Today Dedicated Courier", "84" => "UPS Today Intercity", "85" => "UPS Today Express", "86" => "UPS Today Express Saver" } end def validate_address(address) validate_request = Nokogiri::XML::Builder.new do |xml| xml.AddressValidationRequest { xml.Request { xml.TransactionReference { xml.CustomerContext xml.XpciVersion 1.0001 } xml.RequestAction "XAV" xml.RequestOption "3" } xml.MaximumListSize 3 xml.AddressKeyFormat { xml.AddressLine address.address_lines[0] xml.PoliticalDivision2 address.city xml.PoliticalDivision1 address.state xml.PostcodePrimaryLow address.zip xml.CountryCode address.country } } end @http.commit("/ups.app/xml/XAV", validate_request.to_xml) end def find_rates(package, origin, destination, options={}) rate_request = Nokogiri::XML::Builder.new do |xml| xml.RatingServiceSelectionRequest { xml.Request { xml.RequestAction "Rate" xml.RequestOption "Rate" } if options[:pickup] @options[:pickup].build_type(xml) end @shipper.build(xml, "Shipper") destination.build(xml, "ShipTo") origin.build(xml, "ShipFrom") xml.PaymentInformation { xml.Prepaid { xml.BillShipper { xml.AccountNumber "Ship Number" } } } package.build(xml) } end @http.commit("/ups.app/xml/Rate", rate_request.to_xml) end def request_shipment(package, origin, destination, service, options={}) shipment_request = Nokogiri::XML::Builder.new do |xml| xml.ShipmentConfirmRequest { xml.Request { xml.RequestAction "ShipConfirm" xml.RequestOptions "validate" } if options[:label] xml.LabelSpecification { xml.LabelPrintMethod { xml.Code "GIF" xml.Description "gif file" } xml.HTTPUserAgent "Mozilla/4.5" xml.LabelImageFormat { xml.Code "GIF" xml.Description "gif" } } end @shipper.build(xml, "Shipper") destination.build(xml, "ShipTo") origin.build(xml, "ShipFrom") xml.PaymentInformation { xml.Prepaid { xml.BillShipper { xml.AccountNumber "Ship Number" } } } xml.Service { xml.Code service xml.Description @services[service] } package.build(xml) } end @http.commit("/ups.app/xml/ShipConfirm", shipment_request.to_xml) end def cancel_shipment(shipment_id) cancel_request = Nokogiri::XML::Builder.new do |xml| xml.VoidShipmentRequest { xml.Request { xml.RequestAction "1" xml.RequestOption "1" } xml.ShipmentIdentificationNumber shipment_id } end @http.commit("/ups.app/xml/Void", cancel_request.to_xml) end def track_shipment(tracking_number) track_request = Nokogiri::XML::Builder.new do TrackRequest { Request { RequestAction "Track" RequestOption "activity" } TrackingNumber tracking_number } end @http.commit("/ups.app/xml/Track", track_request.to_xml) end private def access_request(user, password, license) access_request = Nokogiri::XML::Builder.new do AccessRequest { AccessLicenseNumber license UserId user Password <PASSWORD> } end access_request.to_xml end end end<file_sep>source :rubygems gem "nokogiri" gem "rspec" gem "httparty" <file_sep>require "rspec" require "ups_shipping" require "address" require "organization" describe Shipping::UPS do before(:all) do @ups = Shipping::UPS.new("deanchen", "Transcriptic#1", "EC96D31A8D672E28", :test => true) @address = Shipping::Address.new( :address_lines => ["1402 Faber St."], :city => "Durham", :state => "NC", :zip => "27705", :country => "US" ) end it "address object" do @address.to_xml.gsub(/^\s+/, "").gsub(/\s+$/, $/).should == ' <?xml version="1.0"?> <Address> <AddressLine1>1402 Faber St.</AddressLine1> <City>Durham</City> <StateProvinceCode>NC</StateProvinceCode> <PostalCode>27705</PostalCode> <CountryCode>US</CountryCode> </Address> '.gsub(/^\s+/, "").gsub(/\s+$/, $/) end it "organization object" do @organization = Shipping::Organization.new( :name => "Transcriptic", :phone => "1233455678", :address => @address ) puts @organization.to_xml("Shipper") end it "#track_shipment" do tracking_result = @ups.track_shipment("1ZXX31290231000092") tracking_result.should have_key("TrackResponse") tracking_result["TrackResponse"]["Response"]["ResponseStatusCode"].should == "1" end end<file_sep>require "nokogiri" module Shipping class Pickup attr_accessor :address_lines, :pickup_day, :contact_method, :type def initialize(options={}) @type = options[:type] if options[:pickup_day] @pickup_day = options[:pickup_day] end if options[:contact_method] @contact_method = options[:contact_method] end @pickupTypes = { "01" => "Daily Pickup", "03" => "Customer Counter", "06" => "One Time Pickup", "07" => "On Call Air", "19" => "Letter Center", "20" => "Air Service Center" } end def build_schedule(xml) xml.OnCallAir { xml.Schedule { if @pickup_day xml.PickupDay @pickup_day end if @contact_method xml.Method @contact_method end } } end def build_type(xml) xml.PickupType { xml.Code type xml.Description @pickupTypes[type] } end end end <file_sep>$:.unshift File.expand_path("../lib", __FILE__) require 'ups_shipping' Gem::Specification.new do |gem| gem.name = "ups_shipping" gem.version = Shipping::VERSION gem.author = "Transcriptic, Inc" gem.email = "<EMAIL>" gem.homepage = "http://www.github.com/transcriptic/ups-shipping" gem.summary = "UPS shipping API integration." gem.description = "UPS shipping gem for integrating UPS's API into a Ruby script." gem.files = %x{ git ls-files }.split("\n").select { |d| d =~ %r{^(lib/|spec/)} } gem.add_dependency "nokogiri" gem.add_dependency "rspec" gem.add_dependency "httparty" end<file_sep>require "nokogiri" module Shipping class Organization attr_accessor :name, :phone, :email, :address, :shipper_number def initialize(options={}) @name = options[:name] @phone = options[:phone] @address = options[:address] if options[:shipper_number] @shipper_number = options[:shipper_number] end end def build(xml, rootname) xml.send(rootname) { xml.CompanyName @name xml.PhoneNumber @phone if @shipper_number xml.ShipperNumber @shipper_number end @address.build(xml) } end def to_xml(rootname) builder = Nokogiri::XML::Builder.new do |xml| build(xml, rootname) end builder.to_xml end end end <file_sep>require "nokogiri" module Shipping class Address ADDRESS_TYPES = %w{residential commercial po_box} attr_accessor :address_lines, :city, :state, :zip, :country, :type def initialize(options={}) @address_lines = options[:address_lines] @city = options[:city] @state = options[:state] @zip = options[:zip] @country = options[:country] @type = options[:type] end def build(xml) xml.Address { xml.AddressLine1 @address_lines[0] xml.City @city xml.StateProvinceCode @state xml.PostalCode @zip xml.CountryCode @country } end def to_xml() builder = Nokogiri::XML::Builder.new do |xml| build(xml) end builder.to_xml end end end
1bd7fc4ca178c3089ff156bf3b80ce81b66f4f3c
[ "Ruby" ]
8
Ruby
transcriptic/ups-shipping
7f4dae0b15dfbf91d87c01e382b13f263ff14b7f
7381323ff82a17b1294c370bce3b7b5f49dbd7d8
refs/heads/main
<repo_name>samuel0480/FiveM-Cache-Clearer<file_sep>/cache.py import shutil import os import getpass user = getpass.getuser() location = rf"C:\Users\{user}\AppData\Local\FiveM\FiveM.app\cache" dir = "browser" path = os.path.join(location, dir) shutil.rmtree(path, ignore_errors = True) dir = "db" path = os.path.join(location, dir) shutil.rmtree(path, ignore_errors = True) dir = "priv" path = os.path.join(location, dir) shutil.rmtree(path, ignore_errors = True) dir = "servers" path = os.path.join(location, dir) shutil.rmtree(path, ignore_errors = True) dir = "subprocess" path = os.path.join(location, dir) shutil.rmtree(path, ignore_errors = True) dir = "unconfirmed" path = os.path.join(location, dir) shutil.rmtree(path, ignore_errors = True) file = "crashometry" path = os.path.join(location, file) try: os.remove(path) print("% s removed successfully" % path) except OSError as error: print(error) print("File path can not be removed") file = "launcher_skip_mtl2" path = os.path.join(location, file) try: os.remove(path) print("% s removed successfully" % path) except OSError as error: print(error) print("File path can not be removed")
bfffab0b662cc7950d376f83fc8aa5264a458841
[ "Python" ]
1
Python
samuel0480/FiveM-Cache-Clearer
7f08b37a6fc70bf975ebba0944268691109d7e77
e1f1d1aeac6b6d1168973d9a731871cb5805a83b
refs/heads/master
<repo_name>rajeev-ju/mycodes<file_sep>/vector.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; bool comp (int a, int b) { return a > b; } int main() { // your code goes here int m,n,i,j,a,b; cin>>n>>m; vector<int> v[n + 2]; for(i = 0; i < m; i++){ cin>>a>>b; v[a].push_back (b); v[b].push_back (a); } for (int i = 0; i < n; ++i) { sort (v[i].begin(), v[i].end(), greater <int> ()); } for(i = 1; i<=n; i++){ cout<<i<<":"; for(j = 0; j < v[i].size();j++){ cout<<v[i][j]<<" "; } cout<<endl; } return 0; }
44bb5589df57597c796387350b511a51e20bcdf3
[ "C++" ]
1
C++
rajeev-ju/mycodes
8e172091239db931712f1d6866f78a34cc80469c
f2f7734e424bbd925b670e09d839472ffef9c978
refs/heads/master
<file_sep>package com.beijing.util; import java.util.List; //import com.unissoft.pco.entity.customer.Question; public class PageUtils { private int pageNo=1;//当前是第几页 private int pageSize=10;//每页最多显示几条 private int prep;//上一页 private int nextp;//下一页 private int totalPage;//总页数 private int totalRecordes;//总记录数 private int startIndex;//代表分页的起始的索引 (pageNo-1)*pageSize; //private List<Question> recordes;//当前页的所有记录 private String url; //补充添加 private int startPageNo;//起始页 private int endPageNo;//结束页 //每页上面最多有9个数字显示 public int getStartPageNo() { if(getTotalPage()<=9){ startPageNo=1; endPageNo=getTotalPage(); }else{ startPageNo=pageNo-4; endPageNo=pageNo+4; if(startPageNo<=1){ startPageNo=1; endPageNo=startPageNo+8; } if(endPageNo>=getTotalPage()){ endPageNo=getTotalPage(); startPageNo=endPageNo-8; } } return startPageNo; } public void setStartPageNo(int startPageNo) { this.startPageNo = startPageNo; } public int getEndPageNo() { return endPageNo; } public void setEndPageNo(int endPageNo) { this.endPageNo = endPageNo; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getPrep() { if(pageNo<=1){ prep=1; }else{ prep=pageNo-1; } return prep; } public void setPrep(int prep) { this.prep = prep; } public int getNextp() { if(pageNo>=getTotalPage()){ nextp=getTotalPage(); }else{ nextp=pageNo+1; } return nextp; } public void setNextp(int nextp) { this.nextp = nextp; } public int getTotalPage() { if(totalRecordes%pageSize==0){ totalPage = totalRecordes/pageSize; }else{ totalPage = totalRecordes/pageSize+1; } return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getTotalRecordes() { return totalRecordes; } public void setTotalRecordes(int totalRecordes) { this.totalRecordes = totalRecordes; } public int getStartIndex() { startIndex = (pageNo-1)*pageSize; return startIndex; } public void setStartIndex(int startIndex) { this.startIndex = startIndex; } // public List getRecordes() { // return recordes; // } // public void setRecordes(List recordes) { // this.recordes = recordes; // } }
c3908ddaf134e2f083e6f59eb1dee0cde67b8962
[ "Java" ]
1
Java
yeWillBe/some_thing1
be2570088c89a08cb960a4f505054cf74cad67a6
19d8d4c5db2894a14f39f9072710c6d998ed6ec9
refs/heads/master
<repo_name>colealtdelete/StringThings<file_sep>/Python/geturls.py with open('C:/Users/Cole/Documents/StringThings/Python/Test.txt','r') as file: lines = file.readlines() for line in lines[2:]: columns = line.split() print(columns[0] + columns[6])<file_sep>/Bash/geturls.sh awk '{print $1$7}' test.txt
49f57ac3b86affd52c2a63c18e70181344001476
[ "Python", "Shell" ]
2
Python
colealtdelete/StringThings
f82c6b66b8d6f2ce520afbf973c5b7756c3dbfa2
bedf0db1ff1e5d87cf44f6c84880fb8993dd0c84
refs/heads/master
<repo_name>lukabratos/push-notifications-rust<file_sep>/Cargo.toml [package] name = "beams" description = "Pusher Beams Rust Server SDK" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] license = "MIT" [lib] name = "beams" path = "src/lib.rs" [[bin]] name = "beams" path = "src/bin.rs" [dependencies] ureq = { version = "0.4.5", features = ["json"] } serde = "1.0" serde_derive = "1.0" serde_json = "1.0" <file_sep>/src/bin.rs extern crate beams; use beams::publish; pub fn main() { let interests = vec![String::from("pizza"), String::from("avocado")]; let publish_request = r#"{ "apns": { "aps": { "alert": "Hello!" } }, "fcm": { "notification": { "title": "Hello!", "body": "Hello, world!" } } }"#; publish( String::from("id"), String::from("key"), interests, publish_request, ); } <file_sep>/README.md # Pusher Beams Rust Server SDK [![Build Status](https://travis-ci.org/lukabratos/push-notifications-rust.svg?branch=master)](https://travis-ci.org/lukabratos/push-notifications-rust) ```toml [dependencies] beams = "0.1.0" ``` ## Usage ```rust extern crate beams; use beams::publish; pub fn main() { let interests = vec![String::from("pizza"), String::from("avocado")]; let publish_request = r#"{ "apns": { "aps": { "alert": "Hello!" } }, "fcm": { "notification": { "title": "Hello!", "body": "Hello, world!" } } }"#; publish( String::from("id"), String::from("key"), interests, publish_request, ); } ``` <file_sep>/src/lib.rs #[macro_use] extern crate ureq; #[macro_use] extern crate serde_derive; extern crate serde_json; #[derive(Serialize)] struct Payload { interests: Vec<String>, publish_request: serde_json::Value, } pub fn publish( instance_id: String, secret_key: String, interests: Vec<String>, publish_request: &str, ) { println!("{} {}", instance_id, secret_key); println!("{:?}", interests); println!("{:?}", publish_request); let publish_request = serde_json::from_str(publish_request).unwrap(); let payload = Payload { interests: interests, publish_request: publish_request, }; println!("{:?}", json!(payload)); let resp = ureq::post(format!( "https://{}.pushnotifications.pusher.com/publish_api/v1/instances/{}/publishes", instance_id, instance_id )).set("Accept", "application/json") .set("Content-Type", "application/json") .set("Authorization", format!("Bearer {}", secret_key)) .send_json(json!(payload)); if resp.ok() { println!("{:?}", resp); } else { println!("{:?}", resp.status()); } }
0fbb6f94b3f6bcd19cc6090659d978cdd82ced9b
[ "TOML", "Rust", "Markdown" ]
4
TOML
lukabratos/push-notifications-rust
696d35f3863e423dc810cbcc247ad7ad53bce9f6
4e3206fe13ce94d975551e2831d0837d8b9a840c
refs/heads/master
<file_sep><?php namespace BlackFox; class AdminerFiles extends Adminer { public function Execute($PARAMS = [], $REQUEST = []) { $PARAMS['SCRUD'] = 'BlackFox\Files'; parent::Execute($PARAMS, $REQUEST); } }<file_sep><?php /** @var \BlackFox\LanguageSwitcher $this */ ?> <?php /** @var array $RESULT */ ?> <div class="dropdown d-inline-block"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="material-icons">language</span> </button> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton"> <? foreach ($RESULT['LANGUAGES'] as $code => $display): ?> <a class="dropdown-item" href="?<?= http_build_query(array_merge($_GET, ['SwitchLanguage' => $code])) ?>" ><?= $display ?></a> <? endforeach; ?> </div> </div><file_sep><?php return [ 'Action' => [ '3d_rotation', 'accessibility', 'accessibility_new', 'accessible', 'accessible_forward', 'account_balance', 'account_balance_wallet', 'account_box', 'account_circle', 'add_shopping_cart', 'add_task', 'add_to_drive', 'addchart', 'admin_panel_settings', 'alarm', 'alarm_add', 'alarm_off', 'alarm_on', 'all_inbox', 'all_out', 'analytics', 'anchor', 'android', 'announcement', 'api', 'app_blocking', 'arrow_circle_down', 'arrow_circle_up', 'arrow_right_alt', 'article', 'aspect_ratio', 'assessment', 'assignment', 'assignment_ind', 'assignment_late', 'assignment_return', 'assignment_returned', 'assignment_turned_in', 'autorenew', 'backup', 'backup_table', 'batch_prediction', 'book', 'book_online', 'bookmark', 'bookmark_add', 'bookmark_added', 'bookmark_border', 'bookmark_remove', 'bookmarks', 'bug_report', 'build', 'build_circle', 'cached', 'calendar_today', 'calendar_view_day', 'calendar_view_month', 'calendar_view_week', 'camera_enhance', 'cancel_schedule_send', 'card_giftcard', 'card_membership', 'card_travel', 'change_history', 'check_circle', 'check_circle_outline', 'chrome_reader_mode', 'circle_notifications', 'class', 'close_fullscreen', 'code', 'code_off', 'comment_bank', 'commute', 'compare_arrows', 'compress', 'contact_page', 'contact_support', 'contactless', 'copyright', 'credit_card', 'credit_card_off', 'dangerous', 'dashboard', 'dashboard_customize', 'date_range', 'delete', 'delete_forever', 'delete_outline', 'description', 'disabled_by_default', 'dns', 'done', 'done_all', 'done_outline', 'donut_large', 'donut_small', 'drag_indicator', 'dynamic_form', 'eco', 'edit_off', 'eject', 'euro_symbol', 'event', 'event_seat', 'exit_to_app', 'expand', 'explore', 'explore_off', 'extension', 'extension_off', 'face', 'fact_check', 'favorite', 'favorite_border', 'feedback', 'file_present', 'filter_alt', 'find_in_page', 'find_replace', 'fingerprint', 'fit_screen', 'flaky', 'flight_land', 'flight_takeoff', 'flip_to_back', 'flip_to_front', 'flutter_dash', 'g_translate', 'gavel', 'get_app', 'gif', 'grade', 'grading', 'group_work', 'help', 'help_center', 'help_outline', 'hide_source', 'highlight_alt', 'highlight_off', 'history', 'history_toggle_off', 'home', 'horizontal_split', 'hourglass_disabled', 'hourglass_empty', 'hourglass_full', 'http', 'https', 'important_devices', 'info', 'input', 'integration_instructions', 'invert_colors', 'label', 'label_important', 'label_off', 'language', 'launch', 'leaderboard', 'lightbulb', 'line_style', 'line_weight', 'list', 'lock', 'lock_clock', 'lock_open', 'login', 'logout', 'loyalty', 'manage_accounts', 'mark_as_unread', 'markunread_mailbox', 'maximize', 'mediation', 'minimize', 'model_training', 'next_plan', 'nightlight_round', 'no_accounts', 'not_accessible', 'not_started', 'note_add', 'offline_bolt', 'offline_pin', 'online_prediction', 'opacity', 'open_in_browser', 'open_in_full', 'open_in_new', 'open_in_new_off', 'open_with', 'outbound', 'outbox', 'outlet', 'pageview', 'paid', 'pan_tool', 'payment', 'pending', 'pending_actions', 'perm_camera_mic', 'perm_contact_calendar', 'perm_data_setting', 'perm_device_information', 'perm_identity', 'perm_media', 'perm_phone_msg', 'perm_scan_wifi', 'pets', 'picture_in_picture', 'picture_in_picture_alt', 'plagiarism', 'play_for_work', 'polymer', 'power_settings_new', 'pregnant_woman', 'preview', 'print', 'privacy_tip', 'production_quantity_limits', 'published_with_changes', 'query_builder', 'question_answer', 'quickreply', 'receipt', 'record_voice_over', 'redeem', 'remove_done', 'remove_shopping_cart', 'reorder', 'report_problem', 'request_page', 'restore', 'restore_from_trash', 'restore_page', 'room', 'rounded_corner', 'rowing', 'rule', 'saved_search', 'savings', 'schedule', 'schedule_send', 'search', 'search_off', 'segment', 'send_and_archive', 'sensors', 'sensors_off', 'settings', 'settings_accessibility', 'settings_applications', 'settings_backup_restore', 'settings_bluetooth', 'settings_brightness', 'settings_cell', 'settings_ethernet', 'settings_input_antenna', 'settings_input_component', 'settings_input_composite', 'settings_input_hdmi', 'settings_input_svideo', 'settings_overscan', 'settings_phone', 'settings_power', 'settings_remote', 'settings_voice', 'shop', 'shop_2', 'shop_two', 'shopping_bag', 'shopping_basket', 'shopping_cart', 'smart_button', 'source', 'speaker_notes', 'speaker_notes_off', 'spellcheck', 'star_rate', 'stars', 'sticky_note_2', 'store', 'subject', 'subtitles_off', 'supervised_user_circle', 'supervisor_account', 'support', 'swap_horiz', 'swap_horizontal_circle', 'swap_vert', 'swap_vertical_circle', 'swipe', 'sync_alt', 'system_update_alt', 'tab', 'tab_unselected', 'table_view', 'task_alt', 'text_rotate_up', 'text_rotate_vertical', 'text_rotation_angledown', 'text_rotation_angleup', 'text_rotation_down', 'text_rotation_none', 'theaters', 'thumb_down', 'thumb_down_off_alt', 'thumb_up', 'thumb_up_off_alt', 'thumbs_up_down', 'timeline', 'toc', 'today', 'toll', 'touch_app', 'tour', 'track_changes', 'translate', 'trending_down', 'trending_flat', 'trending_up', 'try', 'turned_in', 'turned_in_not', 'unpublished', 'update', 'update_disabled', 'upgrade', 'verified', 'verified_user', 'vertical_split', 'view_agenda', 'view_array', 'view_carousel', 'view_column', 'view_day', 'view_headline', 'view_in_ar', 'view_list', 'view_module', 'view_quilt', 'view_sidebar', 'view_stream', 'view_week', 'visibility', 'visibility_off', 'voice_over_off', 'watch_later', 'wifi_protected_setup', 'work', 'work_off', 'work_outline', 'wysiwyg', 'youtube_searched_for', 'zoom_in', 'zoom_out', ], 'Alert' => [ 'add_alert', 'auto_delete', 'error', 'error_outline', 'notification_important', 'warning', 'warning_amber', ], 'Av' => [ '10k', '1k', '1k_plus', '2k', '2k_plus', '3k', '3k_plus', '4k', '4k_plus', '5g', '5k', '5k_plus', '6k', '6k_plus', '7k', '7k_plus', '8k', '8k_plus', '9k', '9k_plus', 'add_to_queue', 'airplay', 'album', 'art_track', 'av_timer', 'branding_watermark', 'call_to_action', 'closed_caption', 'closed_caption_disabled', 'closed_caption_off', 'control_camera', 'equalizer', 'explicit', 'fast_forward', 'fast_rewind', 'featured_play_list', 'featured_video', 'fiber_dvr', 'fiber_manual_record', 'fiber_new', 'fiber_pin', 'fiber_smart_record', 'forward_10', 'forward_30', 'forward_5', 'games', 'hd', 'hearing', 'hearing_disabled', 'high_quality', 'library_add', 'library_add_check', 'library_books', 'library_music', 'loop', 'mic', 'mic_none', 'mic_off', 'missed_video_call', 'movie', 'music_video', 'new_releases', 'not_interested', 'note', 'pause', 'pause_circle', 'pause_circle_filled', 'pause_circle_outline', 'play_arrow', 'play_circle', 'play_circle_filled', 'play_circle_outline', 'play_disabled', 'playlist_add', 'playlist_add_check', 'playlist_play', 'queue', 'queue_music', 'queue_play_next', 'radio', 'recent_actors', 'remove_from_queue', 'repeat', 'repeat_on', 'repeat_one', 'repeat_one_on', 'replay', 'replay_10', 'replay_30', 'replay_5', 'replay_circle_filled', 'sd', 'shuffle', 'shuffle_on', 'skip_next', 'skip_previous', 'slow_motion_video', 'snooze', 'sort_by_alpha', 'speed', 'stop', 'stop_circle', 'subscriptions', 'subtitles', 'surround_sound', 'video_call', 'video_label', 'video_library', 'video_settings', 'videocam', 'videocam_off', 'volume_down', 'volume_mute', 'volume_off', 'volume_up', 'web', 'web_asset', 'web_asset_off', ], 'Communication' => [ '3p', 'add_ic_call', 'alternate_email', 'app_registration', 'business', 'call', 'call_end', 'call_made', 'call_merge', 'call_missed', 'call_missed_outgoing', 'call_received', 'call_split', 'cancel_presentation', 'cell_wifi', 'chat', 'chat_bubble', 'chat_bubble_outline', 'clear_all', 'comment', 'contact_mail', 'contact_phone', 'contacts', 'desktop_access_disabled', 'dialer_sip', 'dialpad', 'domain_disabled', 'domain_verification', 'duo', 'email', 'forum', 'forward_to_inbox', 'hourglass_bottom', 'hourglass_top', 'import_contacts', 'import_export', 'invert_colors_off', 'list_alt', 'live_help', 'location_off', 'location_on', 'mail_outline', 'mark_chat_read', 'mark_chat_unread', 'mark_email_read', 'mark_email_unread', 'message', 'mobile_screen_share', 'more_time', 'nat', 'no_sim', 'pause_presentation', 'person_add_disabled', 'person_search', 'phone', 'phone_disabled', 'phone_enabled', 'phonelink_erase', 'phonelink_lock', 'phonelink_ring', 'phonelink_setup', 'portable_wifi_off', 'present_to_all', 'print_disabled', 'qr_code', 'qr_code_2', 'qr_code_scanner', 'read_more', 'ring_volume', 'rss_feed', 'rtt', 'screen_share', 'sentiment_satisfied_alt', 'sip', 'speaker_phone', 'stay_current_landscape', 'stay_current_portrait', 'stay_primary_landscape', 'stay_primary_portrait', 'stop_screen_share', 'swap_calls', 'textsms', 'unsubscribe', 'voicemail', 'vpn_key', 'wifi_calling', ], 'Content' => [ 'add', 'add_box', 'add_circle', 'add_circle_outline', 'add_link', 'archive', 'attribution', 'backspace', 'ballot', 'biotech', 'block', 'bolt', 'calculate', 'change_circle', 'clear', 'content_copy', 'content_cut', 'content_paste', 'content_paste_off', 'copy_all', 'create', 'delete_sweep', 'drafts', 'dynamic_feed', 'file_copy', 'filter_list', 'flag', 'font_download', 'font_download_off', 'forward', 'gesture', 'how_to_reg', 'how_to_vote', 'inbox', 'insights', 'inventory', 'inventory_2', 'link', 'link_off', 'low_priority', 'mail', 'markunread', 'move_to_inbox', 'next_week', 'outlined_flag', 'policy', 'push_pin', 'redo', 'remove', 'remove_circle', 'remove_circle_outline', 'reply', 'reply_all', 'report', 'report_gmailerrorred', 'report_off', 'save', 'save_alt', 'select_all', 'send', 'shield', 'sort', 'square_foot', 'stacked_bar_chart', 'stream', 'tag', 'text_format', 'unarchive', 'undo', 'upcoming', 'waves', 'weekend', 'where_to_vote', ], 'Device' => [ '1x_mobiledata', '30fps', '3g_mobiledata', '4g_mobiledata', '4g_plus_mobiledata', '60fps', 'access_alarm', 'access_alarms', 'access_time', 'access_time_filled', 'ad_units', 'add_alarm', 'add_to_home_screen', 'air', 'airplane_ticket', 'airplanemode_active', 'airplanemode_inactive', 'aod', 'battery_alert', 'battery_charging_full', 'battery_full', 'battery_saver', 'battery_std', 'battery_unknown', 'bloodtype', 'bluetooth', 'bluetooth_connected', 'bluetooth_disabled', 'bluetooth_drive', 'bluetooth_searching', 'brightness_auto', 'brightness_high', 'brightness_low', 'brightness_medium', 'cable', 'cameraswitch', 'credit_score', 'dark_mode', 'data_saver_off', 'data_saver_on', 'data_usage', 'developer_mode', 'device_thermostat', 'devices', 'do_not_disturb_on_total_silence', 'dvr', 'e_mobiledata', 'edgesensor_high', 'edgesensor_low', 'flashlight_off', 'flashlight_on', 'flourescent', 'fmd_bad', 'fmd_good', 'g_mobiledata', 'gpp_bad', 'gpp_good', 'gpp_maybe', 'gps_fixed', 'gps_not_fixed', 'gps_off', 'graphic_eq', 'grid_3x3', 'grid_4x4', 'grid_goldenratio', 'h_mobiledata', 'h_plus_mobiledata', 'hdr_auto', 'hdr_auto_select', 'hdr_off_select', 'hdr_on_select', 'lens_blur', 'light_mode', 'location_disabled', 'location_searching', 'lte_mobiledata', 'lte_plus_mobiledata', 'media_bluetooth_off', 'media_bluetooth_on', 'medication', 'mobile_friendly', 'mobile_off', 'mobiledata_off', 'mode_night', 'mode_standby', 'monitor_weight', 'nearby_error', 'nearby_off', 'network_cell', 'network_wifi', 'nfc', 'nightlight', 'note_alt', 'password', 'pattern', 'pin', 'play_lesson', 'price_change', 'price_check', 'quiz', 'r_mobiledata', 'radar', 'remember_me', 'reset_tv', 'restart_alt', 'reviews', 'rsvp', 'screen_lock_landscape', 'screen_lock_portrait', 'screen_lock_rotation', 'screen_rotation', 'screen_search_desktop', 'screenshot', 'sd_storage', 'security_update', 'security_update_good', 'security_update_warning', 'sell', 'send_to_mobile', 'settings_suggest', 'settings_system_daydream', 'share_location', 'shortcut', 'signal_cellular_0_bar', 'signal_cellular_4_bar', 'signal_cellular_alt', 'signal_cellular_connected_no_internet_0_bar', 'signal_cellular_connected_no_internet_4_bar', 'signal_cellular_no_sim', 'signal_cellular_nodata', 'signal_cellular_null', 'signal_cellular_off', 'signal_wifi_0_bar', 'signal_wifi_4_bar', 'signal_wifi_4_bar_lock', 'signal_wifi_bad', 'signal_wifi_connected_no_internet_4', 'signal_wifi_off', 'signal_wifi_statusbar_4_bar', 'signal_wifi_statusbar_connected_no_internet_4', 'signal_wifi_statusbar_null', 'sim_card_download', 'splitscreen', 'sports_score', 'storage', 'storm', 'summarize', 'system_security_update', 'system_security_update_good', 'system_security_update_warning', 'task', 'thermostat', 'timer_10_select', 'timer_3_select', 'tungsten', 'usb', 'usb_off', 'wallpaper', 'water', 'widgets', 'wifi_calling_3', 'wifi_lock', 'wifi_tethering', 'wifi_tethering_error_rounded', 'wifi_tethering_off', ], 'Editor' => [ 'add_chart', 'add_comment', 'align_horizontal_center', 'align_horizontal_left', 'align_horizontal_right', 'align_vertical_bottom', 'align_vertical_center', 'align_vertical_top', 'attach_file', 'attach_money', 'auto_graph', 'bar_chart', 'border_all', 'border_bottom', 'border_clear', 'border_color', 'border_horizontal', 'border_inner', 'border_left', 'border_outer', 'border_right', 'border_style', 'border_top', 'border_vertical', 'bubble_chart', 'drag_handle', 'format_align_center', 'format_align_justify', 'format_align_left', 'format_align_right', 'format_bold', 'format_clear', 'format_color_fill', 'format_color_reset', 'format_color_text', 'format_indent_decrease', 'format_indent_increase', 'format_italic', 'format_line_spacing', 'format_list_bulleted', 'format_list_numbered', 'format_list_numbered_rtl', 'format_paint', 'format_quote', 'format_shapes', 'format_size', 'format_strikethrough', 'format_textdirection_l_to_r', 'format_textdirection_r_to_l', 'format_underlined', 'functions', 'height', 'highlight', 'horizontal_distribute', 'horizontal_rule', 'insert_chart', 'insert_chart_outlined', 'insert_comment', 'insert_drive_file', 'insert_emoticon', 'insert_invitation', 'insert_link', 'insert_photo', 'linear_scale', 'margin', 'merge_type', 'mode', 'mode_comment', 'mode_edit', 'mode_edit_outline', 'monetization_on', 'money_off', 'money_off_csred', 'multiline_chart', 'notes', 'padding', 'pie_chart', 'pie_chart_outline', 'post_add', 'publish', 'query_stats', 'scatter_plot', 'schema', 'score', 'short_text', 'show_chart', 'space_bar', 'stacked_line_chart', 'strikethrough_s', 'subscript', 'superscript', 'table_chart', 'table_rows', 'text_fields', 'title', 'vertical_align_bottom', 'vertical_align_center', 'vertical_align_top', 'vertical_distribute', 'wrap_text', ], 'File' => [ 'approval', 'attach_email', 'attachment', 'cloud', 'cloud_circle', 'cloud_done', 'cloud_download', 'cloud_off', 'cloud_queue', 'cloud_upload', 'create_new_folder', 'download', 'download_done', 'download_for_offline', 'downloading', 'drive_file_move', 'drive_file_rename_outline', 'drive_folder_upload', 'file_download', 'file_download_done', 'file_download_off', 'file_upload', 'folder', 'folder_open', 'folder_shared', 'grid_view', 'request_quote', 'rule_folder', 'snippet_folder', 'text_snippet', 'topic', 'upload', 'upload_file', 'workspaces', ], 'Hardware' => [ 'browser_not_supported', 'cast', 'cast_connected', 'cast_for_education', 'computer', 'connected_tv', 'desktop_mac', 'desktop_windows', 'developer_board', 'developer_board_off', 'device_hub', 'device_unknown', 'devices_other', 'dock', 'earbuds', 'earbuds_battery', 'gamepad', 'headphones', 'headphones_battery', 'headset', 'headset_mic', 'headset_off', 'home_max', 'home_mini', 'keyboard', 'keyboard_alt', 'keyboard_arrow_down', 'keyboard_arrow_left', 'keyboard_arrow_right', 'keyboard_arrow_up', 'keyboard_backspace', 'keyboard_capslock', 'keyboard_hide', 'keyboard_return', 'keyboard_tab', 'keyboard_voice', 'laptop', 'laptop_chromebook', 'laptop_mac', 'laptop_windows', 'memory', 'monitor', 'mouse', 'phone_android', 'phone_iphone', 'phonelink', 'phonelink_off', 'point_of_sale', 'power_input', 'router', 'scanner', 'security', 'sim_card', 'smart_display', 'smart_screen', 'smart_toy', 'smartphone', 'speaker', 'speaker_group', 'tablet', 'tablet_android', 'tablet_mac', 'toys', 'tv', 'videogame_asset', 'videogame_asset_off', 'watch', ], 'Home' => [ 'sensor_door', 'sensor_window', ], 'Image' => [ '10mp', '11mp', '12mp', '13mp', '14mp', '15mp', '16mp', '17mp', '18mp', '19mp', '20mp', '21mp', '22mp', '23mp', '24mp', '2mp', '30fps_select', '3mp', '4mp', '5mp', '60fps_select', '6mp', '7mp', '8mp', '9mp', 'add_a_photo', 'add_photo_alternate', 'add_to_photos', 'adjust', 'animation', 'assistant', 'assistant_photo', 'audiotrack', 'auto_awesome', 'auto_awesome_mosaic', 'auto_awesome_motion', 'auto_fix_high', 'auto_fix_normal', 'auto_fix_off', 'auto_stories', 'autofps_select', 'bedtime', 'blur_circular', 'blur_linear', 'blur_off', 'blur_on', 'brightness_1', 'brightness_2', 'brightness_3', 'brightness_4', 'brightness_5', 'brightness_6', 'brightness_7', 'broken_image', 'brush', 'burst_mode', 'camera', 'camera_alt', 'camera_front', 'camera_rear', 'camera_roll', 'cases', 'center_focus_strong', 'center_focus_weak', 'circle', 'collections', 'collections_bookmark', 'color_lens', 'colorize', 'compare', 'control_point', 'control_point_duplicate', 'crop', 'crop_16_9', 'crop_3_2', 'crop_5_4', 'crop_7_5', 'crop_din', 'crop_free', 'crop_landscape', 'crop_original', 'crop_portrait', 'crop_rotate', 'crop_square', 'dehaze', 'details', 'dirty_lens', 'edit', 'euro', 'exposure', 'exposure_neg_1', 'exposure_neg_2', 'exposure_plus_1', 'exposure_plus_2', 'exposure_zero', 'face_retouching_natural', 'face_retouching_off', 'filter', 'filter_1', 'filter_2', 'filter_3', 'filter_4', 'filter_5', 'filter_6', 'filter_7', 'filter_8', 'filter_9', 'filter_9_plus', 'filter_b_and_w', 'filter_center_focus', 'filter_drama', 'filter_frames', 'filter_hdr', 'filter_none', 'filter_tilt_shift', 'filter_vintage', 'flare', 'flash_auto', 'flash_off', 'flash_on', 'flip', 'flip_camera_android', 'flip_camera_ios', 'gradient', 'grain', 'grid_off', 'grid_on', 'hdr_enhanced_select', 'hdr_off', 'hdr_on', 'hdr_plus', 'hdr_strong', 'hdr_weak', 'healing', 'hevc', 'hide_image', 'image', 'image_aspect_ratio', 'image_not_supported', 'image_search', 'iso', 'landscape', 'leak_add', 'leak_remove', 'lens', 'linked_camera', 'looks', 'looks_3', 'looks_4', 'looks_5', 'looks_6', 'looks_one', 'looks_two', 'loupe', 'mic_external_off', 'mic_external_on', 'monochrome_photos', 'motion_photos_auto', 'motion_photos_off', 'motion_photos_on', 'motion_photos_pause', 'motion_photos_paused', 'movie_creation', 'movie_filter', 'mp', 'music_note', 'music_off', 'nature', 'nature_people', 'navigate_before', 'navigate_next', 'palette', 'panorama', 'panorama_fish_eye', 'panorama_horizontal', 'panorama_horizontal_select', 'panorama_photosphere', 'panorama_photosphere_select', 'panorama_vertical', 'panorama_vertical_select', 'panorama_wide_angle', 'panorama_wide_angle_select', 'photo', 'photo_album', 'photo_camera', 'photo_camera_back', 'photo_camera_front', 'photo_filter', 'photo_library', 'photo_size_select_actual', 'photo_size_select_large', 'photo_size_select_small', 'picture_as_pdf', 'portrait', 'raw_off', 'raw_on', 'receipt_long', 'remove_red_eye', 'rotate_90_degrees_ccw', 'rotate_left', 'rotate_right', 'shutter_speed', 'slideshow', 'straighten', 'style', 'switch_camera', 'switch_video', 'tag_faces', 'texture', 'thermostat_auto', 'timelapse', 'timer', 'timer_10', 'timer_3', 'timer_off', 'tonality', 'transform', 'tune', 'video_camera_back', 'video_camera_front', 'video_stable', 'view_comfy', 'view_compact', 'vignette', 'vrpano', 'wb_auto', 'wb_cloudy', 'wb_incandescent', 'wb_iridescent', 'wb_shade', 'wb_sunny', 'wb_twilight', ], 'Maps' => [ '360', 'add_business', 'add_location', 'add_location_alt', 'add_road', 'agriculture', 'alt_route', 'atm', 'attractions', 'badge', 'bakery_dining', 'beenhere', 'bike_scooter', 'breakfast_dining', 'brunch_dining', 'bus_alert', 'car_rental', 'car_repair', 'category', 'celebration', 'cleaning_services', 'compass_calibration', 'delivery_dining', 'departure_board', 'design_services', 'dinner_dining', 'directions', 'directions_bike', 'directions_boat', 'directions_boat_filled', 'directions_bus', 'directions_bus_filled', 'directions_car', 'directions_car_filled', 'directions_railway', 'directions_railway_filled', 'directions_run', 'directions_subway', 'directions_subway_filled', 'directions_transit', 'directions_transit_filled', 'directions_walk', 'dry_cleaning', 'edit_attributes', 'edit_location', 'edit_location_alt', 'edit_road', 'electric_bike', 'electric_car', 'electric_moped', 'electric_rickshaw', 'electric_scooter', 'electrical_services', 'ev_station', 'fastfood', 'festival', 'flight', 'hail', 'handyman', 'hardware', 'home_repair_service', 'hotel', 'hvac', 'icecream', 'layers', 'layers_clear', 'liquor', 'local_activity', 'local_airport', 'local_atm', 'local_bar', 'local_cafe', 'local_car_wash', 'local_convenience_store', 'local_dining', 'local_drink', 'local_fire_department', 'local_florist', 'local_gas_station', 'local_grocery_store', 'local_hospital', 'local_hotel', 'local_laundry_service', 'local_library', 'local_mall', 'local_movies', 'local_offer', 'local_parking', 'local_pharmacy', 'local_phone', 'local_pizza', 'local_play', 'local_police', 'local_post_office', 'local_printshop', 'local_see', 'local_shipping', 'local_taxi', 'lunch_dining', 'map', 'maps_ugc', 'medical_services', 'menu_book', 'miscellaneous_services', 'money', 'moped', 'moving', 'multiple_stop', 'museum', 'my_location', 'navigation', 'near_me', 'near_me_disabled', 'nightlife', 'no_meals', 'no_transfer', 'not_listed_location', 'park', 'pedal_bike', 'person_pin', 'person_pin_circle', 'pest_control', 'pest_control_rodent', 'pin_drop', 'place', 'plumbing', 'railway_alert', 'ramen_dining', 'rate_review', 'restaurant', 'restaurant_menu', 'run_circle', 'sailing', 'satellite', 'set_meal', 'snowmobile', 'store_mall_directory', 'streetview', 'subway', 'takeout_dining', 'taxi_alert', 'terrain', 'theater_comedy', 'traffic', 'train', 'tram', 'transfer_within_a_station', 'transit_enterexit', 'trip_origin', 'two_wheeler', 'volunteer_activism', 'wine_bar', 'wrong_location', 'zoom_out_map', ], 'Navigation' => [ 'app_settings_alt', 'apps', 'arrow_back', 'arrow_back_ios', 'arrow_back_ios_new', 'arrow_downward', 'arrow_drop_down', 'arrow_drop_down_circle', 'arrow_drop_up', 'arrow_forward', 'arrow_forward_ios', 'arrow_left', 'arrow_right', 'arrow_upward', 'assistant_direction', 'campaign', 'cancel', 'check', 'chevron_left', 'chevron_right', 'close', 'double_arrow', 'east', 'expand_less', 'expand_more', 'first_page', 'fullscreen', 'fullscreen_exit', 'home_work', 'last_page', 'legend_toggle', 'maps_home_work', 'menu', 'menu_open', 'more_horiz', 'more_vert', 'north', 'north_east', 'north_west', 'offline_share', 'payments', 'pivot_table_chart', 'refresh', 'south', 'south_east', 'south_west', 'subdirectory_arrow_left', 'subdirectory_arrow_right', 'switch_left', 'switch_right', 'unfold_less', 'unfold_more', 'waterfall_chart', 'west', ], 'Notification' => [ 'account_tree', 'adb', 'airline_seat_flat', 'airline_seat_flat_angled', 'airline_seat_individual_suite', 'airline_seat_legroom_extra', 'airline_seat_legroom_normal', 'airline_seat_legroom_reduced', 'airline_seat_recline_extra', 'airline_seat_recline_normal', 'bluetooth_audio', 'confirmation_number', 'directions_off', 'disc_full', 'do_disturb', 'do_disturb_alt', 'do_disturb_off', 'do_disturb_on', 'do_not_disturb', 'do_not_disturb_alt', 'do_not_disturb_off', 'do_not_disturb_on', 'drive_eta', 'enhanced_encryption', 'event_available', 'event_busy', 'event_note', 'folder_special', 'imagesearch_roller', 'live_tv', 'mms', 'more', 'network_check', 'network_locked', 'no_encryption', 'no_encryption_gmailerrorred', 'ondemand_video', 'personal_video', 'phone_bluetooth_speaker', 'phone_callback', 'phone_forwarded', 'phone_in_talk', 'phone_locked', 'phone_missed', 'phone_paused', 'power', 'power_off', 'priority_high', 'running_with_errors', 'sd_card', 'sd_card_alert', 'sim_card_alert', 'sms', 'sms_failed', 'support_agent', 'sync', 'sync_disabled', 'sync_problem', 'system_update', 'tap_and_play', 'time_to_leave', 'tv_off', 'vibration', 'voice_chat', 'vpn_lock', 'wc', 'wifi', 'wifi_off', ], 'Places' => [ 'ac_unit', 'airport_shuttle', 'all_inclusive', 'apartment', 'baby_changing_station', 'backpack', 'balcony', 'bathtub', 'beach_access', 'bento', 'bungalow', 'business_center', 'cabin', 'carpenter', 'casino', 'chalet', 'charging_station', 'checkroom', 'child_care', 'child_friendly', 'corporate_fare', 'cottage', 'countertops', 'crib', 'do_not_step', 'do_not_touch', 'dry', 'elevator', 'escalator', 'escalator_warning', 'family_restroom', 'fence', 'fire_extinguisher', 'fitness_center', 'food_bank', 'foundation', 'free_breakfast', 'gite', 'golf_course', 'grass', 'holiday_village', 'hot_tub', 'house', 'house_siding', 'houseboat', 'iron', 'kitchen', 'meeting_room', 'microwave', 'night_shelter', 'no_backpack', 'no_cell', 'no_drinks', 'no_flash', 'no_food', 'no_meeting_room', 'no_photography', 'no_stroller', 'other_houses', 'pool', 'rice_bowl', 'roofing', 'room_preferences', 'room_service', 'rv_hookup', 'smoke_free', 'smoking_rooms', 'soap', 'spa', 'sports_bar', 'stairs', 'storefront', 'stroller', 'tapas', 'tty', 'umbrella', 'villa', 'wash', 'water_damage', 'wheelchair_pickup', ], 'Search' => [ 'bathroom', 'bed', 'bedroom_baby', 'bedroom_child', 'bedroom_parent', 'blender', 'camera_indoor', 'camera_outdoor', 'chair', 'chair_alt', 'coffee', 'coffee_maker', 'dining', 'door_back', 'door_front', 'door_sliding', 'doorbell', 'feed', 'flatware', 'garage', 'light', 'living', 'manage_search', 'podcasts', 'shower', 'window', 'yard', ], 'Social' => [ '6_ft_apart', 'add_moderator', 'add_reaction', 'architecture', 'cake', 'catching_pokemon', 'clean_hands', 'connect_without_contact', 'construction', 'coronavirus', 'deck', 'domain', 'downhill_skiing', 'edit_notifications', 'elderly', 'emoji_emotions', 'emoji_events', 'emoji_flags', 'emoji_food_beverage', 'emoji_nature', 'emoji_objects', 'emoji_people', 'emoji_symbols', 'emoji_transportation', 'engineering', 'facebook', 'female', 'fireplace', 'follow_the_signs', 'group', 'group_add', 'groups', 'health_and_safety', 'hiking', 'history_edu', 'ice_skating', 'ios_share', 'kayaking', 'king_bed', 'kitesurfing', 'location_city', 'luggage', 'male', 'masks', 'military_tech', 'mood', 'mood_bad', 'nights_stay', 'no_luggage', 'nordic_walking', 'notification_add', 'notifications', 'notifications_active', 'notifications_none', 'notifications_off', 'notifications_paused', 'outdoor_grill', 'pages', 'paragliding', 'party_mode', 'people', 'people_alt', 'people_outline', 'person', 'person_add', 'person_add_alt', 'person_add_alt_1', 'person_off', 'person_outline', 'person_remove', 'person_remove_alt_1', 'piano', 'piano_off', 'plus_one', 'poll', 'precision_manufacturing', 'psychology', 'public', 'public_off', 'recommend', 'reduce_capacity', 'remove_moderator', 'safety_divider', 'sanitizer', 'school', 'science', 'self_improvement', 'sentiment_dissatisfied', 'sentiment_neutral', 'sentiment_satisfied', 'sentiment_very_dissatisfied', 'sentiment_very_satisfied', 'share', 'sick', 'single_bed', 'skateboarding', 'sledding', 'snowboarding', 'snowshoeing', 'social_distance', 'sports', 'sports_baseball', 'sports_basketball', 'sports_cricket', 'sports_esports', 'sports_football', 'sports_golf', 'sports_handball', 'sports_hockey', 'sports_kabaddi', 'sports_mma', 'sports_motorsports', 'sports_rugby', 'sports_soccer', 'sports_tennis', 'sports_volleyball', 'surfing', 'switch_account', 'thumb_down_alt', 'thumb_up_alt', 'transgender', 'travel_explore', 'whatshot', ], 'Toggle' => [ 'check_box', 'check_box_outline_blank', 'indeterminate_check_box', 'radio_button_checked', 'radio_button_unchecked', 'star', 'star_border', 'star_border_purple500', 'star_half', 'star_outline', 'star_purple500', 'toggle_off', 'toggle_on', ], ]; <file_sep><?php namespace BlackFox; class ExceptionElementNotFound extends Exception { }<file_sep><?php namespace BlackFox; /** * Class CacheDriverRedis * @package BlackFox */ class CacheRedis extends Cache { private $example_config = [ 'cache' => [ 'hosts' => [[ 'host' => '127.0.0.1', 'port' => 6379, 'timeout' => 1, ]], ], ]; /**@var \Redis $Redis */ private $Redis; public function __construct(array $params = []) { parent::__construct($params); $this->Redis = new \Redis(); foreach ($params['hosts'] as $host) { @$result = $this->Redis->connect( $host['host'], $host['port'], $host['timeout'], $host['retry_interval'] ); if (!$result) { throw new ExceptionCache("Can't connect to Redis server {$host['host']}:{$host['port']}"); } } if (!empty($params['password'])) { $this->Redis->auth($params['password']); } if (!empty($params['dbindex'])) { $this->Redis->select($params['dbindex']); } } public function Get($key) { if (empty($key)) { throw new ExceptionCache("Empty key passed"); } $keys = is_array($key) ? $key : [$key]; $answer = []; foreach ($keys as $key_i) { $answer[$key_i] = $this->Redis->get("val|{$key_i}"); if ($answer[$key_i] === false) { throw new ExceptionCache("Value for key '{$key_i}' not found"); } $answer[$key_i] = unserialize($answer[$key_i]); } return is_array($key) ? $answer : reset($answer); } public function Put(string $key, $value, int $ttl = null, array $tags = []) { $params = (is_null($ttl)) ? [] : ['nx', 'ex' => $ttl]; $result = $this->Redis->set("val|{$key}", serialize($value), $params); if ($result === false) { throw new ExceptionCache("Key exist: '{$key}'"); } if (!empty($tags)) { foreach ($tags as $tag) { $this->Redis->sAdd("key|{$key}", $tag); $this->Redis->sAdd("tag|{$tag}", $key); } } } public function Delete(string $key) { $this->Redis->del("val|{$key}"); if ($this->Redis->exists("key|{$key}")) { $tags = $this->Redis->sMembers("key|{$key}"); $this->Redis->del("key|{$key}"); foreach ($tags as $tag) { $this->Redis->sRem("tag|{$tag}", $key); } } } public function Strike($tags) { $tags = is_array($tags) ? $tags : [$tags]; foreach ($tags as $tag) { if ($this->Redis->exists("tag|{$tag}")) { $keys = $this->Redis->sMembers("tag|{$tag}"); $this->Redis->del("tag|{$tag}"); foreach ($keys as $key) { $this->Delete($key); } } } } public function Clear() { $this->Redis->flushDB(); } }<file_sep><div class="my-2 buttons"> <a class="btn btn-light float-right" data-toggle="modal" data-target="#section-settings" > <span class="material-icons">settings</span> <?= T([ 'en' => 'Settings', 'ru' => 'Настройки', ]) ?> </a> <? if (in_array($RESULT['MODE'], ['SECTION'])): ?> <a class="btn btn-success" href="?NEW&<?= http_build_query($_GET) ?>"> <span class="material-icons">add</span> <?= T([ 'en' => 'Add', 'ru' => 'Создать', ]) ?> </a> <? endif; ?> <div class="clearfix"></div> </div><file_sep><?php namespace BlackFox; class TypeFloat extends Type { public $db_type = 'float'; public function FormatInputValue($value) { return str_replace(',', '.', (float)$value); } public function PrintFormControl($value, $name, $class = 'form-control') { ?> <input type="number" step="any" class="<?= $class ?>" id="<?= $name ?>" name="<?= $name ?>" value="<?= $value ?>" <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> > <? } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { $code = $this->field['CODE']; ?> <div class="row no-gutters"> <div class="col-6"> <input type="number" step="any" class="<?= $class ?>" id="<?= $code ?>" name="<?= $group ?>[><?= $code ?>]" placeholder="<?= T([ 'en' => 'from', 'ru' => 'от', ]) ?>" value="<?= $filter['>' . $code] ?>" > </div> <div class="col-6"> <input type="number" step="any" class="<?= $class ?>" id="<?= $code ?>" name="<?= $group ?>[<<?= $code ?>]" placeholder="<?= T([ 'en' => 'to', 'ru' => 'до', ]) ?>" value="<?= $filter['<' . $code] ?>" > </div> </div> <? } }<file_sep><?php namespace BlackFox; class CaptchaGoogleRecaptchaV2 extends Captcha { public $key; private $secret; public function __construct(Engine $Engine) { $this->key = $Engine->config['google_recaptcha']['key']; $this->secret = $Engine->config['google_recaptcha']['secret']; if (empty($this->key) or empty($this->secret)) { throw new ExceptionCaptcha(T([ 'en' => 'Specify config keys: google_recaptcha->key, google_recaptcha->secret', 'ru' => 'Укажите ключи в конфигурации: google_recaptcha->key, google_recaptcha->secret', ])); } $Engine->AddHeaderScript('https://www.google.com/recaptcha/api.js'); } public function Show($params = []) { ?> <div class="g-recaptcha <?= $params['CSS_CLASS'] ?>" data-sitekey="<?= $this->key ?>"></div> <? } public function Check($response = null, $remoteip = null) { $response = is_null($response) ? $_REQUEST['g-recaptcha-response'] : $response; $context = stream_context_create(['http' => [ 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query([ 'secret' => $this->secret, 'response' => $response, 'remoteip' => $remoteip ?: $_SERVER['REMOTE_ADDR'], ]), ]]); $result = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context); $result = json_decode($result, true); return $result['success']; } }<file_sep><?php /** @var \BlackFox\Unit $this */ ?> <?php /** @var array $RESULT */ ?> <ul class="menu"> <? foreach ($RESULT as $category): ?> <? BuildDefaultMenuRecursive($category); ?> <? endforeach; ?> </ul> <? function BuildDefaultMenuRecursive($item, $level = 1) { ?> <li data-menu-item=""> <div data-menu-item-body="" class="item level-<?= $level ?> <?= $item['ACTIVE'] ? 'active' : '' ?> <?= $item['CURRENT'] ? 'current' : '' ?>"> <? if ($item['CHILDREN']): ?> <i class="menu-point menu-point-category <?= $item['ACTIVE'] ? 'rotate-90' : 'rotate-0' ?>" data-menu-expander="" data-menu-rotate="" ></i> <? else: ?> <i class="menu-point menu-point-item"></i> <? endif; ?> <? if ($item['LINK'] && !$item['EXPANDER']): ?> <a href="<?= $item['LINK'] ?: '#' ?>"> <?= $item['NAME'] ?> </a> <? else: ?> <span data-menu-expander=""> <?= $item['NAME'] ?> </span> <? endif; ?> </div> <? if ($item['CHILDREN']): ?> <ul data-menu-children="" class="level-<?= $level ?> <?= $item['ACTIVE'] ? '' : 'collapse' ?>"> <? foreach ($item['CHILDREN'] as $child): ?> <? BuildDefaultMenuRecursive($child, $level + 1); ?> <? endforeach; ?> </ul> <? endif; ?> </li> <? } ?><file_sep><?php /** @var \BlackFox\Unit $this */ ?> <?php /** @var array $RESULT */ ?> <? if (!empty($RESULT['BREADCRUMBS'])): ?> <ol class="system breadcrumb"> <? foreach ($RESULT['BREADCRUMBS'] as $breadcrumb): ?> <li class="breadcrumb-item"> <? if ($breadcrumb['LINK']): ?> <a href="<?= $breadcrumb['LINK'] ?>"><?= $breadcrumb['NAME'] ?></a> <? else: ?> <span><?= $breadcrumb['NAME'] ?></span> <? endif; ?> </li> <? endforeach; ?> </ol> <? endif; ?> <file_sep><?php namespace BlackFox; trait Instance { /** * Defines global overrides * * @param array $overrides array of classes to be overridden: * key - string, name of the interface or abstract class or concrete class (which must be overridden); * value - string, name of the final class (with trait Instance); * @throws Exception Wrong override... */ public static function AddOverrides(array $overrides) { foreach ($overrides as $old_class_name => $new_class_name) { if ($old_class_name === $new_class_name) { throw new Exception("Wrong override: '{$old_class_name}' => '{$new_class_name}'"); } Instance::$overrides[$old_class_name] = $new_class_name; } } /** * @var Instance[] $overrides array of classes to be overridden: * key - string, name of the interface or abstract class or concrete class (which should be overridden); * value - string, name of the final class (with trait Instance); */ public static $overrides = null; /** @var Instance[] array of instantiated classes: key - class name, value - Object */ public static $instances = []; /** @var bool if the class has been instanced - in most cases it is required to prohibit a change in its internal state */ public $is_global_instance = false; /** * Returns the global instance of this class * * ```php * Class::I()->Method(); * ``` * * @param array $params * @return static global instance * @throws Exception */ public static function I($params = []) { if (Instance::$overrides === null) { Instance::$overrides = []; $config = Engine::GetConfig(); Instance::AddOverrides($config['overrides'] ?: []); } /** @var Instance|string $class */ $class = get_called_class(); if (Instance::$overrides[$class]) { return Instance::$overrides[$class]::I($params); } if (isset(Instance::$instances[$class])) { if (empty($params)) { return Instance::$instances[$class]; } else { throw new Exception("Can't initiate global instance of class '{$class}': global instance already exist"); } } Instance::$instances[$class] = $class::N($params); Instance::$instances[$class]->is_global_instance = true; return Instance::$instances[$class]; } /** * Creates and returns a new instance of this class, * by filling all __construct parameters with: * - $params * - global instances matching parameter type * * ```php * $Object = Class::N(); * $Object->Method(); * ``` * * @param array $params * @return static local instance * @throws Exception */ public static function N($params = []) { try { $class = get_called_class(); if (Instance::$overrides[$class]) { return Instance::$overrides[$class]::N(); } $ReflectionClass = new \ReflectionClass(get_called_class()); try { $Parameters = $ReflectionClass->getMethod('__construct')->getParameters(); } catch (\ReflectionException $error) { $Parameters = []; } $args = []; foreach ($Parameters as $Parameter) { // $params is set: $args from $params if (array_key_exists($Parameter->getName(), $params)) { $args[$Parameter->getName()] = $params[$Parameter->getName()]; continue; } // $Parameter has no type: $args from default value if (!$Parameter->hasType()) { if ($Parameter->isOptional()) { $args[$Parameter->getName()] = $Parameter->getDefaultValue(); continue; } else { throw new Exception("Can't construct class '{$class}': non-optional parameter '{$Parameter->getName()}' doesn't have a type"); } } // $Parameter has a type $ParameterType = $Parameter->getType(); if ($ParameterType->isBuiltin()) { if ($Parameter->isOptional()) { $args[$Parameter->getName()] = $Parameter->getDefaultValue(); continue; } else { throw new Exception("Can't construct class '{$class}': non-optional parameter '{$Parameter->getName()}' has a builtin type"); } } // $Parameter has a non-builtin type $p_class = $ParameterType->getName(); $traits = (new \ReflectionClass($p_class))->getTraits(); if (isset($traits['BlackFox\Instance'])) { /**@var string|self $p_class */ $args[$p_class] = $p_class::I(); } else { throw new Exception("Can't construct class '{$class}': non-optional parameter '{$Parameter->getName()}' of type '{$p_class}' doesn't have 'BlackFox\Instance' trait"); } } return $ReflectionClass->newInstanceArgs($args); } catch (\ReflectionException $error) { throw new Exception($error->GetMessage()); } } }<file_sep><?php if (!function_exists('debug')) { /** * Базовая глобальная отладка * работает только если в /config.php определен ключ 'debug' => true * не работает, если в реквесте указан ключ 'turn_off_debug' (удобно для финальных AJAX-запросов) * * @param mixed $data переменная для отладки * @param string $title название переменной (не обязательно) * @param string $mode способ отладки (не обязательно): * - print_r - вывод print_r в невидимую textarea, отображается по нажатию клавиш alt + TILDE (по умолчанию) * - var_export - вывод var_export в невидимую textarea, отображается по нажатию клавиш alt + TILDE * - var_dump - вывод var_dump в невидимую textarea, отображается по нажатию клавиш alt + TILDE * - console - выводится в консоль браузера * - log - записывается в файл * - email - отправляется на почту * @param string $target путь отправки: имя файла или почтовый адрес */ function debug($data = [], $title = '', $mode = 'print_r', $target = '/debug.txt') { static $config; if (empty($config)) { $config = require($_SERVER['DOCUMENT_ROOT'] . '/config.php'); } if (!$config['debug']) { return; } if (isset($_REQUEST['turn_off_debug']) || isset($_REQUEST['TURN_OFF_DEBUG'])) { return; } if (in_array($mode, ['print_r', 'var_export', 'var_dump'])) { if ($mode === 'print_r') { $data = print_r($data, true); } elseif ($mode === 'var_export') { $data = var_export($data, true); } elseif ($mode === 'var_dump') { ob_start(); var_dump($data); $data = ob_get_clean(); } echo "<textarea class='debug' data-debug='{$title}' style=' display: none; resize: both; position: relative; z-index: 99999; border: 1px green dashed; width: auto; line-height: 1.5; ' >{$title}=" . htmlspecialchars($data) . "</textarea>"; static $need_js = true; if ($need_js) { $need_js = false; ?> <script> if (!window.engine_debug) { document.addEventListener('keydown', function (event) { // alt + TILDE if (event.altKey && event.keyCode === 192) { var debug = document.querySelectorAll('.debug'); debug.forEach(function (element) { element.style.display = (element.style.display == 'none') ? 'inline-block' : 'none'; }); } }); window.engine_debug = true; } </script> <? } } if ($mode === 'console') { echo "<script>console.log('{$title}', " . json_encode($data, true) . ");</script>"; } if ($mode === 'log') { file_put_contents($_SERVER['DOCUMENT_ROOT'] . $target, "\r\n" . str_repeat('-', 50) . "\r\n" . $title . '=' . print_r($data, true), FILE_APPEND); } if ($mode === 'email') { mail($target, "debug from {$_SERVER['SERVER_NAME']}", $title . '=' . print_r($data, true)); } } }<file_sep><?php namespace BlackFox; class TypeEnum extends Type { public $db_type = 'enum'; public function FormatInputValue($value) { if (!isset($this->field['VALUES'][$value])) { throw new ExceptionType("Unknown enum value '{$value}' for field '{$this->field['NAME']}'"); } return $value; } public function FormatOutputValue($element) { $code = $this->field['CODE']; $element["$code|VALUE"] = $this->field['VALUES'][$element[$code]]; return $element; } public function PrintValue($value) { echo $this->field['VALUES'][$value] ?: ''; } public function PrintFormControl($value, $name, $class = 'form-control') { ?> <select class="<?= $class ?>" id="<?= $name ?>" name="<?= $name ?>" <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> > <? if (!$this->field['NOT_NULL']): ?> <option value=""></option> <? endif; ?> <? foreach ($this->field['VALUES'] as $code => $display): ?> <option value="<?= $code ?>" <?= ((string)$code === (string)$value) ? 'selected' : '' ?> ><?= $display ?></option> <? endforeach; ?> </select> <? } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { $code = $this->field['CODE']; ?> <input type="hidden" name="<?= $group ?>[<?= $code ?>]" value="" /> <? foreach ($this->field['VALUES'] as $value => $display): ?> <label class="enum"> <input type="checkbox" class="<?= $class ?>" name="<?= $group ?>[<?= $code ?>][]" value="<?= $value ?>" <?= (in_array($value, $filter[$code] ?: [])) ? 'checked' : '' ?> <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> > <span class="dashed"><?= $display ?></span> </label> <? endforeach; ?> <? } }<file_sep><?php /** @var \BlackFox\Adminer $this */ ?> <?php /** @var array $RESULT */ ?> <?php $this->Debug($this->SCRUD->composition, 'composition'); ?> <? if ($RESULT['MODE'] === 'Create') { $this->ENGINE->TITLE = T([ 'en' => "Adding element of '{$this->SCRUD->name}'", 'ru' => "Добавление элемента '{$this->SCRUD->name}'", ]); } else { $this->ENGINE->TITLE = T([ 'en' => "Editing element #{$RESULT['DATA']['ID']} of '{$this->SCRUD->name}'", 'ru' => "Редактирование элемента №{$RESULT['DATA']['ID']} '{$this->SCRUD->name}'", ]); } ?> <div class="adminer"> <!-- Nav tabs --> <? if (count($RESULT['TABS']) > 1): ?> <ul class="nav nav-tabs" id="tabs" role="tablist"> <? foreach ($RESULT['TABS'] as $tab_code => $tab): ?> <li class="nav-item"> <a class="nav-link <?= ($tab['ACTIVE'] ? 'active' : '') ?>" data-toggle="tab" href="#<?= strtolower($tab_code) ?>" ><?= $tab['NAME'] ?></a> </li> <? endforeach; ?> </ul> <? endif; ?> <!-- Tab panes --> <div class="tab-content <?= (count($RESULT['TABS']) > 1) ? 'tab-content-no-top-border' : '' ?>"> <? foreach ($RESULT['TABS'] as $tab_code => $tab): ?> <div class="tab-pane tab-element <?= ($tab['ACTIVE'] ? 'active' : '') ?>" id="<?= strtolower($tab_code) ?>" role="tabpanel" aria-labelledby="<?= strtolower($tab_code) ?>-tab" > <? $RESULT['TAB'] = $tab; $RESULT['TAB']['CODE'] = $tab_code; require($this->Path("{$tab['VIEW']}.php")); ?> </div> <? endforeach; ?> </div> </div><file_sep><?php namespace BlackFox; /** * Class Type * * Parent for all data types for using in database. */ abstract class Type { /** @var string $db_type symbolic code of database type */ public $db_type = null; /** @var bool indicates that the field is virtual: it is not present in the database, will be generating dynamically */ public $virtual = false; /** @var Database */ public $DB; /** @var array Settings of specific field */ public $field; public function __construct(array &$field, Database $DB) { $this->DB = $DB; $this->field = &$field; $this->ProvideInfoIntegrity(); } public function ProvideInfoIntegrity() { } /** * Format input value from user to save into database. * No escape required. * * @param mixed $value input value from user * @internal array $info type info * @return string input value for database * @throws ExceptionType */ public function FormatInputValue($value) { return $value; } /** * Format the specific value of the output element from the database to the user. * No escape required. * * The element is passed entirely to provide a possibility of adding specific keys. * * @param array $element output element * @internal array $info type info * @return array output element with formatted value|values */ public function FormatOutputValue($element) { return $element; } public function PrepareConditions($table, $operator, $values) { $values = is_array($values) ? $values : [$values]; $values_have_null = false; if (count($values) === 0) { $values_have_null = true; } foreach ($values as $key => $value) { if (is_null($value)) { $values_have_null = true; unset($values[$key]); } else { $values[$key] = $this->FormatInputValue($values[$key]); $values[$key] = $this->DB->Escape($values[$key]); } } $conditions = []; if ($values_have_null) { switch ($operator) { case '!': case '<>': $conditions['null'] = ' IS NOT NULL'; break; default: $conditions['null'] = ' IS NULL'; break; } } if (count($values) === 1) { $value = reset($values); switch ($operator) { case '>>': $conditions['>>'] = ' > \'' . $value . '\''; break; case '!': case '<>': $conditions['<>'] = ' <> \'' . $value . '\''; break; case '<<': $conditions['<<'] = ' < \'' . $value . '\''; break; case '<': $conditions['<'] = ' <= \'' . $value . '\''; break; case '>': $conditions['>'] = ' >= \'' . $value . '\''; break; case '~': $conditions['~'] = ' LIKE \'%' . $value . '%\''; break; default: $conditions['='] = ' = \'' . $value . '\''; break; } } if (count($values) > 1) { if (!empty($values)) { $conditions['in'] = ' IN (\'' . implode('\', \'', $values) . '\')'; } } foreach ($conditions as $key => $condition) { $conditions[$key] = $table . "." . $this->DB->Quote($this->field['CODE']) . $condition; } return $conditions; } /** * This method must generate and return array with keys: * - SELECT - array of SQL parts for SELECT section * - JOIN - array of SQL parts for JOIN section * * Генерирует и возвращает массивы строк, являющихся частями для SQL запроса. * - SELECT - массив SQL частей для секции SELECT * - JOIN - массив SQL частей для секции JOIN * * @param string $table code of targeted table * @param string $prefix required prefix * @param array|null $subfields may contain array of required subfields * @internal array $info * @return array */ public function PrepareSelectAndJoinByField($table, $prefix, $subfields) { $code = $this->field['CODE']; $select["{$prefix}{$code}"] = "{$prefix}{$table}" . "." . $this->DB->Quote("{$code}") . " as " . $this->DB->Quote("{$prefix}{$code}"); return ['SELECT' => $select]; } /** * Подцепляет внешние данные к элементам выборки (если это требуется). * * @param array $elements * @param array $subfields * @param array $subsort * @internal array $info * @return mixed */ public function HookExternalField($elements, $subfields, $subsort) { return $elements; } /** * Предоставляет типу возможность присоединить внешние таблицы при обращении к полю из фильтра * * @param SCRUD $Current объект текущей таблицы * @param string $prefix префикс * @internal array $info * @return array : * - JOIN - ['уникальный алиас присоединяемой таблицы' => 'SQL-строка, описывающая присоединяемую таблицу', ...] * - GROUP - ['уникальный алиас присоединяемой таблицы' => 'SQL-строка, описывающая группировку', ...] */ public function GenerateJoinAndGroupStatements(SCRUD $Current, $prefix) { return [ 'JOIN' => [], 'GROUP' => [], ]; } /** * Формирует отображение значения поля * * @param mixed $value */ public function PrintValue($value) { echo is_array($value) ? '<pre>' . print_r($value, true) . '</pre>' : $value; } /** * Формирует отображение контрола для формы создания\редактирования элемента * * @param mixed $value * @param string $name * @param string $class */ public function PrintFormControl($value, $name, $class = 'form-control') { ?> <? if (is_array($value)): ?> <textarea class="<?= $class ?>" id="<?= $name ?>" name="<?= $name ?>" rows="5" disabled="disabled" ><?= print_r($value, true) ?></textarea> <? else: ?> <input type="text" class="<?= $class ?>" id="<?= $name ?>" name="<?= $name ?>" value="<?= $value ?>" disabled="disabled" /> <? endif; ?> <? } /** * Формирует отображение контролов для формы фильтрации. * Фильтр передается целиком для предоставления возможности формировать несколько фильтрующих контролов для одного поля. * * @param array $filter * @param string $group * @param string $class */ public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { $code = $this->field['CODE']; ?> <input type="text" class="<?= $class ?>" id="<?= $group ?>[<?= $code ?>]" name="<?= $group ?>[<?= $code ?>]" value="<?= $filter[$code] ?>" disabled="disabled" /> <? } }<file_sep><?php namespace BlackFox; class Groups extends SCRUD { public function Init() { $this->name = T([ 'en' => 'User groups', 'ru' => 'Группы пользователей', ]); $this->fields += [ 'ID' => self::ID, 'CODE' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Symbolic code', 'ru' => 'Символьный код', ]), 'NOT_NULL' => true, 'INDEX' => true, 'VITAL' => true, 'UNIQUE' => true, ], 'NAME' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Name', 'ru' => 'Имя', ]), 'NOT_NULL' => true, 'INDEX' => true, 'VITAL' => true, ], 'DESCRIPTION' => [ 'TYPE' => 'TEXT', 'NAME' => T([ 'en' => 'Description', 'ru' => 'Описание', ]), ], 'USERS' => [ 'TYPE' => 'INNER', 'NAME' => T([ 'en' => 'Users', 'ru' => 'Пользователи', ]), 'LINK' => 'Users2Groups', 'INNER_KEY' => 'GROUP', ], ]; } public function GetElementTitle(array $element) { return "{$element['NAME']} ({$element['CODE']})"; } } <file_sep><?php /** @var \BlackFox\Unit $this */ ?> <?php /** @var array $RESULT */ ?><file_sep><? /** @var \BlackFox\Engine $this */ $path = $this->TEMPLATE_PATH; $lang = $this->GetLanguage(); ?> <script>var lang = '<?= $lang ?>';</script> <? // Roboto $this->AddHeaderStyle('https://fonts.googleapis.com/css?family=Roboto:300,400,500,700'); // jquery ?> <script src='<?= $path ?>/lib/jquery/jquery.min.js'></script> <script src='<?= $path ?>/lib/jquery-ui/jquery-ui.min.js'></script> <? // bootstrap $this->AddHeaderStyle($path . '/lib/bootstrap/css/bootstrap.min.css'); $this->AddHeaderScript($path . '/lib/bootstrap/js/bootstrap.bundle.min.js'); // material-design-icons // $this->AddHeaderStyle('https://fonts.googleapis.com/css2?family=Material+Icons'); $this->AddHeaderStyle($path . '/lib/material-design-icons/all.css'); // summernote $this->AddHeaderStyle($path . '/lib/summernote/dist/summernote-bs4.css'); $this->AddHeaderScript($path . '/lib/summernote/dist/summernote-bs4.js'); if ($lang === 'ru') { $this->AddHeaderScript($path . '/lib/summernote/dist/lang/summernote-ru-RU.js'); } // flatpickr $this->AddHeaderScript($path . '/lib/flatpickr/flatpickr.min.js'); $this->AddHeaderStyle($path . '/lib/flatpickr/flatpickr.min.css'); if (!empty($lang) and $lang <> 'en') { $this->AddHeaderScript($path . '/lib/flatpickr/l10n/' . $lang . '.js'); } // select2 $this->AddHeaderScript($path . '/lib/select2/js/select2.full.js'); if (!empty($lang) and $lang <> 'en') { $this->AddHeaderScript($path . '/lib/select2/js/i18n/' . $lang . '.js'); } $this->AddHeaderStyle($path . '/lib/select2/css/select2.min.css'); $this->AddHeaderStyle($path . '/lib/select2-bootstrap/select2-bootstrap.min.css'); // custom $this->AddHeaderScript($path . '/script.js'); $this->AddHeaderStyle($path . '/style.css');<file_sep><? /** @var \BlackFox\Unit $this */ ?> <? /** @var array $RESULT */ ?> <? /** @var \BlackFox\SCRUD $SCRUD */ ?> <? $SCRUD = $RESULT['SCRUD']; ?> <? foreach ($RESULT['FIELDS'] as $code => $field): ?> <div class="<?= $RESULT['CLASS_GROUP'] ?>"> <label class="<?= $RESULT['CLASS_LABEL'] ?> <?= ($field['NOT_NULL']) ? 'mandatory' : '' ?>" for="<?= $RESULT['ELEMENT'] ?>[<?= $code ?>]" title="<?= $field['HINT'] ?>" > <?= $field['NAME'] ?: "{{$code}}" ?> </label> <div class="<?= $RESULT['CLASS_BLOCK'] ?>"> <? // ------------------------------------------------------------------------------------------- $SCRUD->Types[$code]->PrintFormControl($RESULT['DATA'][$code], "{$RESULT['ELEMENT']}[{$code}]", $RESULT['CLASS_CONTROL']); // ------------------------------------------------------------------------------------------- ?> </div> </div> <? endforeach; ?> <file_sep><?php namespace BlackFox; class Core extends \BlackFox\ACore { public $name = 'BlackFox'; public $description = 'Main system module providing basic tools'; public $version = '1.0'; public function GetScheme() { return new Scheme([ Users::I(), Files::I(), Groups::I(), Users2Groups::I(), Pages::I(), Redirects::I(), Log::I(), TableSettings::I(), ]); } public function Upgrade() { $this->GetScheme()->Synchronize(); Cache::I()->Clear(); } public function Menu() { return [ 'BlackFox' => [ 'NAME' => T([ 'en' => 'System', 'ru' => 'Система', ]), 'EXPANDER' => true, 'CHILDREN' => [ 'index' => [ 'NAME' => T([ 'en' => 'Control panel', 'ru' => 'Панель управления', ]), 'LINK' => '/admin/BlackFox/', 'CHILDREN' => [ 'SchemeSynchronizer' => [ 'NAME' => T([ 'en' => 'Scheme synchronizer', 'ru' => 'Синхронизатор схем', ]), 'LINK' => '/admin/BlackFox/SchemeSynchronizer.php', ], 'PHPConsole' => [ 'NAME' => T([ 'en' => 'PHP console', 'ru' => 'PHP консоль', ]), 'LINK' => '/admin/BlackFox/PHPConsole.php', ], 'SQLConsole' => [ 'NAME' => T([ 'en' => 'SQL console', 'ru' => 'SQL консоль', ]), 'LINK' => '/admin/BlackFox/SQLConsole.php', ], 'MaterialDesignIcons' => [ 'NAME' => T([ 'en' => 'Material Design Icons', 'ru' => 'Material Design Icons', ]), 'LINK' => '/admin/BlackFox/MaterialDesignIcons.php', ], ], ], 'BlackFox_Content' => [ 'NAME' => T([ 'en' => 'Content pages', 'ru' => 'Контентные страницы', ]), 'LINK' => '/admin/BlackFox/Pages.php', ], 'BlackFox_Redirects' => [ 'NAME' => T([ 'en' => 'Redirects', 'ru' => 'Редиректы', ]), 'LINK' => '/admin/BlackFox/Redirects.php', ], 'BlackFox_Users' => [ 'NAME' => T([ 'en' => 'Users', 'ru' => 'Пользователи', ]), 'LINK' => '/admin/BlackFox/Users.php', ], 'BlackFox_Groups' => [ 'NAME' => T([ 'en' => 'Groups', 'ru' => 'Группы', ]), 'LINK' => '/admin/BlackFox/Groups.php', ], 'BlackFox_Users2Groups' => [ 'NAME' => T([ 'en' => 'Users in groups', 'ru' => 'Пользователи в группах', ]), 'LINK' => '/admin/BlackFox/Users2Groups.php', ], 'BlackFox_Files' => [ 'NAME' => T([ 'en' => 'Files', 'ru' => 'Файлы', ]), 'LINK' => '/admin/BlackFox/Files.php', ], 'BlackFox_Log' => [ 'NAME' => T([ 'en' => 'Log', 'ru' => 'Журнал', ]), 'LINK' => '/admin/BlackFox/Log.php', ], 'BlackFox_TableSettings' => [ 'NAME' => T([ 'en' => 'Table settings', 'ru' => 'Настройки таблиц', ]), 'LINK' => '/admin/BlackFox/TableSettings.php', ], ], ], ]; } }<file_sep><?php namespace BlackFox; class FactoryType { use Instance; public static $TYPES = [ 'ARRAY' => '\BlackFox\TypeArray', 'BOOLEAN' => '\BlackFox\TypeBoolean', 'DATE' => '\BlackFox\TypeDate', 'DATETIME' => '\BlackFox\TypeDateTime', 'ENUM' => '\BlackFox\TypeEnum', 'FLOAT' => '\BlackFox\TypeFloat', 'INNER' => '\BlackFox\TypeInner', 'LIST' => '\BlackFox\TypeList', 'INTEGER' => '\BlackFox\TypeInteger', 'OUTER' => '\BlackFox\TypeOuter', 'PASSWORD' => <PASSWORD>', 'SET' => '\BlackFox\TypeSet', 'STRING' => '\BlackFox\TypeString', 'TEXT' => '\BlackFox\TypeText', 'TIME' => '\BlackFox\TypeTime', 'FILE' => '\BlackFox\TypeFile', ]; public static function Add($name, $class) { self::$TYPES[$name] = $class; } /** * Get instance of class mapped to code of the type * * @param array $field info of the field * @param Database $Database * @return Type instance of class * @throws Exception */ public static function Get(array $field, Database $Database = null) { $field['TYPE'] = strtoupper($field['TYPE']); if (!isset(self::$TYPES[$field['TYPE']])) { throw new Exception("Class for type '{$field['TYPE']}' not found, field code: '{$field['CODE']}'"); } /** @var Type $class */ $class = self::$TYPES[$field['TYPE']]; return new $class($field, $Database ?: Database::I()); } }<file_sep><?php namespace BlackFox; class Exception extends \Exception { public $array = []; /** * Exception constructor. * @param string|array $exception either a string or an array of strings */ public function __construct($exception = []) { if (empty($exception)) { $exception = get_called_class(); } if (is_array($exception)) { $this->array = $exception; $this->message = implode($this->getImplodeSymbols(), $exception); } if (is_string($exception)) { $this->message = $exception; $this->array = [$exception]; } } public function getArray() { return $this->array; } public function getImplodeSymbols() { return (php_sapi_name() === 'cli') ? "\r\n" : '<br/>'; } }<file_sep><? /** @var \BlackFox\Unit $this */ ?> <? /** @var array $RESULT */ ?> <? $this->Debug($this->PARAMS, 'PAGER'); ?> <? $this->Debug($RESULT, 'PAGES'); ?> <? $get = $_GET; unset($get[$this->PARAMS['VARIABLE']]); $base = http_build_query($get); ?> <div class="pager"> <div class="alert alert-info float-right m-0 p-2"> <strong title="<?= T([ 'en' => 'Showing', 'ru' => 'Отображено', ]) ?>"><?= $this->PARAMS['SELECTED'] ?></strong> / <span title="<?= T([ 'en' => 'Total', 'ru' => 'Всего', ]) ?>"><?= $this->PARAMS['TOTAL'] ?></span> </div> <nav class="d-inline-block"> <ul class="pagination"> <? foreach ($RESULT as $page): ?> <? if ($page['ACTIVE']): ?> <li class="page-item active"> <a class="page-link"> <?= $page["INDEX"] ?> </a> </li> <? elseif ($page['...']): ?> <li class="page-item"> <a class="page-link" href="javascript:if(page = prompt('<?= T([ 'en' => 'Input page number', 'ru' => 'Введите номер страницы', ]) ?>', '')){window.location='?<?= $base ?>&<?= $this->PARAMS['VARIABLE'] ?>='+page}"> <?= $page["INDEX"] ?> </a> </li> <? else : ?> <li class="page-item"> <a class="page-link" href="?<?= http_build_query(array_merge($_GET, [$this->PARAMS['VARIABLE'] => $page['INDEX']])) ?>"> <?= $page["INDEX"] ?> </a> </li> <? endif; ?> <? endforeach; ?> </ul> </nav> <div class="clearfix"></div> </div> <file_sep><?php namespace BlackFox; class Pagination extends \BlackFox\Unit { public $options = [ 'TOTAL' => [ 'TYPE' => 'integer', ], 'CURRENT' => [ 'TYPE' => 'integer', ], 'LIMIT' => [ 'TYPE' => 'integer', ], 'SELECTED' => [ 'TYPE' => 'integer', ], 'SPREAD' => [ 'TYPE' => 'integer', 'DEFAULT' => 7, ], 'VARIABLE' => [ 'TYPE' => 'string', 'DEFAULT' => 'page', ], ]; public function GetActions(array $request = []) { return 'Default'; } public function Default() { return $this->GetPages( $this->PARAMS['TOTAL'], $this->PARAMS['CURRENT'], $this->PARAMS['LIMIT'] ); } private function GetPages($total, $current, $limit) { $RESULT = []; $spread = $this->PARAMS['SPREAD']; $current = $current ?: 1; $pages_count = (int)ceil($total / $limit); $pages = array_fill(1, $pages_count, null); $last_was_excluded = false; foreach ($pages as $page => $crap) { $in_spread = ( ($page === 1) || ($page === $pages_count) || (abs($page - $current) <= $spread) ); if ($in_spread) { $RESULT[$page] = [ 'INDEX' => $page, 'ACTIVE' => ($page === $current), ]; $last_was_excluded = false; } elseif (!$last_was_excluded) { $RESULT[$page] = [ 'INDEX' => '...', '...' => true, ]; $last_was_excluded = true; } else { continue; } } return $RESULT; } } <file_sep><?php \BlackFox\User::I()->Logout(); header('Location: /admin/'); <file_sep><?php namespace BlackFox; class TypeString extends Type { public $db_type = 'varchar'; /** * Deleting all extra spaces * * @param string $value * @return string */ public function FormatInputValue($value) { return trim(mb_ereg_replace('#\s+#', ' ', $value)); } public function PrintFormControl($value, $name, $class = 'form-control') { ?> <input type="text" class="<?= $class ?>" id="<?= $name ?>" name="<?= $name ?>" value="<?= $value ?>" <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> /> <? } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { $code = $this->field['CODE']; ?> <input type="text" class="<?= $class ?>" id="<?= $group ?>[~<?= $code ?>]" name="<?= $group ?>[~<?= $code ?>]" value="<?= $filter['~' . $code] ?>" /> <? } }<file_sep><?php /**@var BlackFox\Engine $this */ $this->TITLE = T([ 'en' => 'PHP console', 'ru' => 'PHP консоль', ]); ?> <form method="post"> <div class="form-group"> <textarea class="form-control" name="PHP" rows="5" ><?= htmlspecialchars($_REQUEST['PHP']) ?></textarea> </div> <input type="submit" value="<?=T([ 'en' => 'Execute', 'ru' => 'Выполнить', ])?>" class="btn btn-success" /> </form> <?php // todo: move to iframe if (!empty($_REQUEST['PHP'])) { echo '<hr/>'; eval($_REQUEST['PHP']); }<file_sep><?php namespace BlackFox; class ExceptionNotImplemented extends Exception { }<file_sep><?php /** @var \BlackFox\Engine $this */ ?> <!DOCTYPE html> <html> <head> <? require('_header.php') ?> <?= $this->GetHeader() ?> <title><?= $this->TITLE ?></title> </head> <body> <nav class="header p-2"> <button class="btn btn-info d-inline-block d-md-none" data-toggle-sidebar="" > <span class="material-icons">menu</span> <span class="d-none d-md-inline-block"><?= T([ 'en' => 'Menu', 'ru' => 'Меню', ]) ?></span> </button> <a class="btn btn-secondary" href="/"> <span class="material-icons">desktop_windows</span> <span class="d-none d-md-inline-block"><?= T([ 'en' => 'Site', 'ru' => 'Сайт', ]) ?></span> </a> <div class="float-right"> <? if ($this->User->IsAuthorized()): ?> <span class="btn-group"> <a class="btn btn-secondary" href="/admin/BlackFox/Users.php?ID=<?= $this->User->ID ?>"> <span class="material-icons">person</span> <span class="d-none d-md-inline-block"><?= $this->User->FIELDS['LOGIN'] ?></span> </a> <a class="btn btn-secondary" href="/admin/logout.php" title="<?= T([ 'en' => 'Logout', 'ru' => 'Выход', ]) ?>"> <span class="material-icons">logout</span> </a> </span> <? else: ?> <? endif; ?> <? \BlackFox\LanguageSwitcher::Run([]); ?> </div> </nav> <main role="main" class="container-fluid p-0"> <div class="row no-gutters"> <div class="sidebar col-12 col-md-2" id="sidebar"> <? \BlackFox\Menu::Run() ?> </div> <div class="main col-12 col-md-10 p-3 p-sm-3"> <? \BlackFox\Breadcrumbs::Run() ?> <h1 class="page-header"><?= $this->TITLE ?></h1> <?= $this->CONTENT ?> </div> </div> </main> </body> </html> <file_sep><?php BlackFox\AdminerUsers::Run(['SCRUD' => '\BlackFox\Users']);<file_sep><?php header('Location: BlackFox'); die();<file_sep><? /** @var \BlackFox\Adminer $this */ ?> <? /** @var array $RESULT */ ?> <form method="get" class="form-horizontal"> <? foreach ($_GET as $code => $value) : ?> <? if (!is_array($value)) : ?> <input type="hidden" name="<?= $code ?>" value="<?= $value ?>"/> <? endif; ?> <? endforeach; ?> <? if (!empty($RESULT['STRUCTURE']['FILTERS'])): ?> <div class="card"> <div class="card-header"><?= T([ 'en' => 'Filter', 'ru' => 'Фильтр', ]) ?></div> <div class="card-body" id="filter"> <? foreach ($RESULT['STRUCTURE']['FILTERS'] as $code => $field): ?> <? if (!isset($this->SCRUD->fields[$code])) continue; ?> <div class="form-group row"> <label class="col-sm-3 col-form-label text-sm-right" title="<?= $code ?>" > <?= $field['NAME'] ?> </label> <div class="col-sm-8"> <? // ------------------------------------------------------------------------------- $this->SCRUD->Types[$code]->PrintFilterControl($RESULT['FILTER'], 'FILTER'); // ------------------------------------------------------------------------------- ?> </div> </div> <? endforeach; ?> <div class="form-group row mb-0"> <div class="col-sm-8 offset-sm-3"> <div class="buttons"> <button class="btn btn-primary" type="submit" > <span class="material-icons">filter_alt</span> <?= T([ 'en' => 'Apply', 'ru' => 'Фильтровать', ]) ?> </button> <a class="btn btn-secondary" href="?" > <span class="material-icons">block</span> <?= T([ 'en' => 'Clear', 'ru' => 'Сбросить', ]) ?> </a> </div> </div> </div> </div> </div> <? endif; ?> </form> <file_sep><?php /** @var $this \BlackFox\Engine */ $icons = require($this->GetAbsolutePath($this->TEMPLATE_PATH) . '/icons.php'); debug($icons, '$icons'); $this->TITLE = 'Material Design Icons'; $selected_type = (string)$_REQUEST['TYPE']; $types = [ '', 'outlined', 'round', 'sharp', 'two-tone', ]; if (!in_array($selected_type, $types)) $selected_type = ''; ?> <div class="btn-group"> <? foreach ($types as $type): ?> <a class="btn btn-<?= $selected_type === $type ? 'primary' : 'secondary' ?>" href="?TYPE=<?= $type ?>" ><?= $type ?: '- default -' ?></a> <? endforeach; ?> </div> <script type="application/javascript"> $.fn.selectText = function () { this.find('input').each(function () { if ($(this).prev().length == 0 || !$(this).prev().hasClass('p_copy')) { $('<p class="p_copy" style="position: absolute; z-index: -1;"></p>').insertBefore($(this)); } $(this).prev().html($(this).val()); }); var element = this[0]; if (document.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if (window.getSelection) { var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); } }; $(function () { $('.material-icons').click(function () { $(this).selectText(); document.execCommand("copy"); }); }); </script> <? foreach ($icons as $group_title => $group): ?> <div class="alert alert-info my-3"><h2 class="mb-0"><?= $group_title ?></h2></div> <? foreach ($group as $icon): ?> <span class="material-icons <?= $_REQUEST['TYPE'] ?> md-48" title="<?= $icon ?>"><?= $icon ?></span> <? endforeach; ?> <? endforeach; ?> <file_sep><?php /** @var $this \BlackFox\Engine */ $url = parse_url($_SERVER['REQUEST_URI']); $path = explode('/', $url['path']); if ($path[0] <> '' or $path[1] <> 'admin') { return $this->Show404(); } $namespace = $path[2]; if (!$this->cores[$namespace]) { return $this->Show404(); } $target = $path[3]; if ($x = strpos($target, '.php')) { $target = substr($target, 0, $x); } $Class = "{$namespace}\\{$target}"; if (is_subclass_of($Class, "BlackFox\\SCRUD")) { \BlackFox\Adminer::Run(['SCRUD' => $Class]); return; } if (is_subclass_of($Class, "BlackFox\\Unit")) { $Class::Run(); return; } return $this->Show404(); <file_sep><?php namespace BlackFox; class LanguageSwitcher extends Unit { public function GetActions(array $request = []) { if ($request['SwitchLanguage']) { return 'SwitchLanguage'; } return 'Default'; } public function Default() { if (count($this->ENGINE->languages) <= 1) { $this->view = null; return null; } $R['LANGUAGES'] = $this->ENGINE->languages; $R['LANGUAGE'] = $this->ENGINE->GetLanguage(); return $R; } public function SwitchLanguage($SwitchLanguage) { $this->ENGINE->SetLanguage($SwitchLanguage); $request = array_diff($_GET, ['SwitchLanguage' => $SwitchLanguage]); $this->Redirect('?' . http_build_query($request)); } }<file_sep><?php namespace BlackFox; class Users extends SCRUD { public function Init() { $this->name = T([ 'en' => 'Users', 'ru' => 'Пользователи', ]); $this->groups = [ 'SYSTEM' => T([ 'en' => 'System', 'ru' => 'Система', ]), 'CONTENT' => T([ 'en' => 'Content', 'ru' => 'Контент', ]), ]; $this->fields += [ 'ID' => self::ID + ['GROUP' => 'SYSTEM'], 'LOGIN' => [ 'TYPE' => 'STRING', 'GROUP' => 'SYSTEM', 'NAME' => T([ 'en' => 'Login', 'ru' => 'Логин', ]), 'NOT_NULL' => true, 'INDEX' => true, 'UNIQUE' => true, 'VITAL' => true, ], 'PASSWORD' => [ 'TYPE' => 'PASSWORD', 'GROUP' => 'SYSTEM', 'NAME' => T([ 'en' => 'Password', 'ru' => 'Пароль', ]), 'DESCRIPTION' => T([ 'en' => 'Database contains sha1 hash of the password', 'ru' => 'В базе хранится sha1 хеш пароля', ]), ], 'SALT' => [ 'TYPE' => 'STRING', 'GROUP' => 'SYSTEM', 'NAME' => T([ 'en' => 'Salt', 'ru' => 'Соль', ]), ], 'HASH' => [ 'TYPE' => 'STRING', 'GROUP' => 'SYSTEM', 'NAME' => T([ 'en' => 'Hash', 'ru' => 'Хэш', ]), 'DESCRIPTION' => T([ 'en' => 'For password recovery', 'ru' => 'Для восстановления пароля', ]), ], 'LANGUAGE' => [ 'TYPE' => 'STRING', 'GROUP' => 'SYSTEM', 'NAME' => T([ 'en' => 'Language', 'ru' => 'Язык', ]), 'DEFAULT' => 'en', ], 'LAST_AUTH' => [ 'TYPE' => 'DATETIME', 'GROUP' => 'SYSTEM', 'NAME' => T([ 'en' => 'Authorization', 'ru' => 'Авторизация', ]), 'DISABLED' => true, ], 'REGISTER_MOMENT' => [ 'TYPE' => 'DATETIME', 'GROUP' => 'SYSTEM', 'NAME' => T([ 'en' => 'Registration', 'ru' => 'Регистрация', ]), 'DISABLED' => true, ], 'FIRST_NAME' => [ 'TYPE' => 'STRING', 'GROUP' => 'CONTENT', 'NAME' => T([ 'en' => '<NAME>', 'ru' => 'Имя', ]), 'VITAL' => true, ], 'LAST_NAME' => [ 'TYPE' => 'STRING', 'GROUP' => 'CONTENT', 'NAME' => T([ 'en' => 'Last name', 'ru' => 'Фамилия', ]), 'VITAL' => true, ], 'MIDDLE_NAME' => [ 'TYPE' => 'STRING', 'GROUP' => 'CONTENT', 'NAME' => T([ 'en' => 'Middle name', 'ru' => 'Отчество', ]), ], 'EMAIL' => [ 'TYPE' => 'STRING', 'GROUP' => 'CONTENT', 'NAME' => T([ 'en' => 'E-mail', 'ru' => 'E-mail', ]), 'VITAL' => true, ], 'PHONE' => [ 'TYPE' => 'STRING', 'GROUP' => 'CONTENT', 'NAME' => T([ 'en' => 'Phone', 'ru' => 'Телефон', ]), ], 'AVATAR' => [ 'TYPE' => 'FILE', 'GROUP' => 'CONTENT', 'NAME' => T([ 'en' => 'Avatar', 'ru' => 'Аватар', ]), 'LINK' => 'BlackFox\Files', ], 'BIRTH_DAY' => [ 'TYPE' => 'DATE', 'GROUP' => 'CONTENT', 'NAME' => T([ 'en' => 'Birthday', 'ru' => 'День рождения', ]), ], 'ABOUT' => [ 'TYPE' => 'TEXT', 'GROUP' => 'CONTENT', 'NAME' => T([ 'en' => 'About', 'ru' => 'О себе', ]), ], 'GROUPS' => [ 'TYPE' => 'INNER', 'NAME' => T([ 'en' => 'Groups', 'ru' => 'Группы', ]), 'LINK' => 'BlackFox\Users2Groups', 'INNER_KEY' => 'USER', ], ]; } /** * Creates a new user * * @param array $fields * @return int created users identifier * @throws Exception */ public function Create($fields) { if (empty($fields['LOGIN'])) { throw new Exception(T([ 'en' => 'Login must be specified', 'ru' => 'Укажите логин', ])); } // prevent doubles for LOGIN if (!empty($this->Read(['LOGIN' => $fields['LOGIN']], ['ID']))) { throw new Exception(T([ 'en' => "User with login '{$fields['LOGIN']}' already exist", 'ru' => "Пользователь с логином '{$fields['LOGIN']}' уже существует", ])); } // auto hash password unset($fields['SALT']); if (!empty($fields['PASSWORD'])) { $fields['SALT'] = bin2hex(random_bytes(32)); $fields['PASSWORD'] = sha1($fields['SALT'] . ':' . $fields['PASSWORD']); } if (empty($fields['REGISTER_MOMENT'])) { $fields['REGISTER_MOMENT'] = time(); } return parent::Create($fields); } /** * Set password for specified user * * @param int $ID users identifier * @param string $password <PASSWORD> * @throws Exception Password must be specified */ public function SetPassword($ID, $password) { if (empty($password)) { throw new Exception(T([ 'en' => 'Password must be specified', 'ru' => 'Укажите пароль', ])); } $salt = bin2hex(random_bytes(32)); $password = sha1($salt . ':' . $password); parent::Update($ID, [ 'SALT' => $salt, 'PASSWORD' => $password, ]); } /** * Checks if users password match database hash * * @param int $ID user identifier * @param string $password <PASSWORD> to check * @return bool * @throws Exception */ public function CheckPassword($ID, $password) { $user = $this->Read($ID, ['PASSWORD', 'SALT']); return ($user['PASSWORD'] === sha1($user['SALT'] . ':' . $password)); } public function AddGroup($ID, $group) { $ID = (int)$ID; if (empty($ID)) { throw new Exception(T([ 'en' => 'User ID required', 'ru' => 'Требуется ID пользователя', ])); } if (is_string($group)) { $group_id = Groups::I()->Pick(['CODE' => $group]); } else { $group_id = (int)$group; } if (empty($group_id)) { throw new Exception(T([ 'en' => 'Group ID/CODE required', 'ru' => 'Требуется ID/CODE группы', ])); } Users2Groups::I()->Create([ 'USER' => $ID, 'GROUP' => $group_id, ]); } public function GetRecoveryString(int $ID) { if (empty($ID)) { throw new Exception(T([ 'en' => 'User ID not specified to generate password recovery string', 'ru' => 'Не указан идентификатор пользователя для генерации строки для восстановления пароля', ])); } $string = sha1(random_bytes(32)); $hash = sha1($string); parent::Update($ID, ['HASH' => $hash]); return $string; } public function GetElementTitle(array $element) { $name = trim("{$element['FIRST_NAME']} {$element['LAST_NAME']}"); if (empty($name)) $name = $element['LOGIN']; if (empty($name)) $name = "№{$element['ID']}"; if (empty($element['ID'])) $name = ""; return $name; } }<file_sep><?php namespace BlackFox; class TypeInteger extends Type { public $db_type = 'int'; public function FormatInputValue($value) { if (!is_numeric($value)) { throw new ExceptionType(T([ 'en' => "Expected numerical value for '{$this->field['CODE']}', received: '{$value}'", 'ru' => "Ожидалось числовое значение для '{$this->field['CODE']}', получено: '{$value}'", ])); } return (int)$value; } public function FormatOutputValue($element) { return $element; // TODO convert to integer (if not null) // $element[$this->info['CODE']] = (int)$element[$this->info['CODE']]; } public function PrintFormControl($value, $name, $class = 'form-control') { ?> <input type="number" class="<?= $class ?>" id="<?= $name ?>" name="<?= $name ?>" placeholder="" value="<?= $value ?>" <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> > <? } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { $code = $this->field['CODE']; ?> <div class="row no-gutters"> <div class="col-6"> <input type="number" step="1" class="<?= $class ?>" id="<?= $group ?>[><?= $code ?>]" name="<?= $group ?>[><?= $code ?>]" placeholder="<?= T([ 'en' => 'from', 'ru' => 'от', ]) ?>" value="<?= $filter['>' . $code] ?>" > </div> <div class="col-6"> <input type="number" step="1" class="<?= $class ?>" id="<?= $group ?>[<<?= $code ?>]" name="<?= $group ?>[<<?= $code ?>]" placeholder="<?= T([ 'en' => 'to', 'ru' => 'до', ]) ?>" value="<?= $filter['<' . $code] ?>" > </div> </div> <? } }<file_sep><?php /** @var \BlackFox\Adminer $this */ ?> <?php /** @var array $RESULT */ ?> <h3 class="group_header"><?= T([ 'en' => 'Summary', 'ru' => 'Сводка', ]) ?></h3> <div class="form-group row"> <label class="col-sm-3 col-form-label text-right"> <?= T([ 'en' => 'File', 'ru' => 'Файл', ]) ?> </label> <div class="col-sm-8 col-form-label text-left"> <a href="<?= $RESULT['DATA']['SRC'] ?>" target="_blank"><?= \BlackFox\Files::I()->GetElementTitle($RESULT['DATA']) ?></a> (<?= \BlackFox\Files::I()->GetPrintableFileSize($RESULT['DATA']['SIZE']) ?>) </div> </div> <? if (substr($RESULT['DATA']['TYPE'], 0, 5) === 'image'): ?> <div class="form-group row"> <label class="col-sm-3 col-form-label text-right"> <?= T([ 'en' => 'Preview', 'ru' => 'Привью', ]) ?> </label> <div class="col-sm-8"> <img src="<?= $RESULT['DATA']['SRC'] ?>" style="max-height: 300px" /> </div> </div> <? endif; ?><file_sep><?php namespace BlackFox; class ExceptionAuthRequired extends Exception { }<file_sep><?php namespace BlackFox; class ExceptionAccessDenied extends Exception { }<file_sep><?php namespace BlackFox; class Adminer extends \BlackFox\Unit { /** @var \BlackFox\SCRUD */ public $SCRUD; /** @var bool is in frame mode */ public $frame = false; /**@var [] possible actions for single element: buttons on the top of the form with popup modals */ public $actions = []; public $options = [ 'SCRUD' => [ 'NAME' => 'SCRUD', ], 'RESTRICTIONS' => [ 'TYPE' => 'array', 'NAME' => 'RESTRICTIONS', 'DEFAULT' => [], ], ]; public function __construct() { parent::__construct(); $this->allow_ajax_request = true; $this->allow_json_request = true; if (isset($_REQUEST['FRAME'])) { $this->frame = true; $this->ENGINE->WRAPPER = 'frame'; } } public function Init($PARAMS = []) { parent::Init($PARAMS); if (!is_subclass_of($PARAMS['SCRUD'], 'BlackFox\SCRUD')) { throw new Exception("Parameter SCRUD ({$PARAMS['SCRUD']}) must be the child of BlackFox\\SCRUD"); } if (is_object($PARAMS['SCRUD'])) { $this->SCRUD = $PARAMS['SCRUD']; } elseif (class_exists($PARAMS['SCRUD'])) { $this->SCRUD = $PARAMS['SCRUD']::N(); } $this->ControlUrl(); $this->ENGINE->TITLE = $this->SCRUD->name; $back_link = $this->GetBackLink(); if ($back_link <> '?') { $this->ENGINE->AddBreadcrumb("...", $back_link); } } public function GetActions(array $request = []) { if ($request['ACTION'] === 'SearchOuter') { return ['SearchOuter']; } $actions = $request['ACTION'] ? [$request['ACTION']] : []; if (isset($request['NEW'])) { return array_merge($actions, ['CreateForm']); } if (!empty($request['ID'])) { return array_merge($actions, ['UpdateForm']); } return array_merge($actions, ['Section']); } public function Section( $FILTER = [], $PAGE = 1, $SORT = ['ID' => 'DESC'], $FIELDS = ['*@@'], $LIMIT = 100 ) { $R['MODE'] = 'SECTION'; $FILTER = $this->PARAMS['RESTRICTIONS'] + $FILTER; $R['FILTER'] = $FILTER; $R['SORT'] = $SORT; $R['SETTINGS'] = $this->LoadTableSettings(); $R['STRUCTURE']['FILTERS'] = $this->SCRUD->ExtractFields(array_merge($R['SETTINGS']['FILTERS'], array_keys($FILTER))); $R['STRUCTURE']['FIELDS'] = $this->SCRUD->ExtractFields($R['SETTINGS']['FIELDS']); // unset column if frame-mode if ($this->frame) { unset($R['STRUCTURE']['FIELDS'][$_GET['FRAME']]); } $R['DATA'] = $this->SCRUD->Search([ 'FILTER' => $FILTER, 'FIELDS' => $FIELDS, 'PAGE' => $PAGE, 'SORT' => $SORT, 'LIMIT' => $LIMIT, ]); debug($this->SCRUD->SQL, 'SQL'); return $R; } public function GetDefaultValues() { $values = []; foreach ($this->SCRUD->fields as $code => $field) { if (isset($field['DEFAULT'])) { $values[$code] = $field['DEFAULT']; } } return $values; } public function GetBackLink() { $back = [ 'FILTER' => $_GET['FILTER'], 'PAGE' => $_GET['PAGE'], 'SORT' => $_GET['SORT'], 'FRAME' => $_GET['FRAME'], ]; $back = array_filter($back, function ($element) { return !empty($element); }); $link = '?' . http_build_query($back); return $link; } public function CreateForm($FILTER = [], $FIELDS = []) { $R['MODE'] = 'Create'; $R['DATA'] = $this->PARAMS['RESTRICTIONS'] + $FILTER + $this->GetDefaultValues() + $FIELDS; $R['BACK'] = $this->GetBackLink(); $R['TABS'] = $this->GetTabsOfCreate(); foreach ($this->PARAMS['RESTRICTIONS'] as $code => $value) { $this->SCRUD->fields[$code]['DISABLED'] = true; } $this->ENGINE->AddBreadcrumb(T([ 'en' => 'Add element', 'ru' => 'Добавление элемента', ])); $this->view = 'Element'; return $R; } public function UpdateForm($ID = null, $FIELDS = []) { $R['MODE'] = 'Update'; $R['DATA'] = $this->SCRUD->Read($this->PARAMS['RESTRICTIONS'] + ['ID' => $ID], ['*@@']); if (empty($R['DATA'])) { throw new Exception(T([ 'en' => 'Element not found', 'ru' => 'Элемент не найден', ])); } $R['DATA'] = $FIELDS + $R['DATA']; $R['BACK'] = $this->GetBackLink(); $R['TABS'] = $this->GetTabsOfUpdate(); $R['ACTIONS'] = $this->actions; foreach ($this->PARAMS['RESTRICTIONS'] as $code => $value) { $this->SCRUD->fields[$code]['DISABLED'] = true; } $this->ENGINE->AddBreadcrumb(T([ 'en' => "Edit element #{$ID}", 'ru' => "Редактирование элемента №{$ID}", ])); $this->view = 'Element'; return $R; } public function Create($FIELDS = [], $REDIRECT = null) { foreach ($this->PARAMS['RESTRICTIONS'] as $code => $value) { $FIELDS[$code] = $value; } $ID = $this->SCRUD->Create($FIELDS); if (empty($REDIRECT)) { $get = $_GET; unset($get['NEW']); $REDIRECT = '?' . http_build_query(array_merge($get, ['ID' => $ID])); } $this->Redirect($REDIRECT, T([ 'en' => "Element <a href='?ID={$ID}'>#{$ID}</a> has been created", 'ru' => "Создан элемент <a href='?ID={$ID}'>№{$ID}</a>", ])); } public function Update($ID, $FIELDS = [], $REDIRECT = null) { foreach ($this->PARAMS['RESTRICTIONS'] as $code => $value) { unset($FIELDS[$code]); } $this->SCRUD->Update($ID, $FIELDS); $this->Redirect($REDIRECT, T([ 'en' => "Element <a href='?ID={$ID}'>#{$ID}</a> has been updated", 'ru' => "Обновлен элемент <a href='?ID={$ID}'>№{$ID}</a>", ])); } public function Delete($ID) { $this->SCRUD->Delete($ID); if (is_array($ID)) { $message = T([ 'en' => "Elements ## " . implode(', ', $ID) . " has been deleted", 'ru' => "Удалены элементы №№ " . implode(', ', $ID), ]); } else { $message = T([ 'en' => "Element #{$ID} has been deleted", 'ru' => "Удален элемент №{$ID}", ]); } $this->Redirect($this->GetBackLink(), $message); } public function ControlUrl() { if (!empty($_POST)) { return; } if ($_SERVER['REQUEST_METHOD'] === 'GET' && is_array($_GET['FILTER'])) { $filter = []; foreach ($_GET['FILTER'] as $key => $value) { if ($this->SCRUD->_hasInformation($value)) { $filter[$key] = $value; } } if (count($filter) < count($_GET['FILTER'])) { $_GET['FILTER'] = $filter; $url = http_build_query($_GET); $url = $this->SanitizeUrl($url); $this->Redirect('?' . $url); } } if (strpos($_SERVER['QUERY_STRING'], '%5B') || strpos($_SERVER['QUERY_STRING'], '%5D')) { $url = http_build_query($_GET); $url = $this->SanitizeUrl($url); $this->Redirect('?' . $url); } } public function SanitizeUrl($url) { $url = str_replace('%5B', '[', $url); $url = str_replace('%5D', ']', $url); $url = str_replace('%25', '%', $url); $url = str_replace('%3A', ':', $url); return $url; } public function LoadTableSettings() { $settings = TableSettings::I()->Read([ 'USER' => $this->USER->ID, 'ENTITY' => get_class($this->SCRUD), ]); if (empty($settings)) { $settings = []; foreach ($this->SCRUD->fields as $code => $field) { if ($field['VITAL'] or $field['PRIMARY']) { $settings['FILTERS'][] = $code; } if (!$field['DISABLED'] or $field['PRIMARY']) { $settings['FIELDS'][] = $code; } } } return $settings; } public function SaveTableSettings($filters = [], $fields = []) { TableSettings::I()->Save( $this->USER->ID, get_class($this->SCRUD), $filters, $fields ); $this->Redirect(null); } public function GetTabsOfCreate() { $tabs = [ 'main' => [ 'NAME' => T([ 'en' => 'Element', 'ru' => 'Элемент', ]), 'VIEW' => 'element_tab_main', 'ACTIVE' => true, ], ]; foreach ($this->SCRUD->fields as $code => $field) { if ($field['TYPE'] === 'INNER') { unset($this->SCRUD->composition[$field['GROUP']]['FIELDS'][$code]); } } return $tabs; } public function GetTabsOfUpdate() { $tabs = [ 'element' => [ 'NAME' => T([ 'en' => 'Element', 'ru' => 'Элемент', ]), 'VIEW' => 'element_tab_main', 'ACTIVE' => true, ], ]; foreach ($this->SCRUD->fields as $code => $field) { if ($field['TYPE'] === 'INNER') { $tabs[$code] = [ 'NAME' => $field['NAME'], 'VIEW' => 'element_tab_external', ]; unset($this->SCRUD->composition[$field['GROUP']]['FIELDS'][$code]); } } return $tabs; } public function SearchOuter($code, $search, $page = 1) { $this->json = true; try { $field = $this->SCRUD->fields[$code]; if (empty($field)) { throw new Exception("[{$code}] not found"); } if ($field['TYPE'] <> 'OUTER') { throw new Exception("[{$code}] is not type OUTER"); } /**@var \BlackFox\SCRUD $Link */ $Link = $field['LINK']::I(); $key = $Link->key(); if (!empty($search)) { $filter = ['LOGIC' => 'OR']; foreach ($Link->fields as $code => $field) { if (!$field['VITAL']) continue; if ($field['TYPE'] === 'STRING') { $filter["~{$code}"] = $search; } if ($field['TYPE'] === 'NUMBER') { $filter["{$code}"] = $search; } } $filter = [$filter]; } else { $filter = []; } $data = $Link->Search([ 'FILTER' => $filter, 'PAGE' => $page, 'FIELDS' => ['@@'], 'LIMIT' => 5, 'ESCAPE' => false, ]); $results = []; foreach ($data['ELEMENTS'] as $element) { $results[] = [ 'id' => $element[$key], 'text' => "[{$element[$key]}] " . $Link->GetElementTitle($element), 'link' => $Link->GetAdminUrl() . "?{$key}={$element[$key]}", ]; } $more = $data['PAGER']['TOTAL'] > $data['PAGER']['CURRENT'] * $data['PAGER']['LIMIT']; return [ 'results' => $results, 'pagination' => ['more' => $more], ]; } catch (Exception $error) { return ['ERROR' => $error->GetArray()]; } } public function ExecuteAction($ID, $action_id, $action_params = []) { $action_params['ID'] = $ID; $ReflectionClass = new \ReflectionClass($this); if (!$ReflectionClass->hasMethod($action_id)) { throw new Exception(T([ 'en' => "Unknown method: '{$action_id}'", 'ru' => "Неизвестный метод: '{$action_id}'", ])); } $ReflectionMethod = $ReflectionClass->getMethod($action_id); $ReflectionParameters = $ReflectionMethod->getParameters(); $args = []; foreach ($ReflectionParameters as $ReflectionParameter) { $args[$ReflectionParameter->name] = $action_params[$ReflectionParameter->name]; } $result = $ReflectionMethod->invokeArgs($this, $args); $this->Redirect(null, (!empty($result) and is_string($result)) ? $result : T([ 'en' => "Action '{$this->actions[$action_id]['NAME']}' executed", 'ru' => "Действие '{$this->actions[$action_id]['NAME']}' выполнено", ])); } public function GetHref(array $element) { return '?' . http_build_query(array_merge($_GET, ['ID' => $element['ID']])); } }<file_sep><?php namespace BlackFox; /** * Class SCRUD -- Search, Create, Read, Update, Delete * * Предоставляет функционал для работы с источниками данных [с таблицами в базе данных]: * - синхронизация структуры таблицы со структурой, описанной в классе-наследнике (включая создание таблицы) * - Search - постраничный поиск [+ выборка] записей в таблице * - Create - создание записей * - Read - чтение первой подходящей по фильтрам записи * - Update - обновление записей * - Delete - удаление указанных записей * * Чтобы создать новый источник данных нужно: * - создать класс-наследник от SCRUD * - переопределить метод Init, определить в нем структуру данных $this->fields * - однократно запустить $this->Synchronize(), например в установщике модуля * - при необходимости переопределить другие методы (например проверки целостности при создании или редактировании записи) * - при необходимости добавить дополнительный функционал, описывающий бизнес-логику работы с данными */ abstract class SCRUD { use Instance; /** @var string последний выполненный SQL-запрос (для отладки) */ public $SQL; /** @var array части от последнего SQL-запроса (для отладки) */ public $parts; /** @var Database коннектор базы данных */ public $Database; /** @var string имя источника данных или таблицы или сущностей в ней */ public $name; /** @var string символьный код таблицы, формируется автоматически, возможно переопределить */ public $code; /** @var array массив полей базы данных */ public $fields = []; /** @var Type[] массив полей базы данных */ public $Types = []; /** @var array массив групп полей базы данных */ public $groups = []; /** @var array композиция групп полей и полей базы данных, формируется автоматически на основе $this->fields и $this->groups */ public $composition = []; /** @var array массив первичных ключей, формируется автоматически */ public $keys = []; /** @var string код авто-прирастающего поля */ public $increment = null; /** * Идентификатор */ const ID = [ 'TYPE' => 'INTEGER', // 'UNSIGNED' => true, // todo UNSIGNED 'NAME' => 'ID', 'INDEX' => true, 'PRIMARY' => true, 'NOT_NULL' => true, 'AUTO_INCREMENT' => true, 'DISABLED' => true, 'VITAL' => true, ]; public $actions = []; public function __construct(Database $Database) { $this->Database = $Database; $this->code = strtolower(implode('_', array_filter(explode('\\', static::class)))); $this->Init(); $this->ProvideIntegrity(); } /** * Returns the only one single primary key if it exist. * Otherwise throws exception. * * @return string * @throws Exception Single primary key required */ public function key() { if (count($this->keys) === 1) { return reset($this->keys); } throw new Exception(T([ 'en' => "Single primary key required for " . static::class, 'ru' => "Требуется одиночный основной ключ для " . static::class, ])); } /** * Обеспечивает целостность данных между свойствами: fields, groups, composition, keys. * - формирует keys перебором fields, * - дополняет groups перебором fields, * - формирует composition перебором groups и fields, * - переопределяет fields объектами Type */ public function ProvideIntegrity() { $this->composition = []; $this->keys = []; if (empty($this->name)) { $this->name = static::class; } if (empty($this->fields)) { throw new Exception(T([ 'en' => "Specify fields for '{$this->name}'", 'ru' => "Отсутствуют поля у '{$this->name}'", ])); } // init keys, increment foreach ($this->fields as $code => $field) { if ($field['PRIMARY']) { $this->keys[] = $code; } if ($field['AUTO_INCREMENT']) { $this->increment = $code; } if (empty($field['GROUP'])) { $this->fields[$code]['GROUP'] = 'ELEMENT'; $this->groups['ELEMENT'] = $this->groups['ELEMENT'] ?: T([ 'en' => 'Element', 'ru' => 'Элемент', ]); continue; } if (empty($this->groups[$field['GROUP']])) { $this->groups[$field['GROUP']] = "[{$field['GROUP']}]"; } } // init composition foreach ($this->groups as $group_code => $group_name) { $this->composition[$group_code] = [ 'NAME' => $group_name, 'FIELDS' => [], ]; foreach ($this->fields as $code => &$field) { if ($field['GROUP'] === $group_code) { $this->composition[$group_code]['FIELDS'][$code] = &$field; } } } if (empty($this->keys)) { throw new Exception(T([ 'en' => "Primary keys required for " . static::class, 'ru' => "Требуется основной ключ для " . static::class, ])); } foreach ($this->fields as $code => &$field) { $field['CODE'] = $code; // auto-completion of LINK attributes without namespaces if (!empty($field['LINK']) && !class_exists($field['LINK'])) { $link_namespace = (new \ReflectionClass($this))->getNamespaceName(); $link = $link_namespace . '\\' . $field['LINK']; if (class_exists($link)) { $field['LINK'] = $link; } else { throw new Exception(T([ 'en' => "Valid class name required for LINK of field '{$code}' of class " . static::class, 'ru' => "Требуется валидное имя класса для LINK-поля '{$code}' для класса " . static::class, ])); } } // init types $this->Types[$code] = FactoryType::I()->Get($field, $this->Database); } } /** * Инициализатор объекта, объявляется в классе-наследнике. * Может использовать другие объекты для формирования структуры. * Должен определить собственные поля: name, fields * Может определить собственные поля: groups, code */ public function Init() { } /** * Synchronize table fields structure from this class to database * * @return array * @throws Exception * @deprecated use class Scheme */ public function Synchronize() { return (new Scheme([$this]))->Synchronize(); } /** * Calculates difference between this class and database structure, * provides SQL code to update database structure * * @return array */ public function Compare() { return $this->Database->CompareTable($this); } /** * Эта функция -- обертка над функцией Select(). * Формирует данные для вывода страницы элементов вместе с постраничной навигацией. * По умолчанию устанавливает LIMIT = 100, PAGE = 1. * Возвращает ассоциативный массив с двумя ключами: * - ELEMENTS - массив элементов (массивов), то что вернула бы функция Select(), * - PAGER - массив для постраничной навигации с ключами: TOTAL, CURRENT, LIMIT, SELECTED * * @param array $params same as Select() * @return array * @throws Exception * @see \BlackFox\SCRUD::Select() */ public function Search($params = []) { $params['LIMIT'] = isset($params['LIMIT']) ? $params['LIMIT'] : 100; $params['PAGE'] = max(1, intval($params['PAGE'])); $result['ELEMENTS'] = $this->Select($params); $result['PAGER']['CURRENT'] = $params['PAGE']; $result['PAGER']['LIMIT'] = $params['LIMIT']; $result['PAGER']['SELECTED'] = count($result['ELEMENTS']); $SQL_for_total = $this->Database->CompileSQLSelect([ 'SELECT' => ['COUNT(*) as total'], 'TABLE' => $this->parts['TABLE'], 'JOIN' => $this->parts['JOIN'], 'WHERE' => $this->parts['WHERE'], ]); $this->SQL = [$this->SQL, $SQL_for_total]; $result['PAGER']['TOTAL'] = (int)$this->Database->Query($SQL_for_total)[0]['total']; return $result; } /** * Выбирает данные из таблицы * * $params - массив с ключами: * (можно передавать небезопасные данные, если не указано иное) * - SORT -- сортировка, одноуровневый ассоциативный массив, ключ - поле, значение - ASC|DESC * - FILTER -- пользовательский фильтр, многоуровневый смешанный массив * - CONDITIONS -- произвольные SQL условия для фильтрации (нельзя передавать небезопасные данные) * - FIELDS -- выбираемые поля, составной массив * - LIMIT -- количество элементов на странице (по умолчанию: *false*) * - PAGE -- номер страницы (по умолчанию: *1*) * - KEY -- по какому полю нумеровать элементы (по умолчанию: *$this->key()*, укажите *null* чтобы нумеровать по возрастанию) * - ESCAPE -- автоматически обрабатывать поля с выбором формата text/html в HTML-безопасный вид? (по умолчанию: *true*) * - GROUP -- группировка, лист, значение - код поля * - INNER_SORTS -- сортировки подцепляемых полей (тип Inner), ключ - код подцепляемого поля, значение - массив сортировки (аналогично SORT) * * @param array $params * @return array список выбранных элементов * @throws Exception */ public function Select($params = []) { $this->_controlParams($params, ['KEY', 'SORT', 'FILTER', 'CONDITIONS', 'FIELDS', 'LIMIT', 'PAGE', 'ESCAPE', 'GROUP', 'INNER_SORTS']); $defParams = [ 'SORT' => [], 'FILTER' => [], 'CONDITIONS' => [], 'FIELDS' => ['*@@'], 'LIMIT' => false, 'PAGE' => 1, 'ESCAPE' => true, 'GROUP' => [], 'INNER_SORTS' => [], ]; try { $defParams['KEY'] = $this->key(); $defParams['SORT'] = [$this->key() => 'DESC']; } catch (Exception $error) { $defParams['KEY'] = null; } $params += $defParams; $params['FIELDS'] = $this->ExplainFields($params['FIELDS']); // если в полях нет ключевого поля - добавить его if (!empty($params['KEY']) and !in_array($params['KEY'], $params['FIELDS'])) { $params['FIELDS'][$params['KEY']] = $params['KEY']; } // parts of SQL $this->parts = [ 'TABLE' => $this->code, 'SELECT' => [], 'JOIN' => [], 'WHERE' => [], 'ORDER' => [], 'GROUP' => [], 'LIMIT' => [], ]; $answer = $this->PreparePartsByFields($params['FIELDS']); $this->parts['SELECT'] += $answer['SELECT']; $this->parts['JOIN'] += $answer['JOIN']; $answer = $this->PreparePartsByFilter($params['FILTER']); $this->parts['WHERE'] += $answer['WHERE']; $this->parts['JOIN'] += $answer['JOIN']; $this->parts['GROUP'] += $answer['GROUP']; $params['CONDITIONS'] = is_array($params['CONDITIONS']) ? $params['CONDITIONS'] : [$params['CONDITIONS']]; $this->parts['WHERE'] += $params['CONDITIONS']; $answer = $this->PreparePartsByGroup($params['GROUP']); $this->parts['JOIN'] += $answer['JOIN']; $this->parts['GROUP'] += $answer['GROUP']; $answer = $this->PreparePartsBySort($params['SORT']); $this->parts['ORDER'] += $answer['ORDER']; $this->parts['JOIN'] += $answer['JOIN']; $this->parts['GROUP'] += $answer['GROUP']; if ($params['LIMIT'] > 0) { $this->parts['LIMIT'] = [ 'FROM' => ($params['PAGE'] - 1) * $params['LIMIT'], 'COUNT' => $params['LIMIT'], ]; } $this->SQL = $this->Database->CompileSQLSelect($this->parts); $elements = $this->Query($this->SQL, $params['KEY']); foreach ($elements as &$row) { $row = $this->FormatArrayKeysCase($row); $row = $this->FormatListStructure($row); $row = $this->FormatOutputValues($row); if ($params['ESCAPE']) { array_walk_recursive($row, function (&$value) { $value = htmlspecialchars($value); }); } } $elements = $this->HookExternalFields($elements, $params['FIELDS'], $params['INNER_SORTS']); return $elements; } /** * Контролирует соответствие массива параметров заданному листу допустимых параметров. * В случае несоответствия кидает ошибку. * * @param array $params массив контролируемых параметров * @param array $keys лист допустимых параметров * @throws Exception Переданы некорректные параметры ... */ private function _controlParams($params = [], $keys = []) { $errors = []; foreach ($params as $key => $value) { if (!in_array($key, $keys)) { $errors[] = $key; } } if (!empty($errors)) { throw new Exception(T([ 'en' => "Wrong params: [" . implode(", ", $errors) . "], allowed params: [" . implode(", ", $keys) . "]", 'ru' => "Переданы некорректные параметры: [" . implode(", ", $errors) . "], допускаются только следующие параметры: [" . implode(", ", $keys) . "]", ])); } } /** * Выбирает первый элемент по фильтру. Можно указать поля и сортировку. * * @param mixed $filter идентификатор | список идентификаторов | ассоциатив фильтров * @param array|string $fields выбираемые поля * @param array $sort сортировка * @param bool $escape автоматически обрабатывать поля с выбором формата text/html в HTML-безопасный вид? (по умолчанию TRUE) * @return array|false ассоциативный массив, представляющий собой элемент * @throws Exception */ public function Read($filter, $fields = ['*@@'], $sort = [], $escape = true) { return reset($this->Select([ 'FILTER' => $filter, 'FIELDS' => $fields, 'SORT' => $sort, 'ESCAPE' => $escape, 'LIMIT' => 1, ])); } /** * Возвращает значение искомого поля первого элемента по фильтру. Можно указать сортировку. * * @param mixed $filter идентификатор | список идентификаторов | ассоциатив фильтров * @param string $field выбираемое поле * @param array $sort сортировка * @param bool $escape автоматически обрабатывать поля с выбором формата text/html в HTML-безопасный вид? (по умолчанию TRUE) * @return mixed значение искомого поля * @throws Exception */ public function GetCell($filter, $field, $sort = [], $escape = true) { return $this->Read($filter, [$field], $sort, $escape)[$field]; } /** * Проверяет присутствует ли элемент с указанным идентификатором в таблице * * @param mixed $filter идентификатор | список идентификаторов | ассоциатив фильтров * @return boolean true - если присутствует, false - если не присутствует * @throws Exception */ public function Present($filter) { return (bool)$this->Read($filter, $this->keys); } /** * Выбирает список идентификаторов\значений указанной колонки. * * @param mixed $filter идентификатор | список идентификаторов | ассоциатив фильтров * @param string $field символьный код выбираемой колонки (не обязательно, по умолчанию - идентификатор) * @param array $sort сортировка (не обязательно) * @param bool $escape * @return array массив идентификаторов элементов * @throws Exception */ public function GetColumn($filter = [], string $field = null, array $sort = [], bool $escape = false) { $field = $field ?: $this->key(); $elements = $this->Select([ 'FILTER' => $filter, 'FIELDS' => [$field], 'SORT' => $sort, 'ESCAPE' => $escape, ]); $rows = []; foreach ($elements as $key => $element) { $rows[$key] = $element[$field]; } return $rows; } /** * Вычисляет количество элементов, подходящих под фильтр. * * @param mixed $filter идентификатор | список идентификаторов | ассоциатив фильтров * @return int * @throws Exception */ public function Count($filter = []) { $answer = $this->PreparePartsByFilter($filter); $this->SQL = $this->Database->CompileSQLSelect([ 'SELECT' => ['COUNT(*) as total'], 'TABLE' => $this->code, 'JOIN' => $answer['JOIN'], 'WHERE' => $answer['WHERE'], // 'GROUP' => $answer['GROUP'], // ??? ]); return (int)$this->Database->Query($this->SQL)[0]['total']; } /** * Вычисляет сумму элементов, подходящих под фильтр. * * @param mixed $filter идентификатор | список идентификаторов | ассоциатив фильтров * @param mixed $field колонка для подсчета суммы * @return int * @throws Exception */ public function Sum($filter = [], $field = '') { $answer = $this->PreparePartsByFilter($filter); $this->SQL = $this->Database->CompileSQLSelect([ 'SELECT' => ['SUM(' . $this->Database->Quote($field) . ') as total'], 'TABLE' => $this->code, 'JOIN' => $answer['JOIN'], 'WHERE' => $answer['WHERE'], // 'GROUP' => $answer['GROUP'], // ??? ]); return (int)$this->Database->Query($this->SQL)[0]['total']; } /** * Анализирует значение на наличие информации. * - 0 - информация присутствует * - 0.0 - информация присутствует * - '0' - информация присутствует * - false - информация присутствует * - null - информация отсутствует * - empty array() - информация отсутствует * - '' - информация отсутствует * - в других случаях - информация присутствует * * Отсутствие информации в переменных PHP эквивалетно в SQL значению NULL: * PHP null == PHP empty array() == PHP '' == SQL NULL == SQL '' * * @param mixed $value значение * @return boolean флаг наличия информации */ public function _hasInformation($value) { if ($value === 0 || $value === 0.0 || $value === '0' || $value === false) { return true; } if (empty($value)) { return false; } return true; } /** * Формирует часть SQL запроса "SET ..., ..., ..." для вставки\изменения. * Если значение пустая строка или null - возвращает "... = NULL". * Если значение пустая строка или null, а поле NOT_NULL - ошибка. * * @param string $code код поля * @param mixed $value значение поля * @return string подстрока для SQL * @throws Exception Поле ... не может быть пустым */ private function _prepareSet($code, $value) { $hasInformation = $this->_hasInformation($value); if (($this->fields[$code]['NOT_NULL'] || $this->fields[$code]['TYPE'] == 'BOOL') && !$hasInformation) { throw new Exception(T([ 'en' => "Field '{$this->fields[$code]['NAME']}' can not be empty", 'ru' => "Поле '{$this->fields[$code]['NAME']}' не может быть пустым", ])); } if ($hasInformation) { $value = $this->_formatFieldValue($code, $value); if (!is_null($value)) { $set = $this->Database->Quote($code) . " = '{$value}'"; } else { $set = $this->Database->Quote($code) . " = NULL"; } } else { $set = $this->Database->Quote($code) . " = NULL"; } return $set; } /** * Создает новые строки в таблице * * @param array $elements лист ассоциативных массивов полей для новых строк * @throws Exception */ public function Insert($elements) { $errors = []; foreach ($elements as $element) foreach ($this->fields as $code => $field) if ($field['NOT_NULL'] && !$field['AUTO_INCREMENT'] && !isset($field['DEFAULT'])) if (!$this->_hasInformation($element[$code])) $errors[] = "Field must be specified: '{$field['NAME']}'"; if ($errors) throw new Exception($errors); $codes = []; foreach ($this->fields as $code => $field) if (!$field->virtual) $codes[] = $this->Database->Quote($code); $rows = []; foreach ($elements as $element) { $values = []; foreach ($this->fields as $code => $field) { if ($field->virtual) continue; if (array_key_exists($code, $element)) { $value = $this->_formatFieldValue($code, $element[$code]); $values[] = is_null($value) ? 'NULL' : "'{$value}'"; } else { $values[] = 'DEFAULT'; } } $rows[] = "\r\n" . '(' . implode(', ', $values) . ')'; } $this->SQL = "INSERT INTO {$this->code} (" . implode(', ', $codes) . ") \r\n VALUES " . implode(', ', $rows); $this->Database->Query($this->SQL); } /** * Создает новую строку в таблице и возвращает ее идентификатор * * @param array $element ассоциативный массив полей для новой строки * @return int|string идентификатор созданной строки * @throws Exception */ public function Create($element) { if (empty($element)) { $this->SQL = "INSERT INTO {$this->code} VALUES ()"; return $this->Database->QuerySingleInsert($this->SQL, $this->increment); } $errors = []; foreach ($this->fields as $code => $field) if ($field['NOT_NULL'] && !$field['AUTO_INCREMENT'] && !isset($field['DEFAULT'])) if (!$this->_hasInformation($element[$code])) $errors[] = T([ 'en' => "Field must be specified: '{$field['NAME']}'", 'ru' => "Не указано обязательное поле '{$field['NAME']}'", ]); if ($errors) throw new Exception($errors); $codes = []; $values = []; foreach ($this->fields as $code => $field) { if (array_key_exists($code, $element)) { $codes[] = $this->Database->Quote($code); $value = $this->_formatFieldValue($code, $element[$code]); $values[] = is_null($value) ? 'NULL' : "'{$value}'"; } } $this->SQL = "INSERT INTO {$this->code} (" . implode(', ', $codes) . ") \r\n VALUES (" . implode(', ', $values) . ')'; return $this->Database->QuerySingleInsert($this->SQL, $this->increment); } /** * Изменяет значения указанных элементов. * * @param mixed $filter идентификатор | список идентификаторов | ассоциатив фильтров * @param array $element ассоциативный массив изменяемых полей * @throws Exception Нет информации для обновления * @throws Exception Поле ... не может быть пустым */ public function Update($filter = [], $element = []) { if (empty($element)) { throw new Exception(T([ 'en' => "No data to update", 'ru' => 'Нет данных для обновления', ])); } $this->SQL = "UPDATE {$this->code} SET "; $rows = []; foreach ($this->fields as $code => $field) { if (array_key_exists($code, $element)) { $rows[] = $this->_prepareSet($code, $element[$code]); } } if (empty($rows)) { throw new Exception(T([ 'en' => "No rows to update", 'ru' => 'Нет строк для обновления', ])); } $this->SQL .= implode(",\r\n", $rows); $answer = $this->PreparePartsByFilter($filter); $this->SQL .= "\r\n WHERE " . implode(' AND ', $answer['WHERE']); $this->Query($this->SQL); } /** * Удаляет строки из таблицы * * @param mixed $filter идентификатор | список идентификаторов | ассоциатив фильтров * @throws Exception * @throws ExceptionSQL */ public function Delete($filter = []) { if (empty($filter)) { $this->SQL = "DELETE FROM {$this->code}"; } else { $answer = $this->PreparePartsByFilter($filter); $this->SQL = "DELETE FROM {$this->code} WHERE " . implode(' AND ', $answer['WHERE']); } $this->Query($this->SQL); } /** * Создает массивы для выборки и джоинов * * @param array $fields поля для выборки * @param string $prefix префикс * @return array массив из двух элементов: * - SELECT - [] * - JOIN - [] * @throws Exception */ public function PreparePartsByFields($fields, $prefix = "") { $select = []; $join = []; foreach ($fields as $code => $content) { if (!is_array($content)) { $code = strtoupper($content); $subfields = null; } else { $code = strtoupper($code); $subfields = $content; } unset($content); if (empty($this->fields[$code])) { throw new Exception(T([ 'en' => "Unknown field code: '{$code}' in table '{$this->code}'", 'ru' => "Неизвестный код поля: '{$code}' в таблице '{$this->code}'", ])); } $result = $this->Types[$code]->PrepareSelectAndJoinByField($this->code, $prefix, $subfields); $select += (array)$result['SELECT']; $join += (array)$result['JOIN']; } return [ 'SELECT' => $select, 'JOIN' => $join, ]; } /** * Подготавливает часть SQL запроса WHERE из фильтра. * Значения в фильтре могут быть: * - *значение* - фильтр будет формироваться по всем правилам * - 0 (zero) - фильтр будет формироваться по всем правилам * - "" (empty string) - фильтр не будет формироваться * - null - фильтр сформируется в "[NOT] IS NULL" * - лист значений - сформируется набор ".. IN (...) [OR ... [NOT] IS NULL]" * * Ключи в фильтре могут быть: * - <символьный код поля> * - <символьный код поля типа ссылка>.<символьный код поля внешнего объекта> * - <символьный код поля типа ссылка>.<символьный код поля типа ссылка>.<символьный код поля внешнего объекта> * - ... * - OR или AND * * Ключи поддерживают префиксы: * - = - равно (по умолчанию) * - ! - не равно * - <> - не равно * - > - больше либо равно * - < - меньше либо равно * - >> - строго больше * - << - строго меньше * - ~ - LIKE * * @param mixed $filter ассоциатив фильтров | список идентификаторов | идентификатор * @return array : * - WHERE - массив строк, представляющих собой SQL-условия, которые следует объеденить операторами AND или OR * - JOIN - ассоциативный массив уникальных SQL-строк, описывающий присоединяемые таблицы * - GROUP - ассоциативный массив уникальных SQL-строк, описывающий группировку * @throws Exception */ public function PreparePartsByFilter($filter) { if (!is_array($filter) and empty($filter)) { throw new ExceptionNotAllowed(T([ 'en' => 'Empty non-array filter passed (ID missed?)', 'ru' => 'Передан пустой скалярный фильтр (потерялся ID?)', ])); } if (is_array($filter) and empty($filter)) { return [ 'WHERE' => [], 'JOIN' => [], 'GROUP' => [], ]; } if (!is_array($filter)) { // filter is identifier $filter = [$this->key() => $filter]; } // if array does not has string keys if (count(array_filter(array_keys($filter), 'is_string')) === 0) { // and if array does not has array values if (count(array_filter($filter, 'is_array')) === 0) { // filter is list of identifiers $filter = [$this->key() => $filter]; } } $where = []; $join = []; $group = []; foreach ($filter as $filter_key => $values) { if ($values === '') { continue; } // вложенные операторы AND и OR if ($filter_key === 'AND' || $filter_key === 'OR' || is_numeric($filter_key)) { if (!is_array($values)) { throw new Exception(T([ 'en' => 'When using nested AND and OR operators in a filter, the value must be an array of conditions', 'ru' => 'При использовании в фильтре вложенных операторов AND и OR значение должно быть массивом условий', ])); } if (!is_numeric($filter_key)) { $logic = $filter_key; } else { $logic = $values['LOGIC']; if (!in_array($logic, ['AND', 'OR'])) { throw new Exception(T([ 'en' => 'When using a digital key in the filter, the array value must contain the key LOGIC = AND|OR', 'ru' => 'При использовании в фильтре цифрового ключа значение-массив должно содержать ключ LOGIC = AND|OR', ])); } unset($values['LOGIC']); } $answer = $this->PreparePartsByFilter($values); if (!empty($answer['WHERE'])) { $where[] = '(' . implode(" {$logic} ", $answer['WHERE']) . ')'; } $join += $answer['JOIN']; $group += $answer['GROUP']; continue; } // вычисление ключа // possible $key : >>FIELD // possible $key : >>EXTERNAL_FIELD.FIELD // possible $key : >>EXTERNAL_FIELD.EXTERNAL_FIELD.FIELD // possible $key : ... preg_match('/^(?P<operator>\W*)(?P<field_path>[a-zA-Z_\.]+)/', $filter_key, $matches); $operator = $matches['operator']; // >> $field_path = $matches['field_path']; $result = $this->_treatFieldPath($field_path); /** @var self $Object */ $Object = $result['OBJECT']; $table = $result['TABLE']; $code = $result['CODE']; $join += $result['JOIN']; $group += $result['GROUP']; if (empty($Object->fields[$code])) { throw new Exception("Can't form filter: unknown field '{$code}'"); } $conditions = $Object->Types[$code]->PrepareConditions($table, $operator, $values); $conditions = "(" . implode(' OR ', $conditions) . ")"; $where[] = $conditions; } return [ 'WHERE' => $where, 'JOIN' => $join, 'GROUP' => $group, ]; } /** * Обрабатывает путь к полю. * Вычисляет объект для обработки поля, псевдоним таблицы и код поля. * Возвращает структуру с ключами: * - OBJECT - объект-наследник SCRUD для обработки поля * - TABLE - псевдоним для таблицы (alias) * - PATH - путь к полю в виде простого списка кодов полей (не включая код финального поля) * - CODE - код финального поля * - JOIN - ассоциативный массив уникальных SQL-строк, описывающий присоединяемые таблицы * - GROUP - ассоциативный массив уникальных SQL-строк, описывающий группировку * * @param string $field_path мнемонический путь к полю, например: 'EXTERNAL_FIELD.EXTERNAL_FIELD.FIELD' * @return array * @throws Exception Unknown external field code * @throws Exception Field is not external */ protected function _treatFieldPath($field_path) { $path = explode(".", $field_path); // EXTERNAL_FIELD.EXTERNAL_FIELD.FIELD $code = array_pop($path); // FIELD if (empty($path)) { return [ 'OBJECT' => $this, 'TABLE' => $this->code, 'PATH' => $path, 'CODE' => $code, 'JOIN' => [], 'GROUP' => [], 'TYPE' => [], ]; } // if (!empty($path)): /** @var self $Object */ /** @var Type $Type */ $Object = $this; $prefix = ''; $join = []; $group = []; foreach ($path as $external) { $fields = &$Object->fields; $types = &$Object->Types; $field = $fields[$external]; $Type = $types[$external]; if (empty($field)) { throw new Exception(T([ 'en' => "Unknown external field code: '{$external}'", 'ru' => "Передан код неизвестного внешнего поля: '{$external}'", ])); } if (empty($field['LINK'])) { throw new Exception(T([ 'en' => "Field is not external: '{$external}'", 'ru' => "Поле не является внешним: '{$external}'", ])); } $answer = $Type->GenerateJoinAndGroupStatements($Object, $prefix); $join += $answer['JOIN']; $group += $answer['GROUP']; // for next iteration $prefix .= $external . "__"; $Object = $field['LINK']::I(); } return [ 'OBJECT' => $Object, 'TABLE' => $prefix . $Object->code, 'PATH' => $path, 'CODE' => $code, 'JOIN' => $join, 'GROUP' => $group, ]; } public function PreparePartsBySort(array $array) { $order = []; $join = []; $group = []; foreach ($array as $field_path => $sort) { if ('{RANDOM}' === $field_path) { $order[] = $this->Database->Random(); continue; } if (!in_array($sort, ['ASC', 'DESC'])) { throw new Exception(T([ 'en' => 'Unknown sort: ' . $sort, 'ru' => 'Неизвестная сортировка: ' . $sort, ])); } $result = $this->_treatFieldPath($field_path); $join += $result['JOIN']; $group += $result['GROUP']; if (count($result['PATH']) > 0) { if (is_a($this->Types[$result['PATH'][0]], 'BlackFox\TypeInner')) { $func = ['ACS' => 'MIN', 'DESC' => 'MAX'][$sort]; $order[] = "{$func}({$result['TABLE']}." . $this->Database->Quote($result['CODE']) . ") {$sort}"; continue; } } $order[] = "{$result['TABLE']}." . $this->Database->Quote($result['CODE']) . " {$sort}"; } return [ 'ORDER' => $order, 'JOIN' => $join, 'GROUP' => $group, ]; } /** * Подготавливает часть SQL запроса GROUP BY * * @param array $array Массив фильтра GROUP * @return array Массив с ключами GROUP BY * @throws Exception */ public function PreparePartsByGroup($array) { $group = []; $join = []; foreach ($array as $field_path) { $result = $this->_treatFieldPath($field_path); $group[] = $this->Database->Quote($result['TABLE']) . '.' . $this->Database->Quote($result['CODE']); $join += $result['JOIN']; } return [ 'GROUP' => $group, 'JOIN' => $join, ]; } /** * Приводит значение в соответствие формату поля. * - Числовые - приводит к числу нужного формата. * - Строковые - обрезает по нужному размеру. * - Списковые - подставляет корректное значение. * - Битовые - подставляет true|false. * - Даты - подставляет дату в формате базы данных. * - Файловые - сохраняет файл в BlackFox\Files и выдает его идентификатор. * * @param string $code код поля * @param mixed $value значение * @return mixed приведенное к формату значение * @throws Exception Unknown field code */ protected function _formatFieldValue($code, $value) { $code = strtoupper($code); if (!isset($this->fields[$code])) { throw new Exception(T([ 'en' => "Unknown field code: '{$code}'", 'ru' => "Неизвестный код поля: '{$code}'", ])); } if (!$this->_hasInformation($value)) { return null; } $value = $this->Types[$code]->FormatInputValue($value); return $this->Database->Escape($value); } /** * Повышает регистр ключей массива на первом уровне вложенности * * @param array $input Входной массив * @return array Выходной массив */ public function FormatArrayKeysCase($input) { return array_change_key_case($input, CASE_UPPER); } /** * Возвращает экземпляр класса SCRUD, на который ссылается поле * * @param mixed $field массив, описывающий поле (с ключем LINK) * @return SCRUD экземпляр * @throws ExceptionNotAllowed */ private function GetLink($field) { if (!class_exists($field['LINK'])) { throw new ExceptionNotAllowed(T([ 'en' => "You must set class name to LINK info of field '{$field['CODE']}' of table '{$this->code}'; now: '{$field['LINK']}'", 'ru' => "Необходимо установить имя класса в ключ LINK поля '{$field['CODE']}' таблицы '{$this->code}'; установлено: '{$field['LINK']}'", ])); } $parents = class_parents($field['LINK']); if (!in_array('BlackFox\SCRUD', $parents)) { throw new ExceptionNotAllowed(T([ 'en' => "You must set class (child of SCRUD) name to LINK info of field '{$field['CODE']}' of table '{$this->code}'; now: '{$field['LINK']}'", 'ru' => "Необходимо установить имя класса (наследник от SCRUD) в ключ LINK поля '{$field['CODE']}' таблицы '{$this->code}'; установлено: '{$field['LINK']}'", ])); } /** @var SCRUD $Link */ $Link = $field['LINK']::I(); return $Link; } public function ExplainFields($fields) { $output = []; foreach ($fields as $key => $value) { if (is_numeric($key) and is_array($value)) { throw new ExceptionNotAllowed("{$this->name}->ExplainFields: Numeric key '{$key}' with array value"); } $o_key = is_numeric($key) ? $value : $key; if (is_array($value)) { if (!isset($this->fields[$key])) { throw new Exception("{$this->name}->ExplainFields: Unknown field with code '{$key}'"); } $output[$o_key] = $this->GetLink($this->fields[$key])->ExplainFields($value); continue; } // if (!is_array($value)): $first_symbol = substr($value, 0, 1); if (!in_array($first_symbol, ['*', '@'])) { $output[$o_key] = $value; continue; } // if (in_array($first_symbol, ['*', '@'])): $last_symbols = substr($value, 1); foreach ($this->fields as $code => $field) { if ($first_symbol === '@' and !$field['VITAL']) { continue; } if (!isset($field['LINK'])) { $output[$code] = $code; continue; } if (empty($last_symbols)) { $output[$code] = $code; continue; } $output[$code] = $this->GetLink($field)->ExplainFields([$last_symbols]); continue; } } return $output; } /** * Преобразует одномерный ассоциативный массив с ключами типа ["EXTERNAL__NAME"] * древовидный ассоциативный массив с ключами типа ["EXTERNAL"]["NAME"]. * Поддерживается неограниченная вложенность. * * @param array $list одномерный ассоциативный массив * @param string $separator разделитель * @return array древовидный ассоциативный массив */ public function FormatListStructure($list, $separator = "__") { $element = []; foreach ($list as $code => $value) { $codes = explode($separator, $code); $link = &$element; foreach ($codes as $path) { $link = &$link[$path]; } $link = $value; } return $element; } /** * Format output element values from database to user. * No escape. * * @param array $element output element * @return array output element with formatted values * @throws Exception Unknown field code */ public function FormatOutputValues($element) { if (!is_array($element)) { return $element; } foreach ($element as $code => $value) { $field = $this->fields[$code]; if (empty($field)) { throw new Exception(T([ 'en' => "Unknown field code '{$code}'", 'ru' => "Неизвестный код поля '{$code}'", ])); } $element = $this->Types[$code]->FormatOutputValue($element); } return $element; } /** * Удаляет все данные из таблицы не затрагивая структуру. */ public function Truncate() { $this->Database->Truncate($this->code); } /** * Удаляет таблицу. */ public function Drop() { $this->Database->Drop($this->code); } /** * Исполняет SQL-запрос, не останавливая выполнение в случае ошибки. * Вместо этого кидает исключение (с текстом ошибки для администраторов). * * @param string $SQL SQL-запрос * @param string $key код колонки значения которой будут использованы как ключ в результирующем массиве (не обязательно) * @return array|int результат выполнения * @throws ExceptionSQL * @throws Exception */ public function Query($SQL, $key = null) { return $this->Database->Query($SQL, $key); } /** * Извлекает набор полей, состоящий из указанных полей. * Используется в компонентах для подготовки форм. * * @param array $codes линейный массив символьных кодов полей * @return array структура */ public function ExtractFields($codes = []) { $fields = []; foreach ($codes as $code) { if (isset($this->fields[$code])) { $fields[$code] = $this->fields[$code]; } } return $fields; } public function GetAdminUrl() { $name = get_called_class(); $name = str_replace('\\', '/', $name); return "/admin/{$name}.php"; } public function GetElementTitle(array $element) { return $element['TITLE'] ?: $element['ID'] ?: null; } /** * Для всех полей в выборке запускает метод HookExternalField. * Это позволяет типу поля подцеплять внешние данные к элементам выборки (если это требуется). * Например тип TypeInner подцепляет все внешние элементы, ссылающиеся на выбранные элементы. * * @param array $elements элементы выборки * @param array $fields * @param array $inner_sorts * @return array элементы выборки, дополненные внешними данными */ private function HookExternalFields($elements, $fields, $inner_sorts) { if (empty($elements)) return $elements; foreach ($fields as $key => $value) { if (!is_array($value)) { $code = strtoupper($value); $subfields = null; } else { $code = strtoupper($key); $subfields = $value; } $subsort = $inner_sorts[$code] ?: []; $elements = $this->Types[$code]->HookExternalField($elements, $subfields, $subsort); } return $elements; } } <file_sep><?php namespace BlackFox; class Log extends SCRUD { public function Init() { $this->name = T([ 'en' => 'Log', 'ru' => 'Журнал', ]); $this->fields = [ 'ID' => self::ID, 'MOMENT' => [ 'TYPE' => 'DATETIME', 'NAME' => T([ 'en' => 'Moment', 'ru' => 'Момент', ]), 'NOT_NULL' => true, ], 'IP' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'IP address', 'ru' => 'IP адрес', ]), ], 'USER' => [ 'TYPE' => 'OUTER', 'NAME' => T([ 'en' => 'User', 'ru' => 'Пользователь', ]), 'INDEX' => true, 'LINK' => 'Users', ], 'TYPE' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Event type', 'ru' => 'Тип события', ]), 'DESCRIPTION' => T([ 'en' => 'Symbolic code', 'ru' => 'Символьный код', ]), 'NOT_NULL' => true, 'INDEX' => true, ], 'MESSAGE' => [ 'TYPE' => 'TEXT', 'NAME' => T([ 'en' => 'Message', 'ru' => 'Сообщение', ]), ], 'DATA' => [ 'TYPE' => 'ARRAY', 'NAME' => T([ 'en' => 'Additional data', 'ru' => 'Дополнительные данные', ]), ], ]; } public function Create($fields) { $fields['MOMENT'] = time(); $fields['USER'] = $fields['USER'] ?: $_SESSION['USER']['ID']; $fields['IP'] = $_SERVER['REMOTE_ADDR']; return parent::Create($fields); } public function Update($filter = [], $fields = []) { throw new ExceptionNotAllowed(); } public function Delete($filter = []) { throw new ExceptionNotAllowed(); } } <file_sep><?php namespace BlackFox; class Pages extends SCRUD { public function Init() { $this->name = T([ 'en' => 'Content pages', 'ru' => 'Контентные страницы', ]); $this->fields = [ 'ID' => self::ID, 'URL' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Url', 'ru' => 'Адрес', ]), 'NOT_NULL' => true, 'INDEX' => true, 'UNIQUE' => true, 'DESCRIPTION' => T([ 'en' => 'Relative to the site root', 'ru' => 'Относительно корня сайта', ]), ], 'TITLE' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Title', 'ru' => 'Заголовок', ]), ], 'DESCRIPTION' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Description', 'ru' => 'Описание', ]), ], 'KEYWORDS' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Key words', 'ru' => 'Ключевые слова', ]), ], 'CONTENT' => [ 'TYPE' => 'TEXT', 'NAME' => T([ 'en' => 'Content', 'ru' => 'Содержимое', ]), 'WYSIWYG' => true, ], ]; } } <file_sep><?php /** @var \BlackFox\Engine $this */ $this->TITLE = 'Welcome'; ?> <p>This is an example main page</p><file_sep><?php /** @var \BlackFox\Engine $this */ ?> <?php /** @var array $errors */ ?> <? foreach ($errors as $error): ?> <div class="alert alert-danger"><?= $error ?></div> <? endforeach; ?><file_sep>This is an example of your server root folder. Tasks: - copy this folder into your server root - rename subfolder 'Site' with the unique name of your project's folder\namespace - update config.php - delete this file<file_sep><?php /** @var \BlackFox\Adminer $this */ ?> <?php /** @var array $RESULT */ ?> <? @include($this->PathInclude('element_actions.php')); ?> <form method="post" enctype="multipart/form-data" class="form-horizontal"> <input type="hidden" name="ACTION" value="<?= $RESULT['MODE'] ?>"/> <? @include($this->PathInclude('element_head.php')); ?> <? foreach ($this->SCRUD->composition as $group_code => $group): ?> <? if (!empty($group['FIELDS'])): ?> <? if (count($this->SCRUD->composition) > 1): ?> <h3 class="group_header" title="<?= $group_code ?>"><?= $group['NAME'] ?></h3> <? endif; ?> <? endif; ?> <? foreach ($group['FIELDS'] as $code => $field): ?> <div class="form-group row"> <label class="col-sm-3 col-form-label text-sm-right <?= ($field['NOT_NULL']) ? 'mandatory' : '' ?> <?= ($field['VITAL']) ? 'vital' : '' ?>" for="FIELDS[<?= $code ?>]" title="<?= $code ?>" > <?= $field['NAME'] ?: "{{$code}}" ?> </label> <div class="col-sm-8"> <? // ------------------------------------------------------------------------------------------- $this->SCRUD->Types[$code]->PrintFormControl($RESULT['DATA'][$code], "FIELDS[{$code}]"); // ------------------------------------------------------------------------------------------- ?> </div> <div class="col-sm-1 col-form-label d-none d-sm-inline-block"> <? if ($field['DESCRIPTION']): ?> <span class="material-icons" title="<?= $field['DESCRIPTION'] ?>" data-toggle="tooltip" >info</span> <? endif; ?> </div> </div> <? endforeach; ?> <? endforeach; ?> <? @include($this->PathInclude('element_foot.php')); ?> <hr/> <div class="buttons"> <? @include($this->PathInclude('element_bottom_buttons.php')); ?> </div> </form><file_sep><?php namespace BlackFox; class TypeOuter extends Type { public $db_type = 'int'; public function ProvideInfoIntegrity() { parent::ProvideInfoIntegrity(); if (empty($this->field['LINK'])) { throw new ExceptionNotAllowed(T([ 'en' => "You must set class name to LINK info of field '{$this->field['CODE']}'", 'ru' => "Необходимо установить имя класса в ключ LINK поля '{$this->field['CODE']}'", ])); } } public function FormatInputValue($value) { if (!is_numeric($value)) { throw new ExceptionType(T([ 'en' => "Expected numerical value for '{$this->field['CODE']}', received: '{$value}'", 'ru' => "Ожидалось числовое значение для '{$this->field['CODE']}', получено: '{$value}'", ])); } return (int)$value; } public function FormatOutputValue($element) { /** @var SCRUD $Link */ $Link = $this->field['LINK']; $code = $this->field['CODE']; if (empty($Link)) { throw new ExceptionType("Field '{$code}': link must be specified"); } if (!in_array('BlackFox\SCRUD', class_parents($Link))) { throw new ExceptionType("Field '{$code}': link '{$Link}' must be SCRUD child"); } $element[$code] = $Link::I()->FormatOutputValues($element[$code]); return $element; } public function PrepareSelectAndJoinByField($table, $prefix, $subfields) { if (empty($subfields)) { return parent::PrepareSelectAndJoinByField($table, $prefix, null); } $code = $this->field['CODE']; /** @var SCRUD $Link */ $Link = $this->field['LINK']::I(); $external_prefix = $prefix . $code . "__"; $raw_link_code = $external_prefix . $Link->code; $join = "LEFT JOIN {$Link->code} AS {$raw_link_code} ON {$prefix}{$table}." . $this->DB->Quote($code) . " = {$raw_link_code}." . $this->DB->Quote($Link->key()); $RESULT = $Link->PreparePartsByFields($subfields, $external_prefix); $RESULT['JOIN'] = array_merge([$raw_link_code => $join], $RESULT['JOIN']); return $RESULT; } public function GenerateJoinAndGroupStatements(SCRUD $Current, $prefix) { // debug($this->info, '$this->info'); /** @var SCRUD $Target */ $Target = $this->field['LINK']::I(); $current_alias = $prefix . $Current->code; $current_key = $this->field['CODE']; $target_alias = $prefix . $this->field['CODE'] . '__' . $Target->code; $target_key = $Target->key(); $statement = "LEFT JOIN {$Target->code} AS {$target_alias} ON {$current_alias}." . $this->DB->Quote($current_key) . " = {$target_alias}." . $this->DB->Quote($target_key); return [ 'JOIN' => [$target_alias => $statement], 'GROUP' => [], ]; } public function PrintValue($value) { /** @var \BlackFox\SCRUD $Link */ $Link = $this->field['LINK']::I(); $url = $Link->GetAdminUrl(); $ID = is_array($value) ? $value['ID'] : $value; ?> <? if ($ID and User::I()->InGroup('root')): ?> <nobr>[<a target="_top" href="<?= $url ?>?ID=<?= $ID ?>"><?= $ID ?></a>]</nobr> <? endif; ?> <?= $Link->GetElementTitle($value); ?> <? } public function PrintFormControl($value, $name, $class = 'form-control') { // TODO move to Adminer ? /** @var \BlackFox\SCRUD $Link */ $Link = $this->field['LINK']::I(); $code = $this->field['CODE']; $ID = is_array($value) ? $value['ID'] : $value; if (!is_array($value) and !empty($value)) { $value = $Link->Read($value, ['@@']); } ?> <div class="d-flex flex-fill" data-outer="" > <a target="_blank" class="btn btn-secondary flex-shrink-1" href="<?= $ID ? $Link->GetAdminUrl() . "?ID={$ID}" : 'javascript:void(0);' ?>" data-outer-link="" > <?= $ID ? "№{$ID}" : '...' ?> </a> <div class="flex-grow-1"> <select class="form-control" id="<?= $name ?>" name="<?= $name ?>" data-link-input="<?= $name ?>" <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> data-type="OUTER" data-code="<?= $code ?>" > <? if (!$this->field['NOT_NULL']): ?> <option value=""></option> <? endif; ?> <? if (!empty($ID)): ?> <option value="<?= $ID ?>" selected="selected" ><?= $Link->GetElementTitle($value) ?></option> <? endif; ?> </select> </div> <? if (!$this->field['DISABLED'] and !$this->field['NOT_NULL']): ?> <button type="button" class="btn btn-secondary flex-shrink-1" data-outer-clean="" > <span class="material-icons">link_off</span> </button> <? endif; ?> </div> <? } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { /** @var \BlackFox\SCRUD $Link */ $Link = $this->field['LINK']::I(); $code = $this->field['CODE']; $IDs = $filter[$code]; if (is_array($IDs) and count($IDs) === 1) { $IDs = reset($IDs); } $elements = !empty($IDs) ? $Link->Select([ 'FILTER' => ['ID' => $IDs], 'FIELDS' => ['@@'], ]) : []; ?> <? if (!is_array($IDs)): ?> <div class="d-flex flex-fill" data-outer="" > <button type="button" class="btn btn-secondary flex-shrink-1" data-outer-multiple="" title="<?= T([ 'en' => 'Select several', 'ru' => 'Выбрать несколько', ]) ?>" > <span class="material-icons">add_link</span> </button> <div class="flex-grow-1"> <select class="form-control" name="<?= $group ?>[<?= $code ?>]" data-type="OUTER" data-code="<?= $code ?>" > <? if (!empty($elements)): ?> <? $element = reset($elements); ?> <option value="<?= $element['ID'] ?>" selected="selected" ><?= $Link->GetElementTitle($element) ?></option> <? endif; ?> </select> </div> <button type="button" class="btn btn-secondary flex-shrink-1" data-outer-clean="" title="<?= T([ 'en' => 'Clean', 'ru' => 'Очистить', ]) ?>" > <span class="material-icons">link_off</span> </button> </div> <? endif; ?> <div <? if (!is_array($IDs)): ?> class="d-none" <? endif; ?> data-outer-multiple="" > <select class="form-control d-none" name="<?= $group ?>[<?= $code ?>][]" data-type="OUTER" data-code="<?= $code ?>" multiple="multiple" <? if (!is_array($IDs)): ?> disabled="disabled" <? endif; ?> > <? foreach ($elements as $element): ?> <option value="<?= $element['ID'] ?>" selected="selected" ><?= $Link->GetElementTitle($element) ?></option> <? endforeach; ?> </select> </div> <? } }<file_sep><? /** @var \BlackFox\Registration $this */ ?> <? /** @var array $RESULT */ ?> <div class="registration"> <h1 class="my-3 text-center"><?= $this->PARAMS['TITLE'] ?></h1> <? $this->ShowAlerts(); ?> <form method="POST" class="form form-horizontal" enctype="multipart/form-data"> <? foreach ($RESULT['FIELDS'] as $code => $field): ?> <? if ($field->info['TYPE'] === 'BOOL'): ?> <div class="form-group text-center"> <? // ------------------------------------------------------------------------------------------- \BlackFox\Users::I()->Types[$code]->PrintFormControl($RESULT['VALUES'][$code], "VALUES[{$code}]"); // ------------------------------------------------------------------------------------------- ?> <label for="VALUES[<?= $code ?>]" class="m-0"> <?= $field['NAME'] ?> </label> </div> <? else: ?> <div class="form-group row"> <label for="VALUES[<?= $code ?>]" class="col-sm-3 form-control-plaintext text-sm-right"> <?= $field['NAME'] ?> <? if (in_array($code, $this->PARAMS['MANDATORY'])): ?> <span class="red">*</span> <? endif; ?> </label> <div class="col-sm-8"> <? // ------------------------------------------------------------------------------------------- \BlackFox\Users::I()->Types[$code]->PrintFormControl($RESULT['VALUES'][$code], "VALUES[{$code}]"); // ------------------------------------------------------------------------------------------- ?> </div> <? if (\BlackFox\Users::I()->fields[$code]['DESCRIPTION']): ?> <div class="col-sm-1 form-control-plaintext sm-hidden"> <span class="material-icons" title="<?= \BlackFox\Users::I()->fields[$code]['DESCRIPTION'] ?>">info</span> </div> <? endif; ?> </div> <? endif; ?> <? endforeach; ?> <? if ($this->PARAMS['CAPTCHA']): ?> <div class="form-group text-center"> <? \BlackFox\Captcha::I()->Show(['CSS_CLASS' => 'd-inline-block']) ?> </div> <? endif; ?> <div class="form-group text-center"> <button class="btn btn-primary" type="submit" name="ACTION" value="Registration"> <span class="material-icons">person_add</span> <?= T([ 'en' => 'Sign up', 'ru' => 'Зарегистрироваться', ]) ?> </button> </div> <? if ($this->PARAMS['AUTHORIZATION']): ?> <hr/> <div class="form-group text-center"> <a class="btn btn-link" href="<?= $this->PARAMS['AUTHORIZATION'] ?>"><?= T([ 'en' => 'Authorization', 'ru' => 'Авторизация', ]) ?></a> </div> <? endif; ?> </form> </div><file_sep><?php /** @var \BlackFox\Adminer $this */ ?> <?php /** @var array $RESULT */ ?> <? if (!empty($RESULT['ACTIONS'])): ?> <div class="actions mb-2 text-right"> <? foreach ($RESULT['ACTIONS'] as $action_id => $action): ?> <button type="button" class="btn btn-info" data-toggle="modal" data-target="#action_<?= $action_id ?>" > <? if ($action['ICON']): ?> <span class="material-icons"><?= $action['ICON'] ?></span> <? endif; ?> <?= $action['NAME'] ?> </button> <? endforeach; ?> </div> <? foreach ($RESULT['ACTIONS'] as $action_id => $action): ?> <div class="modal" id="action_<?= $action_id ?>" tabindex="-1" role="dialog"> <div class="modal-dialog ~modal-dialog-centered" role="document"> <form method="post"> <input type="hidden" name="ACTION" value="ExecuteAction" /> <input type="hidden" name="ACTION_ID" value="<?= $action_id ?>" /> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"><?= $action['NAME'] ?></h5> </div> <div class="modal-body"> <? if ($action['DESCRIPTION']): ?> <p><?= $action['DESCRIPTION'] ?></p> <? endif; ?> <? if (!empty($action['PARAMS'])): ?> <? foreach ($action['PARAMS'] as $param_id => $param): ?> <div class="form-group"> <label class="col-form-label"> <?= $param['NAME'] ?> <? if ($param['NOT_NULL']): ?> <span class="red">*</span> <? endif; ?> </label> <? \BlackFox\FactoryType::Get($param)->PrintFormControl(null, "ACTION_PARAMS[{$param_id}]"); ?> </div> <? endforeach; ?> <? endif; ?> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary"> <?= T([ 'en' => 'Execute', 'ru' => 'Выполнить', ]) ?> </button> <button type="button" class="btn btn-secondary" data-dismiss="modal"> <?= T([ 'en' => 'Cancel', 'ru' => 'Отмена', ]) ?> </button> </div> </div> </form> </div> </div> <? endforeach; ?> <? endif; ?><file_sep><?php namespace BlackFox; class Scheme { /** @var Database */ public $Database; /** @var SCRUD[] */ public $Tables = []; /** * @param SCRUD|string[] $Tables * @throws Exception */ public function __construct(array $Tables) { foreach ($Tables as $Table) { if (is_object($Table)) { $this->Tables[get_class($Table)] = $Table; } else { $this->Tables[$Table] = $Table::I(); } } foreach ($this->Tables as $code => $Table) { if (empty($this->Database)) $this->Database = $Table->Database; if ($this->Database !== $Table->Database) throw new Exception("Can't construct scheme: table '{$code}' has different database than table '" . reset($this->Tables)->code . "'"); } } public function Compare() { $diff = []; foreach ($this->Tables as $table_code => $Table) { $diff = array_merge($diff, $Table->Compare()); } usort($diff, function ($a, $b) { return ($a['PRIORITY'] ?: 0) <=> ($b['PRIORITY'] ?: 0); }); return $diff; } public function Synchronize() { $diff = $this->Compare(); foreach ($diff as &$instruction) { try { $this->Database->Query($instruction['SQL']); $instruction['STATUS'] = 'SUCCESS'; } catch (\Exception $error) { $instruction['STATUS'] = 'ERROR'; $instruction['ERROR'] = $error->GetMessage(); } } return $diff; } }<file_sep><?php BlackFox\Adminer::Run(['SCRUD' => '\BlackFox\TableSettings']);<file_sep># BlackFox BlackFox is a PHP framework based on MVC approach. It provides tools that can help you develop a serious non-typical web-site\application with an extremely complex business model. Visit [website](https://blackfox.tools/) for details.<file_sep><?php namespace BlackFox; abstract class ACore { use Instance; public $description = 'Redefine $name, $description и $version'; public $version = '1.0'; /** * Scans info about all files in specified directory and all subdirectories. * * @param string $directory absolute path to directory * @param int $depth deepness of scan (optional) * @return array list of all files as pathinfo structs: {dirname, basename, extension, filename} */ public function ScanDirectoryRecursive($directory, $depth = null) { $files = []; $names = @scandir($directory); if (!empty($names)) { foreach ($names as $name) { if ($name === '.' or $name === '..') { continue; } if (is_dir("{$directory}/{$name}")) { if ($depth === 0) { continue; } $files += $this->ScanDirectoryRecursive("{$directory}/{$name}", $depth ? ($depth - 1) : $depth); } else { $files["{$directory}/{$name}"] = pathinfo("{$directory}/{$name}"); } } } return $files; } /** * Method returns classes of this module. * * @return array dictionary: key - class name (with namespace), value - absolute path to php-file with class * @throws \ReflectionException */ public function GetClasses() { $ReflectionClass = new \ReflectionClass(get_called_class()); $core_absolute_path = dirname($ReflectionClass->getFileName()); $files = []; $files += $this->ScanDirectoryRecursive("{$core_absolute_path}/classes"); $files += $this->ScanDirectoryRecursive("{$core_absolute_path}/units", 1); $classes = []; foreach ($files as $path => $file) { if ($file['extension'] === 'php') { $classes[$ReflectionClass->getNamespaceName() . '\\' . $file['filename']] = $path; } } return $classes; } /** * @return Scheme * @throws Exception */ public function GetScheme() { throw new Exception(T([ 'en' => 'No scheme found', 'ru' => 'Схема не найдена', ])); } public function Upgrade() { $this->GetScheme()->Synchronize(); // override } public function Load() { // override } /** * Compiles and return the tree of menu for administrative section * See children for examples * * @return array */ public function Menu() { return []; } }<file_sep><?php namespace BlackFox; abstract class Database { use Instance; public $database; /** * Execute SQL query and return a result as array * * @param string $SQL SQL statement * @param string $key optional, indicates which column to form array keys * @return mixed * @throws ExceptionSQL */ abstract public function Query($SQL, $key = null); /** * Execute SQL query and return a result as value of ID, which has been inserted * * @param string $SQL * @param string $increment * @return int|string * @throws ExceptionSQL */ abstract public function QuerySingleInsert($SQL, $increment = null); /** * Process data escape before insert it into SQL query * * @param string $data * @return string */ abstract public function Escape($data); abstract public function Quote($data); abstract public function Random(); public function StartTransaction() { $this->Query('START TRANSACTION'); } public function Rollback() { $this->Query('ROLLBACK'); } public function Commit() { $this->Query('COMMIT'); } abstract public function CompareTable(SCRUD $Table); abstract public function CompileSQLSelect(array $parts); public function Truncate($table) { $this->Query("TRUNCATE TABLE {$table}"); } public function Drop($table) { $this->Query("DROP TABLE IF EXISTS {$table}"); } /** @var array dict of dicts with keys: type, params, getParams */ public $db_types = null; public function InitDBTypes() { $this->db_types = []; } public function GetDBType($code) { if (is_null($this->db_types)) $this->InitDBTypes(); if (empty($this->db_types[$code])) throw new Exception("Unknown db_type: " . $code); return $this->db_types[$code]; } public function GetStructureStringType(Type $Type) { if (empty($Type->db_type)) throw new Exception("Empty db_type in Type: " . get_class($Type)); $db_type = $this->GetDBType($Type->db_type); $string = $db_type['type']; if (is_callable($db_type['getParams'])) { $params = $db_type['getParams']($Type->field); $string .= '(' . implode(',', $params) . ')'; } return $string; } }<file_sep><?php namespace BlackFox; class TypePassword extends TypeString { public function PrintFormControl($value, $name, $class = 'form-control') { ?> <input type="password" class="<?= $class ?>" id="<?= $name ?>" name="<?= $name ?>" value="" <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> /> <? } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { } }<file_sep><?php /** @var \BlackFox\Engine $this */ ?> <!DOCTYPE html> <html> <head> <? require('_header.php'); ?> <?= $this->GetHeader(); ?> <link href="<?= $this->TEMPLATE_PATH ?>/style.css?<?= filemtime($_SERVER['DOCUMENT_ROOT'] . $this->TEMPLATE_PATH . '/style.css') ?>" rel="stylesheet"> <title><?= $this->TITLE ?></title> </head> <body class="frame p-1 p-sm-2"> <?= $this->CONTENT; ?> </body> </html> <file_sep><?php /** @var \BlackFox\Adminer $this */ ?> <?php /** @var array $RESULT */ ?> <? /** @var \BlackFox\Type $Type */ $Type = $this->SCRUD->Types[$RESULT['TAB']['CODE']]; /** @var \BlackFox\SCRUD $Link */ $Link = $Type->field['LINK']::N(); $url = $Link->GetAdminUrl(); $params = http_build_query([ 'FRAME' => $Type->field['INNER_KEY'], 'FILTER' => [ $Type->field['INNER_KEY'] => $RESULT['DATA']['ID'], ], ]); $params = $this->SanitizeUrl($params); ?> <iframe class="external" data-iframe-external="" src="<?= $url ?>?<?= $params ?>" ></iframe><file_sep><?php require_once("BlackFox/includes.php"); \BlackFox\Engine::I()->Work();<file_sep><?php namespace BlackFox; class ExceptionPageNotFound extends Exception { }<file_sep><?php namespace BlackFox; class Breadcrumbs extends Unit { public function GetActions(array $request = []) { return 'Default'; } public function Default() { $RESULT['BREADCRUMBS'] = $this->ENGINE->BREADCRUMBS; return $RESULT; } } <file_sep><?php namespace BlackFox; class Form extends \BlackFox\Unit { public $options = [ 'SCRUD' => [ 'TYPE' => 'object', 'NAME' => 'Essence', ], 'FIELDS' => [ 'TYPE' => 'array', 'NAME' => 'Fields', ], 'DATA' => [ 'TYPE' => 'array', 'NAME' => 'Data', ], 'ELEMENT' => [ 'TYPE' => 'string', 'NAME' => 'Element name', 'DEFAULT' => 'ELEMENT', ], 'CLASS_GROUP' => [ 'TYPE' => 'string', 'DEFAULT' => 'form-group row', ], 'CLASS_LABEL' => [ 'TYPE' => 'string', 'DEFAULT' => 'col-sm-3 col-form-label text-sm-right', ], 'CLASS_BLOCK' => [ 'TYPE' => 'string', 'DEFAULT' => 'col-sm-8', ], 'CLASS_CONTROL' => [ 'TYPE' => 'string', 'DEFAULT' => 'form-control', ], ]; public function GetActions(array $request = []) { return 'Default'; } public function Default() { $R = $this->PARAMS; $fields = []; foreach ($R['FIELDS'] as $key => $value) { if (is_string($value)) { $fields[$value] = $R['SCRUD']->fields[$value]; } else { $fields[$key] = $value; } } $R['FIELDS'] = $fields; return $R; } } <file_sep><?php namespace BlackFox; class ExceptionCaptcha extends Exception { }<file_sep>$(function () { $('[data-menu-expander]').click(function () { $(this).closest('[data-menu-item]').children('[data-menu-children]').toggle(); $(this).closest('[data-menu-item-body]').find('[data-menu-rotate]').toggleClass('rotate-90').toggleClass('rotate-0'); }); });<file_sep><?php namespace BlackFox; class Menu extends Unit { public $options = [ 'BREADCRUMBS' => [ 'TYPE' => 'boolean', 'DEFAULT' => true, ], ]; public function GetActions(array $request = []) { return 'Default'; } protected function GetMenu() { $id = 'admin_menu_' . $this->ENGINE->GetLanguage(); try { $MENU = \BlackFox\Cache::I()->Get($id); } catch (\BlackFox\ExceptionCache $error) { $MENU = []; foreach ($this->ENGINE->cores as $namespace => $core_absolute_folder) { $Core = "\\{$namespace}\\Core"; /**@var ACore $Core */ $MENU = array_merge($MENU, $Core::I()->Menu()); } \BlackFox\Cache::I()->Set($id, $MENU); } return $MENU; } public function Default() { $MENU = $this->GetMenu(); foreach ($MENU as &$item) { $this->SearchActiveItemsRecursive($item, $this->ENGINE->url['path']); } return $MENU; } public function SearchActiveItemsRecursive(&$item, $path) { $item['ACTIVE'] = $item['CURRENT'] = ($item['LINK'] === $path); if (is_array($item['CHILDREN'])) foreach ($item['CHILDREN'] as &$child) $item['ACTIVE'] |= $this->SearchActiveItemsRecursive($child, $path); if ($this->PARAMS['BREADCRUMBS']) if ($item['ACTIVE']) array_unshift($this->ENGINE->BREADCRUMBS, $item); return $item['ACTIVE']; } } <file_sep><?php namespace BlackFox; abstract class UnitSection extends Unit { public function GetActions(array $request = []) { $actions = []; if ($request['ACTION'] or $request['action']) { $actions[] = $request['ACTION'] ?: $request['action']; } $actions[] = $this->SelectMethodForView($request); return $actions; } public function SelectMethodForView($request = []) { if (isset($request['EDIT'])) { $this->view = 'form'; return 'Editing'; } if (isset($request['NEW'])) { $this->view = 'form'; return 'Creating'; } if (!empty($request['ID'])) { $this->view = 'element'; return 'Element'; } $this->view = 'section'; return 'Section'; } /** * Подготавливает данные для отображения страницы со списком элементов. * Контроллирует доступ, кидает исключения. * * @param array $filter * @param int $page * @return array * @throws \Exception */ public function Section($filter = [], $page = 1) { $this->Debug($filter, 'Section $filter'); $this->Debug($page, 'Section $page'); return []; } /** * Подготавливает данные для отображения страницы с просмотра элемента. * Контроллирует доступ, кидает исключения. * * @param $ID * @return array * @throws \Exception */ public function Element($ID) { $this->Debug($ID, 'Element $ID'); return []; } /** * Подготавливает данные для отображения формы редактирования элемента. * Контроллирует доступ, кидает исключения. * * @param $ID * @param array $fields * @return array * @throws \Exception */ public function Editing($ID, $fields = []) { $this->Debug($ID, 'Editing $ID'); $this->Debug($fields, 'Editing $fields'); return []; } /** * Подготавливает данные для отображения формы добавления элемента. * Контроллирует доступ, кидает исключения. * * @param array $fields * @return array * @throws \Exception */ public function Creating($fields = []) { $this->Debug($fields, 'Creating $fields'); return []; } }<file_sep><?php namespace BlackFox; class Captcha { use Instance; public function Show($params = []) { return; } public function Check() { return true; } }<file_sep><?php /** @var \BlackFox\Adminer $this */ ?> <?php /** @var array $RESULT */ ?> <? if ($RESULT['MODE'] <> 'Create'): ?> <? require $this->GetParentView(); ?> <? else: ?> <form method="post" enctype="multipart/form-data"> <label class="btn btn-secondary btn-file m-0"> <span><?= T([ 'en' => 'Select file', 'ru' => 'Выбрать файл', ]) ?></span> <input type="file" name="FIELDS" style="display: none;"> </label> <button type="submit" name="ACTION" value="Create" class="btn btn-secondary" ><?= T([ 'en' => 'Upload', 'ru' => 'Загрузить', ]) ?> </button> </form> <?php $this->ENGINE->AddHeaderScript( $this->ENGINE->GetRelativePath( __DIR__ . '/on_file_change.js' ) ); ?> <? endif; ?> <file_sep><?php /* @var \BlackFox\Engine $this */ $this->Upgrade(); ?> <div class="alert alert-info"> <?= T([ 'en' => 'Upgrade complete', 'ru' => 'Апгрейд завершен', ]) ?> </div><file_sep><?php namespace BlackFox; class ExceptionCache extends Exception { }<file_sep><? /** @var \BlackFox\Adminer $this */ ?> <? /** @var array $RESULT */ ?> <div id="section-settings" class="modal fade" tabindex="-1" role="dialog" > <div class="modal-dialog modal-lg" role="document" style="max-width: 852px; width: 95%;"> <div class="modal-content"> <form method="post"> <div class="modal-header"> <h3 class="modal-title"><?= T([ 'en' => 'Section display settings', 'ru' => 'Настройки отображения секции', ]) ?></h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!-- Tab panes --> <div class="row"> <div class="col-sm-6"> <h4 class="text-center"><?= T([ 'en' => 'Filters', 'ru' => 'Фильтры', ]) ?></h4> <? $SELECTED = $RESULT['SETTINGS']['FILTERS']; $NAME = 'filters'; include('section_settings_list.php'); ?> </div> <div class="col-sm-6"> <h4 class="text-center"><?= T([ 'en' => 'Columns', 'ru' => 'Колонки', ]) ?></h4> <? $SELECTED = $RESULT['SETTINGS']['FIELDS']; $NAME = 'fields'; include('section_settings_list.php'); ?> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary" data-section-settings-save="" name="ACTION" value="SaveTableSettings" > <?= T([ 'en' => 'Save', 'ru' => 'Сохранить', ]) ?> </button> <button type="button" class="btn btn-secondary" data-dismiss="modal"> <?= T([ 'en' => 'Close', 'ru' => 'Закрыть', ]) ?> </button> </div> </form> </div> </div> </div><file_sep><?php return [ 'TEMPLATE' => 'main', ]; <file_sep><?php namespace BlackFox; abstract class Unit { use Instance; /** @var string Наименование */ public $name; /** @var string Описание */ public $description; /** @var array Ассоциативный массив, описывающий возможные параметры */ public $options = []; /** @var Engine $ENGINE */ public $ENGINE; /** @var User $USER */ public $USER; /** @var array предки компонента */ public $parents = []; /** @var Unit get_called_class */ public $class = '...'; /** @var string отображение - имя php файла подключаемого в подпапке /views */ public $view = null; /** @var array запрос пользователя */ public $REQUEST = []; /** @var array параметры вызова */ public $PARAMS = []; /** @var array результат работы */ public $RESULT = []; /** * - TYPE - часть CSS-класса alert-* * - TEXT - контент алерта * @var array сообщения+предупреждения+ошибки возникшие в процессе работы: */ public $ALERTS = []; public $ajax = false; public $json = false; public $allow_ajax_request = false; public $allow_json_request = false; /** @var string абсолютный путь к папке юнита */ public $unit_absolute_folder; /** @var string относительный путь к папке юнита */ public $unit_relative_folder; /** @var string абсолютный путь к папке с отображениями */ public $view_absolute_folder; /** @var string относительный путь к папке с отображениями */ public $view_relative_folder; public function __construct( Engine $Engine = null, User $User = null ) { $this->ENGINE = $Engine ?: Engine::I(); $this->USER = $User ?: User::I(); $this->class = get_called_class(); $this->name = $this->name ?: $this->class; $this->parents[$this->class] = dirname($this->ENGINE->classes[$this->class]); $this->unit_absolute_folder = $this->parents[$this->class]; $this->unit_relative_folder = $this->ENGINE->GetRelativePath($this->unit_absolute_folder); $this->view_absolute_folder = $this->unit_absolute_folder . '/views'; $this->view_relative_folder = $this->unit_relative_folder . '/views'; // collect info about all parents including self, excluding abstract classes $parents = class_parents($this); foreach ($parents as $parent) { if ((new \ReflectionClass($parent))->isAbstract()) { continue; } $this->parents[$parent] = dirname($this->ENGINE->classes[$parent]); } } public static function Run($params = [], $request = []) { /**@var Unit $class */ $class = get_called_class(); /**@var Unit $Unit */ $Unit = $class::I(); try { $Unit->Execute($params, $request); } catch (Exception $error) { $Unit->ENGINE->ShowErrors($error->getArray()); } catch (\Exception $error) { $Unit->ENGINE->ShowErrors([$error->getMessage()]); } } /** * @param array $params * @param array $request * @throws Exception */ public function Execute($params = [], $request = []) { $this->Init($params); $this->SetAlertsFromSession(); $this->ajax = $this->IsRequestTypeAjax(); $this->json = $this->IsRequestTypeJson(); $this->REQUEST = $this->GetRequest($request); $this->RESULT = $this->Controller($this->REQUEST); if ($this->ajax) { $this->ENGINE->TEMPLATE = null; echo $this->ProcessView($this->RESULT); return; } if ($this->json) { $this->ENGINE->TEMPLATE = null; echo json_encode($this->RESULT + ['ALERTS' => $this->ALERTS]); return; } $this->ManageHeaders(); echo $this->ProcessView($this->RESULT); return; } public function IsRequestTypeAjax() { return $this->allow_ajax_request and in_array($this->class, [$_REQUEST['AJAX'], $_REQUEST['ajax']]); } public function IsRequestTypeJson() { return $this->allow_json_request and in_array($this->class, [$_REQUEST['JSON'], $_REQUEST['json']]); } /** * Устанавливает параметры компонента $this->PARAMS: * - проверяет соответствие типов переданных параметров желаемым * - устанавливает параметры по умолчанию * - кидает ошибки в любой непонятной ситуации * * @param array $params параметры компонента на установку * @throws Exception требуется указать параметр... */ public function Init($params = []) { $errors = []; foreach ($this->options as $code => $option) { if (isset($params[$code]) || array_key_exists($code, $params)) { $value = $params[$code]; if (!empty($this->options[$code]['TYPE'])) { $type_expected = strtolower($this->options[$code]['TYPE']); // strtolower - for backward compatibility $type_passed = gettype($value); if ($type_expected <> $type_passed) { $errors[] = "Unit '{$this->class}' initialisation error: param - '{$code}', expecting type - '{$type_expected}', passed value type - '{$type_passed}'"; unset($params[$code]); continue; } } $this->PARAMS[$code] = $value; unset($params[$code]); continue; } if (isset($option['DEFAULT']) || array_key_exists('DEFAULT', $option)) { $this->PARAMS[$code] = $option['DEFAULT']; continue; } $errors[] = "Unit '{$this->class}' initialisation error: required param - '{$code}'"; unset($params[$code]); } if (!empty($errors)) { throw new Exception($errors); } if (!empty($params)) { foreach ($params as $code => $value) { $this->PARAMS[$code] = $value; } } } public function Debug($data, $title = '', $mode = 'print_r', $target = '/debug.txt') { if (function_exists('debug')) { debug($data, $title, $mode, $target); } } /** * Analyzes the $request, matches the required methods for actions. * May setup required view ($this->view). * * @param array $request user input * @return string|array names of methods */ public function GetActions(array $request = []) { $actions = []; $request['ACTION'] = $request['ACTION'] ?: $request['action'] ?: null; $request['VIEW'] = $request['VIEW'] ?: $request['view'] ?: null; if ($request['ACTION']) { $actions[] = $request['ACTION']; } if ($request['VIEW']) { $actions[] = $request['VIEW']; } else { $actions[] = 'Default'; } return $actions; } /** * Контролирует поток управления юнита: * - запрашивает массив действий ($this->GetActions) * - разбивает массив действий на две части: все действия кроме финального + финальное действие * - инициализирует $this->view именем финального действия * - последовательно выполняет все действия кроме финального: * успех -- агрегирует ответ: массив - в результат, строку - в успешные сообщения; * ошибка -- ловит ошибку и отправляет ее в $this->Error; * редирект -- прекращает выполнение. * - выполняет финальное действие: * успех -- преобразует ответ в массив и агрегирует его в результат; * ошибка -- не ловит ошибку, позволяя ей всплыть на уровень выше; * редирект -- прекращает выполнение. * * Все действия кроме финального: * - могут пытаться изменить внутреннее состояние модели * - могут подготавливать дополнительные данные для отображения * * Финальное действие: * - не пытается изменить внутреннее состояние модели * - подготавливает основные данные для отображения * * @param array $request user request * @return array result data * @throws Exception */ public function Controller(array $request = []) { $actions = (array)$this->GetActions($request); $actions = array_filter($actions, 'strlen'); if (empty($actions)) { throw new Exception("Unit '{$this->name}', controller can't find any actions"); } $final_action = array_pop($actions); $this->view = $this->view ?: $final_action; $result = []; foreach ($actions as $action) { try { $answer = $this->Invoke($action, $request); if (is_array($answer)) { $result += $answer; continue; } if (is_string($answer)) { $this->ALERTS[] = ['TYPE' => 'success', 'TEXT' => $answer]; continue; } throw new Exception("Unknown answer type: '" . gettype($answer) . "' for action '{$action}'"); } catch (Exception $Exception) { $result += $this->Error($Exception, $action, $request); } } $result += (array)$this->Invoke($final_action, $request); return $result; } /** * Вызывает метод, контролируя его наличие и публичный доступ к нему. * Метод запускается через ReflectionMethod->invokeArgs() что позволяет самому методу * контролировать принимаемые на вход параметры. Все прочие параметры отсеиваются. * * @param string $method метод - название публичного метода в классе контроллера * @param array $request данные запроса - ассоциативный массив данных пришедших по любому каналу * @return array|string результат выполнения метода (зачастую метод самостоятельно редиректит дальше) * @throws \Exception */ private function Invoke($method, $request) { if (!method_exists($this, $method)) { throw new Exception("Unit '{$this->name}', unknown method - '{$method}'"); } //$this->Debug($action, 'Invoke $action'); //$this->Debug($request, 'Invoke $request'); $reflection = new \ReflectionMethod($this, $method); if (!$reflection->isPublic()) { throw new Exception("Unit '{$this->name}', method '{$method}' is not public"); } $request = array_change_key_case($request); $parameters = $reflection->getParameters(); //$this->Debug($parameters, 'Invoke $parameters'); $arguments = []; foreach ($parameters as $parameter) { $code = strtolower($parameter->name); if (isset($request[$code])) { $arguments[$code] = $request[$code]; } else { try { $arguments[$code] = $parameter->getDefaultValue(); } catch (\Exception $error) { $arguments[$code] = null; } } } //$this->Debug($arguments, 'Invoke $arguments'); return $reflection->invokeArgs($this, $arguments); } /** * Вызывается при ловле ошибки выполнения любого действия из под контроллера. * Может переопределяться в классах-наследниках для переопределения логики обработки ошибок. * * @param Exception $Exception * @param string $action * @param array $request * @return array */ public function Error(Exception $Exception, $action = null, $request = []) { $this->Debug($Exception, '$Exception'); foreach ($Exception->getArray() as $error) { $this->ALERTS[] = [ 'TYPE' => 'danger', 'TEXT' => $error, ]; } return []; } public function SetAlertsFromSession() { if (!empty($_SESSION['ALERTS'][$this->class])) { $this->ALERTS = $_SESSION['ALERTS'][$this->class]; $_SESSION['ALERTS'][$this->class] = []; } } public function GetRequest($request = []) { return array_merge_recursive($request, $_REQUEST, $this->ConvertFilesStructure($_FILES)); } /** * Connects the [$RESULT] to a [$this->view] * and returns the resulting content * * @param array $RESULT result data * @return null|string content (html) * @throws Exception */ public function ProcessView($RESULT) { if (empty($this->view)) { return null; } ob_start(); $this->Debug([ 'PARAMS' => $this->PARAMS, 'ALERTS' => $this->ALERTS, 'RESULT' => $RESULT, ], $this->class); $view_file = $this->Path("{$this->view}.php"); require($view_file); $content = ob_get_clean(); if (!empty($this->ALERTS)) { ob_start(); $this->ShowAlerts(); $content = ob_get_clean() . $content; } return $content; } /** * Возвращает абсолютный путь к шаблону: * - ищет возможный шаблон в текущем компоненте * - ищет возможный шаблон во всех компонентах-родителях * - возвращает ошибку если подходящий шаблон не найден * * @param string $path путь к шаблону относительно корневой директории шаблона * @return string абсолютный путь к шаблону * @throws Exception View not found... */ public function Path($path) { foreach ($this->parents as $unit => $unit_folder) { $search = "{$unit_folder}/views/{$path}"; if (file_exists($search)) { return $search; } } throw new Exception("Unit '{$this->class}'; View not found: '{$path}'"); } public function PathInclude($path) { try { return $this->Path($path); } catch (Exception $error) { return null; } } public function GetParentView() { $view_file = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)[0]['file']; $view_file = str_replace('\\', '/', $view_file); $view_folder = str_replace('\\', '/', $this->view_absolute_folder); $view_relative_path = str_replace($view_folder, '', $view_file); //debug($this->units, '$this->units'); foreach ($this->parents as $unit => $unit_folder) { if ($this->class === $unit) { continue; } $search = "{$unit_folder}/views{$view_relative_path}"; if (file_exists($search)) { return $search; } } throw new Exception("Parent's view not found"); } public function ShowAlerts() { foreach ($this->ALERTS as $message) { echo "<div class='alert alert-{$message['TYPE']}'>{$message['TEXT']}</div>"; } $this->ALERTS = []; } /** * Корректирует неадекватную структуру суперглобального массива $_FILES. * Возвращает рекурсивно упорядоченный массив пришедших файлов. * * @param array $input ожидается массив $_FILES * @return array массив со скорректированной структурой */ private function ConvertFilesStructure($input) { $output = []; foreach ($input as $key => $file) { $output[$key] = $this->ConvertFilesStructureRecursive( $file['name'], $file['type'], $file['tmp_name'], $file['error'], $file['size'] ); } return $output; } private function ConvertFilesStructureRecursive($name, $type, $tmp_name, $error, $size) { if (!is_array($name)) { return [ 'name' => $name, 'type' => $type, 'tmp_name' => $tmp_name, 'error' => $error, 'size' => $size, ]; } $output = []; foreach ($name as $key => $_crap) { $output[$key] = $this->ConvertFilesStructureRecursive( $name[$key], $type[$key], $tmp_name[$key], $error[$key], $size[$key] ); } return $output; } /** * Добавляет в сессию уведомления (если они указаны). * Перенаправляет на другой URL. * Завершает выполнение скрипта. * * @param string|null $url URL-адрес (null = $_SERVER['REQUEST_URI']) * @param string|array $alerts строка, уведомление об успехе * | массив строк, уведомлений об успехе * | массив массивов, представляющих собой уведомления в формате [TEXT => '...', TYPE => (success|info|warning|danger)] */ public function Redirect($url, $alerts = []) { $url = $url ?: $_SERVER['REQUEST_URI']; $alerts = is_array($alerts) ? $alerts : [$alerts]; foreach ($alerts as &$alert) { if (is_string($alert)) { $alert = ['TEXT' => $alert, 'TYPE' => 'success']; } } if ($this->json) { echo json_encode([ 'URL' => $url, 'ALERTS' => $alerts, ]); } else { header('Location: ' . ($url)); $_SESSION['ALERTS'][$this->class] = $alerts; } die(); } /** * Добавляет в заголовки страницы файлы 'style.css' и 'script.js' если они существуют */ public function ManageHeaders() { // style.css try { $style_absolute_path = $this->Path('style.css'); $style_relative_path = $this->ENGINE->GetRelativePath($style_absolute_path); $this->ENGINE->AddHeaderStyle($style_relative_path); } catch (Exception $error) { } // script.js try { $script_absolute_path = $this->Path('script.js'); $script_relative_path = $this->ENGINE->GetRelativePath($script_absolute_path); $this->ENGINE->AddHeaderScript($script_relative_path); } catch (Exception $error) { } } } <file_sep>$(function () { $('[data-datetimepicker]').flatpickr({ locale: lang, dateFormat: "Y-m-d H:i:S", enableTime: true, time_24hr: true, allowInput: true }); $('[data-datepicker]').flatpickr({ locale: lang, enableTime: false, dateFormat: "Y-m-d", allowInput: true }); if ($(window).width() < 768) { $('#sidebar').hide(); } $(window).on('resize', function () { if ($(window).width() < 768) { $('#sidebar').hide(); } else { $('#sidebar').show(); } }); $('[data-toggle-sidebar]').click(function () { $('#sidebar').toggle(); }) }); <file_sep><?php namespace BlackFox; class Postgres extends Database { private $link; public function __construct(array $params) { $this->database = $params['DATABASE']; $connection_string = [ "host={$params['HOST']}", "port={$params['PORT']}", "dbname={$params['DATABASE']}", "user={$params['USER']}", "password={$<PASSWORD>['<PASSWORD>']}", ]; $this->link = pg_pconnect(implode(' ', $connection_string)); if ($this->link === false) { throw new Exception(pg_last_error()); } } public function InitDBTypes() { $this->db_types = [ // ----------------------------------------- 'bool' => [ 'type' => 'bool', ], 'int' => [ 'type' => 'numeric', 'params' => ['numeric_precision', 'numeric_scale'], 'getParams' => function (array $field) { return [$field['LENGTH'] ?: 11, 0]; }, ], 'float' => [ 'type' => 'numeric', 'params' => ['numeric_precision', 'numeric_scale'], 'getParams' => function (array $field) { return [$field['LENGTH'] ?: 13, $field['DECIMALS'] ?: 2]; }, ], // ----------------------------------------- 'varchar' => [ 'type' => 'varchar', 'params' => ['character_maximum_length'], 'getParams' => function (array $field) { return [$field['LENGTH'] ?: 255]; }, ], 'text' => [ 'type' => 'text', ], // ----------------------------------------- 'enum' => [ 'type' => 'varchar', 'params' => ['character_maximum_length'], 'getParams' => function (array $field) { // returning max string length from values $max = max(array_map('strlen', array_keys($field['VALUES']))); return [$max]; }, ], 'set' => [ 'type' => 'varchar', 'params' => ['character_maximum_length'], 'getParams' => function (array $field) { // returning sum of string lengths from values + commas $sum = strlen(implode(',', array_keys($field['VALUES']))); return [$sum]; }, ], // ----------------------------------------- 'time' => [ 'type' => 'time', ], 'date' => [ 'type' => 'date', ], 'datetime' => [ 'type' => 'timestamp', ], // ----------------------------------------- ]; } public function QuerySingleInsert($SQL, $increment = null) { if (!empty($increment)) { $SQL .= " RETURNING " . $this->Quote($increment); } $result = $this->Query($SQL); if (empty($increment) or empty($result)) { return null; } return reset($result)[$increment]; } public function Query($SQL, $key = null) { @$result = pg_query($this->link, $SQL); if ($result === false) { throw new ExceptionSQL(pg_last_error($this->link), $SQL); } $data = []; while ($row = pg_fetch_assoc($result)) { if (isset($key) and isset($row[$key])) { $data[$row[$key]] = $row; } else { $data[] = $row; } } return $data; } public function Escape($data) { if (is_null($data)) { return null; } return pg_escape_string($this->link, $data); } public function Quote($id) { return '"' . $id . '"'; } public function Random() { return 'random()'; } public function CompareTable(SCRUD $Table): array { $diff = []; $diff = array_merge($diff, $this->CompareTableFieldsAndPrimaryKeys($Table)); $diff = array_merge($diff, $this->CompareTableIndexes($Table)); $diff = array_merge($diff, $this->CompareTableConstraints($Table)); return $diff; } public function CompareTableFieldsAndPrimaryKeys(SCRUD $Table): array { $diff = []; $check = $this->Query("SELECT * FROM pg_catalog.pg_tables WHERE tablename='{$Table->code}'"); if (empty($check)) { // no table found: creating a new one with fields and primary keys $data = []; foreach ($Table->fields as $code => $field) { if ($Table->Types[$code]->virtual) continue; $type = $this->GetStructureStringType($Table->Types[$code]); $null = ($field["NOT_NULL"] || $field['PRIMARY']) ? 'NOT NULL' : 'NULL'; $default = ''; if (isset($field['DEFAULT'])) { if (is_bool($field['DEFAULT'])) { $default = "DEFAULT " . ($field['DEFAULT'] ? 'true' : 'false'); } elseif (is_array($field['DEFAULT'])) { $default = "DEFAULT '" . implode(',', $field['DEFAULT']) . "'"; } elseif (is_string($field['DEFAULT']) or is_numeric($field['DEFAULT'])) { $default = "DEFAULT '{$field['DEFAULT']}'"; } else { throw new ExceptionType("Table '{$Table->code}', column '{$code}', unsupported type for DEFAULT value: " . gettype($field['DEFAULT'])); } } if ($field["AUTO_INCREMENT"]) { $sequence_name = strtolower($Table->code . '_' . $code . '_seq'); $sequences = $this->Query(" SELECT * FROM information_schema.sequences WHERE sequence_catalog='{$this->database}' AND sequence_name='{$sequence_name}' ", 'sequence_name'); if (empty($sequences[$sequence_name])) { $diff[] = [ 'MESSAGE' => 'Create a sequence', 'PRIORITY' => -2, 'TABLE' => $Table->code, 'SQL' => "CREATE SEQUENCE {$sequence_name};", ]; } $default = "DEFAULT nextval('{$sequence_name}')"; } $data[] = [ 'MESSAGE' => 'Add column', 'FIELD' => $code, 'SQL' => trim($this->Quote($code) . " $type $null $default"), ]; } if (!empty($Table->keys)) { $data[] = [ 'MESSAGE' => 'Add primary keys', 'SQL' => "PRIMARY KEY (" . implode(", ", array_map([$this, 'Quote'], $Table->keys)) . ")", ]; } $SQL = "CREATE TABLE {$Table->code} (\r\n" . implode(",\r\n", array_column($data, 'SQL')) . "\r\n);"; $diff[] = [ 'MESSAGE' => 'Create a new table', 'TABLE' => $Table->code, 'SQL' => $SQL, 'DATA' => $data, ]; } else { // table exist: comparing fields and primary keys $data = []; $columns = $this->Query("SELECT * FROM information_schema.columns WHERE table_catalog='{$this->database}' AND table_name ='{$Table->code}' ORDER BY ordinal_position;", 'column_name'); $columns = array_change_key_case($columns, CASE_UPPER); foreach ($Table->fields as $code => $field) { $code_quoted = $this->Quote($code); $column = $columns[$code]; if ($Table->Types[$code]->virtual) continue; // RENAME COLUMN if ($field['CHANGE'] and !empty($columns[$field['CHANGE']]) and empty($column)) { $diff[] = [ 'MESSAGE' => 'Rename column', 'PRIORITY' => -1, 'TABLE' => $Table->code, 'FIELD' => $code, 'REASON' => "{$field['CHANGE']} -> {$code}", 'SQL' => "ALTER TABLE {$Table->code} RENAME COLUMN " . $this->Quote($field['CHANGE']) . " TO {$code_quoted}", ]; $column = $columns[$field['CHANGE']]; unset($columns[$field['CHANGE']]); } // ADD COLUMN if (!isset($column)) { $type = $this->GetStructureStringType($Table->Types[$code]); $null = ($field["NOT_NULL"] || $field['PRIMARY']) ? 'NOT NULL' : 'NULL'; $default = ''; if (isset($field['DEFAULT'])) { if (is_bool($field['DEFAULT'])) { $default = "DEFAULT " . ($field['DEFAULT'] ? 'true' : 'false'); } elseif (is_array($field['DEFAULT'])) { $default = "DEFAULT '" . implode(',', $field['DEFAULT']) . "'"; } elseif (is_string($field['DEFAULT']) or is_numeric($field['DEFAULT'])) { $default = "DEFAULT '{$field['DEFAULT']}'"; } else { throw new ExceptionType("Table '{$Table->code}', column '{$code}', unsupported type for DEFAULT value: " . gettype($field['DEFAULT'])); } } if ($field['AUTO_INCREMENT']) { $sequence_name = strtolower($Table->code . '_' . $code . '_seq'); $sequences = $this->Query(" SELECT * FROM information_schema.sequences WHERE sequence_catalog='{$this->database}' AND sequence_name='{$sequence_name}' ", 'sequence_name'); if (empty($sequences[$sequence_name])) { $diff[] = [ 'MESSAGE' => 'Create a sequence', 'PRIORITY' => -2, 'TABLE' => $Table->code, 'SQL' => "CREATE SEQUENCE {$sequence_name};", ]; } $default = "DEFAULT nextval('{$sequence_name}')"; } $data[] = [ 'MESSAGE' => 'Add column', 'FIELD' => $code, 'SQL' => "ADD COLUMN {$code_quoted} {$type} {$null} {$default}", ]; unset($columns[$code]); continue; } // ALTER COLUMN: $db_type = $this->GetDBType($Table->Types[$code]->db_type); if ($db_type['type'] <> $column['udt_name']) { $type = $this->GetStructureStringType($Table->Types[$code]); $data[] = [ 'MESSAGE' => 'Change type', 'FIELD' => $code, 'REASON' => "{$column['udt_name']} -> $type", 'SQL' => "ALTER COLUMN {$code_quoted} TYPE {$type} USING {$code_quoted}::{$type}", ]; } else { // checking $db_type params $params_need = []; if (is_callable($db_type['getParams'])) { $params_need = $db_type['getParams']($field); } $params_have = []; if (is_array($db_type['params'])) foreach ($db_type['params'] as $param) $params_have[] = $column[$param]; if ($params_have <> $params_need) { $type = $this->GetStructureStringType($Table->Types[$code]); $data[] = [ 'MESSAGE' => 'Adjust type params', 'FIELD' => $code, 'REASON' => implode(',', $params_have) . " -> " . implode(',', $params_need), 'SQL' => "ALTER COLUMN {$code_quoted} TYPE {$type}", ]; } } // NULL -> NOT NULL if ($field["NOT_NULL"] and $column['is_nullable'] == 'YES') { $data[] = [ 'MESSAGE' => 'Set not null', 'FIELD' => $code, 'SQL' => "ALTER COLUMN {$code_quoted} SET NOT NULL", ]; } // NOT NULL -> NULL if (!$field["NOT_NULL"] and $column['is_nullable'] == 'NO') { $data[] = [ 'MESSAGE' => 'Drop not null', 'FIELD' => $code, 'SQL' => "ALTER COLUMN {$code_quoted} DROP NOT NULL", ]; } // DEFAULT if (!$field["AUTO_INCREMENT"]) { if (isset($field['DEFAULT'])) { $default = !is_array($field['DEFAULT']) ? $field['DEFAULT'] : implode(',', $field['DEFAULT']); if ($column['data_type'] == 'boolean') { $pg_default = $default ? 'true' : 'false'; } else { $pg_default = "'{$default}'::{$column['data_type']}"; } if ($pg_default <> $column['column_default']) { $data[] = [ 'MESSAGE' => 'Set default', 'FIELD' => $code, 'SQL' => "ALTER COLUMN {$code_quoted} SET DEFAULT '{$default}'", ]; } } if (!isset($field['DEFAULT']) and !empty($column['column_default'])) { $data[] = [ 'MESSAGE' => 'Drop default', 'REASON' => $column['column_default'], 'FIELD' => $code, 'SQL' => "ALTER COLUMN {$code_quoted} DROP DEFAULT", ]; } } // AUTO_INCREMENT if ($field["AUTO_INCREMENT"]) { $sequence_name = strtolower($Table->code . '_' . $code . '_seq'); $sequence_need_new_max_value = false; $sequence_need_new_max_value_reason = ''; $sequences = $this->Query(" SELECT * FROM information_schema.sequences WHERE sequence_catalog='{$this->database}' AND sequence_name='{$sequence_name}' ", 'sequence_name'); if (empty($sequences[$sequence_name])) { // sequence doesn't exist $diff[] = [ 'MESSAGE' => 'Create a sequence', 'PRIORITY' => -2, 'TABLE' => $Table->code, 'SQL' => "CREATE SEQUENCE \"{$sequence_name}\";", ]; $sequence_need_new_max_value = true; $sequence_need_new_max_value_reason = 'new sequence'; } else { // sequence does exist $sequence_current_value = $this->Query("SELECT last_value FROM {$sequence_name}")[0]['last_value']; $table_last_id = $this->Query("SELECT max({$code_quoted}) AS m FROM {$Table->code}")[0]['m']; if (!empty($table_last_id) and $table_last_id > $sequence_current_value) { $sequence_need_new_max_value = true; $sequence_need_new_max_value_reason = "table_last_id = {$table_last_id}, sequence_current_value = {$sequence_current_value}"; } } // check if sequence need a new value if ($sequence_need_new_max_value) { $diff[] = [ 'MESSAGE' => 'Restart sequence', 'PRIORITY' => -1, 'TABLE' => $Table->code, 'REASON' => $sequence_need_new_max_value_reason, 'SQL' => "SELECT setval('{$sequence_name}', (SELECT max({$code_quoted})+1 FROM {$Table->code})::integer, false);", ]; } // check if default is correct if ("nextval('{$sequence_name}'::regclass)" <> $column['column_default']) { $data[] = [ 'MESSAGE' => 'Link to sequence', 'REASON' => $column['column_default'], 'FIELD' => $code, 'SQL' => "ALTER COLUMN {$code_quoted} SET DEFAULT nextval('{$sequence_name}')", ]; } } unset($columns[$code]); } // DROP COLUMN foreach ($columns as $code => $column) { $data[] = [ 'MESSAGE' => 'Drop superfluous column', 'FIELD' => $column['column_name'], 'SQL' => "DROP COLUMN " . $this->Quote($column['column_name']), ]; unset($columns[$code]); } // PRIMARY KEYS $rows = $this->Query(" SELECT * FROM information_schema.key_column_usage WHERE table_catalog='{$this->database}' AND table_name='{$Table->code}' AND constraint_name = ( SELECT constraint_name FROM information_schema.table_constraints WHERE table_catalog = '{$this->database}' AND table_name = '{$Table->code}' AND constraint_type = 'PRIMARY KEY' ) ORDER BY ordinal_position"); $db_pkey_name = ''; $db_pkey_cols = []; foreach ($rows as $row) { $db_pkey_name = $row['constraint_name']; $db_pkey_cols[] = $row['column_name']; } if ($Table->keys <> $db_pkey_cols) { if (!empty($db_pkey_name)) $diff[] = [ 'MESSAGE' => 'Drop primary', 'PRIORITY' => -1, 'TABLE' => $Table->code, 'SQL' => "ALTER TABLE {$Table->code} DROP CONSTRAINT {$db_pkey_name};", ]; if (!empty($Table->keys)) $diff[] = [ 'MESSAGE' => 'Add primary', 'PRIORITY' => +1, 'TABLE' => $Table->code, 'SQL' => "ALTER TABLE {$Table->code} ADD PRIMARY KEY (" . implode(',', array_map([$this, 'Quote'], $Table->keys)) . ");", ]; } if (!empty($data)) { $SQL = "ALTER TABLE {$Table->code} \r\n" . implode(",\r\n", array_column($data, 'SQL')); $diff[] = [ 'MESSAGE' => 'Modify table', 'TABLE' => $Table->code, 'DATA' => $data, 'SQL' => $SQL, ]; } } return $diff; } public function CompareTableIndexes(SCRUD $Table): array { $diff = []; $SQL = "SELECT a.attname as column_name, i.relname as index_name, ix.indisunique as index_unique FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid and i.oid = ix.indexrelid and a.attrelid = t.oid and a.attnum = ANY(ix.indkey) and t.relkind = 'r' and t.relname ='{$Table->code}' ORDER BY t.relname, i.relname "; $indexes = $this->Query($SQL, 'column_name'); foreach ($Table->fields as $code => $field) { if (in_array($code, $Table->keys)) { continue; } if ($field['FOREIGN']) { $field['INDEX'] = true; } if ($field['UNIQUE']) { $field['INDEX'] = true; } if ($field['INDEX'] === 'UNIQUE') { $field['INDEX'] = true; $field['UNIQUE'] = true; } $unique = ($field['UNIQUE']) ? 'UNIQUE' : ''; $index = $indexes[$code]; // index is: present in database, missing in code - drop it if (isset($index) and !$field['INDEX']) { $diff[] = [ 'MESSAGE' => 'Drop index', 'PRIORITY' => -1, 'TABLE' => $Table->code, 'SQL' => "DROP INDEX " . $this->Quote($index['index_name']), ]; continue; } // index is: missing in database, present in code - create it if ($field['INDEX'] and !isset($index)) { $diff[] = [ 'MESSAGE' => 'Create index', 'PRIORITY' => +1, 'TABLE' => $Table->code, 'SQL' => "CREATE {$unique} INDEX ON {$Table->code} (" . $this->Quote($code) . ")", ]; continue; } // index is: present in database, present in code - check unique if (isset($index)) { if (($field['UNIQUE'] and $index['index_unique'] == 'f') or (!$field['UNIQUE'] and $index['index_unique'] == 't')) { $diff[] = [ 'MESSAGE' => 'Change index (drop)', 'PRIORITY' => -1, 'TABLE' => $Table->code, 'SQL' => "DROP INDEX " . $this->Quote($index['index_name']), ]; $diff[] = [ 'MESSAGE' => 'Change index (create)', 'PRIORITY' => +1, 'TABLE' => $Table->code, 'SQL' => "CREATE {$unique} INDEX ON {$Table->code} (" . $this->Quote($code) . ")", ]; continue; } } } return $diff; } public function CompareTableConstraints(SCRUD $Table): array { $diff = []; $db_constraints = $this->Query(" SELECT tc.table_schema, tc.constraint_name, tc.table_name, kcu.column_name, ccu.table_schema AS foreign_table_schema, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name, rc.update_rule, rc.delete_rule, -1 FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema JOIN information_schema.referential_constraints AS rc ON rc.constraint_name = tc.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='{$Table->code}'; ", 'constraint_name'); foreach ($Table->fields as $code => $field) { if (!$field['FOREIGN'] or $field['TYPE'] <> 'OUTER') continue; $action = is_string($field['FOREIGN']) ? $field['FOREIGN'] : 'RESTRICT'; /** @var SCRUD $Link */ $Link = $field['LINK']::I(); $link_key = $field['INNER_KEY'] ?: $Link->key(); $db_constraint_name = "fkey {$Table->code}.{$code} ref {$Link->code}.{$link_key}"; $db_constraint = $db_constraints[$db_constraint_name]; if (empty($db_constraint)) { $diff[] = [ 'MESSAGE' => 'Create constraint', 'PRIORITY' => +2, 'TABLE' => $Table->code, 'SQL' => "ALTER TABLE {$Table->code} ADD CONSTRAINT \"{$db_constraint_name}\" FOREIGN KEY (\"{$code}\") REFERENCES \"{$Link->code}\" (\"{$link_key}\") ON DELETE {$action} ON UPDATE {$action};", ]; continue; } $is_different = ( false or $Link->code <> $db_constraint['foreign_table_name'] or $link_key <> $db_constraint['foreign_column_name'] or $action <> $db_constraint['update_rule'] or $action <> $db_constraint['delete_rule'] ); if ($is_different) { $diff[] = [ 'MESSAGE' => 'Change constraint (drop)', 'PRIORITY' => -2, 'TABLE' => $Table->code, 'SQL' => "ALTER TABLE {$Table->code} DROP CONSTRAINT \"{$db_constraint['constraint_name']}\";", ]; $diff[] = [ 'MESSAGE' => 'Change constraint (add)', 'PRIORITY' => +2, 'TABLE' => $Table->code, 'SQL' => "ALTER TABLE {$Table->code} ADD CONSTRAINT \"{$db_constraint_name}\" FOREIGN KEY (\"{$code}\") REFERENCES \"{$Link->code}\" (\"{$link_key}\") ON DELETE {$action} ON UPDATE {$action};", ]; } unset($db_constraints[$db_constraint_name]); } foreach ($db_constraints as $db_constraint) { $diff[] = [ 'MESSAGE' => 'Drop constraint', 'PRIORITY' => -2, 'TABLE' => $Table->code, 'SQL' => "ALTER TABLE {$Table->code} DROP CONSTRAINT \"{$db_constraint['constraint_name']}\";", ]; } return $diff; } public function CreateTableConstraints($table, $fields) { foreach ($fields as $code => $field) { if (!isset($field['FOREIGN'])) { continue; } $action = is_string($field['FOREIGN']) ? $field['FOREIGN'] : 'RESTRICT'; /** @var SCRUD $Link */ $Link = $field['LINK']::I(); $link_key = $field['INNER_KEY'] ?: $Link->key(); $this->Query("ALTER TABLE \"{$table}\" ADD FOREIGN KEY (\"{$code}\") REFERENCES \"{$Link->code}\" (\"{$link_key}\") ON DELETE {$action} ON UPDATE {$action}"); } } public function CompileSQLSelect(array $parts) { $SQL = []; $SQL[] = 'SELECT'; // if ($parts['LIMIT']) $SQL[] = 'SQL_CALC_FOUND_ROWS'; $SQL[] = implode(",\r\n", $parts['SELECT']); $SQL[] = "FROM {$parts['TABLE']}"; $SQL[] = implode("\r\n", $parts['JOIN']); if ($parts['WHERE']) $SQL[] = "WHERE " . implode("\r\nAND ", $parts['WHERE']); if ($parts['GROUP']) $SQL[] = "GROUP BY " . implode(", ", $parts['GROUP']); if ($parts['ORDER']) $SQL[] = "ORDER BY " . implode(", ", $parts['ORDER']); if ($parts['LIMIT']) $SQL[] = "LIMIT {$parts['LIMIT']['COUNT']} OFFSET {$parts['LIMIT']['FROM']}"; return implode("\r\n", $SQL); } private function RecreateEnumType() { // TODO make Postgres enum types from strings to actually enums /* CREATE TYPE admin_level1 AS ENUM ('classifier', 'moderator'); CREATE TABLE blah ( user_id integer primary key, power admin_level1 not null ); INSERT INTO blah(user_id, power) VALUES (1, 'moderator'), (10, 'classifier'); ALTER TYPE admin_level1 ADD VALUE 'god'; INSERT INTO blah(user_id, power) VALUES (42, 'god'); -- .... oops, maybe that was a bad idea CREATE TYPE admin_level1_new AS ENUM ('classifier', 'moderator'); -- Remove values that won't be compatible with new definition -- You don't have to delete, you might update instead DELETE FROM blah WHERE power = 'god'; -- Convert to new type, casting via text representation ALTER TABLE blah ALTER COLUMN power TYPE admin_level1_new USING (power::text::admin_level1_new); -- and swap the types DROP TYPE admin_level1; ALTER TYPE admin_level1_new RENAME TO admin_level1; */ } public function Truncate($table) { $this->Query("TRUNCATE TABLE {$table} RESTART IDENTITY"); } }<file_sep><?php namespace BlackFox; class TypeSet extends Type { public $db_type = 'set'; public function FormatInputValue($values) { if (!is_array($values)) { $values = [$values]; } foreach ($values as $value) { if (!isset($this->field['VALUES'][$value])) { throw new ExceptionType("Unknown set value '{$value}' for field '{$this->field['NAME']}'"); } } $value = implode(',', $values); return $value; } public function FormatOutputValue($element) { $code = $this->field['CODE']; if (empty($element[$code])) { $element[$code] = []; } else { $element[$code] = explode(",", $element[$code]); } $element["$code|VALUES"] = []; foreach ($element["$code"] as $key) { $element["$code|VALUES"][$key] = $this->field['VALUES'][$key]; } return $element; } public function PrintValue($value) { if (empty($value)) return; ?> <ul class="set"> <? foreach ($value as $code): ?> <li><?= $this->field['VALUES'][$code] ?></li> <? endforeach; ?> </ul> <? } public function PrintFormControl($value, $name, $class = 'form-control') { ?> <input type="hidden" name="<?= $name ?>" value="" /> <? foreach ($this->field['VALUES'] as $code => $display): ?> <div> <label class="enum"> <input type="checkbox" class="<?= $class ?>" name="<?= $name ?>[]" value="<?= $code ?>" <?= (in_array($code, $value ?: [])) ? 'checked' : '' ?> <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> > <span class="dashed"><?= $display ?></span> </label> </div> <? endforeach; ?> <? } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { $code = $this->field['CODE']; ?> <input type="hidden" name="<?= $group ?>[<?= $code ?>]" value="" /> <? foreach ($this->field['VALUES'] as $value => $display): ?> <div class="col-xs-3"> <label class="enum"> <input type="checkbox" class="<?= $class ?>" name="<?= $group ?>[<?= $code ?>][]" value="<?= $value ?>" <?= (in_array($value, $filter[$code] ?: [])) ? 'checked' : '' ?> <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> > <span class="dashed"><?= $display ?></span> </label> </div> <? endforeach; ?> <? } }<file_sep><?php namespace BlackFox; class Redirects extends \BlackFox\SCRUD { public function Init() { $this->name = T([ 'en' => 'Redirects', 'ru' => 'Редиректы', ]); $this->fields = [ 'ID' => self::ID, 'URL' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'URL', 'ru' => 'Адрес', ]), 'NOT_NULL' => true, 'INDEX' => true, 'UNIQUE' => true, ], 'REDIRECT' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Redirect', 'ru' => 'Редирект', ]), 'NOT_NULL' => true, ], 'COUNT' => [ 'TYPE' => 'INTEGER', 'NAME' => T([ 'en' => 'Click counter', 'ru' => 'Количество переходов', ]), 'DEFAULT' => 0, 'NOT_NULL' => true, 'DISABLED' => true, ], 'NOTES' => [ 'TYPE' => 'TEXT', 'NAME' => T([ 'en' => 'Notes', 'ru' => 'Заметки', ]), ], ]; } } <file_sep><?php /** @var \BlackFox\Engine $this */ $this->TITLE = 'Router example'; ?> <pre> <? print_r($this->ParseUrlPathRelative()); ?> </pre> <file_sep><?php /** @var \BlackFox\Unit $this */ ?> <div class="authorization"> <h1 class="text-center my-3"><?= $this->PARAMS['TITLE'] ?></h1> <div class=" col-sm-8 offset-sm-2 col-md-6 offset-md-3 " > <? $this->ShowAlerts(); ?> <form class="form card p-3" method="POST"> <div class="form-group"> <input type="text" name="login" value="<?= $RESULT['LOGIN'] ?>" class="form-control" placeholder="<?= T([ 'en' => 'Login', 'ru' => 'Логин', ]) ?>" <? if (empty($RESULT['LOGIN'])): ?> autofocus="autofocus" <? endif; ?> /> </div> <div class="form-group"> <input type="<PASSWORD>" name="password" class="form-control" placeholder="<?= T([ 'en' => '<PASSWORD>', 'ru' => '<PASSWORD>', ]) ?>" <? if (!empty($RESULT['LOGIN'])): ?> autofocus="autofocus" <? endif; ?> /> </div> <? if ($this->PARAMS['CAPTCHA']): ?> <div class="form-group text-center"> <? \BlackFox\Captcha::I()->Show(['CSS_CLASS' => 'd-inline-block']) ?> </div> <? endif; ?> <div class="form-group text-center mb-0"> <button type="submit" class="btn btn-primary" name="ACTION" value="Login"> <span class="material-icons">login</span> <?= T([ 'en' => 'Sing in', 'ru' => 'Войти', ]) ?> </button> </div> </form> </div> <? if ($this->PARAMS['REGISTRATION']): ?> <div class="form-group text-center"> <a class="btn btn-link" href="<?= $this->PARAMS['REGISTRATION'] ?>"><?= T([ 'en' => 'Registration', 'ru' => 'Регистрация', ]) ?></a> </div> <? endif; ?> </div><file_sep><?php namespace BlackFox; class TypeText extends Type { public $db_type = 'text'; public function PrintValue($value) { if ($this->field['WYSIWYG']) { $value = htmlspecialchars_decode($value); $value = strip_tags($value); } if (mb_strlen($value) > 250) { $value = mb_substr($value, 0, 250) . '...'; } echo $value; } public function PrintFormControl($value, $name, $class = 'form-control') { ?> <textarea class="<?= $class ?>" id="<?= $name ?>" name="<?= $name ?>" <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> rows="5" <? if ($this->field['WYSIWYG']): ?> data-wysiwyg="" data-wysiwyg-height="300" <? endif; ?> ><?= $value ?></textarea> <? } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { $code = $this->field['CODE']; ?> <input type="text" class="<?= $class ?>" id="<?= $group ?>[~<?= $code ?>]" name="<?= $group ?>[~<?= $code ?>]" value="<?= $filter['~' . $code] ?>" /> <? } }<file_sep><?php namespace BlackFox; class ExceptionSQL extends Exception { public $error; public $SQL; public function __construct($error, $SQL) { $this->error = $error; $this->SQL = $SQL; $message = implode($this->getImplodeSymbols(), [ $error, '<pre>', $SQL, '</pre>', ]); parent::__construct($message); } }<file_sep><?php /**@var BlackFox\Engine $this */ $this->TITLE = T([ 'en' => 'Control panel', 'ru' => 'Панель управления', ]); ?> <ul> <li><a href="SchemeSynchronizer.php">SchemeSynchronizer</a></li> <li><a href="PHPConsole.php">PHPConsole</a></li> <li><a href="SQLConsole.php">SQLConsole</a></li> </ul> <file_sep><?php /** @var \BlackFox\Engine $this */ ?> <!DOCTYPE html> <html> <head> <?= $this->GetHeader() ?> <title><?= $this->TITLE ?></title> </head> <body> <h1><?= $this->TITLE ?></h1> <?= $this->CONTENT ?> </body> </html><file_sep><?php BlackFox\AdminerFiles::Run(['SCRUD' => '\BlackFox\Files']);<file_sep><?php namespace BlackFox; class TableSettings extends SCRUD { public function Init() { $this->name = T([ 'en' => 'Personal table settings', 'ru' => 'Персональные настройки таблиц', ]); $this->fields = [ 'ID' => self::ID, 'USER' => [ 'TYPE' => 'OUTER', 'NAME' => T([ 'en' => 'User', 'ru' => 'Пользователь', ]), 'LINK' => 'BlackFox\Users', ], 'ENTITY' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Entity', 'ru' => 'Сущность', ]), 'NOT_NULL' => true, ], 'FILTERS' => [ 'TYPE' => 'LIST', 'NAME' => T([ 'en' => 'Filters set', 'ru' => 'Набор фильтров', ]), ], 'FIELDS' => [ 'TYPE' => 'LIST', 'NAME' => T([ 'en' => 'Fields set', 'ru' => 'Набор полей', ]), ], ]; } /** * Saves display settings of entity table * Сохраняет настройки отображения таблицы сущности * * @param int $user_id user identifier * @param string $entity_code symbolic code of entity * @param array $filters sorted list of filters * @param array $fields sorted list of fields * @throws \BlackFox\Exception */ public function Save($user_id, $entity_code, $filters, $fields) { $element = $this->Read([ 'USER' => $user_id, 'ENTITY' => $entity_code, ]); if (empty($element)) { $this->Create([ 'USER' => $user_id, 'ENTITY' => $entity_code, 'FILTERS' => $filters, 'FIELDS' => $fields, ]); } else { $this->Update($element['ID'], [ 'FILTERS' => $filters, 'FIELDS' => $fields, ]); } } } <file_sep><?php require_once("classes/patterns/Instance.php"); require_once("classes/abstract/ACore.php"); require_once("classes/Engine.php"); require_once("functions/debug.php"); require_once("functions/T.php"); @include_once(__DIR__ . '/../includes.php'); <file_sep><?php // Script for initial install from console if (php_sapi_name() <> 'cli') die('Console usage only'); $_SERVER["DOCUMENT_ROOT"] = __DIR__ . '/../'; require_once("includes.php"); \BlackFox\Engine::I()->Upgrade(); echo "\r\n BlackFox core has been upgraded;"; try { $group_id = \BlackFox\Groups::I()->Create([ 'CODE' => 'root', 'NAME' => 'Root', ]); echo "\r\n Group 'root' created;"; $user_id = \BlackFox\Users::I()->Create([ 'LOGIN' => 'Root', 'PASSWORD' => '<PASSWORD>', ]); echo "\r\n User 'Root' created;"; \BlackFox\Users2Groups::I()->Create([ 'USER' => $user_id, 'GROUP' => $group_id, ]); echo "\r\n User linked to group;"; } catch (\BlackFox\Exception $error) { echo "\r\n Error: " . $error->GetMessage(); }<file_sep><?php /**@var BlackFox\Engine $this */ $this->TITLE = T([ 'en' => 'SQL console', 'ru' => 'SQL консоль', ]); ?> <form method="post"> <div class="form-group"> <textarea class="form-control" name="SQL" rows="5" ><?= htmlspecialchars($_REQUEST['SQL']) ?></textarea> </div> <input type="submit" value="<?= T([ 'en' => 'Execute', 'ru' => 'Выполнить', ]) ?>" class="btn btn-success" /> </form> <?php if (!empty($_REQUEST['SQL'])) { echo '<hr/>'; try { $data = $this->Database->Query($_REQUEST['SQL']); } catch (\BlackFox\ExceptionSQL $error) { echo "<div class='alert alert-danger'>{$error->getMessage()}</pre></div>"; } } ?> <? if (!empty($data)): ?> <table class="table table-bordered table-hover bg-white"> <tr> <? foreach (reset($data) as $column => $trash_value): ?> <th><?= $column ?></th> <? endforeach; ?> </tr> <? foreach ($data as $row): ?> <tr> <? foreach ($row as $column => $value): ?> <td><?= htmlspecialchars($value) ?></td> <? endforeach; ?> </tr> <? endforeach; ?> </table> <? endif; ?> <file_sep><?php namespace BlackFox; class HtmlImage { /** * Shows image as adaptive div with 100% width and proportional height. * * @param string $src path to image * @param float $proportion height/width * @param string $position css background-position (optional, default: center center) */ public static function Proportional($src, $proportion = 1.0, $position = 'center center') { ?> <div style="position: relative; width: 100%;"> <div style="display: block; padding-top: <?= ceil($proportion * 100) ?>%; "></div> <div style=" position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-image: url('<?= $src ?>'); background-size: cover; background-position: <?= $position ?>; "></div> </div> <? } /** * Shows image as adaptive div with 100% width and specified height. * * @param string $src path to image * @param string $height height with units (for example: '100px') * @param string $position css background-position (optional, default: center center) */ public static function FixedHeight($src, $height, $position = 'center center') { ?> <div style="position: relative; width: 100%;"> <div style="display: block; padding-top: <?= $height ?>; "></div> <div style=" position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-image: url('<?= $src ?>'); background-size: cover; background-position: <?= $position ?>; "></div> </div> <? } /** * Shows image as adaptive div with 100% width and 100% height. * Requires to be in container with height. * * @param string $src path to image * @param string $position css background-position (optional, default: center center) */ public static function Fill($src, $position = 'center center') { ?> <div style="position: relative; width: 100%; height: 100%;"> <div style=" position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-image: url('<?= $src ?>'); background-size: cover; background-position: <?= $position ?>; "></div> </div> <? } }<file_sep><?php namespace BlackFox; class TypeArray extends TypeText { public function FormatInputValue($value) { $value = is_array($value) ? $value : [$value]; $value = json_encode($value, JSON_UNESCAPED_UNICODE); return parent::FormatInputValue($value); } public function FormatOutputValue($element) { $code = $this->field['CODE']; $element[$code] = json_decode($element[$code], true); if (json_last_error()) { $element[$code] = null; } return $element; } public function PrintValue($value) { echo '<pre>'; print_r($value); echo '</pre>'; } public function PrintFormControl($value, $name, $class = 'form-control') { ?> <textarea class="<?= $class ?>" id="<?= $name ?>" name="<?= $name ?>" disabled="disabled" rows="5" ><? print_r($value) ?></textarea> <? } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { } }<file_sep><?php namespace BlackFox; class TypeDateTime extends Type { public $db_type = 'datetime'; public function FormatInputValue($value) { if (is_numeric($value)) { $value = date('Y-m-d H:i:s', $value); } else { $value = date('Y-m-d H:i:s', strtotime($value)); } return $value; } public function FormatOutputValue($element) { $code = $this->field['CODE']; $element[$code . '|TIMESTAMP'] = strtotime($element[$code]); return $element; } /* * // TODO replicate somewhere ? public function GetStructureString() { $string = parent::GetStructureString(); if ($this->info['TRIGGER'] === 'CREATE') { $string = "{$string} DEFAULT CURRENT_TIMESTAMP"; } if ($this->info['TRIGGER'] === 'UPDATE') { $string = "{$string} ON UPDATE CURRENT_TIMESTAMP"; } return $string; } */ public function PrepareConditions($table, $operator, $values) { if ($operator === '~') { $code = $this->field['CODE']; $data = date('Y-m-d', strtotime($values)); $condition = "DATE({$table}." . $this->DB->Quote($code) . ") = '{$data}'"; return ['~' => $condition]; } return parent::PrepareConditions($table, $operator, $values); } public function PrintFormControl($value, $name, $class = 'form-control') { ?> <input type="text" class="form-control" id="<?= $name ?>" name="<?= $name ?>" placeholder="" value="<?= $value ?>" <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> data-datetimepicker="" /> <? } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { $code = $this->field['CODE']; ?> <div class="row no-gutters"> <div class="col-6"> <input type="text" class="<?= $class ?>" id="<?= $group ?>[><?= $code ?>]" name="<?= $group ?>[><?= $code ?>]" placeholder="<?= T([ 'en' => 'from', 'ru' => 'от', ]) ?>" value="<?= $filter['>' . $code] ?>" data-datetimepicker="" /> </div> <div class="col-6"> <input type="text" class="<?= $class ?>" id="<?= $group ?>[><?= $code ?>]" name="<?= $group ?>[<<?= $code ?>]" placeholder="<?= T([ 'en' => 'to', 'ru' => 'до', ]) ?>" value="<?= $filter['<' . $code] ?>" data-datetimepicker="" /> </div> </div> <? } }<file_sep><?php namespace BlackFox; class TypeBoolean extends Type { public $db_type = 'bool'; public function FormatOutputValue($element) { $value = &$element[$this->field['CODE']]; if ($value === 'f') { $value = false; } else { $value = (bool)$value; } return $element; } public function FormatInputValue($value) { return $value ? 1 : 0; } public function ProvideInfoIntegrity() { $this->field['NOT_NULL'] = true; $this->field['DEFAULT'] = (bool)($this->field['DEFAULT'] ?: false); } public function PrintValue($value) { echo ($value) ? T([ 'en' => 'Yes', 'ru' => 'Да', ]) : T([ 'en' => 'No', 'ru' => 'Нет', ]); } public function PrintFormControl($value, $name, $class = 'form-control') { ?> <input type="hidden" name="<?= $name ?>" value="0" /> <input style="margin: 0.4rem 0" type="checkbox" id="<?= $name ?>" name="<?= $name ?>" placeholder="" value="1" <?= ($value) ? 'checked' : '' ?> <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> /> <? } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { $code = $this->field['CODE']; ?> <select class="<?= $class ?>" name="<?= $group ?>[<?= $code ?>]" > <option value=""><?= T([ 'en' => '- do not filter -', 'ru' => '- не фильтровать -', ]) ?></option> <option value="0" <?= ($filter[$code] === '0') ? 'selected' : '' ?>><?= T([ 'en' => 'No', 'ru' => 'Нет', ]) ?></option> <option value="1" <?= ($filter[$code] === '1') ? 'selected' : '' ?>><?= T([ 'en' => 'Yes', 'ru' => 'Да', ]) ?></option> </select> <? } }<file_sep><?php // require_once('<Site>/classes/Engine.php');<file_sep><?php /** * This is an example of /config.php * * Tasks: * - replace word 'Site' with the unique name of your project's folder\namespace * - select database engine * - configure key 'database' * - delete this comment */ return [ 'debug' => true, 'cores' => [ 'Site' => $_SERVER['DOCUMENT_ROOT'] . '/Site', 'BlackFox' => $_SERVER['DOCUMENT_ROOT'] . '/BlackFox', ], 'roots' => [ '/Site/root' => $_SERVER['DOCUMENT_ROOT'] . '/Site/root', '/BlackFox/root' => $_SERVER['DOCUMENT_ROOT'] . '/BlackFox/root', ], 'templates' => [ 'main' => '/Site/templates/main', 'admin' => '/BlackFox/templates/admin', ], 'languages' => [ //'en' => 'English', //'ru' => 'Русский', ], 'overrides' => [ // pick one: // 'BlackFox\Database' => 'BlackFox\MySQL', // 'BlackFox\Database' => 'BlackFox\Postgres', // pick none or one: // 'BlackFox\Captcha' => 'BlackFox\KCaptcha', // 'BlackFox\Captcha' => 'BlackFox\CaptchaGoogleRecaptchaV2', // pick none or one: // 'BlackFox\Cache' => 'BlackFox\CacheRedis', ], 'database' => [ 'HOST' => 'localhost', 'PORT' => 3306, 'USER' => '', 'PASSWORD' => '', 'DATABASE' => '', ], ];<file_sep><?php namespace BlackFox; class _dummy extends \BlackFox\Unit { public function GetActions(array $request = []) { return parent::GetActions($request); } public function Default() { } } <file_sep><? /** @var \BlackFox\Adminer $this */ ?> <? /** @var array $RESULT */ ?> <? /** @var array $SELECTED */ ?> <? /** @var string $NAME */ ?> <div class="mb-2 d-flex justify-content-center"> <button type="button" class="btn btn-outline-secondary text-nowrap" data-settings-select="settings-<?= $NAME ?>"> <span class="material-icons">done_all</span> <span class="d-none d-md-inline-block"><?= T([ 'en' => 'Select all', 'ru' => 'Выбрать все', ]) ?></span> </button> <button type="button" class="btn btn-outline-secondary text-nowrap" data-settings-unselect="settings-<?= $NAME ?>"> <span class="material-icons">remove_done</span> <span class="d-none d-md-inline-block"><?= T([ 'en' => 'Unselect all', 'ru' => 'Снять все', ]) ?></span> </button> <button type="button" class="btn btn-outline-secondary text-nowrap" data-settings-sort="settings-<?= $NAME ?>"> <span class="material-icons">sort</span> <span class="d-none d-md-inline-block"><?= T([ 'en' => 'Sort by default', 'ru' => 'Сортировать', ]) ?></span> </button> </div> <ul class="sortable" data-connected-sortable="settings-<?= $NAME ?>" id="settings-<?= $NAME ?>"> <? $unselected = $this->SCRUD->fields; ?> <? foreach ($SELECTED as $code): ?> <? $field = $this->SCRUD->fields[$code] ?> <? unset($unselected[$code]) ?> <li data-order="<?= array_search($code, array_keys($this->SCRUD->fields)) ?>"> <label class="m-0"> <input type="checkbox" name="<?= $NAME ?>[]" value="<?= $code ?>" checked="checked" /> <span><?= $field['NAME'] ?></span> </label> </li> <? endforeach; ?> <? foreach ($unselected as $code => $field): ?> <li data-order="<?= array_search($code, array_keys($this->SCRUD->fields)) ?>"> <label class="m-0"> <input type="checkbox" name="<?= $NAME ?>[]" value="<?= $code ?>" /> <span><?= $field['NAME'] ?></span> </label> </li> <? endforeach; ?> </ul> <file_sep><?php namespace BlackFox; class AdminerUsers extends Adminer { public function Execute($PARAMS = [], $REQUEST = []) { $PARAMS['SCRUD'] = \BlackFox\Users::N(); parent::Execute($PARAMS, $REQUEST); } public function Init($PARAMS = []) { parent::Init($PARAMS); unset($this->SCRUD->fields['SALT']); unset($this->SCRUD->fields['HASH']); unset($this->SCRUD->fields['PASSWORD']); $this->SCRUD->ProvideIntegrity(); $this->actions += [ 'Login' => [ 'NAME' => T([ 'en' => 'Authorize', 'ru' => 'Авторизоваться', ]), 'ICON' => 'vpn_key', 'DESCRIPTION' => T([ 'en' => 'Authorize by this user', 'ru' => 'Авторизоваться под этим пользователем', ]), ], 'SetPassword' => [ 'NAME' => T([ 'en' => 'Set new password', 'ru' => 'Установить новый пароль', ]), 'ICON' => 'password', 'PARAMS' => [ 'password' => [ 'TYPE' => 'PASSWORD', 'NAME' => T([ 'en' => 'Password', 'ru' => 'Пароль', ]), 'NOT_NULL' => true, ], ], ], ]; } public function Login($ID) { User::I()->Login($ID); $this->Redirect('/'); } public function SetPassword($ID, $password) { Users::I()->SetPassword($ID, $password); return T([ 'en' => 'New password has been set', 'ru' => 'Новый пароль установлен', ]); } }<file_sep><?php namespace BlackFox; class ExceptionNotAllowed extends Exception { }<file_sep><?php namespace BlackFox; class Authorization extends Unit { public function __construct() { parent::__construct(); $this->name = T([ 'en' => 'Authorization', 'ru' => 'Авторизация', ]); $this->description = T([ 'en' => 'Provides a form and authorization mechanism on the site', 'ru' => 'Предоставляет форму и механизм авторизации на сайте', ]); $this->options = [ 'CAPTCHA' => [ 'TYPE' => 'BOOLEAN', 'NAME' => T([ 'en' => 'Use captcha', 'ru' => 'Использовать каптчу', ]), 'DEFAULT' => true, ], 'MESSAGE' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Message', 'ru' => 'Сообщение', ]), 'DEFAULT' => '', ], 'TITLE' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Title', 'ru' => 'Заголовок', ]), 'DEFAULT' => T([ 'en' => 'Authorization', 'ru' => 'Авторизация', ]), ], 'REDIRECT' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Redirect', 'ru' => 'Переадресация', ]), 'DESCRIPTION' => T([ 'en' => 'Where to redirect the user upon successful authorization', 'ru' => 'Куда переадресовать пользователя при успешной авторизации', ]), 'DEFAULT' => null, ], 'REGISTRATION' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Registration', 'ru' => 'Регистрация', ]), 'DESCRIPTION' => T([ 'en' => 'Link to registration', 'ru' => 'Ссылка на регистрацию', ]), 'DEFAULT' => null, ], ]; $this->allow_ajax_request = true; $this->allow_json_request = true; } public function GetActions(array $request = []) { if ($request['ACTION'] === 'Login') { return ['Login', 'Form']; } return ['Form']; } public function Form($login = null, $password = null, $redirect = null) { $this->ENGINE->TITLE = $this->name; if ($this->PARAMS['MESSAGE'] and empty($this->ALERTS)) { $this->ALERTS[] = ['TYPE' => 'info', 'TEXT' => $this->PARAMS['MESSAGE']]; } if (!empty($redirect)) { $_SESSION['USER']['REDIRECT'] = $redirect; } return [ 'LOGIN' => $login, 'PASSWORD' => $<PASSWORD>, ]; } public function Login($login = null, $password = null) { if ($this->PARAMS['CAPTCHA']) { if (!Captcha::I()->Check()) { throw new ExceptionCaptcha(T([ 'en' => 'You must pass the captcha', 'ru' => 'Необходимо пройти капчу', ])); } } User::I()->Authorization($login, $password); $url = $this->PARAMS['REDIRECT']; if ($_SESSION['USER']['REDIRECT']) { $url = $_SESSION['USER']['REDIRECT']; unset($_SESSION['USER']['REDIRECT']); } $this->Redirect($url); } } <file_sep><?php return [ 'TITLE' => T([ 'en' => 'Administrative section', 'ru' => 'Административная часть', ]), 'TEMPLATE' => 'admin', 'ACCESS' => [ '*' => false, 'root' => true, ], ];<file_sep><?php namespace BlackFox; class Files extends SCRUD { public function Init() { $this->name = T([ 'en' => 'Files', 'ru' => 'Файлы', ]); $this->groups = [ 'SYSTEM' => T([ 'en' => 'System fields', 'ru' => 'Системные поля', ]), 'FILE' => T([ 'en' => 'File', 'ru' => 'Файл', ]), ]; $this->fields += [ 'ID' => self::ID + ['GROUP' => 'SYSTEM'], 'CREATE_DATE' => [ 'TYPE' => 'DATETIME', 'NAME' => T([ 'en' => 'Create date', 'ru' => 'Дата создания', ]), 'GROUP' => 'SYSTEM', 'DISABLED' => true, ], 'CREATE_BY' => [ 'TYPE' => 'OUTER', 'NAME' => T([ 'en' => 'Created by', 'ru' => 'Кем создан', ]), 'LINK' => 'Users', 'GROUP' => 'SYSTEM', 'DISABLED' => true, ], 'NAME' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Name', 'ru' => 'Имя', ]), 'VITAL' => true, 'GROUP' => 'FILE', ], 'SIZE' => [ 'TYPE' => 'INTEGER', 'NAME' => T([ 'en' => 'Size', 'ru' => 'Размер', ]), 'VITAL' => true, 'GROUP' => 'FILE', ], 'TYPE' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Type', 'ru' => 'Тип', ]), 'VITAL' => true, 'GROUP' => 'FILE', ], 'SRC' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Src', 'ru' => 'Путь', ]), 'VITAL' => true, 'GROUP' => 'FILE', ], ]; } public function GetNewSrc($full_name) { $extension = end(explode('.', $full_name)); if (empty($extension)) { throw new Exception(T([ 'en' => "File must have extension", 'ru' => 'Файл должен обладать расширением', ])); } $dir = ''; $src = ''; while (true) { $name = sha1(time() . $full_name) . '.' . $extension; $dir = '/upload/' . substr($name, 0, 3); $src = $dir . '/' . $name; if (file_exists($_SERVER['DOCUMENT_ROOT'] . $src)) { continue; } break; } @mkdir($_SERVER['DOCUMENT_ROOT'] . '/upload'); @mkdir($_SERVER['DOCUMENT_ROOT'] . $dir); return $src; } public function Create($fields = []) { if (isset($fields['tmp_name'])) { if ($fields['error'] !== 0) { return null; } $src = $this->GetNewSrc($fields['name']); move_uploaded_file($fields['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . $src); return parent::Create([ 'CREATE_DATE' => time(), 'CREATE_BY' => User::I()->ID, 'NAME' => $fields['name'], 'SIZE' => $fields['size'], 'TYPE' => $fields['type'], 'SRC' => $src, ]); } else { return parent::Create($fields); } } public function Update($ids = array(), $fields = array()) { throw new ExceptionNotAllowed(); } public function CreateFromContent($name, $content) { $src = $this->GetNewSrc($name); $path = $_SERVER['DOCUMENT_ROOT'] . $src; file_put_contents($path, $content); return $this->Create([ 'CREATE_DATE' => time(), 'NAME' => $name, 'SIZE' => filesize($path), 'TYPE' => filetype($path), 'SRC' => $src, ]); } public function GetElementTitle(array $element = []) { return $element['NAME']; } public function GetPrintableFileSize($size) { if ($size > 1024 * 1024) { return ceil($size / 1024 * 1024) . T([ 'en' => ' mb.', 'ru' => ' мб.', ]); } if ($size > 1024) { return ceil($size / 1024) . T([ 'en' => ' kb.', 'ru' => ' кб.', ]); } return $size . T([ 'en' => ' b.', 'ru' => ' б.', ]); } }<file_sep><?php /** @var \BlackFox\Unit $this */ /** @var array $RESULT */ $this->ENGINE->TITLE = T([ 'en' => 'Scheme synchronizer', 'ru' => 'Синхронизатор схем', ]); ?> <form method="post" class="~float-right"> <a class="btn btn-secondary" href="?" > <span class="material-icons">sync</span> <?= T([ 'en' => 'Refresh', 'ru' => 'Обновить', ]) ?> </a> <button type="submit" name="ACTION" value="SynchronizeAll" class="btn btn-primary" > <span class="material-icons">sync_problem</span> <?= T([ 'en' => 'Synchronize all', 'ru' => 'Синхронизировать всё', ]) ?> </button> </form> <hr/> <? foreach ($RESULT['CORES'] as $namespace => $CORE): ?> <h2> <span class="material-icons">folder_open</span> <?= $namespace ?> </h2> <? if (!empty($CORE['ERROR'])): ?> <div class="alert alert-danger"> <?= $CORE['ERROR'] ?> </div> <? elseif (empty($CORE['DIFFS'])): ?> <div class="alert alert-success"> <span class="material-icons">download_done</span> <?= T([ 'en' => 'Everything is synchronized', 'ru' => 'Всё синхронизированно', ]) ?> </div> <? else: ?> <table class="table table-bordered table-hover bg-white"> <tr> <th>...</th> <th>SQL</th> <th></th> </tr> <? foreach ($CORE['DIFFS'] as $diff): ?> <tr> <td> <?= $diff['MESSAGE'] ?><!-- <? if ($diff['TABLE']): ?> -->: <strong><?= $diff['TABLE'] ?></strong> <? if ($diff['FIELD']): ?> <ul class="mb-0"> <li><?= $diff['FIELD'] ?></li> </ul> <? endif; ?> <? if (!empty($diff['DATA'])): ?> <ul> <? foreach ($diff['DATA'] as $data): ?> <li> <?= $data['MESSAGE'] ?><!-- <? if ($data['FIELD']): ?> -->: <strong><?= $data['FIELD'] ?></strong> <? if ($data['REASON']): ?> <?= $data['REASON'] ?> <? endif; ?> <!-- <? endif; ?> --> </li> <? endforeach; ?> </ul> <? endif; ?> <!-- <? endif; ?> --> </td> <td> <div class="mb-0" style="white-space: pre-line; font-family: monospace; font-size: 16px;"><?= $diff['SQL'] ?></div> <? /* <? if (!empty($diff['DATA'])): ?> <br/> <table class="table-bordered"> <tr> <th>Message</th> <th>Column</th> <th>Reason</th> <th>SQL</th> </tr> <? foreach ($diff['DATA'] as $data): ?> <tr> <td><?= $data['MESSAGE'] ?></td> <td><?= $data['FIELD'] ?></td> <td><?= $data['REASON'] ?></td> <td> <pre class="mb-0"><?= $data['SQL'] ?></pre> </td> </tr> <? endforeach; ?> </table> <? endif; ?> */ ?> </td> <td> <? if ($RESULT['MODE'] === 'Compare'): ?> <form method="post"> <input type="hidden" name="SQL" value="<?= htmlspecialchars($diff['SQL']) ?>" /> <button type="submit" name="ACTION" value="RunSQL" class="btn btn-primary" > <span class="material-icons">mediation</span> </button> </form> <? else: ?> <? if ($diff['STATUS'] === 'SUCCESS'): ?> <div class="alert alert-success">Success</div> <? else: ?> <div class="alert alert-danger"><?= $diff['ERROR'] ?></div> <? endif; ?> <? endif; ?> </td> </tr> <? endforeach; ?> </table> <? endif; ?> <? endforeach; ?><file_sep><?php namespace BlackFox; class Utility { /** * Форматирует дату в любом формате (стока|таймштамп) * Возвращает пустую строку если дата пуста * * @param string|int $date дата в любом формате * @param string $format формат (по умолчанию 'd.m.Y H:i') * @return string отформатированная дата */ public static function Date($date, $format = 'd.m.Y H:i') { if (empty($date)) { return ''; } if (!is_numeric($date)) { $date = strtotime($date); } return date($format, $date); } public static function strftime($date, $format = '%e %h %G, %H:%M') { if (empty($date)) { return ''; } if (!is_numeric($date)) { $date = strtotime($date); } $answer = strftime($format, $date); /* if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $format = iconv('utf-8', 'cp1251', $format); $answer = strftime($format, $date); $answer = iconv('cp1251', 'utf-8', $answer); } */ return $answer; } /** * Форматирует имя пользователя * * @param array $user массив данных пользователя (FIRST_NAME, LAST_NAME, LOGIN, ID) * @return string */ public static function Name($user = []) { $name = trim("{$user['FIRST_NAME']} {$user['LAST_NAME']}"); if (empty($name)) { $name = $user['LOGIN']; } if (empty($name)) { $name = "[ID:{$user['ID']}]"; } return $name; } /** * Если передан массив - возвращает из него значение идентификатора, * в ином случае - возвращает то что было передано * * @param array|string|int $element_or_id элемент или идентификатор * @param string $key символьный код идентификатора, не обязательно, по умолчанию - 'ID' * @return string|int */ public static function GetID($element_or_id, $key = 'ID') { return is_array($element_or_id) ? $element_or_id[$key] : $element_or_id; } }<file_sep><?php /** @var \BlackFox\Adminer $this */ ?> <?php /** @var array $RESULT */ ?> <button class="btn btn-primary" type="submit" name="REDIRECT" value="<?= $RESULT['BACK'] ?>" > <span class="material-icons">save</span> <span class="d-none d-md-inline-block"><?= T([ 'en' => 'Save', 'ru' => 'Сохранить', ]) ?></span> </button> <button class="btn btn-success" type="submit" name="REDIRECT" value="" > <span class="material-icons">save_alt</span> <span class="d-none d-md-inline-block"><?= T([ 'en' => 'Apply', 'ru' => 'Применить', ]) ?></span> </button> <a href="<?= $RESULT['BACK'] ?>" class="btn btn-secondary" > <span class="material-icons">block</span> <span class="d-none d-md-inline-block"><?= T([ 'en' => 'Cancel', 'ru' => 'Отмена', ]) ?></span> </a> <? if ($RESULT['MODE'] === 'Update'): ?> <button class="btn btn-danger float-right" type="submit" name="ACTION" value="Delete" data-confirm="<?= T([ 'en' => 'Confirm deletion', 'ru' => 'Подтвердите удаление', ]) ?>" > <span class="material-icons">delete_outline</span> <span class="d-none d-md-inline-block"><?= T([ 'en' => 'Delete', 'ru' => 'Удалить', ]) ?></span> </button> <? endif; ?><file_sep><?php namespace BlackFox; class TypeInner extends Type { public $virtual = true; public function ProvideInfoIntegrity() { if (empty($this->field['INNER_KEY'])) { throw new Exception(T([ 'en' => "For field '{$this->field['CODE']}' (of type INNER) you must specify key 'INNER_KEY'", 'ru' => "Для поля '{$this->field['CODE']}' (тип INNER) необходимо указать ключ 'INNER_KEY'", ])); } } public function PrepareSelectAndJoinByField($table, $prefix, $subfields) { // этот метод отвечает только за FIELDS, которые подтягиваются отдельно в методе HookExternalField // this method is only responsible for FIELDS, which are pulled separately in the HookExternalField method return []; } public function HookExternalField($elements, $subfields, $subsort) { if (empty($elements)) return $elements; $code = $this->field['CODE']; $ids = array_keys($elements); foreach ($elements as $id => $element) { $elements[$id][$code] = []; } /** @var SCRUD $Link */ $Link = $this->field['LINK']::I(); $target_key = $this->field['INNER_KEY']; try { $link_key_primary = $Link->key(); } catch (Exception $error) { $link_key_primary = $target_key; } if (empty($subfields)) { $subfields = [$link_key_primary]; } $subfields[$target_key] = $target_key; $data = $Link->Select([ 'FILTER' => [$target_key => $ids], 'FIELDS' => $subfields, 'SORT' => $subsort, ]); foreach ($data as $associative) { $ID = $associative[$target_key]; unset($associative[$target_key]); // remove looking back identifier $elements[$ID][$code][$associative[$link_key_primary]] = $associative; } return $elements; } public function GenerateJoinAndGroupStatements(SCRUD $Current, $prefix) { /** @var SCRUD $Target */ $Target = $this->field['LINK']::I(); $current_alias = $prefix . $Current->code; $current_key = $Current->key(); $target_alias = $prefix . $this->field['CODE'] . '__' . $Target->code; $target_key = $this->field['INNER_KEY']; $join_statement = "LEFT JOIN {$Target->code} AS {$target_alias} ON {$current_alias}." . $this->DB->Quote($current_key) . " = {$target_alias}." . $this->DB->Quote($target_key); $group_statement = "{$Current->code}." . $this->DB->Quote($current_key); return [ 'JOIN' => [$target_alias => $join_statement], 'GROUP' => [$current_alias => $group_statement], ]; } public function PrintValue($value) { /** @var \BlackFox\SCRUD $Link */ $Link = $this->field['LINK']::I(); $url = $Link->GetAdminUrl(); ?> <ul> <? foreach ($value as $row): ?> <li> <nobr> <? if (User::I()->InGroup('root')): ?> [<a target="_top" href="<?= $url ?>?ID=<?= $row['ID'] ?>"><?= $row['ID'] ?></a>] <? endif; ?> <?= $Link->GetElementTitle($row); ?> </nobr> </li> <? endforeach; ?> </ul> <? } public function PrintFormControl($value, $name, $class = 'form-control') { } public function PrintFilterControl($filter, $group = 'FILTER', $class = 'form-control') { } }<file_sep><?php namespace BlackFox; class TypeFile extends TypeOuter { public function ProvideInfoIntegrity() { if (empty($this->field['LINK'])) { $this->field['LINK'] = 'BlackFox\Files'; } } public function FormatInputValue($value) { if (is_numeric($value)) { return (int)$value; } if (is_array($value)) { return $this->field['LINK']::I()->Create($value); } return null; } public function PrintValue($value) { ?> <? if (!empty($value['SRC'])): ?> <? if (User::I()->InGroup('root')): ?> <? /** @var \BlackFox\Files $Link */ $Link = $this->field['LINK']::I(); ?> [<a target="_blank" href="<?= $Link->GetAdminUrl() ?>?ID=<?= $value['ID'] ?>"><?= $value['ID'] ?></a>] <? endif; ?> <a target="_blank" href="<?= $value['SRC'] ?>"><?= $value['NAME'] ?></a> <? endif; ?> <? } public function PrintFormControl($value, $name, $class = 'form-control') { Engine::I()->AddHeaderScript(Engine::I()->GetRelativePath(__DIR__ . '/TypeFile.js')); /** @var \BlackFox\Files $Link */ $Link = $this->field['LINK']::I(); $url = $Link->GetAdminUrl(); $ID = isset($value['ID']) ? $value['ID'] : null; ?> <div data-file=""> <? if (!empty($ID)): ?> <div class="form-control-plaintext"> [<a href="<?= "{$url}?ID={$ID}" ?>"><?= $ID ?></a>] <a target="_blank" href="<?= $value['SRC'] ?>" style="color: green" ><?= $Link->GetElementTitle($value) ?></a> (<?= $Link->GetPrintableFileSize($value['SIZE']) ?>) <label> <input class="<?= $class ?>" data-file-delete="" type="checkbox" name="<?= $name ?>" value="" /> Удалить </label> </div> <? endif; ?> <div data-file-selector="" style="<?= (!empty($ID)) ? 'display: none;' : '' ?>" > <label for="<?= $name ?>"> <span class="btn btn-info"> <span class="material-icons">upload_file</span> <span data-file-name=""><?= T([ 'en' => 'Select file', 'ru' => 'Выбрать файл', ]) ?></span> </span> <input class="d-none invisible <?= $class ?>" type="file" id="<?= $name ?>" name="<?= $name ?>" placeholder="" <?= (!empty($ID)) ? 'disabled' : '' ?> /> </label> </div> </div> <? } }<file_sep>$(function () { // visual auto-completion of file selection $(document).on('change', '[data-file] input:file', function (e) { var filename = $(this).val(); if (filename.substring(3, 11) == 'fakepath') { filename = filename.substring(12); } $(this) .closest('[data-file]') .find('[data-file-name]') .text(filename); }); // expand file selection when deleting it $(document).on('change', '[data-file-delete]', function (e) { if ($(this).prop('checked')) { $(this).closest('[data-file]') .find('[data-file-selector]').slideDown() .find('input:file').prop('disabled', false) ; } else { $(this).closest('[data-file]') .find('[data-file-selector]').slideUp() .find('input:file').prop('disabled', true) ; } }); });<file_sep><?php namespace BlackFox; class Engine { use Instance; public $config = []; public $cores = []; public $roots = []; public $templates = []; /** * dictionary of available classes * - key - is a full class name with namespace * - value - absolute path to the file with class definition * @var array */ public $classes = []; /** * dictionary of available languages * - key - symbolic code of the language * - value - display name of the language * @var array */ public $languages = []; public $url = []; /** @var Database $Database */ public $Database; /** @var User $User */ public $User; /** @var Cache $Cache */ public $Cache; public $TITLE = ""; public $KEYWORDS = ""; public $DESCRIPTION = ""; public $HEADERS = []; public $CONTENT = ""; public $BREADCRUMBS = []; public $SECTION = []; public $TEMPLATE = ""; public $TEMPLATE_PATH = ""; public $WRAPPER = "wrapper"; public $DELAYED = []; public static function GetConfig(): array { return require($_SERVER['DOCUMENT_ROOT'] . '/config.php'); } /** * Engine constructor: * - Initializes configuration * - Initializes (and prolongs) user session * - Links autoload class system to $this->AutoloadClass() * - Links unhandled exception handler to $this->ExceptionHandler() * - Loads module 'BlackFox' * - Initializes the main connection to the default database * - Initializes the main connection to the default cache * @throws Exception * @throws \ReflectionException */ public function __construct() { $this->InitConfig(static::GetConfig()); $this->InitSession(); $this->InitAutoloadClasses(); $this->InitExceptionHandler(); $this->RegisterCoreClasses('BlackFox'); $this->InitDatabase(); $this->InitCache(); } /** * Parses main config into props: config, roots, cores, templates, languages. * @param array $config */ public function InitConfig(array $config) { $this->config = $config; $this->roots = $config['roots']; $this->cores = $config['cores']; $this->templates = $config['templates']; $this->languages = $config['languages']; } public function InitSession() { session_start(); $lifetime = $this->config['session_lifetime'] ?: 7 * 24 * 60 * 60; setcookie(session_name(), session_id(), time() + $lifetime, '/'); } public function InitAutoloadClasses() { spl_autoload_register([$this, 'AutoloadClass']); } public function InitExceptionHandler() { set_exception_handler([$this, 'ExceptionHandler']); } public function ExceptionHandler(\Throwable $Exception) { if (php_sapi_name() <> 'cli') echo '<xmp>'; echo "\r\nFATAL ERROR!"; echo "\r\nMessage: " . $Exception->getMessage(); echo "\r\nFile: " .$Exception->getFile(); echo "\r\nLine: " .$Exception->getLine(); if ($this->config['debug']) { echo "\r\n\r\n"; echo $Exception->getTraceAsString(); echo "\r\n\r\n"; print_r($Exception); } } /** * Initializes the main connection to the default database */ public function InitDatabase() { $this->Database = Database::I(['params' => $this->config['database']]); } /** * Initializes the main connection to the default cache */ public function InitCache() { $this->Cache = Cache::I(['params' => $this->config['cache'] ?: []]); } /** * Checks access for section: * - if user has no access - throws an exception * - if user has access - does nothing * * - group '*' means 'everyone' * - group '@' means 'authorized' * * @param array $rules section rules: ['<group_code>' => '<true\false>', ...] * @throws ExceptionAccessDenied * @throws ExceptionAuthRequired * @internal object $this->USER */ public function CheckSectionAccess($rules = []) { $rules = $rules ?: []; $rules['*'] = isset($rules['*']) ? $rules['*'] : true; if ($rules['*'] === true) { return; } unset($rules['*']); if ($rules['@'] === true) { if ($this->User->IsAuthorized()) { return; } } foreach ($rules as $rule_group => $rule_right) { if ($rule_right === true) { if (in_array($rule_group, $this->User->GROUPS ?: [])) { return; } } } if ($this->User->IsAuthorized()) { throw new ExceptionAccessDenied(T([ 'en' => 'This section requires higher privileges', 'ru' => 'Доступ запрещен', ])); } else { throw new ExceptionAuthRequired(T([ 'en' => 'This section requires authorization', 'ru' => 'Для доступа в этот раздел необходима авторизация', ])); } } /** * Loads all Engine properties associated with requested page: * - SECTION - array content of closest ancestor '.section.php' file * - TEMPLATE - symbol code of template, defined by section * - WRAPPER - symbol code of wrapper, defined by section * - TEMPLATE_PATH - relative path to root of template * - TITLE - title of section * * All these properties can be reset in the future execution of the script! */ public function LoadSectionInfo() { $this->url = parse_url($_SERVER['REQUEST_URI']); if ($this->url === false) throw new Exception("Can't parse url"); $path_to_section_config = $this->SearchAncestorFile($this->url['path'], '.section.php'); $this->SECTION = !empty($path_to_section_config) ? require($path_to_section_config) : []; $this->TITLE = isset($this->SECTION['TITLE']) ? $this->SECTION['TITLE'] : $this->TITLE; if (isset($this->SECTION['TEMPLATE'])) { $this->SetTemplate($this->SECTION['TEMPLATE']); } if (isset($this->SECTION['WRAPPER'])) { $this->SetWrapper($this->SECTION['WRAPPER']); } } /** * Sets props TEMPLATE and TEMPLATE_PATH * @param string $template symbol code of new template * @throws Exception */ public function SetTemplate($template) { if ($template === null) { $this->TEMPLATE = null; $this->TEMPLATE_PATH = null; return; } if (empty($this->templates[$template])) { throw new Exception("Template not found: '{$template}'"); } $this->TEMPLATE = $template; $this->TEMPLATE_PATH = $this->templates[$template]; } /** * Sets prop WRAPPER * @param string $wrapper symbol code of new wrapper * @throws Exception */ public function SetWrapper($wrapper) { if ($wrapper === null) { $this->WRAPPER = null; return; } if (!empty($wrapper)) { $wrapper_file = $this->GetAbsolutePath($this->TEMPLATE_PATH . "/{$wrapper}.php"); if (!file_exists($wrapper_file)) { throw new Exception("Wrapper not found: '{$wrapper}'; of template: '{$this->TEMPLATE}'"); } } $this->WRAPPER = $wrapper; } private function TrimSlashes($string) { return implode('/', array_filter(explode('/', $string))); } /** * Handy to use in .router.php * @param array $keys * @return array of url parts */ public function ParseUrlPathRelative($keys = []) { $file = debug_backtrace()[0]['file']; $file = str_replace('\\', '/', $file); $info = pathinfo($file); $dirname = $info['dirname']; $dirname_relative = null; foreach ($this->roots as $root_relative_folder => $root_absolute_folder) { if (strpos($dirname, $root_absolute_folder) !== false) { $dirname_relative = str_replace($root_absolute_folder, '', $dirname); break; } } $dirname_relative = $this->TrimSlashes($dirname_relative); $path = $this->TrimSlashes($this->url['path']); $request_relative = str_replace($dirname_relative, '', $path); $request_relative = $this->TrimSlashes($request_relative); $result_array = explode('/', $request_relative); if (empty($keys)) { return $result_array; } $result_dictionary = []; foreach ($keys as $index => $key) { $result_dictionary[$key] = $result_array[$index]; } return $result_dictionary; } /** * Loads the default instance of the user */ public function InitUser() { /** @var User $USER */ $this->User = User::I(['ID' => $_SESSION['USER']['ID']]); if (!empty($this->User->FIELDS)) $_SESSION['USER']['LANG'] = $this->User->FIELDS['LANG']; } /** * Main entry point of the Engine: * * - Loads all properties associated with requested page * - Loads the default instance of the user * * - Generates the content by using method $this->ShowContent() * - If needed, generates wrapper and puts content into it * - Outputs the result of the work */ public function Work() { $this->LoadSectionInfo(); $this->InitUser(); $this->SetContent(); $this->WrapContent(); $this->ProcessDelayed(); echo $this->CONTENT; } /** * Launch wrapper * if $this->TEMPLATE and $this->WRAPPER are not empty */ public function WrapContent() { if (empty($this->TEMPLATE) or empty($this->WRAPPER)) { return; } $wrapper = $this->GetAbsolutePath($this->templates[$this->TEMPLATE] . "/{$this->WRAPPER}.php"); if (!file_exists($wrapper)) { throw new Exception("Wrapper file not found: '{$wrapper}'"); } ob_start(); require($wrapper); $this->CONTENT = ob_get_clean(); } /** * For each row in $this->DELAYED calls the callable and replaces designation (in content) with result of call */ public function ProcessDelayed() { foreach ($this->DELAYED as $delayed) { $insert = call_user_func_array($delayed['CALLABLE'], $delayed['PARAMS']); $this->CONTENT = str_replace($delayed['TEMPLATE'], $insert, $this->CONTENT); } } /** * Adds style file to headers. * @param string $path relative/http path to the style file */ public function AddHeaderStyle($path) { $path_absolute = $_SERVER['DOCUMENT_ROOT'] . $path; $version = !file_exists($path_absolute) ? '' : '?' . filemtime($path_absolute); $this->HEADERS[$path] = [ 'TYPE' => 'STYLE', 'PATH' => $path, 'STRING' => "<link rel='stylesheet' href='{$path}{$version}'/>", ]; } /** * Adds script file to headers. * @param string $path relative/http path to the script file */ public function AddHeaderScript($path) { $path_absolute = $_SERVER['DOCUMENT_ROOT'] . $path; $version = !file_exists($path_absolute) ? '' : '?' . filemtime($path_absolute); $this->HEADERS[$path] = [ 'TYPE' => 'SCRIPT', 'PATH' => $path, 'STRING' => "<script src='{$path}{$version}'></script>", ]; } /** * Adds any string to headers. * @param string $string arbitrary string */ public function AddHeaderString($string) { $this->HEADERS[] = [ 'TYPE' => 'STRING', 'STRING' => $string, ]; } /** * Makes and returns printable string of html header, * combining Engine's HEADERS property together. * * @return string */ public function MakeHeader() { $strings = []; foreach ($this->HEADERS as $header) { $strings[] = $header['STRING']; } return implode("\r\n\t", $strings); } /** * Makes and returns a designation of delayed call for MakeHeader method */ public function GetHeader() { return $this->AddDelayedCall([$this, 'MakeHeader']); } /** * Adds row to $this->DELAYED, * returns a designation to print, witch will be replaced later with the result of callable * * @param mixed $callable * @param array $params (optional) * @return string designation to print */ public function AddDelayedCall($callable, $params = []) { $id = uniqid(); $template = "[[[DELAYED_{$id}]]]"; $this->DELAYED[$id] = [ 'TEMPLATE' => $template, 'CALLABLE' => $callable, 'PARAMS' => $params, ]; return $template; } /** * This method tries to generate main content of the page with several steps: * - if requested file exist - executes it and exit * - if requested directory with file 'index.php' exist - executes it and exit * - if there are somewhere in ancestors file '.router.php' exist - executes it and exit * - if redirect exist - does redirect and die * - if content page exist - prints it and exit * If nothing works - throws ExceptionPageNotFound * @throws ExceptionPageNotFound * @throws Exception */ public function MakeContent() { // request for specific file or directory with 'index.php' foreach ($this->roots as $root_absolute_folder) { $request_path = $root_absolute_folder . $this->url['path']; if (is_dir($request_path)) { $request_path .= 'index.php'; } if (file_exists($request_path)) { require($request_path); return; } } // request for non-existing file $path_to_router = $this->SearchAncestorFile($this->url['path'], '.router.php'); if ($path_to_router) { require($path_to_router); return; } // redirect $redirect = Redirects::I()->Read(['URL' => $this->url['path']]); if ($redirect) { Redirects::I()->Update($redirect['ID'], ['COUNT' => $redirect['COUNT'] + 1]); header("Location: {$redirect['REDIRECT']}"); die(); } // content from database $page = Pages::I()->Read(['URL' => $this->url['path']]); if ($page) { $this->TITLE = $page['TITLE']; $this->KEYWORDS = $page['KEYWORDS']; $this->DESCRIPTION = $page['DESCRIPTION']; echo htmlspecialchars_decode($page['CONTENT']); return; } throw new ExceptionPageNotFound(); } /** * This method unconditionally displays the content for the page, using $this->MakeContent(). * If any exception occurs during the process of content generation - * catches it and launches the corresponding alternative method: * - ShowErrors * - ShowAuthForm * - Show404 * - Show403 */ public function ShowContent() { try { $this->CheckSectionAccess($this->SECTION['ACCESS']); $this->MakeContent(); } catch (ExceptionAuthRequired $Exception) { $this->ShowAuthForm($Exception->getMessage()); } catch (ExceptionPageNotFound $Exception) { $this->Show404(); } catch (ExceptionAccessDenied $Exception) { $this->Show403(); } catch (Exception $Exception) { $this->ShowErrors($Exception->getArray()); } catch (\Exception $Exception) { $this->ShowErrors([$Exception->getMessage()]); } } public function SetContent() { ob_start(); $this->ShowContent(); $this->CONTENT = ob_get_clean(); } /** * Launches auth unit with no frame * @param string $message reason to auth */ public function ShowAuthForm($message = null) { header('HTTP/1.0 401 Unauthorized'); $this->WRAPPER = 'frame'; $this->TITLE = $message; \BlackFox\Authorization::Run(['MESSAGE' => $message]); } /** * This method tries to show passed array of errors, * using file 'errors.php' from the current template folder. * Otherwise displays them as plain divs. * @param string|array $errors */ public function ShowErrors($errors = []) { if (!is_array($errors)) { $errors = [$errors]; } if (!empty($this->TEMPLATE)) { $template_errors = $this->GetAbsolutePath($this->templates[$this->TEMPLATE] . "/errors.php"); if (file_exists($template_errors)) { require($template_errors); return; } } foreach ($errors as $error) { echo "<div class='alert alert-danger'>{$error}</div>"; } } public function Show404() { header('HTTP/1.0 404 Not Found'); $this->TITLE = '404 Not Found'; $this->ShowErrors(['404 Not Found']); } public function Show403() { header('HTTP/1.0 403 Forbidden'); $this->TITLE = '403 Forbidden'; $this->WRAPPER = 'frame'; $this->ShowErrors(['403 Forbidden']); } /** * Auto-loader for classes. * * @param string $class class that needs to be loaded * @throws Exception * @todo use RegisterCoreClasses once */ public function AutoloadClass($class) { if (isset($this->classes[$class])) { require_once($this->classes[$class]); return; } list($namespace) = explode('\\', $class); if ($this->cores[$namespace]) { $this->RegisterCoreClasses($namespace); if (isset($this->classes[$class])) { require_once($this->classes[$class]); return; } } } /** * Searches for all classes of the module and registers them in the engine, filling the array $this->classes * * @param string $namespace symbolic code of the core/namespace * @throws Exception * @throws \ReflectionException */ public function RegisterCoreClasses($namespace) { $Core = "{$namespace}\\Core"; $this->classes[$Core] = $this->cores[$namespace] . '/Core.php'; require_once($this->classes[$Core]); if (!is_subclass_of($Core, 'BlackFox\ACore')) { throw new Exception(T([ 'en' => "Module '{$namespace}' must be the child of 'BlackFox\ACore'", 'ru' => "Модуль '{$namespace}' должен быть наследником 'BlackFox\ACore'", ])); } /**@var ACore $Core */ $this->classes += $Core::I()->GetClasses(); $Core::I()->Load(); } /** * Converts relative path to absolute path * * @param string $relative_path relative path * @return string absolute path */ public function GetAbsolutePath(string $relative_path) { return $_SERVER['DOCUMENT_ROOT'] . $relative_path; } /** * Converts absolute path to path, relative to document root or specified root * * @param string $absolute_path absolute path * @param string $root_path root path (optional, document root by default) * @return string relative path * @throws Exception */ public function GetRelativePath(string $absolute_path, string $root_path = null) { $root_path = $root_path ?: $_SERVER['DOCUMENT_ROOT']; $root_path = str_replace('\\', '/', $root_path); $absolute_path = str_replace('\\', '/', $absolute_path); if (strpos(strtolower($absolute_path), strtolower($root_path)) === false) { throw new Exception("Can't find relative path for absolute path '{$absolute_path}' with root '{$root_path}'"); } $relative_path = substr($absolute_path, strlen($root_path)); return $relative_path; } /** * Upgrade all active cores: * for every active core - launches it's Upgrade() method. */ public function Upgrade() { foreach ($this->cores as $namespace => $core_absolute_folder) { $Core = "{$namespace}\\Core"; /* @var \BlackFox\ACore $Core */ $Core::I()->Upgrade(); } } /** * Search for the nearest file up the hierarchy of directories. * * @param string $uri path to directory, relative server root * @param string $filename the name of the file to search for * @return null|string absolute path to the search file (if file found), null (if no file found) * @throws Exception */ public function SearchAncestorFile($uri, $filename) { if (empty($uri)) { throw new Exception("Specify uri"); } if (empty($filename)) { throw new Exception("Specify filename"); } $folders = array_filter(explode('/', $uri)); $path = '/'; $paths = ['/' . $filename]; foreach ($folders as $folder) { $path = $path . $folder . '/'; $paths[] = $path . $filename; } $paths = array_reverse($paths); foreach ($paths as $path) { foreach ($this->roots as $root_absolute_folder) { if (file_exists($root_absolute_folder . $path)) { $file = $root_absolute_folder . $path; return $file; } } } return null; } /** * Adds breadcrumbs to the end of the chain. * If the link is not specified, it takes a link to the current request (SERVER REQUEST_URI) * * @param string $name breadcrumb name * @param string $link breadcrumb link (optional) */ public function AddBreadcrumb($name, $link = null) { $this->BREADCRUMBS[] = [ 'NAME' => $name, 'LINK' => $link, ]; } public function GetLanguage() { $_lang = &$_SESSION['USER']['LANGUAGE']; if (!empty($_lang)) return $_lang; if (is_object($this->User) and $this->User->IsAuthorized()) { $_lang = $this->User->FIELDS['LANGUAGE']; } else { $_lang = $this->GetDefaultLanguage(); } return $_lang; } public function GetDefaultLanguage() { $browser_language_string = $_SERVER['HTTP_ACCEPT_LANGUAGE']; if (!empty($browser_language_string)) { $browser_language_string = explode(',', $browser_language_string); $browser_languages = []; foreach ($browser_language_string as $item) { list($language, $priority) = explode(';', $item); $browser_languages[$priority ?: 'q=1.0'] = $language; } foreach ($browser_languages as $priority => $browser_language) { if (isset($this->languages[$browser_language])) { return $browser_language; } } } return reset(array_keys($this->languages)); } public function SetLanguage(string $language) { if (empty($language)) { throw new Exception(T([ 'en' => 'No language specified', 'ru' => 'Язык не указан', ])); } if (!isset($this->languages[$language])) { throw new Exception(T([ 'en' => "Language '{$language}' not found", 'ru' => "Язык '{$language}' не найден", ])); } $_SESSION['USER']['LANGUAGE'] = $language; if ($this->User->IsAuthorized()) { Users::I()->Update($this->User->ID, ['LANGUAGE' => $language]); } } }<file_sep><?php // Script for upgrade from console if (php_sapi_name() <> 'cli') die('Console usage only'); $_SERVER["DOCUMENT_ROOT"] = __DIR__ . '/../'; require_once("includes.php"); $time1 = microtime(true); \BlackFox\Engine::I()->Upgrade(); $time2 = microtime(true); echo $time2 - $time1;<file_sep><?php namespace BlackFox; class TypeList extends TypeText { public function FormatInputValue($value) { $value = is_array($value) ? $value : [$value]; $value = array_filter($value, 'strlen'); $value = json_encode($value, JSON_UNESCAPED_UNICODE); return parent::FormatInputValue($value); } public function FormatOutputValue($element) { $code = $this->field['CODE']; $element[$code] = json_decode($element[$code], true); if (json_last_error()) { $element[$code] = []; } return $element; } public function PrintValue($value) { if (empty($value)) return; ?> <ul class="list"> <? foreach ($value as $element): ?> <li><?= $element ?></li> <? endforeach; ?> </ul> <? } public function PrintFormControl($value, $name, $class = 'form-control') { $value = (array)$value; ?> <div data-list="<?= $name ?>"> <input type="hidden" name="<?= $name ?>" value="" /> <button class="btn btn-secondary" type="button" data-add=""> <span class="material-icons">add</span> Добавить </button> <div class="input-group" data-template="" style="display: none;"> <div class="input-group-prepend" data-sort=""> <span class="input-group-text"> <span class="material-icons">open_with</span> </span> </div> <input type="text" class="<?= $class ?>" name="<?= $name ?>[]" value="" disabled="disabled" > <div class="input-group-append"> <button class="btn btn-secondary" type="button" data-delete=""> <span class="material-icons">delete</span> </button> </div> </div> <? foreach ($value as $element): ?> <div class="input-group" data-element=""> <div class="input-group-prepend" data-sort=""> <span class="input-group-text"> <span class="material-icons">open_with</span> </span> </div> <input type="text" class="<?= $class ?>" name="<?= $name ?>[]" value="<?= $element ?>" <?= ($this->field['DISABLED']) ? 'disabled' : '' ?> > <div class="input-group-append"> <button class="btn btn-secondary" type="button" data-delete=""> <span class="material-icons">delete</span> </button> </div> </div> <? endforeach; ?> </div> <? } }<file_sep><?php namespace BlackFox; class Registration extends Unit { public function Init($PARAMS = []) { $this->options = [ 'CAPTCHA' => [ 'TYPE' => 'BOOLEAN', 'NAME' => T([ 'en' => 'Use captcha', 'ru' => 'Использовать каптчу', ]), 'DEFAULT' => true, ], 'TITLE' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Title', 'ru' => 'Заголовок', ]), 'DEFAULT' => T([ 'en' => 'Registration', 'ru' => 'Регистрация', ]), ], 'AUTHORIZATION' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Authorization url', 'ru' => 'Адрес входа в систему', ]), 'DEFAULT' => '/', ], 'REDIRECT' => [ 'TYPE' => 'STRING', 'NAME' => T([ 'en' => 'Redirect url', 'ru' => 'Адрес переадресации', ]), 'DESCRIPTION' => T([ 'en' => 'Where to redirect the user upon successful registration', 'ru' => 'Куда переадресовать пользователя при успешной регистрации', ]), 'DEFAULT' => '/', ], 'FIELDS' => [ 'TYPE' => 'ARRAY', 'NAME' => T([ 'en' => 'Requesting fields', 'ru' => 'Запрашиваемые поля', ]), 'VALUES' => [], 'DEFAULT' => [ 'LOGIN', '<PASSWORD>', 'EMAIL', 'FIRST_NAME', 'LAST_NAME', 'MIDDLE_NAME', ], ], 'MANDATORY' => [ 'TYPE' => 'ARRAY', 'NAME' => T([ 'en' => 'Mandatory fields', 'ru' => 'Обязательные поля', ]), 'VALUES' => [], 'DEFAULT' => [ 'LOGIN', 'PASSWORD', ], ], ]; foreach (Users::I()->fields as $code => $field) { if ($code === 'ID') { continue; } $this->options['FIELDS']['VALUES'][$code] = $field['NAME']; $this->options['FIELDS']['DEFAULT'][] = $field['NAME']; } parent::Init($PARAMS); } public function Default($VALUES = []) { $RESULT['FIELDS'] = Users::I()->ExtractFields($this->PARAMS['FIELDS']); $RESULT['VALUES'] = $VALUES; $this->ENGINE->TITLE = $this->PARAMS['TITLE']; return $RESULT; } public function Registration($VALUES = []) { if ($this->PARAMS['CAPTCHA']) { if (!Captcha::I()->Check()) { throw new ExceptionCaptcha(T([ 'en' => 'You must pass the captcha', 'ru' => 'Необходимо пройти капчу', ])); } } $ID = Users::I()->Create($VALUES); User::I()->Login($ID); $url = $this->PARAMS['REDIRECT']; if ($_SESSION['USER']['REDIRECT']) { $url = $_SESSION['USER']['REDIRECT']; unset($_SESSION['USER']['REDIRECT']); } $this->Redirect($url); } }<file_sep><?php namespace BlackFox; /** * Base cache driver should to be replaced with any working child. * To replace classes go to config, section 'overrides'. */ class Cache { use Instance; public function __construct(array $params = []) { } /** * Method tries to get cached value(s) by it's\their's key(s): * - if key+value has been found - returns the value in original type * - if no such key+value exist - throws ExceptionCache * * @param string|array $key key(s) * @return mixed value(s) * @throws ExceptionCache "Value for key '...' not found" */ public function Get($key) { throw new ExceptionCache("Value for key '{$key}' not found"); } /** * Method tries to save value: * - if no such key+value exist - save it * - if such key already exist - throws ExceptionCache * * @param string $key key * @param mixed $value value * @param int|null $ttl time to live (optional) * @param array $tags tags (optional) * @throws ExceptionCache "Key already exist: '{$key}'" */ public function Put(string $key, $value, int $ttl = null, array $tags = []) { } /** * Method cleans key+value if such key exist. * Otherwise does nothing. * * @param string $key key */ public function Delete(string $key) { } /** * Method saves value independently of existing keys. * * @param string $key key * @param mixed $value value * @param int|null $ttl time to live (optional) * @param array $tags tags (optional) * @throws ExceptionCache */ public function Set(string $key, $value, int $ttl = null, array $tags = []) { $this->Delete($key); $this->Put($key, $value, $ttl, $tags); } /** * Method deletes all key+value pairs, tagged with passed tag(s). * * @param string|array $tags tag(s) */ public function Strike($tags) { } /** * Method cleans all cache completely. */ public function Clear() { } }<file_sep><?php namespace BlackFox; class MySQL extends Database { private $link; public function __construct(array $params) { $this->database = $params['DATABASE']; $this->link = mysqli_connect( $params['HOST'], $params['USER'], $params['PASSWORD'], $params['DATABASE'], $params['PORT'] ); if ($this->link === false) { throw new Exception(mysqli_connect_error()); } mysqli_set_charset($this->link, $params['CHARSET'] ?: 'utf8'); } public function InitDBTypes() { $this->db_types = [ // ----------------------------------------- 'bool' => [ 'type' => 'tinyint', 'getParams' => function (array $field) { return [1]; }, ], 'int' => [ 'type' => 'int', 'getParams' => function (array $field) { return [$field['LENGTH'] ?: 11]; }, ], 'float' => [ 'type' => 'float', 'getParams' => function (array $field) { return [$field['LENGTH'] ?: 13, $field['DECIMALS'] ?: 2]; }, ], // ----------------------------------------- 'varchar' => [ 'type' => 'varchar', 'getParams' => function (array $field) { return [$field['LENGTH'] ?: 255]; }, ], 'text' => [ 'type' => 'text', ], // ----------------------------------------- 'enum' => [ 'type' => 'enum', 'getParams' => function (array $field) { return ['\'' . implode('\',\'', array_keys($field['VALUES'])) . '\'']; }, ], 'set' => [ 'type' => 'set', 'getParams' => function (array $field) { return ['\'' . implode('\',\'', array_keys($field['VALUES'])) . '\'']; }, ], // ----------------------------------------- 'time' => ['type' => 'time'], 'date' => ['type' => 'date'], 'datetime' => ['type' => 'datetime'], // ----------------------------------------- ]; } public function Query($SQL, $key = null) { $result = mysqli_query($this->link, $SQL); if ($result === false) { throw new ExceptionSQL(mysqli_error($this->link), $SQL); } if ($result === true) { return null; } $data = []; while ($row = mysqli_fetch_assoc($result)) { if (isset($key) and isset($row[$key])) { $data[$row[$key]] = $row; } else { $data[] = $row; } } return $data; } public function QuerySingleInsert($SQL, $increment = null) { $result = mysqli_query($this->link, $SQL); if ($result === false) { throw new ExceptionSQL(mysqli_error($this->link), $SQL); } if ($result === true) { return mysqli_insert_id($this->link); } } public function Escape($data) { if (is_null($data)) { return null; } return mysqli_real_escape_string($this->link, $data); } public function Quote($id) { return '`' . $id . '`'; } public function Random() { return 'rand()'; } public function GetStructureString(Type $Type) { $field = $Type->field; $structure_string = $this->GetStructureStringType($Type); $null = ($field["NOT_NULL"] || $field['PRIMARY']) ? "NOT NULL" : "NULL"; $default = ""; if (isset($field['DEFAULT'])) { if (is_bool($field['DEFAULT'])) { $default = "DEFAULT " . ($field['DEFAULT'] ? 'true' : 'false'); } elseif (is_array($field['DEFAULT'])) { $default = "DEFAULT '" . implode(',', $field['DEFAULT']) . "'"; } elseif (is_string($field['DEFAULT'])) { $default = "DEFAULT '{$field['DEFAULT']}'"; } elseif (is_numeric($field['DEFAULT'])) { $default = "DEFAULT {$field['DEFAULT']}"; } else { throw new Exception("Unknown default value type of '{$field['CODE']}'"); } } $auto_increment = ($field["AUTO_INCREMENT"]) ? "AUTO_INCREMENT" : ""; $comment = ($field["NAME"]) ? " COMMENT '{$field["NAME"]}'" : ""; $structure_string = $this->Quote($field['CODE']) . " $structure_string $null $default $auto_increment $comment"; $structure_string = preg_replace('/\s+/', ' ', $structure_string); return $structure_string; } private function GetConstraints($table) { return $this->Query(" SELECT KEY_COLUMN_USAGE.CONSTRAINT_NAME, KEY_COLUMN_USAGE.COLUMN_NAME, KEY_COLUMN_USAGE.REFERENCED_TABLE_NAME, KEY_COLUMN_USAGE.REFERENCED_COLUMN_NAME, REFERENTIAL_CONSTRAINTS.UPDATE_RULE, REFERENTIAL_CONSTRAINTS.DELETE_RULE FROM information_schema.KEY_COLUMN_USAGE INNER JOIN information_schema.REFERENTIAL_CONSTRAINTS ON REFERENTIAL_CONSTRAINTS.CONSTRAINT_NAME = KEY_COLUMN_USAGE.CONSTRAINT_NAME AND REFERENTIAL_CONSTRAINTS.CONSTRAINT_SCHEMA = KEY_COLUMN_USAGE.TABLE_SCHEMA WHERE KEY_COLUMN_USAGE.TABLE_SCHEMA = '{$this->database}' AND KEY_COLUMN_USAGE.TABLE_NAME = '{$table}' ", 'CONSTRAINT_NAME'); } public function CompareTable(SCRUD $Table) { $diff = []; $diff = array_merge($diff, $this->CompareTableFieldsAndPrimaryKeys($Table)); $diff = array_merge($diff, $this->CompareTableIndexes($Table)); $diff = array_merge($diff, $this->CompareTableConstraints($Table)); return $diff; } public function CompareTableFieldsAndPrimaryKeys(SCRUD $Table) { if (empty($Table->fields)) throw new Exception("Can't compare table fields: no fields found, table '{$Table->name}' [{$Table->code}]"); $diff = []; $check = $this->Query("SHOW TABLES LIKE '{$Table->code}'"); if (empty($check)) { // no table found: creating a new one with fields and primary keys $data = []; foreach ($Table->fields as $code => $field) { if ($Table->Types[$code]->virtual) continue; $data[] = [ 'MESSAGE' => 'Add column', 'FIELD' => $code, 'SQL' => $this->GetStructureString($Table->Types[$code]), ]; } if (!empty($Table->keys)) { $data[] = [ 'MESSAGE' => 'Add primary keys', 'SQL' => "PRIMARY KEY (" . implode(", ", $Table->keys) . ")", ]; } $SQL = "CREATE TABLE `{$Table->code}` (\r\n" . implode(",\r\n", array_column($data, 'SQL')) . "\r\n);"; $diff[] = [ 'MESSAGE' => 'Create a new table', 'TABLE' => $Table->code, 'SQL' => $SQL, 'DATA' => $data, ]; } else { // table exist: comparing fields and primary keys $data = []; $columns = $this->Query("SHOW FULL COLUMNS FROM " . $Table->code, 'Field'); $columns = array_change_key_case($columns, CASE_UPPER); $db_keys = []; foreach ($columns as $code => $column) if ($column['Key'] === 'PRI') $db_keys[] = $code; $last_after_code = ''; foreach ($Table->fields as $code => $field) { if ($field['PRIMARY']) { $keys[] = $code; } if ($Table->Types[$code]->virtual) continue; $structure_string = $this->GetStructureString($Table->Types[$code]); if (!empty($last_after_code)) $structure_string .= " AFTER " . $this->Quote($last_after_code); if (!empty($columns[$code])) { $reason = $this->IsFieldDifferentFromColumn($Table->Types[$code], $columns[$code]); if ($reason) { $data[] = [ 'MESSAGE' => 'Modify column', 'FIELD' => $code, 'REASON' => $reason, 'SQL' => "MODIFY COLUMN $structure_string", ]; } } elseif (!empty($field['CHANGE']) and !empty($columns[$field['CHANGE']])) { $data[] = [ 'MESSAGE' => 'Rename column', 'FIELD' => $code, 'SQL' => "CHANGE COLUMN `{$field['CHANGE']}` $structure_string", ]; unset($columns[$field['CHANGE']]); } else { $data[] = [ 'MESSAGE' => 'Add column', 'FIELD' => $code, 'SQL' => "ADD COLUMN $structure_string", ]; } $last_after_code = $code; unset($columns[$code]); } foreach ($columns as $code => $column) { $data[] = [ 'MESSAGE' => 'Drop column', 'FIELD' => $code, 'SQL' => "DROP COLUMN `{$code}`", ]; } if ($Table->keys <> $db_keys) { if (!empty($Table->keys)) { $data[] = [ 'MESSAGE' => 'Modify primary keys', 'SQL' => "DROP PRIMARY KEY, ADD PRIMARY KEY (" . implode(", ", array_map([$this, 'Quote'], $Table->keys)) . ")", ]; } else { $data[] = [ 'MESSAGE' => 'Drop primary keys', 'SQL' => "DROP PRIMARY KEY", ]; } } if (!empty($data)) { $SQL = "ALTER TABLE `{$Table->code}` \r\n" . implode(",\r\n", array_column($data, 'SQL')); $diff[] = [ 'MESSAGE' => 'Modify table', 'TABLE' => $Table->code, 'DATA' => $data, 'SQL' => $SQL, ]; } } return $diff; } public function CompareTableIndexes(SCRUD $Table) { $diff = []; try { $db_indexes = $this->Query("SHOW INDEX FROM `{$Table->code}`", 'Column_name'); } catch (\Exception $error) { $db_indexes = []; } foreach ($Table->fields as $code => $field) { if ($field['PRIMARY']) continue; // skip primary keys if ($field['FOREIGN']) { $field['INDEX'] = true; } if ($field['UNIQUE']) { $field['INDEX'] = true; } if ($field['INDEX'] === 'UNIQUE') { $field['INDEX'] = true; $field['UNIQUE'] = true; } $unique = ($field['UNIQUE']) ? 'UNIQUE' : ''; $db_index = $db_indexes[$code]; // index is: present in database, missing in code - drop it if (isset($db_index) and !$field['INDEX']) { $diff[] = [ 'MESSAGE' => 'Drop index', 'TABLE' => $Table->code, 'FIELD' => $code, 'PRIORITY' => -1, 'SQL' => "ALTER TABLE `{$Table->code}` DROP INDEX `{$db_index['Key_name']}`", ]; continue; } // index is: missing in database, present in code - create it if ($field['INDEX'] and !isset($db_index)) { $diff[] = [ 'MESSAGE' => 'Add index', 'TABLE' => $Table->code, 'FIELD' => $code, 'PRIORITY' => 1, 'SQL' => "ALTER TABLE `{$Table->code}` ADD {$unique} INDEX `{$code}` (`{$code}`)", ]; continue; } // index is: present in database, present in code - check unique if (isset($db_index)) { if (($field['UNIQUE'] and $db_index['Non_unique']) or (!$field['UNIQUE'] and !$db_index['Non_unique'])) { $diff[] = [ 'MESSAGE' => 'Modify index (drop)', 'TABLE' => $Table->code, 'FIELD' => $code, 'PRIORITY' => -1, 'SQL' => "ALTER TABLE `{$Table->code}` DROP INDEX `{$db_index['Key_name']}`", ]; $diff[] = [ 'MESSAGE' => 'Modify index (add)', 'TABLE' => $Table->code, 'FIELD' => $code, 'PRIORITY' => 1, 'SQL' => "ALTER TABLE `{$Table->code}` ADD {$unique} INDEX `{$code}` (`{$code}`)", ]; continue; } } } return $diff; } public function CompareTableConstraints(SCRUD $Table) { $diff = []; $db_constraints = $this->GetConstraints($Table->code); foreach ($Table->fields as $code => $field) { if (!isset($field['FOREIGN'])) continue; $action = is_string($field['FOREIGN']) ? $field['FOREIGN'] : 'RESTRICT'; /** @var SCRUD $Link */ $Link = $field['LINK']::I(); $link_key = $field['INNER_KEY'] ?: $Link->key(); $fkey = "fkey {$Table->code}.{$code} ref {$Link->code}.{$link_key}"; if (!isset($db_constraints[$fkey])) { $diff[] = [ 'MESSAGE' => 'Add constraint', 'PRIORITY' => 2, 'TABLE' => $Table->code, 'FIELD' => $code, 'SQL' => "ALTER TABLE `{$Table->code}` ADD CONSTRAINT `{$fkey}` \r\n FOREIGN KEY (`{$code}`) REFERENCES `{$Link->code}` (`{$link_key}`) ON DELETE {$action} ON UPDATE {$action}", ]; continue; } $constraint = $db_constraints[$fkey]; $changed = false; $changed |= $constraint['COLUMN_NAME'] <> $code; $changed |= $constraint['REFERENCED_TABLE_NAME'] <> $Link->code; $changed |= $constraint['REFERENCED_COLUMN_NAME'] <> $link_key; $changed |= $constraint['UPDATE_RULE'] <> $action; $changed |= $constraint['DELETE_RULE'] <> $action; if ($changed) { $diff[] = [ 'MESSAGE' => 'Alter constraint (drop)', 'PRIORITY' => -2, 'TABLE' => $Table->code, 'FIELD' => $code, 'SQL' => "ALTER TABLE `{$Table->code}` DROP CONSTRAINT `{$fkey}`", ]; $diff[] = [ 'MESSAGE' => 'Alter constraint (add)', 'PRIORITY' => 2, 'TABLE' => $Table->code, 'FIELD' => $code, 'SQL' => "ALTER TABLE `{$Table->code}` ADD CONSTRAINT `{$fkey}` \r\n FOREIGN KEY (`{$code}`) REFERENCES `{$Link->code}` (`{$link_key}`) ON DELETE {$action} ON UPDATE {$action}", ]; } unset($db_constraints[$fkey]); } foreach ($db_constraints as $db_constraint) { $diff[] = [ 'MESSAGE' => 'Drop constraint', 'PRIORITY' => -2, 'TABLE' => $Table->code, 'FIELD' => $code, 'SQL' => "ALTER TABLE `{$Table->code}` DROP FOREIGN KEY `{$db_constraint['CONSTRAINT_NAME']}`", ]; } return $diff; } public function IsFieldDifferentFromColumn(Type $Type, array $column) { $field = $Type->field; // type $structure_string = $this->GetStructureStringType($Type); if ($structure_string <> $column['Type']) return "Change type: {$column['Type']} -> {$structure_string}"; // not null if ($field['NOT_NULL'] and $column['Null'] == 'YES') return 'NULL -> NOT_NULL'; if (!$field['NOT_NULL'] and $column['Null'] <> 'YES') return 'NOT_NULL -> NULL'; // auto increment if ($field['AUTO_INCREMENT'] and false === strpos($column['Extra'], 'auto_increment')) return 'Add auto increment'; // default $default = $field['DEFAULT']; if (is_array($default)) $default = implode(',', $default); if (is_bool($default)) $default = (int)$default; if ((string)$default <> (string)$column['Default']) return "Change default: " . (string)$column['Default'] . " -> " . (string)$default; return false; } public function CompileSQLSelect(array $parts) { $SQL = []; $SQL[] = 'SELECT'; $SQL[] = implode(",\r\n", $parts['SELECT']); $SQL[] = "FROM {$parts['TABLE']}"; $SQL[] = implode("\r\n", $parts['JOIN']); if ($parts['WHERE']) $SQL[] = "WHERE " . implode("\r\nAND ", $parts['WHERE']); if ($parts['GROUP']) $SQL[] = "GROUP BY " . implode(", ", $parts['GROUP']); if ($parts['ORDER']) $SQL[] = "ORDER BY " . implode(", ", $parts['ORDER']); if ($parts['LIMIT']) $SQL[] = "LIMIT {$parts['LIMIT']['FROM']}, {$parts['LIMIT']['COUNT']}"; return implode("\r\n", $SQL); } }<file_sep><?php namespace BlackFox; class SchemeSynchronizer extends \BlackFox\Unit { public function GetActions(array $request = []) { if ($request['ACTION'] === 'SynchronizeAll') { return ['SynchronizeAll']; } return parent::GetActions($request); } public function RunSQL(string $SQL) { $this->ENGINE->Database->Query($SQL); return "Success: <pre>{$SQL}</pre>"; } public function Default() { $R['MODE'] = 'Compare'; $R['CORES'] = $this->Do(false); $this->view = 'Default'; return $R; } public function SynchronizeAll() { $R['MODE'] = 'Synchronize'; $R['CORES'] = $this->Do(true); $this->view = 'Default'; return $R; } private function Do(bool $synchronize) { $R = []; foreach ($this->ENGINE->cores as $namespace => $core_absolute_folder) { /* @var \BlackFox\ACore $Core */ $Core = "{$namespace}\\Core"; try { $Scheme = $Core::I()->GetScheme(); if (!$synchronize) { $R[$namespace]['DIFFS'] = $Scheme->Compare(); } else { $R[$namespace]['DIFFS'] = $Scheme->Synchronize(); } } catch (\Exception $error) { $R[$namespace]['ERROR'] = $error->GetMessage(); continue; } } return $R; } } <file_sep><?php /** @var \BlackFox\Adminer $this */ ?> <?php /** @var array $RESULT */ ?> <div class="adminer"> <? require($this->Path('section_settings.php')); ?> <? if (!$this->frame): ?> <? require($this->Path('filter.php')) ?> <? endif; ?> <? require($this->Path('section_top_buttons.php')); ?> <form method="post"> <table id="data" class="table table-bordered table-hover table-responsive-sm"> <tr> <th class="sort" width="1%"><span></span></th> <? $get = $_GET; unset($get['SORT']); $url = $this->SanitizeUrl('?' . http_build_query($get)); ?> <? foreach ($RESULT['STRUCTURE']['FIELDS'] as $structure_code => $field): ?> <? if (!isset($this->SCRUD->fields[$structure_code])) continue; ?> <? $direction = (($RESULT['SORT'][$structure_code] === 'ASC') ? 'DESC' : 'ASC'); $sort_href = $url . "&SORT[{$structure_code}]={$direction}"; $is_numeric = in_array($field['TYPE'], [ 'NUMBER', 'FLOAT', 'LINK', ]); // $icon_class = $is_numeric ? 'numeric' : 'alpha'; ?> <th class="sort<?= isset($RESULT['SORT'][$structure_code]) ? ' active' : '' ?>"> <a href="<?= $sort_href ?>"> <? if ($RESULT['SORT'][$structure_code]): ?> <div class="sort-icon"> <? if ($RESULT['SORT'][$structure_code] === 'ASC'): ?> ⇩ <? endif; ?> <? if ($RESULT['SORT'][$structure_code] === 'DESC'): ?> ⇧ <? endif; ?> </div> <? endif; ?> <?= $field['NAME'] ?> </a> </th> <? endforeach; ?> </tr> <? if (empty($RESULT['DATA']['ELEMENTS'])): ?> <tr> <td colspan="<?= 1 + count($RESULT['STRUCTURE']['FIELDS']) ?>" class="text-center"> <?= T([ 'en' => '- no data -', 'ru' => '- нет данных -', ]) ?> </td> </tr> <? endif; ?> <? foreach ($RESULT['DATA']['ELEMENTS'] as $row): ?> <? $href = $this->GetHref($row); $ondblclick = "window.location.href='{$href}'"; ?> <tr ondblclick="<?= $ondblclick ?>"> <? if ($RESULT['MODE'] <> 'POPUP'): ?> <td class="p-2"> <input type="checkbox" name="ID[]" value="<?= $row['ID'] ?>" /> </td> <? endif; ?> <? foreach ($RESULT['STRUCTURE']['FIELDS'] as $code => $field): ?> <? if (!isset($this->SCRUD->fields[$code])) continue; ?> <td> <div class="table-content table-content-<?= $this->SCRUD->fields[$code]['TYPE'] ?>"> <? ob_start(); // ------------------------------------------------- $this->SCRUD->Types[$code]->PrintValue($row[$code]); // ------------------------------------------------- $content = ob_get_clean(); ?> <? if ($this->SCRUD->fields[$code]['PRIMARY']): ?> <a href="<?= $href ?>"><?= $content ?></a> <? else: ?> <?= $content ?> <? endif; ?> </div> </td> <? endforeach; ?> </tr> <? endforeach; ?> <? if (in_array($RESULT['MODE'], ['SECTION'])): ?> <tr> <td colspan="<?= 1 + count($RESULT['STRUCTURE']['FIELDS']) ?>"> <button class="btn btn-danger" type="submit" name="ACTION" value="Delete" data-confirm="<?= T([ 'en' => 'Confirm deletion of selected elements', 'ru' => 'Подтвердите удаление выделенных элементов', ]) ?>" > <span class="material-icons">delete</span> <?= T([ 'en' => 'Delete selected', 'ru' => 'Удалить выделенные', ]) ?> </button> </td> </tr> <? endif; ?> </table> </form> <? \BlackFox\Pagination::Run($RESULT['DATA']['PAGER'] + ['VARIABLE' => 'PAGE']) ?> </div> <file_sep><?php namespace BlackFox; class User { use Instance; /** @var null|int user identifier */ public $ID = null; /** @var array user fields (associative) */ public $FIELDS = []; /** @var array user groups (list) */ public $GROUPS = []; public function __construct($ID) { $this->Init($ID); } /** * Load the data about user * * @param null|int $ID null or user identifier * @throws Exception User not found */ public function Init($ID) { $this->ID = $ID ?: null; $this->FIELDS = []; $this->GROUPS = []; if (empty($this->ID)) return; $this->FIELDS = Users::I()->Read($this->ID); $group_ids = Users2Groups::I()->GetColumn(['USER' => $this->ID], 'GROUP'); if (!empty($group_ids)) $this->GROUPS = Groups::I()->GetColumn($group_ids, 'CODE'); } /** * Try to authorize the user with his requisites * * @param string $login * @param string $password * @throws Exception User not found * @throws Exception An incorrect password was entered */ public function Authorization(string $login, string $password) { if (empty($login)) { throw new Exception(T([ 'en' => 'Login must be specified', 'ru' => 'Не указан логин', ])); } $user = Users::I()->Read(['LOGIN' => $login], ['ID', 'SALT', 'LOGIN', 'PASSWORD']); if (empty($user)) { Log::I()->Create([ 'TYPE' => 'USER_AUTH_NOT_FOUND', 'MESSAGE' => "User '{$login}' not found", 'DATA' => ['LOGIN' => $login], ]); throw new Exception(T([ 'en' => "User '{$login}' not found", 'ru' => "Пользователь '{$login}' не существует", ])); } if ($user['PASSWORD'] <> sha1($user['SALT'] . ':' . $password)) { Log::I()->Create([ 'TYPE' => 'USER_AUTH_WRONG_PASSWORD', 'MESSAGE' => "An incorrect password was entered, login: '{$login}'", 'DATA' => ['LOGIN' => $login], 'USER' => $user['ID'], ]); throw new Exception(T([ 'en' => 'An incorrect password was entered', 'ru' => 'Введен некорректный пароль', ])); } $this->Login($user['ID']); } /** * Authorize the user by his identifier * * @param int $ID user identifier * @throws Exception User not found */ public function Login(int $ID) { if (!Users::I()->Present($ID)) { throw new Exception(T([ 'en' => "User #{$ID} not found", 'ru' => "Пользователь №{$ID} не найден", ])); } Users::I()->Update($ID, ['LAST_AUTH' => time()]); Log::I()->Create([ 'USER' => $ID, 'TYPE' => 'USER_AUTH_SUCCESS', 'MESSAGE' => 'Successful authorization', ]); $_SESSION['USER']['ID'] = $ID; $this->Init($ID); } public function Logout() { unset($_SESSION['USER']); $this->Init(null); } public function IsAuthorized() { return !empty($this->ID); } /** * Check group affiliation * * @param string $group code of the group * @return bool */ public function InGroup(string $group) { return in_array($group, $this->GROUPS); } /** * Check groups affiliation * * @param array $groups list of codes of groups * @return bool */ public function InAnyOfGroups(array $groups) { return (bool)array_intersect($groups, $this->GROUPS); } }<file_sep><?php if (!function_exists('T')) { /** * It finds language code * It picks corresponding value from input array * * @param array $variants * @return string */ function T(array $variants) { $code = \BlackFox\Engine::I()->GetLanguage(); return $variants[$code] ?: reset($variants); } }<file_sep><?php namespace BlackFox; class Users2Groups extends SCRUD { public function Init() { $this->name = T([ 'en' => 'Users in groups', 'ru' => 'Пользователи в группах', ]); $this->fields = [ 'ID' => self::ID, 'USER' => [ 'TYPE' => 'OUTER', 'LINK' => 'Users', 'NAME' => T([ 'en' => 'User', 'ru' => 'Пользователь', ]), 'VITAL' => true, 'FOREIGN' => 'CASCADE', ], 'GROUP' => [ 'TYPE' => 'OUTER', 'LINK' => 'Groups', 'NAME' => T([ 'en' => 'Group', 'ru' => 'Группа', ]), 'VITAL' => true, 'FOREIGN' => 'CASCADE', ], ]; } public function Create($fields = []) { // TODO make double primary for SCRUD $element = $this->Read([ 'USER' => $fields['USER'], 'GROUP' => $fields['GROUP'], ]); if (!empty($element)) { return $element['ID']; } else { return parent::Create($fields); } } public function GetElementTitle(array $element) { return $element['GROUP']['NAME']; } }<file_sep><?php namespace BlackFox; class ExceptionType extends Exception { }<file_sep><?php namespace Site; class Core extends \BlackFox\ACore { public function Upgrade() { } public function Menu() { } }
006d1a6fa2d4649449a86d36af89118a163d5666
[ "Markdown", "JavaScript", "PHP" ]
121
PHP
Screww/BlackFox
118eb74281b1c9bf9525a68ed7122ffed7e732d9
aa014e1d7aae0f79b1fa627a8da94c591be76c09
refs/heads/master
<file_sep>darknet detector demo ./path.conf ./main.cfg ./weights/main.backup <file_sep># yolo_template 默认使用voc的cfg文件 初次需要 `cd weights` 运行 `./download_default_weight.sh` 下载与训练模型 训练图片时把图片放到 `pictures/{两位数字+英文类型名称}/images/{图片名称}.jpg` 对应的annotation 放到 `pictures/{两位数字+英文类型名称}/labels/{图片名称}.txt` `{图片名称}.txt` 文件中的头两个数字 必须和 文件夹的两位数字 一致 必须是连续数字 `{图片名称}.txt` 解释: `两位数字的编号` `对象x中心 / 图片weight` `对象y中心 / 图片height` `对象weight / 图片weight` `对象height / 图片height` 运行 `python crun.py` 根据放入的图片自动编辑配置文件 然后 `./run.sh` 开始学习 执行 `./test.sh` 打开摄像头测试 <file_sep>while true do darknet detector train ./path.conf ./main.cfg ./weights/main.backup done <file_sep>wget -O main.backup https://pjreddie.com/media/files/darknet53.conv.74
77d78db5317ed929f000aa9380585aa930e0bcc4
[ "Markdown", "Shell" ]
4
Shell
ku-robo/yolo_template
28864c66e5fb4c4658aea914a306f6f3a02207d3
2405157555e6f14686f6a11ed655b849e3a0440d
refs/heads/master
<file_sep>import React from 'react' import './liquids.css' function MenuLiquids(props){ if(props.buttonl){ return( <div className= "liquidsOption"> <button className="water" onClick={() => { props.onClick([{ food: Object.keys(props.listLiquids.Menu["Agua 500 ml"])[0], price: props.listLiquids.Menu["Agua 500 ml"]["Agua 500 ml"]}])}}>Agua (500 ml) $500</button> <button className="waterBig" onClick={() => { props.onClick([{ food: Object.keys(props.listLiquids.Menu["Agua 750 ml"])[0], price: props.listLiquids.Menu["Agua 750 ml"]["Agua 750 ml"]}])}}>Agua (750 ml) $800</button> <button className="soda" onClick={() => { props.onClick([{ food: Object.keys(props.listLiquids.Menu["Gaseosa 500 ml"])[0], price: props.listLiquids.Menu["Gaseosa 500 ml"]["Gaseosa 500 ml"]}])}}>Gaseosa (500 ml) $700</button> <button className= "bigSoda" onClick={() => { props.onClick([{ food: Object.keys(props.listLiquids.Menu["Gaseosa 750 ml"])[0], price: props.listLiquids.Menu["Gaseosa 750 ml"]["Gaseosa 750 ml"]}])}}> Gaseosa (750 ml) $1000 </button> </div> )} else{ return null } } export default MenuLiquids;<file_sep>import React from 'react'; import './kitchen.css'; function KitchenOrder(props) { const showList = props.listOrder.map((item, i) => { return ( <li key={i} className= "detailList">{item.food} ${item.price} <button className="btndelete" onClick = {()=>props.deleteProduct(item)}>X</button></li> )}) const total = props.listOrder.reduce((before, after) => { return (before + after.price)},0) return ( <div> <div className="title_kitchen">Pedido</div> <div className="content"> {props.nameClient}</div> <ul className="requested_detail">{showList}</ul> <ul className="total">Total = ${total}</ul> <div className= "btnSubmitOrder"> <button className="btnsubmit" onClick= {props.submitFireBase}> Enviar a Cocina </button> <button className="btnsubmit" onClick = {props.openKitchen}>Ver pedidos</button> </div> </div> ) } export default KitchenOrder<file_sep>import React, { Component } from 'react'; import './appp.css'; import Menubf from './breakfast'; import './breakfast.css'; import OptionBreakfast from './optionBreakfast'; import './optionBreakfast.css'; import MenuFood from './food'; import OptionFood from './optionFood'; import OptionLiquids from './optionliquids'; import MenuLiquids from './liquids'; import { database } from './provider.js'; import './kitchenorderreturn'; import Kitchenreturn from './kitchenorderreturn.js'; import KitchenOrder from './kitchen.js' class BurgerQueen extends Component { constructor(props) { super(props) this.state = { name: "", input: "", watch: false, watchfood: false, watchliquids: false, data: props.data, list: [], hidediv: false, message: "", divPrincipal: false, } this.upDate = this.upDate.bind(this); this.upDate2 = this.upDate2.bind(this); this.buttonsBreakfast = this.buttonsBreakfast.bind(this); this.buttonFood = this.buttonFood.bind(this); this.buttonLiquids = this.buttonLiquids.bind(this); this.addlist = this.addlist.bind(this); this.deleteList = this.deleteList.bind(this); this.submit = this.submit.bind(this); this.updateOrdersData = this.updateOrdersData.bind(this); this.openKitchen=this.openKitchen.bind(this); this.buttonReturn=this.buttonReturn.bind(this); database.ref('cocina').on('value',function(snap){ this.updateOrdersData(snap.val()); }.bind(this)) } upDate() { this.setState({ ...this.state, input: "", name: this.state.input, }) } deleteList(h){ this.setState({ ...this.state, list: this.state.list.filter((delete1) => { return delete1 !== h }) }) } submit(){ const submitOrder = { name: this.state.name, list: this.state.list } let saveOrder = database.ref("cocina").push().key; let updates = {} setTimeout(()=>{this.setState({ ...this.state, list: [], name: "", }); }, 0); updates["cocina/" + saveOrder] = submitOrder; database.ref().update(updates) return } updateOrdersData(ordersData){ this.setState({ ...this.state, message: ordersData }); } addlist(a){ this.setState({ ...this.state, list: this.state.list.concat(a) }) } buttonsBreakfast() { this.setState({ ...this.state, watch: true, watchfood:false, watchliquids:false, }) } buttonReturn(){ this.setState({ ...this.state, divPrincipal: false, hidediv: false, }) } buttonFood() { this.setState({ ...this.state, watchfood: true, watch: false, watchliquids: false }) } buttonLiquids(){ this.setState({ ...this.state, watchliquids: true, watch: false, watchfood: false, }) } upDate2(e) { this.setState({ ...this.state, input: e.target.value }) } openKitchen(){ this.setState({ ...this.state, hidediv: true, divPrincipal: true, }) } container() { return (this.state.name) } render() { return ( <div> <div className="title"> Burger Queen </div> {!this.state.divPrincipal && <div className="main"> <div className="garzon"> <div className="title_garzon"></div> <div className = "clientName"> <input className="mailing_data" placeholder="<NAME>" value={this.state.input} onChange={this.upDate2} ></input> <button onClick={this.upDate} className="click_data">Listo</button> </div> <div className="garzon_menu_option"> <div className="option_menu"> <OptionBreakfast buttonbf={this.buttonsBreakfast}/> <OptionFood buttonf={this.buttonFood}/> <OptionLiquids buttonl={this.buttonLiquids}/> </div> <div className= "menu_option"> <Menubf listBreakfast={this.state.data} buttonbf={this.state.watch} onClick={this.addlist}/> <MenuFood listFood={this.state.data} buttonf={this.state.watchfood} onClick={this.addlist}/> <MenuLiquids listLiquids={this.state.data} buttonl={this.state.watchliquids} onClick={this.addlist} /> </div> </div> </div> <div className="kitchen"> <KitchenOrder submitFireBase={this.submit} deleteProduct={this.deleteList} listOrder={this.state.list} openKitchen = {this.openKitchen} nameClient={this.container()}/> </div> </div>} {this.state.hidediv && <div className = "kitchenlist"> <Kitchenreturn btnreturn = {this.buttonReturn} returnMessage = {this.state.message} /> </div>} </div> )} } export default BurgerQueen; <file_sep>import React from 'react'; import './kitchenorderreturn.css' function Kitchenreturn(props){ console.log(props) let content = Object.values(props.returnMessage) // let nameReturn = content[content.length -1] // console.log(nameReturn) const content2 = content.map((item, i) => { console.log(item.list); const list2 = item.list.map((element,i) => { console.log(element) return ( <div key={i}> <li>{element.food}.</li> </div> ) }) return( <div key={i} className= 'orderClient3'> <div className= 'titleOrder'>Cliente: {item.name}</div> <div className = 'listOrderClient' > {list2}</div> </div> ) }) return( <div className = "orderClient1"> <div className = "orderClient2">{content2}</div> <div className = "contentbtn"><button className = "btnreturn" onClick={props.btnreturn} >Volver</button></div> </div> ) } export default Kitchenreturn;<file_sep>[VER DEMO](https://anagalvezsalas11.github.io/SCL007-BurgerQueen/) # Burger Queen Aplicación que permite a los Garzones de un Restorant tomar los pedidos en una tablet, y desde ahí se puedan enviar a cocina, guardando la información en una base de datos (Firebase). La interfaz muestra dos menús (desayuno y resto del día), cada uno con todos sus productos. El usuario debe poder ir eligiendo que productos agregar y la interfaz debe ir mostrando el resumen del pedido con el valor total, se puede borrar los item que se haya eligido antes de enviar a cocina. Tecnologías utilizadas: * Firebase * React * CSS <file_sep>import React from 'react'; import './optionBreakfast.css'; function OptionBreakfast(props) { return( <button onClick={props.buttonbf} className="breakfastButton">Desayuno</button> ) } export default OptionBreakfast<file_sep> // Initialize Firebase import * as firebase from 'firebase'; let config = { apiKey: "<KEY>", authDomain: "burguer-queen-71d9d.firebaseapp.com", databaseURL: "https://burguer-queen-71d9d.firebaseio.com", projectId: "burguer-queen-71d9d", storageBucket: "burguer-queen-71d9d.appspot.com", messagingSenderId: "1067443614641" }; firebase.initializeApp(config); export const database = firebase.database();<file_sep>import React from 'react'; import './optionLiquids.css' function Liquids(d){ return( <div className= "liquids"> <button onClick={d.buttonl} className="buttonLiquids">Líquidos</button> </div> ) } export default Liquids;<file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import './appp.css'; import BurgerQueen from './appp.js'; import data from './data.json' ReactDOM.render( <BurgerQueen data={data}/>, document.getElementById('root') ) <file_sep>import React from 'react'; import './breakfast.css'; function Menubf(props) { if (props.buttonbf) { return ( <div className="setbuttonBf"> <button className="americanCoffee" onClick={() => { props.onClick([{ food: Object.keys(props.listBreakfast.Menu["Cafe americano"])[0], price: props.listBreakfast.Menu["Cafe americano"]["cafe americano"] }])}}>Café Americano $500</button> <button className="coffeeMilk" onClick={() => { props.onClick([{ food: Object.keys(props.listBreakfast.Menu["Cafe con leche"])[0], price: props.listBreakfast.Menu["Cafe con leche"]["cafe con leche"] }])}} >Cafe con Leche $700</button> <button className="sandwich" onClick={() =>{ props.onClick([{ food: Object.keys(props.listBreakfast.Menu["Sandwich de jamon y queso"])[0], price: props.listBreakfast.Menu["Sandwich de jamon y queso"]["Sandwich de jamon y queso"] }])}}>Sandwich Jamon y Queso $1.000</button> <button className="juice" onClick={() => { props.onClick([{ food: Object.keys(props.listBreakfast.Menu["Jugo natural"])[0], price: props.listBreakfast.Menu["Jugo natural"]["Jugo natural"] }])}}>Jugo Natural $700</button> </div> ) } else { return null } } export default Menubf;
3654a210c87b130d49b3eb81a6432111dd7a107e
[ "JavaScript", "Markdown" ]
10
JavaScript
AnaGalvezSalas11/SCL007-BurgerQueen
f28e3661d4618f9da76f870fadb9bb3b4e7589a4
13ed292023dadf9af93eaafea23d3b4b84965ab1
refs/heads/master
<file_sep>import json from data_gen.data import randomizers from data_gen.data.util import get_template def get_random_child_health_case(seed_values): template = get_template('child-health-case.json') return randomize_template_values(template, seed_values) def randomize_template_values(template_string, seed_values): formatted_case = template_string % seed_values.context return json.loads(formatted_case) <file_sep>import uuid from datetime import datetime import jsonobject class ChangeMeta(jsonobject.JsonObject): """ Metadata about a change. """ # stolen from CommCare HQ's ChangeMeta _allow_dynamic_properties = False document_id = jsonobject.DefaultProperty(required=True) # Only relevant for Couch documents document_rev = jsonobject.StringProperty() # 'couch' or 'sql' data_source_type = jsonobject.StringProperty(required=True) # couch database name or one of data sources listed in corehq.apps.change_feed.data_sources data_source_name = jsonobject.StringProperty(required=True) # doc_type property of doc or else the topic name document_type = jsonobject.DefaultProperty() document_subtype = jsonobject.StringProperty() domain = jsonobject.StringProperty() is_deletion = jsonobject.BooleanProperty() publish_timestamp = jsonobject.DateTimeProperty(default=datetime.utcnow) # note: this has been added and is different from commcarehq document = jsonobject.DefaultProperty() # track of retry attempts attempts = jsonobject.IntegerProperty(default=0) def get_form_meta(document): # todo: other fields return ChangeMeta( document_id=document['form_id'], data_source_type='sql', data_source_name='form-sql', document_type='XFormInstance', document_subtype=document['xmlns'], document=document, ) def get_case_meta(document): # todo: other fields return ChangeMeta( document_id=document['case_id'], data_source_type='sql', data_source_name='case-sql', document_type='CommCareCase', document_subtype=document['type'], document=document, ) def get_ledger_meta(document): # todo: other fields return ChangeMeta( document_id=document['_id'], data_source_type='sql', data_source_name='ledger-sql', document_type='ledger', document_subtype=None, document=document, ) <file_sep> FORM_TOPIC = 'datagen-form' CASE_TOPIC = 'datagen-case' LEDGER_TOPIC = 'datagen-ledger' <file_sep> EXPECTED_PREGNANT_ITEMS = 13 <file_sep>from datetime import datetime from ..randomizers import DATE_FORMAT_STRING from . import const from .base import DataGenTestBase from .util import remove_ledgers class TestPregnantAndMother(DataGenTestBase): def test_is_pregnant(self): pregnant_count = mother_count = 0 for i in range(100): data_generator = self.get_next_data_generator() if data_generator.is_pregnant: pregnant_count += 1 else: mother_count += 1 # just make sure we generate a few of each, and that mother makes up the majority self.assertTrue(pregnant_count > 10) self.assertTrue(mother_count > 50) def test_pregnant_types(self): data_generator = self._get_random_pregnant_data_generator() data = remove_ledgers(data_generator.get_data()) self.assertEqual(const.EXPECTED_PREGNANT_ITEMS, len(data)) def test_mother_types(self): while True: data_generator = self.get_next_data_generator() if not data_generator.is_pregnant and not data_generator.change_phone_number: data = list(data_generator.get_data()) self.assertEqual(6, len(data)) break def test_bp_dates(self): data_generator = self._get_random_pregnant_data_generator() ccs_record_case = data_generator.get_pregnant_ccs_record_case() self.assertTrue(ccs_record_case['case_json']['bp1_date'] < ccs_record_case['case_json']['bp2_date']) self.assertTrue(ccs_record_case['case_json']['bp2_date'] < ccs_record_case['case_json']['bp3_date']) def test_edds_are_random_in_future(self): edds = [] now = datetime.utcnow() for i in range(5): data_generator = self.get_next_data_generator() ccs_record_case = data_generator.get_pregnant_ccs_record_case() edd_string = ccs_record_case['case_json']['edd'] edd = datetime.strptime(edd_string, DATE_FORMAT_STRING) self.assertTrue(edd not in edds) self.assertTrue(edd >= now) edds.append(edd) def test_adds_are_random_and_in_past(self): adds = [] now = datetime.utcnow() for i in range(5): data_generator = self.get_next_data_generator() ccs_record_case = data_generator.get_mother_ccs_record_case() add_string = ccs_record_case['case_json']['add'] add = datetime.strptime(add_string, DATE_FORMAT_STRING) self.assertTrue(add not in adds) self.assertTrue(add <= now) adds.append(add) <file_sep>import random from datetime import timedelta from data_gen.data.birth_preparedness import get_random_bp_form from data_gen.data.ledgers import get_random_anc_visit_ledgers from data_gen.data.post_natal_care import get_random_pnc_form from data_gen.data.ebf_form import get_random_ebf_form from data_gen.data.cf_form import get_random_cf_form from data_gen.data.take_home_ration import get_random_thr_form from data_gen.data.delivery import get_random_delivery_form from data_gen.data.tasks import get_random_pregnant_tasks_case from ..kafka.meta import get_form_meta, get_case_meta, get_ledger_meta from ..kafka import topics from ..kafka.producer import ChangeProducer from .ccs_record_case import get_random_mother_ccs_record_case, get_random_pregnant_ccs_record_case from .child_health_case import get_random_child_health_case from .growth_monitoring import get_random_growth_monitoring_form from .household_case import get_random_household_case from .locations import get_all_locations from .randomizers import get_next_uuid from .person_case import get_random_mother_case, get_random_child_case, get_random_pregnant_case from .util import DataUnit, SeedValues, CaseIds, datetime_to_string def generate_data(count): print('generating {} items!'.format(count)) producer = ChangeProducer('localhost:9092') locations = get_all_locations() # random_instance = random.Random("cas-data-generator-{}".format(count)) random_instance = random.Random() for i in range(count): location = random_instance.choice(locations) data_generator = DataGenerator(random_instance, location) for data_unit in data_generator.get_data(): producer.send_change(data_unit.topic, data_unit.data) producer.producer.flush() print('done!') class DataGenerator: def __init__(self, random_instance, location): self.random_instance = random_instance # one in four should be pregnant, the rest should be mothers self.is_pregnant = random_instance.random() > .75 # one in ten should change their phone number self.change_phone_number = random_instance.random() > .9 case_ids = CaseIds( household=get_next_uuid(self.random_instance), mother_person=get_next_uuid(self.random_instance), pregnant_person=get_next_uuid(self.random_instance), child_person=get_next_uuid(self.random_instance), child_health=get_next_uuid(self.random_instance), pregnant_ccs_record=get_next_uuid(self.random_instance), ccs_record=get_next_uuid(self.random_instance), pregnant_tasks=get_next_uuid(self.random_instance), ) self.seed_values = SeedValues( random_instance=self.random_instance, location=location, case_ids=case_ids ) def get_data(self): yield DataUnit(topics.CASE_TOPIC, get_case_meta(self.get_household_case())) if self.is_pregnant: yield DataUnit(topics.CASE_TOPIC, get_case_meta(self.get_pregnant_case())) yield DataUnit(topics.CASE_TOPIC, get_case_meta(self.get_pregnant_ccs_record_case())) if self.change_phone_number: yield DataUnit(topics.CASE_TOPIC, get_case_meta(self.get_pregnant_case_new_number())) # forms for i in range(3): yield DataUnit(topics.FORM_TOPIC, get_form_meta(self.get_bp_form(i + 1))) yield DataUnit(topics.FORM_TOPIC, get_form_meta(self.get_pnc_form())) yield DataUnit(topics.FORM_TOPIC, get_form_meta(self.get_ebf_form())) yield DataUnit(topics.FORM_TOPIC, get_form_meta(self.get_cf_form())) yield DataUnit(topics.FORM_TOPIC, get_form_meta(self.get_thr_form())) yield DataUnit(topics.FORM_TOPIC, get_form_meta(self.get_delivery_form())) yield DataUnit(topics.CASE_TOPIC, get_case_meta(self.get_pregnant_tasks_case())) for ledger in self.get_anc_visit_ledgers(): yield DataUnit(topics.LEDGER_TOPIC, get_ledger_meta(ledger)) else: yield DataUnit(topics.CASE_TOPIC, get_case_meta(self.get_mother_case())) yield DataUnit(topics.CASE_TOPIC, get_case_meta(self.get_mother_ccs_record_case())) yield DataUnit(topics.CASE_TOPIC, get_case_meta(self.get_child_case())) yield DataUnit(topics.CASE_TOPIC, get_case_meta(self.get_child_health_case())) if self.change_phone_number: yield DataUnit(topics.CASE_TOPIC, get_case_meta(self.get_mother_case_new_number())) yield DataUnit(topics.FORM_TOPIC, get_form_meta(self.get_growth_monitoring_form())) # cases def get_household_case(self): return get_random_household_case(self.seed_values) def get_mother_case(self): return get_random_mother_case(self.seed_values) def get_mother_case_new_number(self): return get_random_mother_case(self.seed_values, override_context={ 'mother_phone_number': self.seed_values.context['updated_phone_number'], 'server_modified_on': datetime_to_string( self.seed_values.context['raw_server_modified_on'] + timedelta(days=30) ), }) def get_mother_ccs_record_case(self): return get_random_mother_ccs_record_case(self.seed_values) def get_child_case(self): return get_random_child_case(self.seed_values) def get_child_health_case(self): return get_random_child_health_case(self.seed_values) def get_pregnant_case(self): return get_random_pregnant_case(self.seed_values) def get_pregnant_case_new_number(self): return get_random_pregnant_case(self.seed_values, override_context={ 'mother_phone_number': self.seed_values.context['updated_phone_number'], 'server_modified_on': datetime_to_string( self.seed_values.context['raw_server_modified_on'] + timedelta(days=30) ), }) def get_pregnant_ccs_record_case(self): return get_random_pregnant_ccs_record_case(self.seed_values) def get_pregnant_tasks_case(self): return get_random_pregnant_tasks_case(self.seed_values) # forms def get_bp_form(self, visit_number): return get_random_bp_form(self.seed_values, visit_number) def get_growth_monitoring_form(self): return get_random_growth_monitoring_form(self.seed_values) def get_pnc_form(self): return get_random_pnc_form(self.seed_values) def get_ebf_form(self): return get_random_ebf_form(self.seed_values) def get_cf_form(self): return get_random_cf_form(self.seed_values) def get_thr_form(self): return get_random_thr_form(self.seed_values) def get_delivery_form(self): return get_random_delivery_form(self.seed_values) def get_anc_visit_ledgers(self): return get_random_anc_visit_ledgers(self.seed_values) <file_sep>import json from data_gen.data.randomizers import get_next_uuid, get_next_yes_no, get_still_live_cases, get_nextInt, get_next_bool_value, get_next_child_birth_location from data_gen.data.util import get_template def get_random_delivery_form(seed_values): template = get_template('forms/delivery-form.json') return randomize_template_values(template, seed_values) def randomize_template_values(template_string, seed_values): form_context = { 'form_id': get_next_uuid(seed_values.random_instance), 'submission_time': seed_values.context['add'], 'random_yes_no': get_next_yes_no(seed_values.random_instance), 'still_live_birth': get_still_live_cases(seed_values.random_instance), 'days_visit_late': get_nextInt(seed_values.random_instance) * 10, 'num_children_del': get_nextInt(seed_values.random_instance), 'unscheduled_visit': int(get_next_bool_value(seed_values.random_instance)), 'child_birth_location': get_next_child_birth_location(seed_values.random_instance) } form_context.update(seed_values.context) formatted_case = template_string % form_context return json.loads(formatted_case) <file_sep>from . import const from .base import DataGenTestBase from .util import remove_ledgers class TestPhoneNumbers(DataGenTestBase): def test_override_phone_number_pregnant(self): while True: data_generator = self.get_next_data_generator() if data_generator.is_pregnant and data_generator.change_phone_number: data = remove_ledgers(data_generator.get_data()) self.assertEqual(const.EXPECTED_PREGNANT_ITEMS + 1, len(data)) initial_person = data[1] updated_person = data[3] self.assertEqual(initial_person.data['document']['case_id'], updated_person.data['document']['case_id']) if (initial_person.data['document']['case_json']['contact_phone_number'] or updated_person.data['document']['case_json']['contact_phone_number']): self.assertNotEqual(initial_person.data['document']['case_json']['contact_phone_number'], updated_person.data['document']['case_json']['contact_phone_number']) self.assertTrue(initial_person.data['document']['server_modified_on'] < updated_person.data['document']['server_modified_on']) break def test_override_phone_number_mother(self): while True: data_generator = self.get_next_data_generator() if not data_generator.is_pregnant and data_generator.change_phone_number: data = list(data_generator.get_data()) self.assertEqual(7, len(data)) initial_person = data[1] updated_person = data[5] self.assertEqual(initial_person.data['document']['case_id'], updated_person.data['document']['case_id']) if (initial_person.data['document']['case_json']['contact_phone_number'] or updated_person.data['document']['case_json']['contact_phone_number']): self.assertNotEqual(initial_person.data['document']['case_json']['contact_phone_number'], updated_person.data['document']['case_json']['contact_phone_number']) self.assertTrue(initial_person.data['document']['server_modified_on'] < updated_person.data['document']['server_modified_on']) break <file_sep>import json from .randomizers import get_next_uuid, get_nextInt from .util import get_template def get_random_thr_form(seed_values): template = get_template('forms/thr-form.json') return randomize_template_values(template, seed_values) def randomize_template_values(template_string, seed_values): form_context = { 'submission_time': seed_values.context['thr_date'], 'form_id': get_next_uuid(seed_values.random_instance), 'days_ration_given_mother': get_nextInt(seed_values.random_instance) } form_context.update(seed_values.context) formatted_case = template_string % form_context return json.loads(formatted_case) <file_sep>from data_gen.kafka.topics import LEDGER_TOPIC from .base import DataGenTestBase class LedgersTest(DataGenTestBase): def test_pregnant_types(self): while True: data_generator = self._get_random_pregnant_data_generator() data = list(data_generator.get_data()) ledgers = [d for d in data if d[0] == LEDGER_TOPIC] if len(ledgers) < 2: continue tasks_case = data_generator.get_pregnant_tasks_case() self.assertEqual(int(tasks_case["case_json"]["num_anc_complete"]), len(ledgers)) for ledger in ledgers: ledger_doc = ledger[1]['document'] self.assertEqual('immuns', ledger_doc['section_id']) self.assertEqual(tasks_case['case_id'], ledger_doc['case_id']) self.assertTrue(1700 < ledger_doc['balance'] < 20000) break <file_sep>from .util import iter_fixture def get_all_locations(): return [Location(loc_dict) for loc_dict in iter_fixture('locations-short.csv')] class Location: def __init__(self, location_dict): self._location_dict = location_dict def get_owner_id(self): return self._location_dict["center_id"] def get_user_id(self): return self._location_dict["center_id"] def get_username(self): return self._location_dict["center_name"] <file_sep>import json from data_gen.data.randomizers import get_next_uuid, get_next_yes_no, get_anemia_state, get_int, get_anc_blood_pressure_state, get_decimal, get_nextInt from data_gen.data.util import get_template def get_random_bp_form(seed_values, visit_number): template = get_template('forms/bp/bp{}.json'.format(visit_number)) return randomize_template_values(template, seed_values, visit_number) def randomize_template_values(template_string, seed_values, visit_number): seed_value_key = 'bp{}_date'.format(visit_number) form_context = { 'form_id': get_next_uuid(seed_values.random_instance), 'submission_time': seed_values.context[seed_value_key], 'random_yes_no': get_next_yes_no(seed_values.random_instance), 'anemia': get_anemia_state(seed_values.random_instance), 'random_int': get_int(seed_values.random_instance), 'anc_blood_pressure': get_anc_blood_pressure_state(seed_values.random_instance), 'random_decimal': get_decimal(seed_values.random_instance), 'ifa_last_seven_days': get_nextInt(seed_values.random_instance) } form_context.update(seed_values.context) formatted_case = template_string % form_context return json.loads(formatted_case) <file_sep>from . import const from .base import DataGenTestBase from .util import remove_ledgers from data_gen.data.randomizers import YES_NO_OPTIONS as yes_no_options, NOT_BREASFEEDING_OPTIONS class TestEBFForm(DataGenTestBase): def test_ebf_form(self): data_generator = self._get_random_pregnant_data_generator() data = remove_ledgers(data_generator.get_data()) self.assertEqual(const.EXPECTED_PREGNANT_ITEMS, len(data)) ccs_record_case = data[2] ebf_form_data = data[7] self.assertEqual(ccs_record_case.data['document']['case_id'], ebf_form_data.data['document']['form']['case_load_ccs_record0']['case']['@case_id']) self.assertNotEqual('%(form_id)s', ebf_form_data.data['document']['form_id']) self.assertEqual(ebf_form_data.data['document']['received_on'], ebf_form_data.data['document']['form']['meta']['timeEnd']) # bool fields here self.assertIn(ebf_form_data.data['document']['form']['child']['item']['eating'], yes_no_options) self.assertIn(ebf_form_data.data['document']['form']['child']['item']['tea_other'], yes_no_options) self.assertIn(ebf_form_data.data['document']['form']['child']['item']['water_or_milk'], yes_no_options) self.assertIn(ebf_form_data.data['document']['form']['child'] ['item']['counsel_adequate_bf'], yes_no_options) self.assertIn(ebf_form_data.data['document']['form']['child'] ['item']['not_breasfeeding'], NOT_BREASFEEDING_OPTIONS) <file_sep>Data Generator for CAS ---------------------- Creates a Kafka feed that simulates a subset of CAS data using fake data. ## Prerequisites - Python 3.7+ - A valid [Kafka](https://kafka.apache.org) setup ## Installation ``` pip install -r requirements.txt ``` ## Configuration Assumes Kafka is available at `localhost:9092`. Edit `main.py` with the appropriate address if you need to change it. ## Usage ``` python main.py [count] ``` Where `count` is the number of items *of each type* (forms/cases) to generate. ## Testing To see the output you can use the following commands: ```python kafka-console-consumer.sh --topic datagen-form --bootstrap-server http://localhost:9092 --from-beginning kafka-console-consumer.sh --topic datagen-case --bootstrap-server http://localhost:9092 --from-beginning ``` ## Running tests To run tests just run the following in the root of the repository: ``` pytest ``` ## Source Data The household case with ID `0d3ebba1-cf52-4d89-aea4-2fe5ec9c9ed9` on the India server has been used as a basis for the case templates (including its child cases, etc.). You can [view the case here](https://india.commcarehq.org/a/icds-dashboard-qa/reports/case_data/0d3ebba1-cf52-4d89-aea4-2fe5ec9c9ed9/#related) and use the [raw doc view](https://india.commcarehq.org/hq/admin/raw_doc/?id=0d3ebba1-cf52-4d89-aea4-2fe5ec9c9ed9) to see the raw JSON. The following table is the list of Case IDs used: Description | Case Type | Case ID ------------------- | ---------- | ------- Household | household | [0d3ebba1-cf52-4d89-aea4-2fe5ec9c9ed9](https://india.commcarehq.org/a/icds-dashboard-qa/reports/case_data/0d3ebba1-cf52-4d89-aea4-2fe5ec9c9ed9/#related) Pregnant Person | person | [7802432e-548d-499c-90cc-5b0b41f203f0](https://india.commcarehq.org/a/icds-dashboard-qa/reports/case_data/7802432e-548d-499c-90cc-5b0b41f203f0/) Pregnant CCS Record | ccs_record | [d02668b4-0175-4fe7-920d-c0ea3568d6b3](https://india.commcarehq.org/a/icds-dashboard-qa/reports/case_data/d02668b4-0175-4fe7-920d-c0ea3568d6b3/) Mother's Person | person | [23eb689a-8997-471f-946e-db06355296a6](https://india.commcarehq.org/a/icds-dashboard-qa/reports/case_data/23eb689a-8997-471f-946e-db06355296a6/) Child's Person | person | [51407edd-6c91-421f-9558-2f517fc359ae](https://india.commcarehq.org/a/icds-dashboard-qa/reports/case_data/51407edd-6c91-421f-9558-2f517fc359ae/) Mother's CCS Record | ccs_record | [d8962f84-6327-41bd-8572-076c621f7eae](https://india.commcarehq.org/a/icds-dashboard-qa/reports/case_data/d8962f84-6327-41bd-8572-076c621f7eae/) Pregnant Tasks | tasks | [1ec6da6a-9fe3-4752-b951-ec1176e49145](https://india.commcarehq.org/a/icds-dashboard-qa/reports/case_data/1ec6da6a-9fe3-4752-b951-ec1176e49145/) And for Forms: Description | Form Type | Form ID -----------------------------| ------------| ------- Birth Preparedness | BP | [4623a1a0-8182-4764-8be1-5f7a7ebb31b1](https://india.commcarehq.org/a/icds-dashboard-qa/reports/form_data/4623a1a0-8182-4764-8be1-5f7a7ebb31b1/#form-xml) Exclusive Breastfeeding Form | EBF | [f552a82b-795e-4720-ba98-d7a6bf85da04](https://india.commcarehq.org/a/icds-cas/reports/form_data/f552a82b-795e-4720-ba98-d7a6bf85da04/) Complementary Feeding | CF | [516bafbb-52f5-4490-9349-88e9cf8cba81](https://india.commcarehq.org/a/icds-cas/reports/form_data/516bafbb-52f5-4490-9349-88e9cf8cba81) Post Natal Care | PNC | [c28f99cb-e706-4e28-a245-60147a1f692d](https://india.commcarehq.org/a/icds-cas/reports/form_data/c28f99cb-e706-4e28-a245-60147a1f692d/#form-xml) Take Home Ration | THR | [5cbb6dcb-89de-4da2-a3b1-5237f4dd3182]https://india.commcarehq.org/a/icds-cas/reports/form_data/5cbb6dcb-89de-4da2-a3b1-5237f4dd3182/#form-data Delivery Form | Delivery | [a684eab2-db48-4ffa-9cdb-8ade3e36ff8b]https://india.commcarehq.org/a/icds-cas/reports/form_data/a684eab2-db48-4ffa-9cdb-8ade3e36ff8b/ <file_sep>from . import const from .base import DataGenTestBase from .util import remove_ledgers from data_gen.data.randomizers import YES_NO_OPTIONS as yes_no_options class TestPNCForm(DataGenTestBase): def test_pnc_form(self): data_generator = self._get_random_pregnant_data_generator() data = remove_ledgers(data_generator.get_data()) self.assertEqual(const.EXPECTED_PREGNANT_ITEMS, len(data)) ccs_record_case = data[2] pnc_form_data = data[6] # redundant case test # note: try to avoid in further test cases # self.assertEqual(ccs_record_case.data['document']['case_id'], # data_generator.seed_values.case_ids.pregnant_ccs_record) self.assertEqual(ccs_record_case.data['document']['case_id'], pnc_form_data.data['document']['form']['case_load_ccs_record0']['case']['@case_id']) self.assertNotEqual( '%(form_id)s', pnc_form_data.data['document']['form_id'] ) self.assertEqual( pnc_form_data.data['document']['received_on'], pnc_form_data.data['document']['form']['meta']['timeEnd'], ) # bool fields here self.assertIn(pnc_form_data.data['document']['form']['child']['item']['is_ebf'], yes_no_options) <file_sep>import json from kafka import KafkaProducer class ChangeProducer(object): # heavily inspired by CommCare HQ's ChangeProducer class def __init__(self, servers): self.producer = KafkaProducer( bootstrap_servers=servers, client_id="datagen-producer", retries=3, acks=1, key_serializer=lambda key: str(key).encode() ) def send_change(self, topic, change_meta): message = change_meta.to_json() message_json_dump = json.dumps(message).encode('utf-8') self.producer.send(topic, message_json_dump, key=change_meta.document_id) <file_sep> from . import const from .base import DataGenTestBase from .util import remove_ledgers from data_gen.data.randomizers import ANEMIA_STATES, MAX_VALUE, ANC_BLOOD_PRESSURE_STATES, YES_NO_OPTIONS as random_yes_no class TestBPForm(DataGenTestBase): def _get_form_root_property(self, form, property, internal_form='bp1'): return form.data['document']['form'][internal_form][property] def _get_form_iter_0_property(self, form, property, internal_form='bp1'): return form.data['document']['form'][internal_form]['iteration']['item'][0]['filter']['anc_details'][property] def test_bp_form(self): data_generator = self._get_random_pregnant_data_generator() data = remove_ledgers(data_generator.get_data()) self.assertEqual(const.EXPECTED_PREGNANT_ITEMS, len(data)) ccs_record_case = data[2] bp_form_data = data[3:6] for bp_form in bp_form_data: self.assertEqual(ccs_record_case.data['document']['case_id'], data_generator.seed_values.case_ids.pregnant_ccs_record) self.assertEqual(ccs_record_case.data['document']['case_id'], bp_form.data['document']['form']['case_load_ccs_record0']['case']['@case_id']) self.assertNotEqual( '%(form_id)s', bp_form.data['document']['form_id'] ) self.assertEqual( bp_form.data['document']['received_on'], bp_form.data['document']['form']['meta']['timeEnd'], ) bp1, bp2, bp3 = bp_form_data self.assertTrue( bp1.data['document']['form']['meta']['timeEnd'] < bp2.data['document']['form']['meta']['timeEnd'] ) self.assertTrue( bp2.data['document']['form']['meta']['timeEnd'] < bp3.data['document']['form']['meta']['timeEnd'] ) # bool fields here self.assertIn(self._get_form_root_property(bp1, 'resting'), random_yes_no) self.assertIn(self._get_form_root_property(bp1, 'eating_extra'), random_yes_no) self.assertIn(self._get_form_root_property(bp1, 'bleeding', 'bp2'), random_yes_no) self.assertIn(self._get_form_root_property(bp1, 'swelling', 'bp2'), random_yes_no) self.assertIn(self._get_form_root_property(bp1, 'blurred_vision', 'bp2'), random_yes_no) self.assertIn(self._get_form_root_property(bp1, 'convulsions', 'bp2'), random_yes_no) self.assertIn(self._get_form_root_property(bp1, 'rupture', 'bp2'), random_yes_no) self.assertIn(self._get_form_iter_0_property(bp1, 'anc_abnormalities'), random_yes_no) # switch case fields here self.assertIn(self._get_form_root_property(bp1, 'anemia'), ANEMIA_STATES) self._get_form_iter_0_property(bp1, 'anc_blood_pressure') self.assertIn(self._get_form_iter_0_property(bp1, 'anc_blood_pressure'), ANC_BLOOD_PRESSURE_STATES) # range cases self.assertGreater(int(self._get_form_iter_0_property(bp1, 'anc_weight')), 0) self.assertLess(int(self._get_form_iter_0_property(bp1, 'anc_weight')), MAX_VALUE) self.assertGreater(int(self._get_form_iter_0_property(bp1, 'bp_sys')), 0) self.assertLess(int(self._get_form_iter_0_property(bp1, 'bp_sys')), MAX_VALUE) self.assertGreater(int(self._get_form_iter_0_property(bp1, 'bp_dias')), 0) self.assertLess(int(self._get_form_iter_0_property(bp1, 'bp_dias')), MAX_VALUE) self.assertGreater(float(self._get_form_iter_0_property(bp1, 'anc_hemoglobin')), 0) self.assertLess(float(self._get_form_iter_0_property(bp1, 'anc_hemoglobin')), float(MAX_VALUE)) <file_sep>import datetime import random import uuid RANDOM_EXAMPLE = random.Random("a") RANDOM_FORM1 = random.Random("form1") RANDOM_FORM2 = random.Random("form2") DATE_FORMAT_STRING = '%Y-%m-%d' ACTIVITY_LIST = ["prayer_hygiene", "conversation", "cognitive", "physical_outdoor", "arts_crafts", "language", "packup"] MEAL_SERVED_LIST = ["cooked_served_hot", "cooked_served_cold", "packed_served_hot", "packed_served_cold", "not_served"] START_DATETIME = datetime.datetime(2018, 7, 1) END_DATETIME = datetime.datetime(2019, 7, 1) LOCATIONS_FILE = "locations.csv" CASE_LIST = [] ANEMIA_STATES = ["", "severe", "moderate", "normal"] MAX_VALUE = 32767 ANC_BLOOD_PRESSURE_STATES = ["", "normal", "high", "not_measured"] CHILD_BIRTH_LOCATIONS = ["", "transit", "hospital", "home"] MIGRATION_STATUS = ["migrated", ""] DELIVERY_NATURES = ["", "vaginal", "caesarean", "instrumental"] STILL_LIVE_CASES = ["live", "still"] CASTES = ["st", "sc", "other"] NOT_BREASFEEDING_OPTIONS = ["not_enough_milk", "pregnant_again", "child_too_old", "child_mother_sick"] YES_NO_OPTIONS = ["yes", "no"] # Functions to get specific variables within templates def get_next_uuid(randomObj): return str(uuid.UUID(int=randomObj.getrandbits(128))) def get_nextInt(randomObj): return randomObj.randint(0, 10) def get_next_activity(randomObj): return randomObj.sample(ACTIVITY_LIST, randomObj.randint(0, len(ACTIVITY_LIST) - 1)) def get_next_meal_served(randomObj): return randomObj.sample(MEAL_SERVED_LIST, randomObj.randint(0, len(MEAL_SERVED_LIST) - 1)) def get_next_yes_no(randomObj): return randomObj.choice(YES_NO_OPTIONS) def get_int(randomObj): return randomObj.randint(0, MAX_VALUE) def get_decimal(randomObj): return randomObj.random() * MAX_VALUE def get_anemia_state(randomObj): return randomObj.choice(ANEMIA_STATES) def get_anc_blood_pressure_state(randomObj): return randomObj.choice(ANC_BLOOD_PRESSURE_STATES) def get_next_child_birth_location(randomObj): return randomObj.choice(CHILD_BIRTH_LOCATIONS) def get_next_child_id(randomObj): # TO-DO: Fix this return get_next_uuid(randomObj) def get_next_datetime_modified(randomObj, start=START_DATETIME, end=END_DATETIME): delta_microseconds = (end - start).days * 24 * 60 * 60 * 1000000 randomObj.random() return start + datetime.timedelta(microseconds=randomObj.random() * delta_microseconds) def get_next_date(randomObj): return get_next_datetime_modified(randomObj) def get_next_edd(random_instance): start = datetime.datetime.utcnow() end = start + datetime.timedelta(days=240) # pregnancy due dates are expected sometime in the next ~8 months return get_next_datetime_modified(random_instance, start, end) def get_next_gps_location(randomObj): latitude = str(int(randomObj.random() * 180) - 90) longitude = str(int(randomObj.random() * 360) - 180) return latitude + " " + longitude + " 0.0 25.55" def get_next_device_id(randomObj): return str(int(randomObj.random() * 1000000000000000)) def get_next_ip(randomObj): place1 = str(int(randomObj.random() * 256)) place2 = str(int(randomObj.random() * 256)) place3 = str(int(randomObj.random() * 256)) place4 = str(int(randomObj.random() * 256)) return place1 + "." + place2 + "." + place3 + "." + place4 def get_next_child_name(randomObj): # TO-DO: Fix this return get_next_uuid(randomObj) def get_next_wfa(randomObj): return round(randomObj.random() * 20 - 10, 4) def get_next_zscore(randomObj): return round(randomObj.random() * 6 - 3, 2) def get_next_age_days(randomObj): return randomObj.randint(0, 999) def get_next_sex(randomObj): return randomObj.choice(["M", "F"]) def get_next_location_dict(locationCycle): nextRow = locationCycle.next() return {"location_id": nextRow[0], "name": nextRow[2]} def get_random_location_dict(randomObj): return { 'location_id': get_next_uuid(randomObj), 'name': get_next_child_name(randomObj), } def get_next_phone_number(random_instance): """ Returns a phone number like: +91XXXXNNNNNN or an empty string with 5% probability """ if random_instance.random() < .95: return f'+91{random_instance.randint(1000000000, 9999999999)}' else: return '' def get_next_bool_value(randomObj): return randomObj.choice([True, False]) def get_random_migration_status(randomObj): return randomObj.choice(MIGRATION_STATUS) def get_random_delivery_nature(randomObj): return randomObj.choice(DELIVERY_NATURES) def get_still_live_cases(randomObj): return randomObj.choice(STILL_LIVE_CASES) def get_caste(randomObj): return randomObj.choice(CASTES) def get_registered_status(randomObj): return randomObj.choice(["not_registered", ""]) def get_not_breasfeeding_values(randomObj): return randomObj.choice(NOT_BREASFEEDING_OPTIONS) <file_sep>import argparse from data_gen.data.generator import generate_data parser = argparse.ArgumentParser(description='Generate fake CAS data.') parser.add_argument('multiplier', type=int, help='Number of items of each data type to generate') args = parser.parse_args() generate_data(args.multiplier) <file_sep>import json from data_gen.data.util import get_template def get_random_household_case(seed_values): template = get_template('household-case.json') return randomize_template_values(template, seed_values) def randomize_template_values(template_string, seed_values): formatted_case = template_string % seed_values.context return json.loads(formatted_case) <file_sep> from .base import DataGenTestBase class TestCaseRelationships(DataGenTestBase): def test_basic(self): data_generator = self.get_next_data_generator() hh_case = data_generator.get_household_case() mother_case = data_generator.get_mother_case() ccs_record_case = data_generator.get_mother_ccs_record_case() child_case = data_generator.get_child_case() child_health_case = data_generator.get_child_health_case() preg_case = data_generator.get_pregnant_case() preg_ccs_record = data_generator.get_pregnant_ccs_record_case() # mother case parent is household self.assertEqual(hh_case['case_id'], mother_case['indices'][0]['referenced_id']) self.assertEqual('parent', mother_case['indices'][0]['identifier']) # ccs record case parent is mother self.assertEqual(mother_case['case_id'], ccs_record_case['indices'][0]['referenced_id']) self.assertEqual('parent', ccs_record_case['indices'][0]['identifier']) # child case parent is household self.assertEqual(hh_case['case_id'], child_case['indices'][1]['referenced_id']) self.assertEqual('parent', child_case['indices'][1]['identifier']) # child case "mother" index is mother self.assertEqual(mother_case['case_id'], child_case['indices'][0]['referenced_id']) self.assertEqual('mother', child_case['indices'][0]['identifier']) # child health case parent index is child self.assertEqual(child_case['case_id'], child_health_case['indices'][0]['referenced_id']) self.assertEqual('parent', child_health_case['indices'][0]['identifier']) # pregnant case parent is household self.assertEqual(hh_case['case_id'], preg_case['indices'][0]['referenced_id']) self.assertEqual('parent', preg_case['indices'][0]['identifier']) # pregnant ccs record case parent is pregnant self.assertEqual(preg_case['case_id'], preg_ccs_record['indices'][0]['referenced_id']) self.assertEqual('parent', preg_ccs_record['indices'][0]['identifier']) <file_sep>from . import const from .base import DataGenTestBase from .util import remove_ledgers from data_gen.data.randomizers import YES_NO_OPTIONS as yes_no_options class TestCFForm(DataGenTestBase): def test_cf_form(self): data_generator = self._get_random_pregnant_data_generator() data = remove_ledgers(data_generator.get_data()) self.assertEqual(const.EXPECTED_PREGNANT_ITEMS, len(data)) ccs_record_case = data[2] ebf_form_data = data[8] self.assertEqual(ccs_record_case.data['document']['case_id'], ebf_form_data.data['document']['form']['case_load_ccs_record0']['case']['@case_id']) self.assertNotEqual('%(form_id)s', ebf_form_data.data['document']['form_id']) self.assertEqual(ebf_form_data.data['document']['received_on'], ebf_form_data.data['document']['form']['meta']['timeEnd']) <file_sep>import json from datetime import datetime from data_gen.data.util import get_template, string_to_datetime def get_random_anc_visit_ledgers(seed_values): template = get_template('ledgers/ledger.json') return [ randomize_anc_visit_values(template, seed_values, i + 1) for i in range(seed_values.context['num_anc_complete']) ] def randomize_anc_visit_values(template_string, seed_values, visit_number): context = {} context.update(seed_values.context) context['case_id'] = context['pregnant_tasks_case_id'] context['section_id'] = 'immuns' context['entry_id'] = 'anc_{}'.format(visit_number) visit_date_string = context['anc{}_date'.format(visit_number)] visit_date = string_to_datetime(visit_date_string) days_since_epoch = (visit_date - datetime(1970, 1, 1)).days context['balance'] = days_since_epoch formatted_case = template_string % context return json.loads(formatted_case) <file_sep>from . import const from .base import DataGenTestBase from .util import remove_ledgers from data_gen.data.randomizers import STILL_LIVE_CASES, YES_NO_OPTIONS as random_yes_no class TestDeliveryForm(DataGenTestBase): def test_delivery_form(self): yes_no_options = ['yes', 'no'] data_generator = self._get_random_pregnant_data_generator() data = remove_ledgers(data_generator.get_data()) self.assertEqual(const.EXPECTED_PREGNANT_ITEMS, len(data)) ccs_record_case = data[2] delivery_form_data = data[10] # redundant case test # note: try to avoid in further test cases # self.assertEqual(ccs_record_case.data['document']['case_id'], # data_generator.seed_values.case_ids.pregnant_ccs_record) self.assertEqual(ccs_record_case.data['document']['case_id'], delivery_form_data.data['document']['form']['case_load_ccs_record0']['case']['@case_id']) self.assertNotEqual( '%(form_id)s', delivery_form_data.data['document']['form_id'] ) self.assertEqual( delivery_form_data.data['document']['received_on'], delivery_form_data.data['document']['form']['meta']['timeEnd'], ) self.assertIn(delivery_form_data.data['document']['form']['child'] ['breastfed_within_first_hour'], yes_no_options) self.assertIn(delivery_form_data.data['document']['form'] ['child']['still_live_birth'], STILL_LIVE_CASES) self.assertTrue(delivery_form_data.data['document']['form']['days_visit_late'].isdigit()) self.assertTrue(delivery_form_data.data['document']['form']['num_children_del'].isdigit()) self.assertIn(delivery_form_data.data['document']['form'] ['unscheduled_visit'], ['0', '1']) <file_sep>from data_gen.kafka.topics import LEDGER_TOPIC def remove_ledgers(data): return [d for d in data if d[0] != LEDGER_TOPIC] <file_sep>import json from data_gen.data.util import get_template def get_random_pregnant_tasks_case(seed_values): template = get_template('pregnant-tasks-case.json') return randomize_template_values(template, seed_values) def randomize_template_values(template_string, seed_values): formatted_case = template_string % seed_values.context return json.loads(formatted_case) <file_sep>import json from data_gen.data import randomizers from data_gen.data.util import get_template def get_random_pregnant_case(seed_values, override_context=None): template = get_template('preg-woman-person-case.json') return randomize_template_values(template, seed_values, override_context) def get_random_mother_case(seed_values, override_context=None): template = get_template('mother-person-case.json') return randomize_template_values(template, seed_values, override_context) def get_random_child_case(seed_values): template = get_template('child-person-case.json') return randomize_template_values(template, seed_values) def randomize_template_values(template_string, seed_values, override_context=None): context = seed_values.context if override_context: print('ovewriting: {}'.format(override_context)) context.update(override_context) formatted_case = template_string % seed_values.context return json.loads(formatted_case) <file_sep>import random from unittest import TestCase from ..generator import DataGenerator from ..locations import get_all_locations class DataGenTestBase(TestCase): @classmethod def setUpClass(cls): cls.random_instance = random.Random('unit-tests') cls.locations = get_all_locations() @classmethod def get_next_data_generator(cls): location = cls.random_instance.choice(cls.locations) return DataGenerator(cls.random_instance, location) def _get_random_pregnant_data_generator(self): while True: data_generator = self.get_next_data_generator() if data_generator.is_pregnant and not data_generator.change_phone_number: return data_generator <file_sep>from . import const from .base import DataGenTestBase from .util import remove_ledgers class TestTHRForm(DataGenTestBase): def test_thr_form(self): data_generator = self._get_random_pregnant_data_generator() data = remove_ledgers(data_generator.get_data()) self.assertEqual(const.EXPECTED_PREGNANT_ITEMS, len(data)) ccs_record_case = data[2] thr_form_data = data[9] # redundant case test # note: try to avoid in further test cases # self.assertEqual(ccs_record_case.data['document']['case_id'], # data_generator.seed_values.case_ids.pregnant_ccs_record) self.assertEqual(ccs_record_case.data['document']['case_id'], thr_form_data.data['document']['form']['case_load_ccs_record_0']['case']['@case_id']) self.assertNotEqual( '%(form_id)s', thr_form_data.data['document']['form_id'] ) self.assertEqual( thr_form_data.data['document']['received_on'], thr_form_data.data['document']['form']['meta']['timeEnd'], ) self.assertTrue(thr_form_data.data['document']['form'] ['mother_thr']['days_ration_given_mother'].isdigit()) <file_sep>import csv import os from collections import namedtuple from datetime import timedelta, datetime from faker import Faker from . import randomizers DataUnit = namedtuple('DataUnit', ['topic', 'data']) CaseIds = namedtuple('CaseIds', [ 'household', 'mother_person', 'pregnant_person', 'child_person', 'child_health', 'pregnant_ccs_record', 'ccs_record', 'pregnant_tasks', ]) class SeedValues(namedtuple('SeedValues', ['random_instance', 'location', 'case_ids'])): @property def fake(self): if not hasattr(self, '_fake'): self._fake = Faker() self._fake.random = self.random_instance return self._fake @property def context(self): if not hasattr(self, '_context'): # edd - estimate delivery date # add - actual delivery date # as of now we are assuming add to be 1 day after edd # basis of bp_dates, delivery_dates and pnc_dates # are based on the add and edd # https://confluence.dimagi.com/pages/viewpage.action?spaceKey=ICDS&title=Home+Visit+Scheduler+Details edd = randomizers.get_next_edd(self.random_instance) lmp = edd - timedelta(days=280) # 280 = gestational age num_anc_complete = self.random_instance.randint(0, 4) bp1_date = edd - timedelta(days=270) bp2_date = edd - timedelta(days=75) bp3_date = edd - timedelta(days=45) add = edd + timedelta(days=1) modified_date = datetime.now() # Need to be fix # As of now it will take a random date from the next 360 days as per the lmp random_date = lmp + timedelta(days=randomizers.get_nextInt(self.random_instance) * 36) opened_on = lmp - timedelta(days=10) pnc1_date = add + timedelta(days=1) ebf1_date = add + timedelta(days=21) cf1_date = add + timedelta(days=182) anc1_date = edd - timedelta(days=274) anc2_date = max([anc1_date + timedelta(days=30), edd - timedelta(days=274)]) anc3_date = max([anc2_date + timedelta(days=30), edd - timedelta(days=274)]) anc4_date = max([anc3_date + timedelta(days=30), edd - timedelta(days=91)]) thr_date = add + timedelta(days=randomizers.get_nextInt(self.random_instance) * 120) next_visit_date_delivery = add + timedelta(days=randomizers.get_nextInt(self.random_instance)) # server_modified_on is actually the latest datetime when the case # is updated for raw data we are assuming this to be bp3_date self._context = { 'household_case_id': self.case_ids.household, 'mother_person_case_id': self.case_ids.mother_person, 'child_person_case_id': self.case_ids.child_person, 'pregnant_person_case_id': self.case_ids.pregnant_person, 'ccs_record_case_id': self.case_ids.ccs_record, 'pregnant_ccs_record_case_id': self.case_ids.pregnant_ccs_record, 'child_health_case_id': self.case_ids.child_health, 'pregnant_tasks_case_id': self.case_ids.pregnant_tasks, 'user_id': self.location.get_user_id(), 'owner_id': self.location.get_owner_id(), 'pregnant_name': self.fake.name_female(), 'mother_name': self.fake.name_female(), 'child_name': self.fake.name(), 'husband_name': self.fake.name_male(), 'mother_phone_number': randomizers.get_next_phone_number(self.random_instance), 'updated_phone_number': randomizers.get_next_phone_number(self.random_instance), 'add': randomizers.get_next_date(self.random_instance).strftime(randomizers.DATE_FORMAT_STRING), 'edd': edd.strftime(randomizers.DATE_FORMAT_STRING), 'lmp': lmp.strftime(randomizers.DATE_FORMAT_STRING), 'server_modified_on': datetime_to_string(pnc1_date), 'raw_server_modified_on': pnc1_date, 'bp1_date': datetime_to_string(bp1_date), 'bp2_date': datetime_to_string(bp2_date), 'bp3_date': datetime_to_string(bp3_date), 'pnc1_date': datetime_to_string(pnc1_date), 'anc1_date': datetime_to_date_string(anc1_date), 'anc2_date': datetime_to_date_string(anc2_date), 'anc3_date': datetime_to_date_string(anc3_date), 'anc4_date': datetime_to_date_string(anc4_date), 'thr_date': datetime_to_string(thr_date), 'ebf1_date': datetime_to_string(ebf1_date), 'cf1_date': datetime_to_string(cf1_date), 'child_birth_location': randomizers.get_next_child_birth_location(self.random_instance), 'preg_order': randomizers.get_nextInt(self.random_instance), 'date_death': random_date.strftime(randomizers.DATE_FORMAT_STRING), 'last_date_thr': random_date.strftime(randomizers.DATE_FORMAT_STRING), 'num_anc_complete': num_anc_complete, 'num_pnc_visits': int(self.random_instance.random() * 4), 'opened_on': datetime_to_string(opened_on), 'random_yes_no': randomizers.get_next_yes_no(self.random_instance), 'closed': randomizers.get_next_bool_value(self.random_instance), 'migration_status': randomizers.get_random_migration_status(self.random_instance), 'delivery_nature': randomizers.get_random_delivery_nature(self.random_instance), 'next_visit_date_delivery': datetime_to_string(next_visit_date_delivery), 'caste': randomizers.get_caste(self.random_instance), 'registered_status': randomizers.get_registered_status(self.random_instance), 'not_breasfeeding': randomizers.get_not_breasfeeding_values(self.random_instance) } return self._context def get_template(template_name): template_filename = os.path.join(os.path.dirname(__file__), 'templates', template_name) with open(template_filename, "r") as f: template_string = f.read() return template_string def iter_fixture(fixture_name): template_filename = os.path.join(os.path.dirname(__file__), 'fixtures', fixture_name) with open(template_filename, "r") as f: reader = csv.DictReader(f) yield from reader def datetime_to_string(dt): return f'{dt.isoformat()}Z' def datetime_to_date_string(dt): return dt.date().isoformat() def string_to_datetime(str): return datetime.strptime(str, '%Y-%m-%d') <file_sep>import json from data_gen.data.util import get_template def get_random_mother_ccs_record_case(seed_values): template = get_template('ccs-record-case.json') return randomize_template_values(template, seed_values) def get_random_pregnant_ccs_record_case(seed_values): template = get_template('preg-ccs-record-case.json') return randomize_template_values(template, seed_values) def randomize_template_values(template_string, seed_values): formatted_case = template_string % seed_values.context return json.loads(formatted_case) <file_sep>import json import datetime from . import randomizers from .util import get_template def get_random_growth_monitoring_form(seed_values): template = get_template('growth-monitoring-form.json') return randomize_template_values(template, seed_values) def randomize_template_values(template_string, seed_values): random_generator = seed_values.random_instance wfa = randomizers.get_next_wfa(random_generator) wfa_pos = abs(wfa) weight = randomizers.get_nextInt(random_generator) zscore = randomizers.get_next_zscore(random_generator) zscore_wfa = zscore * 3 zscore_icon = "red" if zscore_wfa < 3 else "yellow" if zscore_wfa < 2 else "green" nutrition_status = "severely underweight" if zscore_wfa < 3 else "moderately underweight" if zscore_wfa < 2 else "normal" datetime_modified_datetime = randomizers.get_next_datetime_modified(random_generator) datetime_modified = datetime.datetime.strftime(datetime_modified_datetime, "%Y-%m-%dT%H:%M:%S.%fZ") date_modified = datetime.datetime.strftime(datetime_modified_datetime, "%Y-%m-%d") age_days = randomizers.get_next_age_days(random_generator) age_weeks = age_days / 7.0 age_weeks_rounded = int(age_weeks) age_months = age_days / 30.25 age_months_rounded = int(age_months) age_dob = datetime.datetime.strftime(datetime_modified_datetime - datetime.timedelta(days = age_days),"%Y-%m-%d") yes_no = randomizers.get_next_yes_no(random_generator) sex = randomizers.get_next_sex(random_generator) form_id = randomizers.get_next_uuid(random_generator) formXML_id = randomizers.get_next_uuid(random_generator) deviceID = randomizers.get_next_device_id(random_generator) child_name = randomizers.get_next_child_name(random_generator) last_sync_token = randomizers.get_next_uuid(random_generator) submit_ip = randomizers.get_next_ip(random_generator) newForm = template_string % dict( wfa=wfa, child_id=seed_values.case_ids.child_person, weight=weight, zscore=zscore, zscore_wfa=zscore_wfa, zscore_icon=zscore_icon, nutrition_status=nutrition_status, age_days=age_days, age_weeks=age_weeks, age_weeks_rounded=age_weeks_rounded, age_months=age_months, age_months_rounded=age_months_rounded, age_dob=age_dob, yes_no=yes_no, owner_id=seed_values.location.get_owner_id(), sex=sex, form_id=form_id, user_id=seed_values.location.get_user_id(), username=seed_values.location.get_username(), formXML_id=formXML_id, datetime_modified=datetime_modified, date_modified=date_modified, deviceID=deviceID, child_name=child_name, wfa_pos=wfa_pos, last_sync_token=last_sync_token, submit_ip=submit_ip ) return json.loads(newForm)
89bd9753ce3f206119a39abb374e948bfc83e899
[ "Markdown", "Python" ]
32
Python
dimagi/cas-data-gen
862e2358303aed89d92f354c544b90f3dc024a67
e5a557b4de78f3723be0fd026f764ceecece28ac
refs/heads/master
<repo_name>RaD/example_module_replace<file_sep>/tasks/module_b.py import threading import time SLEEP = 3 TICK = 0.1 class ThreadTaskB(threading.Thread): name = 'Task B' counter = 0 def __init__(self, event): super(ThreadTaskB, self).__init__() self.event = event def run(self): print('thread {} started'.format(self.name)) while not self.event.is_set(): time.sleep(TICK) self.counter -= TICK if self.counter < 0.: self.counter = SLEEP print('{} tick'.format(self.name)) print('thread {} finished'.format(self.name)) <file_sep>/README.rst Dynamic Module Replacing ======================== This example shows the possibility of dynamically replacing the working Python modules. We use this ability to change the source code of threaded tasks. thread Task A started thread Task B started Task A tick Task B tick Task B tick Task A tick Task B tick Task A tick Task B tick thread Task B finished thread Task Bzz started Task Bzz tick Task A tick Task Bzz tick Task A tick Task Bzz tick Task Bzz tick thread Task B started thread Task Bzz finished Task B tick Task A tick ^C thread Task B finished thread Task A finished <file_sep>/main.py from __future__ import print_function """Demo of dynamic module replacing. Each module consists of a Thread-like class. To control the execution this thread we use Event object. Also we keep MTIME value of a module file because it help us to make decision of reloading module. """ import threading import pkgutil import os import time import sys PREFIX_CLASS = 'Thread' RELOAD_TIMEOUT = 10 class AttrDict(dict): """http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python""" def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self last_info = AttrDict() # here we keep an information about each thread path = os.path.join(os.path.dirname(__file__), 'tasks') def get_class(module): """Returns the class name. Each class has to begin with PREFIX.""" try: class_name = [i for i in dir(module) if i.startswith(PREFIX_CLASS)][0] except IndexError: return None else: return getattr(module, class_name) class ReloadException(Exception): pass def reload_module(module_name): """Reloads and returns the module by its name.""" full_name = '{}.{}'.format(path, module_name) # try to import the module try: module = __import__(full_name, fromlist=[module_name]) except ImportError: msg = 'Could not import {} module.'.format(module_name) raise ReloadException(msg) # get original name pycfile = module.__file__ pyfile = pycfile.replace('.pyc', '.py') # check the module existence and readability try: with open (pyfile, 'rU') as f: code = f.read() except: msg = 'Error opening file: {}. Does it exist?'.format(pyfile) raise ReloadException(msg) # compile loaded source code try: compile(code, module_name, 'exec') except: msg = 'Error in compilation: {}'.format(str(sys.exc_info()[0])) raise ReloadException(msg) # check the consistence of source code try: execfile(pyfile) except: msg = 'Error in execution: {}'.format(str(sys.exc_info()[0])) raise ReloadException(msg) # and finally reload the module return reload(sys.modules[full_name]) def main_loop(): while True: modules = pkgutil.iter_modules(path=[path]) for loader, module_name, is_package in modules: info = last_info.get(module_name) mtime = os.path.getmtime(os.path.join('.', 'tasks', module_name+'.py')) if not info: # initial import module = __import__('{}.{}'.format(path, module_name), fromlist=[module_name]) else: # repeat importing if info.mtime == mtime: continue else: info.event.set() module = reload_module(module_name) # restart thread klass = get_class(module) event = threading.Event() thread = klass(event) thread.start() last_info[module_name] = AttrDict(mtime=mtime, thread=thread, event=event) time.sleep(RELOAD_TIMEOUT) if __name__ == '__main__': try: main_loop() except KeyboardInterrupt: for info in last_info.values(): info.event.set() sys.exit(0)
ca809d3aed4503ca5d888df2c93de5f087f60dd4
[ "Python", "reStructuredText" ]
3
Python
RaD/example_module_replace
e4139b5797457af41b7d357b3e9d937344a6a1dc
d6e1ee49a5b3ee8b54dcbf2b76a3fabd50b5d3a7
refs/heads/master
<repo_name>DevrajRangani411/Hi-Tech<file_sep>/index.php <?php include('php/header.php')?> <section class="breadcrumb_part"> <div class="container"> <div class="row"> <div class="col-lg-12"> <?php $qry = "SELECT * FROM appartment where AppartmentId='".$_SESSION['a_id']."'"; $result = $con->query($qry); if($result->num_rows > 0){ while($row = $result->fetch_assoc()){ ?> <div class="breadcrumb_iner"> <h2><?php echo $row['Appartment_Name'] ?></h2> </div> <?php } } ?> </div> </div> </div> </section> <?php if(isset($_POST['add'])) { $qrycheckblock="select * from block where AppartmentId='".$_SESSION['a_id']."'"; $checkresult=$con->query($qrycheckblock); $flag=0; if($checkresult->num_rows >0){ while($rowresult=$checkresult->fetch_assoc()) { if($rowresult['BlockNumber'] == $_POST['blockno']) { $flag=1; } } } if($flag==0){ $qryblockadd="insert into block (BlockNumber,AppartmentID) values ('".$_POST['blockno']."','".$_SESSION['a_id']."')"; $con->query($qryblockadd);} else { echo '<script type="text/javascript"> test(); </script>'; } } ?> <script type="text/javascript"> test(); </script> <!-- feature part here --> <section class="feature_part section_padding"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-3 col-sm-6"> <a href="Announcement.php"> <div class="single_feature_part"> <img src="img/icon/megaphone.svg" alt="#"> <h4>Annoucement</h4> </div></a> </div> <div class="col-lg-3 col-sm-6"> <a href="userBill.php"> <div class="single_feature_part"> <img src="img/icon/bill.svg" alt=""> <h4>My Bills</h4> </div></a> </div> <div class="col-lg-3 col-sm-6"> <a href="Emerg-ppl.php"> <div class="single_feature_part"> <img src="img/icon/call.svg" alt="#"> <h4>Emergency Directory</h4> </div></a> </div> <div class="col-lg-3 col-sm-6"> <a href="buildingMaintenance.php"> <div class="single_feature_part"> <img src="img/icon/wallet.svg" alt="#"> <h4>Society Maintenance</h4> </div></a> </div> <div class="col-lg-3 col-sm-6"> <a href="members.php"><div class="single_feature_part"> <img src="img/icon/team-building%20(1).svg" alt="#"> <h4>Members</h4><br> </div></a> </div> <div class="col-lg-3 col-sm-6"> <a href="Gate-Pass.php"> <div class="single_feature_part"> <img src="img/icon/feature_icon_1.svg" alt="#"> <h4>Gate Pass</h4><br> </div></a> </div> <div class="col-lg-3 col-sm-6"> <a href="parkingreserve.php"> <div class="single_feature_part"> <img src="img/icon/parking.svg" alt="#"> <h4>Parking</h4> </div></a> </div> <div class="col-lg-3 col-sm-6"> <a href="complain.php"> <div class="single_feature_part"> <img src="img/icon/customer.svg" alt="#"> <h4>Complains</h4> </div> </a> </div> <?php $qry1="select * from users where EmailAddress='".$_SESSION['Email']."'"; $result1=$con->query($qry1); if($result1->num_rows > 0){ $row1 = $result1->fetch_assoc(); if($row1['isSecretary'] == 1){ ?> <div class="col-lg-3 col-sm-6"> <a href="" data-toggle="modal" data-target="#modal-new-event"> <div class="single_feature_part"> <img src="img/icon/appartment.svg" alt="#"> <h4>Block Add</h4> </div> </a> </div> <?php }}?> <div class="col-lg-3 col-sm-6"> <a href="UserProfile.php"> <div class="single_feature_part"> <img src="img/icon/team-building.svg" alt="#"> <h4>Profile</h4> </div></a> </div> <div class="col-lg-3 col-sm-6"> <a href="Vehical.php"> <div class="single_feature_part"> <img src="img/icon/car.svg" alt="#"> <h4>Vehical Information</h4> </div></a> </div> <div class="col-lg-3 col-sm-6"> <a href="SocietyInfo.php"> <div class="single_feature_part"> <img src="img/icon/address.svg" alt="#"> <h4>Society Information</h4> </div> </a> </div> </div> </div> </section> <div class="modal fade" id="modal-new-event"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Add Block</h4> </div> <form action="" method="post" enctype="multipart/form-data"> <div class="modal-body"> <div class="form-group p_star"> <span class="input-group-addon"> <h3>Block No</h3> </span> <input type="text" class="form-control" placeholder="Block No" name="blockno" required> </div><br> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger pull-left" data-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-primary" name="add" >Add</button> </div> </form> </div> </div> </div> <script type="text/javascript"> function test() { alert('In test Function'); } </script> <!-- feature part end --> <!--::footer_part start::--> <?php include('php/footer.php')?> <file_sep>/forgotPwd.php <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>pillloMart</title> <link rel="icon" href="img/favicon.png"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="css/bootstrap.min.css"> <!-- animate CSS --> <link rel="stylesheet" href="css/animate.css"> <!-- owl carousel CSS --> <link rel="stylesheet" href="css/owl.carousel.min.css"> <!-- font awesome CSS --> <link rel="stylesheet" href="css/all.css"> <!-- flaticon CSS --> <link rel="stylesheet" href="css/flaticon.css"> <link rel="stylesheet" href="css/themify-icons.css"> <!-- font awesome CSS --> <link rel="stylesheet" href="css/magnific-popup.css"> <!-- swiper CSS --> <link rel="stylesheet" href="css/slick.css"> <!-- style CSS --> <link rel="stylesheet" href="css/style.css"> </head> <!-- breadcrumb part start--> <section class="breadcrumb_part"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="breadcrumb_iner"> <h2>Forgot Password</h2> </div> </div> </div> </div> </section> <!-- breadcrumb part end--> <!--================login_part Area =================--> <section class="login_part section_padding "> <div class="container"> <div class="row align-items-center"> <div class="col-lg-6 col-md-6"> <div class="login_part_form"> <div class="login_part_form_iner"> <h3>Enter Your Register Email Address<br></h3> <?php if(isset($_POST['verify'])) { require("php/connect_db.php"); $qry = "SELECT * FROM users WHERE EmailAddress='".$_POST['name']."'"; $result = $con->query($qry); if($result->num_rows ==1) { $var=rand(999,10000); $t=time(); $timestamp = date("Y-m-d h:i:s",strtotime(date("Y-m-d h:i:s",$t)) +180); $qry1 = "insert into tempotpverify(EmailAddress,otp,timestamp) values ('".$_POST['name']."','".$var."','".$timestamp."')"; $con->query($qry1); $to = $_POST['name']; $subject = 'Otp Verify'; $message = "Hi, Your Otp for reset password is '".$var."' Valid Only for 3 minutes"; $headers = 'From: [er.darshanghetiya]@gmail.com' . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/html; charset=utf-8'; if(mail($to, $subject, $message, $headers)) { session_start(); $_SESSION['verifyemail']=$_POST['name']; require("php/close_db.php"); header("Location:otpverify.php"); } } else { echo "<h3>Please enter Register Email Address.</h3>"; require("php/close_db.php"); } } ?> <form class="row contact_form" action="" method="post"> <div class="col-md-12 form-group p_star"> <input type="text" class="form-control" id="name" name="name" value="" placeholder="Email Address" required> </div> <div class="col-md-12 form-group"> <button type="submit" value="submit" name="verify"class="btn_3"> Proceed To Verify OTP </button> </div> </form> </div> </div> </div> </div> </div> </section> <!--================login_part end =================--> <!--::footer_part start::--> <footer class="footer_part"> <div class="copyright_part"> <div class="container"> <div class="row "> <div class="col-lg-12"> <div class="copyright_text"> <P> <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --> Copyright &copy;<script> document.write(new Date().getFullYear()); </script> All rights reserved <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --> </P> </div> </div> </div> </div> </div> </footer> <file_sep>/Building-join.php <?php include('php/header.php')?> <!-- breadcrumb part start--> <section class="breadcrumb_part"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="breadcrumb_iner"> <h2>Join Building</h2> </div> </div> </div> </div> </section> <!-- breadcrumb part end--> <?php if(isset($_POST['join'])) { require("php/connect_db.php"); $qry = "SELECT * FROM users WHERE EmailAddress='".$_SESSION['Email']."'"; $result = $con->query($qry); $row = $result->fetch_assoc(); $qry2="SELECT * FROM appartment WHERE AppartmentId='".$_POST["name"]."'"; $result1 = $con->query($qry2); $row1 = $result1->fetch_assoc(); if($result1->num_rows > 0) { $qry3 = "SELECT * FROM block WHERE AppartmentId='".$row1['AppartmentId']."'"; $result3 = $con->query($qry3); $row3 = $result3->fetch_assoc(); if($result3->num_rows>0) { $qry4="select * from block where BlockNumber = '".$_POST['block_num']."' and AppartmentId='".$row1['AppartmentId']."'"; $result4=$con->query($qry4); if($result4->num_rows==1) { $qry1 = "UPDATE users set status=1,AppartmentId='".$row1['AppartmentId']."',BlockNumber='".$_POST['block_num']."',Secretary_Name='".$row1['Secretary_Name']."' where EmailAddress='".$_SESSION['Email']."'"; if($con->query($qry1)) { echo '<h3>Appartment Code is Right</h3>'; session_start(); $_SESSION['a_id']=$row1['AppartmentId']; $_SESSIONs['bno']=$row1['BlockNumber']; header("Location: index.php"); }else{ echo "Server Error Please try Again later .."; } } else { echo "<h3>Please Contact Your Secretary To Add Your Block or Make Sure You enter right block Number</h3>"; } } } else{ echo '<h3>Appartment Code is Wrong please check again</h3>'; } require("php/close_db.php"); } ?> <!--================login_part Area =================--> <section class="login_part section_padding "> <div class="container"> <div class="row align-items-center"> <div class="col-lg-6 col-md-6"> <div class="login_part_form"> <div class="login_part_form_iner"> <h3>Enter Your Building Code<br></h3> <form class="row contact_form" action="" method="post"> <div class="col-md-12 form-group p_star"> <input type="text" class="form-control" name="name" value="" placeholder="Building Code" required> </div> <div class="col-md-12 form-group p_star"> <input type="text" class="form-control" name="block_num" value="" placeholder="Block Number" required> </div> <div class="col-md-12 form-group"> <button type="submit" value="submit" name="join" class="btn_3"> Join Your Building </button> </div> </form> </div> </div> </div> </div> </div> </section> <!--================login_part end =================--> <!--::footer_part start::--> <footer class="footer_part"> <div class="copyright_part"> <div class="container"> <div class="row "> <div class="col-lg-12"> <div class="copyright_text"> <P> <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --> Copyright &copy;<script> document.write(new Date().getFullYear()); </script> All rights reserved <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --> </P> </div> </div> </div> </div> </div> <?php include('php/footer.php')?>
98231a566c92c98d01016e48bf23a9f903d7a44f
[ "PHP" ]
3
PHP
DevrajRangani411/Hi-Tech
eaa940db066e2346d733b8af7db9702534d774a9
a7dabca21de624fea951e765132b5913b0e22bf0
refs/heads/master
<repo_name>Lysicik/lab1<file_sep>/Lab2/Program.cs using System; namespace ConsoleApp3 { class Program { static void Main(string[] args) { Circle a = new Circle(1); Rectangle b = new Rectangle(4, 7); Square c = new Square(7); a.Print(); b.Print(); c.Print(); Console.ReadKey(); } } } <file_sep>/Lab2/Rectangle.cs using System; namespace ConsoleApp3 { public class Rectangle : Figure, IPrint { public Rectangle(double height = 0, double width = 0) { Height = height; Width = width; } public double Height { get; set; } public double Width { get; set; } public override string FigureName => "Прямоугольник"; public override double Area() { return Width * Height; } public void Print() => Console.WriteLine(this.ToString()); public override string ToString() { return $"{FigureName}, S = {Area()}, A = {Height}, B = {Width}"; } } }
f79c142e13915f32b0cbfd5ff7ba02ef6759b0fb
[ "C#" ]
2
C#
Lysicik/lab1
fd91ac06c3ba4905b9d1701b13b65fd1d0ebd713
1a5d4af32288ba4025cfa96edc541d17ab07aa7a
refs/heads/master
<repo_name>anusaini/CiEsVi<file_sep>/src/lib/wc.test.js const wc = require('./wc') const expect = require('chai').expect describe('wc', () => { it('returns { lines: 4, words: 12, letters: 23 } for input "a,b,c\n1,2,3\n4,5,6\n7,8,9"', () => { const actual = wc('a,b,c\n1,2,3\n4,5,6\n7,8,9', '\n') const expected = { lines: 4, words: 12, letters: 23 } expect(actual).to.deep.equal(expected) }) }) <file_sep>/src/lib/TableManager.js const Turtler = require('turtler') class TableManager { constructor(data, options) { this.data = data } get table() { if (!this.tableData) { const turtle = new Turtler(this.data) this.tableData = { ascii: turtle.ascii(), markdown: turtle.markdown(), html: turtle.html() } } return this.tableData } } module.exports = TableManager <file_sep>/src/lib/CiEsVi.js const TableManager = require('./TableManager') const SortingManager = require('./SortingManager') const StatManager = require('./StatManager') class CiEsVi { constructor(csv, options) { this.options = options this.data = csv this.rows = csv.split(options.rowSplitter) this.columns = this.data[0].split(options.colSplitter) this.matrix = this.rows.map(row => row.split(this.options.colSplitter)) this.count = { col: this.columns.length, row: this.data.length } this.sortingManager = new SortingManager(this.rows) this.statManager = new StatManager(); } get table() { this.TableManager = this.TableManager || new TableManager([this.matrix.map(String)]) return this.TableManager.table } sortedArray(compare, sortId) { return this.sortingManager.sort(compare, sortId) } sortedCSV(compare, sortId) { return this.sortedArray(compare, sortId).join(this.options.rowSplitter) } get stats() { return { punctuation: this.statManager.punctuationStat(this.data), wc: this.statManager.wc(this.data, this.options.rowSplitter) } } } module.exports = CiEsVi <file_sep>/CHANGELOG.md # Changes ## Version 1.1.1 - Fixes wc word count bug - Closes [#2](https://github.com/anusaini/CiEsVi/issues/2) - Closes [#3](https://github.com/anusaini/CiEsVi/issues/3) - Introduces Jasmine and Chai as dev dependencies - Tests wc.js ## Version 1.1.0 - Introduce `node-punctuation-stats` to library - Get punctuation stats via `(new CiEsVi(data)).stats` - Get word count `wc` stats via `(new CiEsVi(data)).stats` ## Version 1.0.0 - First working code ## Version 0.0.0 - Placeholder <file_sep>/src/index.js const CiEsVi = require('./lib/CiEsVi') module.exports = { CiEsVi } <file_sep>/README.md # CiEsVi A CSV library - node module ## Usage ```javascript > var CiEsVi = require('ciesvi').CiEsVi > var c = new CiEsVi(`a,b,c\n1,2,3\n4,5,6\n7,8,9`, { rowSplitter: '\n', colSplitter: ',' }) > c CiEsVi { options: { rowSplitter: '\n', colSplitter: ',' }, data: 'a,b,c\n1,2,3\n4,5,6\n7,8,9', rows: [ 'a,b,c', '1,2,3', '4,5,6', '7,8,9' ], columns: [ 'a' ], matrix: [ [ 'a', 'b', 'c' ], [ '1', '2', '3' ], [ '4', '5', '6' ], [ '7', '8', '9' ] ], count: { col: 1, row: 23 }, sortingManager: SortingManager { rows: [ 'a,b,c', '1,2,3', '4,5,6', '7,8,9' ], cache: [] } } > c.table { ascii: 'a,b,c | 1,2,3 | 4,5,6 | 7,8,9\n=======================\n', markdown: '| a,b,c | 1,2,3 | 4,5,6 | 7,8,9 |\n|-------|-------|-------|-------|\n', html: '<table> <thead> <tr> <th>a,b,c</th><th>1,2,3</th><th>4,5,6</th><th>7,8,9</th> </tr> </thead> <tbody> </tbody> </table>' } > c CiEsVi { options: { rowSplitter: '\n', colSplitter: ',' }, data: 'a,b,c\n1,2,3\n4,5,6\n7,8,9', rows: [ 'a,b,c', '1,2,3', '4,5,6', '7,8,9' ], columns: [ 'a' ], matrix: [ [ 'a', 'b', 'c' ], [ '1', '2', '3' ], [ '4', '5', '6' ], [ '7', '8', '9' ] ], count: { col: 1, row: 23 }, sortingManager: SortingManager { rows: [ 'a,b,c', '1,2,3', '4,5,6', '7,8,9' ], cache: [ desc: [Array] ] } } > c.stats { punctuation: { punctuations: [ '!', '?', '.', ',', ';', ':' ], found: [ [Object], [Object], [Object], [Object], [Object], [Object] ], total: 8, message: 'Found 8 punctuations of 6 types: ! ? . , ; :' }, wc: { lines: 4, words: 12, letters: 23 } } ``` ## License MIT <file_sep>/CONTRIBUTIONS.md # Contributions <NAME> Git Faf A Next Random
5d2e0590fa395a25d1e4af4a3e7775d34fda2027
[ "JavaScript", "Markdown" ]
7
JavaScript
anusaini/CiEsVi
77522c9507c05d2a4e59f7c8740b170ee787fa02
2bf9a453f7fd910ebf2229b77900fd7f8a1299f8
refs/heads/master
<repo_name>nmkqjqr/DatabaseOperation<file_sep>/cmake/dependencies/Boost.cmake set(Boost_FIND_QUIETLY TRUE) set(Boost_USE_MULTITHREADED ON) find_package(Boost 1.72.0 COMPONENTS date_time) if (NOT Boost_DATE_TIME_FOUND) find_package(Boost 1.72.0) endif() set(Boost_RELEASE_VERSION "${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}") boost_external_report(Boost RELEASE_VERSION INCLUDE_DIR LIBRARIES) <file_sep>/tests/Main.cpp // OCILIBDemo.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include <ocilib.h> #include <ocilib.hpp> #pragma comment( lib, "D:/Cpp/soci-4.0.0/SOCI4VS/SOCI/lib/ociliba.lib" ) using namespace ocilib; using namespace std; void err_handler(OCI_Error* err) { const otext* loText = OCI_ErrorGetString(err); printf("%s\n", loText); } int main() { #ifdef _WIN32 //控制台显示乱码纠正 // system("chcp 65001"); //设置字符集(使用SetConsoleCP(65001)设置无效,原因未知) SetConsoleOutputCP(65001); //CONSOLE_FONT_INFOEX info = { 0 }; // 以下设置字体来支持中文显示。 //info.cbSize = sizeof(info); //info.dwFontSize.Y = 16; // leave X as zero //info.FontWeight = FW_NORMAL; //wcscpy_s(info.FaceName, L"Consolas"); //SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), NULL, &info); #endif /*OCI_Connection* cn; OCI_Statement* st; OCI_Resultset* rs; if (!OCI_Initialize(err_handler, NULL, OCI_ENV_DEFAULT)) { return EXIT_FAILURE; } cn = OCI_ConnectionCreate("FAST", "V45GDYH", "1", OCI_SESSION_DEFAULT); printf("Server major version : %i\n", OCI_GetServerMajorVersion(cn)); printf("Server minor version : %i\n", OCI_GetServerMinorVersion(cn)); printf("Server revision version : %i\n\n", OCI_GetServerRevisionVersion(cn)); printf("Connection version : %i\n\n", OCI_GetVersionConnection(cn)); st = OCI_StatementCreate(cn); OCI_ExecuteStmt(st, "select C_FUN_CODE, C_FUN_NAME from t_s_fun"); rs = OCI_GetResultset(st); while (OCI_FetchNext(rs)) { printf("%i - %s\n", OCI_GetString(rs, 1), OCI_GetString(rs, 2)); } OCI_ConnectionFree(cn); OCI_Cleanup();*/ try { if (!OCI_Initialize(err_handler, NULL, OCI_ENV_DEFAULT)) { return EXIT_FAILURE; } /*Environment::Initialize(Environment::Default | Environment::Threaded, "");*/ Environment::CharsetMode loCharMode = Environment::GetCharset(); Environment::SessionFlags loFlags = Environment::SessionDefault; Connection con("FAST", "V45GDYH", "1", loFlags); printf("Connection string: %i\n", (std::string)con.GetConnectionString()); printf("Server major version : %i\n", con.GetServerMajorVersion()); printf("Server minor version : %i\n", con.GetServerMinorVersion()); printf("Server revision version : %i\n\n", con.GetServerRevisionVersion()); printf("Connection version : %i\n\n", con.GetVersion()); Statement st(con); st.Execute("select C_FUN_CODE, C_FUN_NAME from t_s_fun"); Resultset rs = st.GetResultset(); int liIndex = 0; while (rs.Next()) { ostring loC_FUN_CODE = rs.Get<ostring>(1); ostring loC_FUN_NAME = rs.Get<ostring>(2); /*string lcCode = WStrToStr(loC_FUN_CODE); string lcName = WStrToStr(loC_FUN_NAME);*/ string loContent = "序号:" + std::to_string(liIndex) + "---" + loC_FUN_CODE.c_str() + " - " + loC_FUN_NAME.c_str(); /*string lcContent = WStrToStr(loContent);*/ /*lcContent = Utf8ToGBK(lcContent.c_str());*/ std::cout << loContent << std::endl; liIndex++; } } catch (std::exception & ex) { std::cout << ex.what() << std::endl; } Environment::Cleanup(); system("PAUSE"); return EXIT_SUCCESS; } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件 <file_sep>/VS/tests/CTestTestfile.cmake # CMake generated Testfile for # Source directory: D:/Cpp/SOCI/SOCI/SOCI4.0.0/tests # Build directory: D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/tests # # This file includes the relevant testing commands required for # testing this directory and lists subdirectories to be tested as well. subdirs("empty") subdirs("db2") subdirs("firebird") subdirs("mysql") subdirs("odbc") subdirs("oracle") subdirs("postgresql") subdirs("sqlite3") <file_sep>/VS/src/backends/sqlite3/CMakeFiles/Export/cmake/SOCI-debug.cmake #---------------------------------------------------------------- # Generated CMake target import file for configuration "Debug". #---------------------------------------------------------------- # Commands may need to know the format version. set(CMAKE_IMPORT_FILE_VERSION 1) # Import target "SOCI::soci_core" for configuration "Debug" set_property(TARGET SOCI::soci_core APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(SOCI::soci_core PROPERTIES IMPORTED_IMPLIB_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_core_4_0.lib" IMPORTED_LOCATION_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_core_4_0.dll" ) list(APPEND _IMPORT_CHECK_TARGETS SOCI::soci_core ) list(APPEND _IMPORT_CHECK_FILES_FOR_SOCI::soci_core "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_core_4_0.lib" "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_core_4_0.dll" ) # Import target "SOCI::soci_core_static" for configuration "Debug" set_property(TARGET SOCI::soci_core_static APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(SOCI::soci_core_static PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX" IMPORTED_LOCATION_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/libsoci_core_4_0.lib" ) list(APPEND _IMPORT_CHECK_TARGETS SOCI::soci_core_static ) list(APPEND _IMPORT_CHECK_FILES_FOR_SOCI::soci_core_static "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/libsoci_core_4_0.lib" ) # Import target "SOCI::soci_empty" for configuration "Debug" set_property(TARGET SOCI::soci_empty APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(SOCI::soci_empty PROPERTIES IMPORTED_IMPLIB_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_empty_4_0.lib" IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG "SOCI::soci_core" IMPORTED_LOCATION_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_empty_4_0.dll" ) list(APPEND _IMPORT_CHECK_TARGETS SOCI::soci_empty ) list(APPEND _IMPORT_CHECK_FILES_FOR_SOCI::soci_empty "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_empty_4_0.lib" "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_empty_4_0.dll" ) # Import target "SOCI::soci_empty_static" for configuration "Debug" set_property(TARGET SOCI::soci_empty_static APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(SOCI::soci_empty_static PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX" IMPORTED_LOCATION_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/libsoci_empty_4_0.lib" ) list(APPEND _IMPORT_CHECK_TARGETS SOCI::soci_empty_static ) list(APPEND _IMPORT_CHECK_FILES_FOR_SOCI::soci_empty_static "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/libsoci_empty_4_0.lib" ) # Import target "SOCI::soci_odbc" for configuration "Debug" set_property(TARGET SOCI::soci_odbc APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(SOCI::soci_odbc PROPERTIES IMPORTED_IMPLIB_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_odbc_4_0.lib" IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG "SOCI::soci_core;odbc32.lib;odbc32.lib" IMPORTED_LOCATION_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_odbc_4_0.dll" ) list(APPEND _IMPORT_CHECK_TARGETS SOCI::soci_odbc ) list(APPEND _IMPORT_CHECK_FILES_FOR_SOCI::soci_odbc "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_odbc_4_0.lib" "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_odbc_4_0.dll" ) # Import target "SOCI::soci_odbc_static" for configuration "Debug" set_property(TARGET SOCI::soci_odbc_static APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(SOCI::soci_odbc_static PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX" IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG "odbc32.lib;odbc32.lib" IMPORTED_LOCATION_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/libsoci_odbc_4_0.lib" ) list(APPEND _IMPORT_CHECK_TARGETS SOCI::soci_odbc_static ) list(APPEND _IMPORT_CHECK_FILES_FOR_SOCI::soci_odbc_static "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/libsoci_odbc_4_0.lib" ) # Import target "SOCI::soci_oracle" for configuration "Debug" set_property(TARGET SOCI::soci_oracle APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(SOCI::soci_oracle PROPERTIES IMPORTED_IMPLIB_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_oracle_4_0.lib" IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG "SOCI::soci_core;F:/app/yss/product/11.2.0/dbhome_1/OCI/lib/MSVC/oci.lib;F:/app/yss/product/11.2.0/dbhome_1/OCI/lib/MSVC/oraocci11.lib;F:/app/yss/product/11.2.0/dbhome_1/OCI/lib/MSVC/ociw32.lib" IMPORTED_LOCATION_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_oracle_4_0.dll" ) list(APPEND _IMPORT_CHECK_TARGETS SOCI::soci_oracle ) list(APPEND _IMPORT_CHECK_FILES_FOR_SOCI::soci_oracle "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_oracle_4_0.lib" "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_oracle_4_0.dll" ) # Import target "SOCI::soci_oracle_static" for configuration "Debug" set_property(TARGET SOCI::soci_oracle_static APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(SOCI::soci_oracle_static PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX" IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG "F:/app/yss/product/11.2.0/dbhome_1/OCI/lib/MSVC/oci.lib;F:/app/yss/product/11.2.0/dbhome_1/OCI/lib/MSVC/oraocci11.lib;F:/app/yss/product/11.2.0/dbhome_1/OCI/lib/MSVC/ociw32.lib" IMPORTED_LOCATION_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/libsoci_oracle_4_0.lib" ) list(APPEND _IMPORT_CHECK_TARGETS SOCI::soci_oracle_static ) list(APPEND _IMPORT_CHECK_FILES_FOR_SOCI::soci_oracle_static "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/libsoci_oracle_4_0.lib" ) # Import target "SOCI::soci_sqlite3" for configuration "Debug" set_property(TARGET SOCI::soci_sqlite3 APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(SOCI::soci_sqlite3 PROPERTIES IMPORTED_IMPLIB_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_sqlite3_4_0.lib" IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG "SOCI::soci_core;D:/Cpp/SQLite/VS/lib/SQLite.lib;D:/Cpp/SQLite/VS/lib/SQLite.lib" IMPORTED_LOCATION_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_sqlite3_4_0.dll" ) list(APPEND _IMPORT_CHECK_TARGETS SOCI::soci_sqlite3 ) list(APPEND _IMPORT_CHECK_FILES_FOR_SOCI::soci_sqlite3 "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_sqlite3_4_0.lib" "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_sqlite3_4_0.dll" ) # Import target "SOCI::soci_sqlite3_static" for configuration "Debug" set_property(TARGET SOCI::soci_sqlite3_static APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(SOCI::soci_sqlite3_static PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX" IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG "D:/Cpp/SQLite/VS/lib/SQLite.lib;D:/Cpp/SQLite/VS/lib/SQLite.lib" IMPORTED_LOCATION_DEBUG "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/libsoci_sqlite3_4_0.lib" ) list(APPEND _IMPORT_CHECK_TARGETS SOCI::soci_sqlite3_static ) list(APPEND _IMPORT_CHECK_FILES_FOR_SOCI::soci_sqlite3_static "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/libsoci_sqlite3_4_0.lib" ) # Commands beyond this point should not need to know the version. set(CMAKE_IMPORT_FILE_VERSION) <file_sep>/VS/include/soci/soci-config.h // // Copyright (C) 2004-2008 <NAME>, <NAME> // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef SOCICONFIG_H_INCLUDED #define SOCICONFIG_H_INCLUDED // // SOCI has been build with support for: // // Boost library /* #undef SOCI_HAVE_BOOST */ // Boost date_time library /* #undef SOCI_HAVE_BOOST_DATE_TIME */ // Enables C++11 support /* #undef SOCI_HAVE_CXX11 */ // DB2 backend /* #undef SOCI_HAVE_DB2 */ // EMPTY backend #define SOCI_HAVE_EMPTY // FIREBIRD backend /* #undef SOCI_HAVE_FIREBIRD */ // MYSQL backend /* #undef SOCI_HAVE_MYSQL */ // ODBC backend #define SOCI_HAVE_ODBC // ORACLE backend #define SOCI_HAVE_ORACLE // POSTGRESQL backend /* #undef SOCI_HAVE_POSTGRESQL */ // SQLITE3 backend #define SOCI_HAVE_SQLITE3 #endif // SOCICONFIG_H_INCLUDED <file_sep>/tests/AllDemo/AllDemo.cpp // AllDemo.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <windows.h> //#include <ctime> //#include <algorithm> //#include <cassert> //#include <clocale> //#include <cstdlib> //#include <cmath> //#include <iomanip> //#include <limits> //#include <typeinfo> #include <iostream> #include <string> #include <cstring> #include <soci/soci.h> #include <soci/sqlite3/soci-sqlite3.h> #include <soci/oracle/soci-oracle.h> #ifdef SOCI_HAVE_BOOST // explicitly pull conversions for Boost's optional, tuple and fusion: #include <boost/version.hpp> #include "soci/boost-optional.h" #include "soci/boost-tuple.h" #include "soci/boost-gregorian-date.h" #if defined(BOOST_VERSION) && BOOST_VERSION >= 103500 #include "soci/boost-fusion.h" #endif // BOOST_VERSION #endif // SOCI_HAVE_BOOST #include "soci-compiler.h" #if defined(_MSC_VER) && (_MSC_VER < 1500) #undef SECTION #define SECTION(name) INTERNAL_CATCH_SECTION(name, "dummy-for-vc8") #endif using namespace std; using namespace soci; int main() { #ifdef _WIN32 //控制台显示乱码纠正 /*system("chcp 65001"); *///设置字符集(使用SetConsoleCP(65001)设置无效,原因未知) SetConsoleOutputCP(65001); CONSOLE_FONT_INFOEX info = { 0 }; // 以下设置字体来支持中文显示。 info.cbSize = sizeof(info); info.dwFontSize.Y = 23; // leave X as zero info.FontWeight = 700; wcscpy_s(info.FaceName, L"Consolas"); SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), NULL, &info); #endif #ifdef _MSC_VER // Redirect errors, unrecoverable problems, and assert() failures to STDERR, // instead of debug message window. // This hack is required to run assert()-driven tests by Buildbot. // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); #endif //_MSC_VER session sql("oracle", "service=FAST user=V45GDYH password=1 charset=utf8 ncharset=utf8"); rowset<row> rs = (sql.prepare << "select C_FUN_CODE,C_FUN_NAME from t_s_fun"); int liIndex = 0; for (rowset<row>::iterator it = rs.begin(); it != rs.end(); ++it) { cout << u8"序号:" << liIndex << endl; const row& row = *it; string lcCode = row.get<string>("C_FUN_CODE"); string lcName = row.get<string>("C_FUN_NAME"); cout << " C_FUN_CODE:" << lcCode << " C_FUN_NAME:" << lcName << endl; liIndex++; } session Sqlite("sqlite3", "D:/Cpp/SOCI/SOCI/SOCI4.0.0/VS/lib/soci_sqlite3_test/CompareData.db3"); rowset<row> Sqliters = (Sqlite.prepare << "select C_NAME,I_NAME from T_CONNECT"); liIndex = 0; for (rowset<row>::iterator it = Sqliters.begin(); it != Sqliters.end(); ++it) { cout << u8"序号:" << liIndex << endl; const row& row = *it; string lcName = row.get<string>("C_NAME"); string lcServer = row.get<string>("I_NAME"); cout << u8" 名称:" << lcName << u8" 服务地址:" << lcServer << endl; liIndex++; } system("PAUSE"); return 0; } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
c7841f103d96678d80f88d28dab2bffad116a0d6
[ "C", "CMake", "C++" ]
6
CMake
nmkqjqr/DatabaseOperation
2b240e8e32973b5d90a39bc299e86a65564c402d
5d7d4d2713b67d92b32d8308b6423705cb0b24bf
refs/heads/main
<file_sep>import { Request, Response } from "express"; import jwt from "jsonwebtoken"; import { User } from "../models/User"; import bcrypt from "bcrypt"; import dotenv from "dotenv"; import { matchedData, validationResult } from "express-validator"; dotenv.config(); export const signup = async (request: Request, response: Response) => { const errors = validationResult(request); if (!errors.isEmpty()) { response.json({ error: errors.mapped() }); return; } const data = matchedData(request); if (data.name && data.email && data.password) { const emailExists = await User.findOne({ where: { email: data.email } }); if (!emailExists) { const user = User.build(); user.name = data.name; user.email = data.email; user.password = await bcrypt.hash(data.password, 10); await user.save(); const token = jwt.sign({ id: user.id, email: user.email, password: user.password }, process.env.JWT_SECRET as string, { expiresIn: process.env.JWT_EXPIRESIN }); return response.json({ user: user, token: token }); } return response.json({ error: "e-mail já cadastrado." }); } else { return response.json({ error: "preencha todos os campos." }); } } export const signin = async (request: Request, response: Response) => { const errors = validationResult(request); if (!errors.isEmpty()) { response.json({ error: errors.mapped() }); return; } const data = matchedData(request); const user = await User.findOne({ where: { email: data.email } }); if (user && data.password) { const compare = await bcrypt.compare(data.password, user.password); if (compare) { const token = jwt.sign({ id: user.id, email: user.email, password: user.password }, process.env.JWT_SECRET as string, { expiresIn: process.env.JWT_EXPIRESIN }); return response.json({ user: user, token: token }); } else { return response.json({ error: "e-mail e/ou senha incorretos." }); } } else { return response.json({ error: "e-mail e/ou senha incorretos." }); } } export const users = async (request: Request, response: Response) => { const users = await User.findAll(); return response.json({ users: users }); } export const user = async (request: Request, response: Response) => { const { idUser } = request.params; const user = await User.findByPk(idUser); if (user) { return response.json({ user: user }); } else { return response.json({ error: "user não encontrado." }); } } export const update = async (request: Request, response: Response) => { const { idUser } = request.params; const errors = validationResult(request); if (!errors.isEmpty()) { response.json({ error: errors.mapped() }); return; } const data = matchedData(request); const user = await User.findByPk(idUser); if (user) { if (data.name) { user.name = data.name; } if (data.email) { const emailExists = await User.findOne({ where: { email: data.email } }); if (!emailExists) { user.email = data.email; } else { return response.json({ error: "e-mail já cadastrado." }); } } if (data.password) { user.password = await bcrypt.hash(data.password, 10); } await user.save(); return response.json({ user: user }); } else { return response.json({ error: "user não encontrado." }); } } export const deletar = async (request: Request, response: Response) => { const { idUser } = request.params; const user = await User.findByPk(idUser); if (user) { await user.destroy(); return response.json({ success: "user deletado com sucesso." }); } else { return response.json({ error: "user não encontrado." }); } }<file_sep>import { NextFunction, Request, Response } from "express"; import jwt from "jsonwebtoken"; import dotenv from "dotenv"; import { User } from "../models/User"; dotenv.config(); export const get = async (request: Request, response: Response, next: NextFunction) => { const { token } = request.query; if (token) { const auth = jwt.verify(token as string, process.env.JWT_SECRET as string, (error: any, decoded: any) => { if (error) { return { error: error }; } else { return decoded; } }); const { email, password, error } = auth as any; if (error) { return response.json({ error: error }); } else { const user = await User.findOne({ where: { email: email, password: <PASSWORD> } }); if (user) { return next(); } else { response.json({ error: "unauthorized" }); } } } else { return response.json({ error: "token inválido." }); } } export const post = async (request: Request, response: Response, next: NextFunction) => { const { token } = request.body; if (token) { const auth = jwt.verify(token as string, process.env.JWT_SECRET as string, (error: any, decoded: any) => { if (error) { return { error: error }; } else { return decoded; } }); const { email, password, error } = auth as any; if (error) { return response.json({ error: error }); } else { const user = await User.findOne({ where: { email: email, password: <PASSWORD> } }); if (user) { return next(); } else { response.json({ error: "unauthorized" }); } } } else { return response.json({ error: "token inválido." }); } }<file_sep>import { Router } from "express"; import * as UserController from "../controllers/UserController"; import * as Auth from "../middlewares/AuthMiddleware"; import * as Verify from "../verifications/Verify"; const router = Router(); router.post("/signup", Verify.signup, UserController.signup); router.post("/signin", Verify.signin, UserController.signin); router.get("/users", Auth.get, UserController.users); router.get("/user/:idUser", Auth.get, UserController.user); router.put("/update/:idUser", Verify.update, Auth.post, UserController.update); router.delete("/deletar/:idUser", Auth.post, UserController.deletar); export default router;<file_sep>import { checkSchema } from "express-validator"; export const signup = checkSchema({ name: { trim: true, notEmpty: true, isLength: { options: { min: 2 } }, errorMessage: "Name precisa ter pelomenos 2 caracteres" }, email: { isEmail: true, normalizeEmail: true, errorMessage: "E-mail inválido" }, password: { notEmpty: true, isLength: { options: { min: 2 } }, errorMessage: "Password precisa ter pelo menos 2 caracteres" } }); export const signin = checkSchema({ email: { isEmail: true, normalizeEmail: true, errorMessage: "E-mail inválido" }, password: { notEmpty: true, isLength: { options: { min: 2 } }, errorMessage: "Password precisa ter pelo menos 2 caracteres" } }); export const update = checkSchema({ token: { notEmpty: true }, name: { optional: true, trim: true, notEmpty: true, isLength: { options: { min: 2 } }, errorMessage: "Name precisa ter pelomenos 2 caracteres" }, email: { optional: true, isEmail: true, normalizeEmail: true, errorMessage: "E-mail inválido" }, password: { optional: true, notEmpty: true, isLength: { options: { min: 2 } }, errorMessage: "Password precisa ter pelo menos 2 caracteres" } });<file_sep>import express, { Request, Response } from "express"; import dontenv from "dotenv"; import path from "path"; import cors from "cors"; import routes from "./routes/"; dontenv.config(); const server = express(); server.use(cors({ origin: "*", methods: ["GET", "POST", "PUT", "DELETE"] })); server.use(express.static(path.join(__dirname, "../public"))); server.use(express.json()); server.use(express.urlencoded({ extended: true })); server.use(routes); server.use((request: Request, response: Response) => { response.status(404); response.json({ error: "Endpoint não encontrado." }); }); server.listen(process.env.PORT);<file_sep># Api simples para sistema de login utilizando autenticação JWT 0 - Comando para baixar as dependências do projeto: npm install 1 - Configurar os seguintes arquivos com seus dados do banco de dados MYSQL: ".env", "config/config.json" 2 - Para executar as migrations no banco de dados basta rodar o comando: npx sequelize-cli db:migrate 3 - Comando para dar start em desenvolvimento: npm run start-dev 4 - Comando para dar start em produção: npm run start 5 - Comando para monitorar e converter arquivos typescript para javascript: tsc -w 6 - Segue abaixo os endpoints desta API --- POST: /signup (Parâmetros: name, email, password) --- POST: /signin (Parâmetros: email, password) --- GET: /users (PRECISA ESTAR AUTENTICADO) (Parâmetro obrigátorio: token) --- GET: /user/id (PRECISA ESTAR AUTENTICADO) (Parâmetro obrigátorio: token) --- PUT: /update/id (PRECISA ESTAR AUTENTICADO) (Parâmetro obrigátorio: token) (Parâmetros opcionais: name, email, password) --- DELETE: /deletar/id (PRECISA ESTAR AUTENTICADO) (Parâmetro obrigátorio: token) OBS: Caso queira colocar essa API em produção alterar a função sign do jwt nas funções "signin" e "signup" do UserController, passando apenas o id como parâmetro sendo assim tornando o token seguro é cumprindo a LGPD, como desenvolvi essa API apenas para compartilhar conhecimento passei como parâmetro na função sign do jwt, todos os dados informados pelo usuário, dessa forma quem descriptografar o token vai ter acesso a todas as informações sensíveis de determinado usuário. # End!
94f47ca7a115137752b3cb67b9ceda2fd70383b7
[ "Markdown", "TypeScript" ]
6
TypeScript
euygor/api-nodejs
5fb2bdff44a23eab526a443d0c53fa1ba35b1441
48457b8e89f411db41629eadf81803e99b0dd4da
refs/heads/master
<repo_name>zdkhqh/Restaurant<file_sep>/src/controller/InfoController.java package controller; import com.jfinal.core.Controller; import com.jfinal.kit.Ret; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Record; import com.jfinal.upload.UploadFile; import model.Info; import util.FormUtil; import util.SqlBuilder; import java.util.Date; public class InfoController extends Controller { public void get_info_page() { FormUtil formUtil = new FormUtil(getParaMap()); setAttr("infoPage", Db.paginate(formUtil.getPageNumber(), formUtil.getPageSize(), "select *", "from info where type = 2 order by id DESC")); render("/get_info_page.html"); } public void get_info() { Record record = Db.findFirst("select * from info where type = 1;"); if (record == null) record = new Record(); setAttr("info", record); render("/get_info.html"); } public void get_info_by_id() { renderJson(Db.findFirst("select * from info where id =?", getPara("id"))); } public void add_info() { UploadFile uploadFile = getFile(); Info info = getModel(Info.class, "info", true); if (info != null) { if (uploadFile != null) info.setPic(uploadFile.getFileName()); info.setTime(new Date()); if (info.getId() == null ? info.save() : info.update()) { if (info.getType() == 1) redirect("get_info.html"); else redirect("/info/get_info_page.html"); return; } } renderJson(Ret.fail()); } public void delete_info() { SqlBuilder.dao(Info.dao).deleteById(getParaToInt("id")); redirect("/info/get_info_page.html"); } public void update_info() { renderJson(SqlBuilder.dao(Info.dao).update(getBean(Info.class, ""))); } } <file_sep>/src/controller/AdminController.java package controller; import com.jfinal.aop.Before; import com.jfinal.aop.Clear; import com.jfinal.core.Controller; import com.jfinal.ext.interceptor.POST; import com.jfinal.kit.Ret; import com.jfinal.plugin.activerecord.Page; import intercept.AdminIntercept; import model.Admin; import service.AdminService; import util.AdminThreadContext; import util.FormUtil; import util.SqlBuilder; import util.TimeUtil; public class AdminController extends Controller { /** * 登陆入口 */ @Clear(AdminIntercept.class) @Before(POST.class) public void login() { if (AdminService.loginCheck(getParaMap())) { redirect("/admin/index"); } else { setAttr("msg", "账号或密码不得为空或错误!"); render("/login.html"); } } /** * 登出 */ public void loginout() { Integer id = (Integer) getSession().getAttribute("id"); if (id != null) { if (AdminService.loginOut()) { redirect("/admin/index"); return; } } renderJson(Ret.fail("error", "退出失败!")); } /** * 设置当前登录管理员信息 */ private void setCurrentAdmin() { setAttr("admin_id", AdminThreadContext.getId());//设置管理员id //设置管理员显示名称,优先显示nickname,若没有则显示账号 setAttr("admin_name", AdminThreadContext.getNickname() == null ? AdminThreadContext.getUsername() : AdminThreadContext.getNickname()); } /** * 获得当前管理员信息和时间信息,后台首页显示用 */ public void index() { setCurrentAdmin(); setAttr("time", TimeUtil.getDateYYYYMMDDEAByTime(TimeUtil.getNow())); render("/index.html"); } /** * 管理员信息分页展示 */ public void get_admin_page() { Page<Admin> adminPage = SqlBuilder.dao(Admin.dao).page(new FormUtil(getParaMap())); renderJson(Ret.ok("data", adminPage)); } /** * 管理员账号信息修改 */ public void update_admin() { Admin admin = getBean(Admin.class, ""); if (AdminService.updateAdmin(admin)) { renderJson(Ret.ok("data", "修改信息成功!")); } else { renderJson(Ret.fail("error", "修改信息失败!")); } } /** * 删除管理员 */ public void delete_admin() { if (AdminService.deleteById(getParaToInt("id", -1))) { renderJson(Ret.ok("data", "删除管理员成功!")); } else { renderJson(Ret.ok("data", "删除管理员失败!")); } } /** * 新增管理员 */ public void add_admin() { Admin admin = getBean(Admin.class, ""); if (AdminService.addAdmin(admin) > 0) { renderJson(Ret.ok("data", "新增管理员成功!")); } else { renderJson(Ret.fail("error", "新增管理员失败!")); } } /** * 获得单个管理员信息 */ public void get_admin() { renderJson(Ret.ok("data", AdminService.getById(getParaToInt("id")))); } } <file_sep>/src/util/FlywayApp.java package util; import com.jfinal.plugin.IPlugin; import config.WebConfig; import org.flywaydb.core.Flyway; public class FlywayApp implements IPlugin { private static Flyway getFlyway() { Flyway flyway = new Flyway(); flyway.setDataSource(WebConfig.db_url, WebConfig.db_user, WebConfig.db_password); return flyway; } public static void migrate() { getFlyway().migrate(); } public static void repair() { getFlyway().repair(); } @Override public boolean start() { migrate(); return true; } @Override public boolean stop() { return false; } } <file_sep>/README.md # Restaurant Restaurant REPOSITORY 前台显示: 1.显示成长历程,创始人介绍,团队介绍,企业快讯,最新资讯 2.菜单 3.预定 后台管理: 1.管理员登陆 2.管理员修账号信息 3.管理员列表分页查看 4.管理员账号删除 5.对前台的信息增删改查等等。。。。。。 <file_sep>/webconfig.properties devMode = true db_ip=127.0.0.1:3306 db_name=restaurant db_user=root db_password=<PASSWORD> web_listen_port=80 <file_sep>/src/controller/IndexController.java package controller; import com.jfinal.core.Controller; import com.jfinal.kit.StrKit; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Record; import java.util.List; public class IndexController extends Controller { public void index() { //前台首页 render("/page/index.html"); } public void contact() { //联系我们 render("/page/contact.html"); } public void about() { //餐厅介绍 Record record = Db.findFirst("select * from info where type = 1;"); if (record == null) record = new Record(); setAttr("info", record); render("/page/about.html"); } public void food() { List list = Db.find("select * from menu order by id DESC"); setAttr("menuList", list); render("/page/food.html"); } public void news() { Integer id = getParaToInt("id"); Record record; if (id == null) record = Db.findFirst("select * from info where type=2 order by id DESC"); else record = Db.findFirst("select * from info where type=2 and id =?", id); if (record == null) record = new Record(); setAttr("info", record); List list = Db.find("select * from info where type=2 order by id DESC"); setAttr("infoList", list); Record record2 = Db.findFirst("select * from info where type=2 order by id DESC"); if (record2 == null) record2 = new Record(); if (StrKit.equals(record.getStr("Id"), record2.getStr("Id"))) { setAttr("isLast", true); } else { setAttr("isLast", false); } render("/page/news.html"); } public void Book(){ render("/page/Book.html"); } } <file_sep>/pom.xml <?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>restaurant</groupId> <artifactId>restaurant</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>restaurant Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.jfinal</groupId> <artifactId>jetty-server</artifactId> <version>8.1.8</version> <!-- 此处的 scope 值为 compile 仅为支持 IDEA 下启动项目 打 war 包时需要改成 provided,以免将一些无用的 jar 打进去 --> <scope>compile</scope> </dependency> <dependency> <groupId>com.jfinal</groupId> <artifactId>jfinal</artifactId> <version>3.3</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.29</version> </dependency> <dependency> <groupId>com.jfinal</groupId> <artifactId>cos</artifactId> <version>2017.5</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>RELEASE</version> </dependency> <!--flyway--> <dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> <version>5.0.3</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.3.170</version> </dependency> </dependencies> <build> <finalName>restaurant</finalName> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>3.0.0</version> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>config.Run</mainClass> </manifest> </archive> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep>/src/model/BaseMenu.java package model; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.IBean; /** * Generated by JFinal, do not modify this file. */ @SuppressWarnings({"serial", "unchecked"}) public abstract class BaseMenu<M extends BaseMenu<M>> extends Model<M> implements IBean { public M setId(java.lang.Integer Id) { set("Id", Id); return (M)this; } public java.lang.Integer getId() { return getInt("Id"); } public M setTitle(java.lang.String title) { set("title", title); return (M)this; } public java.lang.String getTitle() { return getStr("title"); } public M setDescribe(java.lang.String describe) { set("describe", describe); return (M)this; } public java.lang.String getDescribe() { return getStr("describe"); } public M setPrice(java.lang.Double price) { set("price", price); return (M)this; } public java.lang.Double getPrice() { return getDouble("price"); } public M setPic(java.lang.String pic) { set("pic", pic); return (M)this; } public java.lang.String getPic() { return getStr("pic"); } } <file_sep>/src/config/UrlHandler.java package config; import com.jfinal.handler.Handler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UrlHandler extends Handler { @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) { if (target.endsWith(".shtml")) target = target.substring(0, target.length() - 6); else if (target.endsWith(".html") || target.endsWith(".shtm")) target = target.substring(0, target.length() - 5); else if (target.endsWith(".jsp") || target.endsWith(".asp") || target.endsWith(".stm ") || target.endsWith(".htm")) target = target.substring(0, target.length() - 4); request.setAttribute("cxt", request.getContextPath()); next.handle(target, request, response, isHandled); } } <file_sep>/src/intercept/AdminIntercept.java package intercept; import com.jfinal.aop.Interceptor; import com.jfinal.aop.Invocation; import util.AdminThreadContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * 拦截器,用于拦截非登陆用户 */ public class AdminIntercept implements Interceptor { public void intercept(Invocation inv) { Integer id = (Integer) inv.getController().getSession().getAttribute("id"); if (id == null) { inv.getController().render("/login.html"); } else { HttpServletRequest request = inv.getController().getRequest(); request.setAttribute("admin_id", AdminThreadContext.getId());//设置管理员id //设置管理员显示名称,优先显示nickname,若没有则显示账号 request.setAttribute("admin_name", AdminThreadContext.getNickname() == null ? AdminThreadContext.getUsername() : AdminThreadContext.getNickname()); inv.invoke(); } } }
763be8af83a1adb0272fe85ac2a5a71409cb24bb
[ "Markdown", "Java", "Maven POM", "INI" ]
10
Java
zdkhqh/Restaurant
06eb708e180656740c3cfe767ae8263cc895fe89
e8aaf40af87c89db6ee3a6b570fffec09b75e7df
refs/heads/master
<repo_name>EsthefanieHolguin/Sistema-de-reserva-de-horas<file_sep>/src/main/java/cl/accenture/curso_java/sistema_de_reserva/controladores/InicioSesionController.java package cl.accenture.curso_java.sistema_de_reserva.controladores; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; /** * @author <NAME> * */ @ManagedBean @SessionScoped public class InicioSesionController implements Serializable { /** * */ private static final long serialVersionUID = -4396136258065169961L; private String nombreUsuario; private String password; private boolean error; private String mensaje; public InicioSesionController() { this.nombreUsuario=""; this.password=""; this.mensaje=""; } public String getNombreUsuario() { return nombreUsuario; } public void setNombreUsuario(String nombreUsuario) { this.nombreUsuario = nombreUsuario; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public boolean isError() { return error; } public void setError(boolean error) { this.error = error; } public String getMensaje() { return mensaje; } public void setMensaje(String mensaje) { this.mensaje = mensaje; } public static long getSerialversionuid() { return serialVersionUID; } public String iniciarSesion() { if( this.nombreUsuario.equals( "esthefanieholguin" ) && this.password.equals( "<PASSWORD>" ) ){ this.mensaje = ""; this.error = false; return ""; }else{ this.error = true; this.mensaje = "Usuario y/o Password incorrectos"; return ""; } } }
ce3ac6e3ce45ec419516c4dc34b9a753070659d3
[ "Java" ]
1
Java
EsthefanieHolguin/Sistema-de-reserva-de-horas
1c462a7ef6f1432b732c11a5baec2a2374b976a8
bac056429309d4b0e73e629bb4b24ab1be3b7be1
refs/heads/main
<repo_name>alwaz-shahid/lucia-sophia<file_sep>/components/Gallery.js import React, { useEffect } from 'react'; import Image from 'next/image' import { m, useAnimation } from "framer-motion"; import { useInView } from "react-intersection-observer"; import { gallery } from '../animations'; function Gallery({ srcOne, srcTwo, txtOne, txtTwo }) { const controls = useAnimation() const { ref, inView } = useInView() useEffect(() => { if (inView) { controls.start('visible') } if (!inView) { controls.start('hidden') } }, [controls, inView]) return ( <m.section ref={ref} variants={gallery} animate={controls} initial='hidden' className="w-full min-h-screen center flex-wrap"> <div className="flex items-center justify-around min-w-full"> <div className="w-2/6"> <Image src={srcOne} height={500} width={350} className="object-cover shadow-lg scale-100 transform transition duration-500 ease-in-out hover:scale-105" /> </div> <div className="w-1/2"> <h4 className="txt-main text-base md:text-xl custom-roboto text-center"> {txtOne}</h4> </div> </div> <div className="flex items-center justify-around min-w-full"> <div className="w-1/2"> <h4 className="txt-main text-base md:text-xl custom-roboto txt-shd text-center"> {txtTwo}</h4> </div> <div className="w-2/6 text"> <Image src={srcTwo} height={500} width={350} className="object-cover shadow-lg scale-100 transform transition duration-500 ease-in-out hover:scale-105" /> </div> </div> </m.section> ); } export default Gallery;<file_sep>/animations/index.js export const container = { hidden: { opacity: 1, scale: 0.9 }, visible: { opacity: 1, scale: 1, transition: { duration: 0.5, delayChildren: 1.5, staggerChildren: 1 } } } export const item = { hidden: { opacity: 0.2, }, visible: { opacity: 1, transition: { duration: 0.5, delayChildren: 1, ease: "easeInOut" } } } export const boxVariants = { hidden: {x:10 ,opacity: 0.2}, visible: { x:0, opacity: 1, transition: { duration: 0.5, delayChildren: 1, ease: "easeInOut" } } } export const gallery = { hidden: {x:30 ,opacity: 0.2}, visible: { x:0, opacity: 1, transition: { duration: 0.5, delayChildren: 1.5, ease: "easeIn" } } } export const cardAnimation = { hidden: {opacity:0}, visible: { opacity: 1, transition: { duration: 0.3, delayChildren: 1, ease: "easeIn", }, } } export const tagL = { hidden: { y:40,opacity: 0}, visible: { y:0, opacity: 1, transition: { duration: 0.5, } } }<file_sep>/components/common/Dropdown.js import React from 'react'; import Link from 'next/link' const DropDown = ({ names }) => { return ( <div className="p-10"> <div className="dropdown inline-block relative rounded-xl"> <button className="bg-yellow-400 hover:bg-yellow-500 txt-main font-semibold py-2 px-4 rounded inline-flex items-center custom-montserrat"> <span className="mr-1">Category</span> <svg className="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> <path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" /> </svg> </button> <ul className="dropdown-menu absolute z-40 hidden txt-main pt-1"> {names.map(({ name }, id) => <Link href={`/products/category/${name}`}> <a className="rounded-t bg-gray-200 hover:bg-gray-400 custom-roboto font-medium py-2 px-4 block whitespace-no-wrap" >{name}</a> </Link> )} </ul> </div> </div> ); }; export default DropDown <file_sep>/next.config.js module.exports = { env: { STRAPI_GRAPHQL_URL: 'https://rocky-ocean-85600.herokuapp.com/graphql', STRAPI_URL: 'https://rocky-ocean-85600.herokuapp.com', SERVICE_ID: 'service_x1vtaeg', TEMPLATE_ID: 'template_a3ki6qb', USER_ID: 'user_fcLsvvjdcR8yEn0OQzA26' }, future: { webpack5: true, }, images: { domains: ["res.cloudinary.com", "cloudinary.com", "images.unsplash.com", "unsplash.com", "localhost"], loader: 'default', }, async headers() { return [ { // matching all API routes source: "/api/:path*", headers: [ { key: "Access-Control-Allow-Credentials", value: "true" }, { key: "Access-Control-Allow-Origin", value: "*" }, { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" }, { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }, ] } ] } }; <file_sep>/pages/testimonials.js import Head from "next/head"; import { client } from "../lib/apollo"; import { GET_ALL_REVIEWS } from "../lib/queries"; import { useQuery } from "@apollo/client"; import LogoLoader from "../components/common/LogoLoader"; import Testomonial from "../components/common/Testomonial"; function testimonial({reviews}) { const { data, loading, error } = useQuery(GET_ALL_REVIEWS); if (loading) return <LogoLoader /> if (error) return <h1>Error Occured</h1> return ( <section className="min-h-screen center flex-col pt-20"> <h1 className="custom-montserrat w-full text-center font-semibold underline txt-main text-2xl md:text-4xl py-10">Here's what they say</h1> <div className="w-full h-full flex flex-wrap items-center justify-around"> {reviews.map(({ name, date, feature, testimonial, id }) => <Testomonial key={id} name={name} date={date} feature={feature} review={testimonial} /> )} </div> </section> ) } export default testimonial export async function getStaticProps() { const { data } = await client.query({ query: GET_ALL_REVIEWS }); return { props: { reviews: data.reviews }, revalidate: 10 }; } <file_sep>/components/common/HotProductCard.jsx import Image from 'next/image' import Link from 'next/link' import Button from './Button' import { m, useAnimation } from "framer-motion"; import { useInView } from "react-intersection-observer"; import { useEffect } from "react"; import { cardAnimation } from '../../animations'; import { AiFillTags } from 'react-icons/ai' import { BiShoppingBag } from 'react-icons/bi' function HotProductCard({ imgUrl, desc, title, price, link, hot, newProd, inStock, slug }) { const controls = useAnimation() const { ref, inView } = useInView() useEffect(() => { if (inView) { controls.start('visible') } if (!inView) { controls.start('hidden') } }, [controls, inView]) // let Url = process.env.STRAPI_GRAPHQL_URL +imgUrl let show = hot ? '' : 'hidden' let stockCol = inStock ? 'text-green-600' : "text-red-600" let stockTxt = inStock ? 'In stock' : "Out of stock" return ( <m.div ref={ref} variants={cardAnimation} animate={controls} initial='hidden' whileTap={{ scale: 1.1 }} className={`rounded-xl center flex-col md:flex-row items-baseline bg-gray-100 bg-opacity-40 hover:bg-opacity-30 shadow-xl hover:shadow-2xl overflow-hidden my-10 w-11/12 xs:w-7/12 md:w-3/4 md:grid grid-flow-row grid-cols-5 md:place-items-start md:place-content-center h-full translate-y-0 transform transition duration-500 ease-in-out hover:translate-y-2 ${show}`}> <div className="overflow-hidden h-full md:col-start-1 md:col-span-2 md:bg-center md:bg-cover md:flex "> <Image src={imgUrl || NEXT_PUBLIC_DEFAULT_IMAGE} alt={title} width={350} height={300} className="rounded-2xl shadow-xl w-max object-fill absolute lg:min-h-full scale-100 transform transition duration-500 ease-in-out hover:scale-110 " /> </div> <div className="md:col-start-3 md:col-span-3 flex flex-col items-start justify-center md:justify-between py-1 px-4 md:pl-2 divide-y divide-solid divide-red-600 min-w-full"> <div className="w-full flex md:p-0 justify-between items-center"> <div className="flex flex-col items-start md:m-0 my-1 cursor-pointer"> <h3 className="md:m-0 my-1 txt-main custom-montserrat font-semibold text-base md:text-xl lg:text-2xl md:py-2 align-self-baseline ">{title}</h3> <p className={`md:m-0 my-1 custom-montserrat md:text-xs text-xs md:font-bold ${stockCol}`}>{stockTxt}</p> <p className="md:m-0 my-1 lg:text-base md:text-xs py-2 font-semibold transpara txt-gradient bg-gradient-to-r from-gray-700 to-gray-900 center"><AiFillTags/> ${price}</p> </div> {newProd && <span className="mx-2 px-2 py-1 rounded-xl text-gray-700 shadow-md custom-montserrat font-bold text-xs animate-bounce bg-gradient-to-br from-yellow-300 to-yellow-600 cursor-pointer"> New </span>} </div> <div className="md:m-0 my-1 align-self-center cursor-pointer overflow-ellipsis"> <p className="lg:text-sm text-xs text-gray-900 custom-montserrat overflow-ellipsis align-top font-medium min-w-full py-2">{desc}</p> <div className=" py-1 flex flex-wrap items-center md:h-20 lg:h-32 justify-start cursor-pointer"> <Button><a rel="noopener noreferrer" target="_blank" className="lg:text-base text-xs w-full lg:w-max center" href={link}><BiShoppingBag/> Buy Now </a></Button> <Button><Link passHref={true} href={`/products/${slug}`}><a rel="noopener noreferrer" className="lg:text-base text-xs w-full lg:w-max ">View Product</a></Link></Button> </div> </div> </div> </m.div> ) } export default HotProductCard <file_sep>/components/common/ActiveLink.jsx import { useRouter } from "next/router"; import Link from "next/link"; const ActiveLink = ({ href,children }) => { const router = useRouter(); const isCurrentPath = router.pathname === href || router.asPath === href; const active = isCurrentPath?'border-yellow-500 border-b font-semibold ':''; (function prefetchPages() { if (typeof window !== "undefined") { router.prefetch(router.pathname); } })(); const handleClick = (event) => { router.push(href); }; return ( <Link href={href} onClick={handleClick}> <a className={`active-link px-2 txt-main custom-roboto font-medium text-base hover:opacity-80 ${active}`}>{children}</a> </Link> ); }; export default ActiveLink; <file_sep>/components/VideoPlayBack.js import React,{useRef,useEffect} from 'react'; export default function VideoPlayBack({poster, src}) { const videoRef = useRef(); useEffect(() => { setTimeout(() => { videoRef.current.play() }, 5000) }, []); return ( <> <video className="w-full min-h-screen object-cover opacity-70 absolute z-0" poster={poster} ref={videoRef} controls loop autoPlay="autoPlay" controls={false} muted> <source src={src} type="video/mp4" /> </video> </> ) } // export default VideoPlayBack;<file_sep>/components/Layout.jsx import React from 'react' import Navbar from './Navbar' import Head from 'next/head' import Footer from './Footer' import { domMax, LazyMotion } from 'framer-motion' import { m, useAnimation } from "framer-motion"; import { useInView } from "react-intersection-observer"; import { useEffect } from "react"; function Layout({ children }) { const controls = useAnimation() const { ref, inView } = useInView() useEffect(() => { if (inView) { controls.start('visible') } if (!inView) { controls.start('hidden') } }, [controls, inView]) return ( <LazyMotion features={domMax}> <Head> <meta name="viewport" content="initial-scale=1.0, width=device-width" key="viewport" /> <link rel="icon" href="/favicon.webp" /> <meta charSet="utf-8" /> </Head> <Navbar /> <m.section ref={ref} > {children} </m.section> <Footer /> </LazyMotion> ) } export default Layout <file_sep>/components/Navbar.jsx import Link from 'next/link'; import { useState, useCallback, useEffect } from 'react'; import { BiMenuAltRight } from 'react-icons/bi' import ActiveLink from "./common/ActiveLink"; const useMediaQuery = (width) => { const [targetReached, setTargetReached] = useState(false); const updateTarget = useCallback((e) => { if (e.matches) { setTargetReached(true); } else { setTargetReached(false); } }, []); useEffect(() => { const media = window.matchMedia(`(max-width: ${width}px)`) media.addEventListener('change', e => updateTarget(e)) // Check on mount (callback is not called until a change occurs) if (media.matches) { setTargetReached(true) } return () => media.removeEventListener('change', e => updateTarget(e)) }, []) return targetReached; }; const Navbar = () => { let listener = null const [scrollState, setScrollState] = useState(false) useEffect(() => { listener = document.addEventListener("scroll", e => { var scrolled = document.scrollingElement.scrollTop if (scrolled >= 80) { setScrollState(true) } if (scrolled < 80) { setScrollState(false) } }) return () => { document.removeEventListener("scroll", listener) } }, [scrollState]) const [showMenu, setShowMenu] = useState(false) function toggleMenu() { setShowMenu(!showMenu) } const menu = <ul onClick={toggleMenu} className="w-full min-h-screen center flex-col absolute z-30 mainbg bg-opacity-40 shadow-xl right-0 top-0 cursor-pointer py-4"> <div className="custom-montserrat font-extrabold text-3xl text-yellow-600 cursor-pointer mb-4 border-b-2 border-yellow-500 w-full text-center py-2"> LuciaSophia. </div> <li className="py-6 px-2 sm:text-lg text-base" onClick={toggleMenu}> <ActiveLink href={"/"}>Home</ActiveLink> </li> <li className="py-6 px-2 sm:text-lg text-base" onClick={toggleMenu}> <ActiveLink href={"/products"}>Products</ActiveLink> </li> <li className="py-6 px-2 sm:text-lg text-base" onClick={toggleMenu}> <ActiveLink href={"/testimonials"}>What They Say ?</ActiveLink> </li> <li className="py-6 px-2 sm:text-lg text-base" onClick={toggleMenu}> <ActiveLink href={"/#about"}>About us</ActiveLink> </li> <li className="py-6 px-2 sm:text-lg text-base" onClick={toggleMenu}> <ActiveLink href={"/#footer"}>Contact us</ActiveLink> </li> </ul> const isBreakpoint = useMediaQuery(768) let bg = scrollState ? 'mainbg shadow-xl fixed' : ' absolute ' return ( <> { isBreakpoint ? ( <nav className={`${bg} flex w-full justify-between items-center py-4 h-16 z-20 px-4`}> <Link href="/"> <div className="custom-montserrat font-extrabold text-yellow-600 text-2xl cursor-pointer"> LuciaSophia <span className=" text-yellow-600 animate-pulse">.</span> </div> </Link> <div><BiMenuAltRight size={30} onClick={toggleMenu} className="text-gray-700 rounded-full" /> </div> {showMenu && menu} </nav> ) : ( <nav className={`${bg} sm:flex justify-between items-center py-4 px-4 lg:px-8 h-14 w-full overflow-hidden fixed z-20`} > <Link href="/"> <div className="custom-montserrat font-extrabold text-3xl text-yellow-600 cursor-pointer" > LuciaSophia <span className=" text-yellow-600 animate-pulse">.</span> </div> </Link> <div className="flex items-center justify-start lg:w-1/2 md:w-2/3"> <ul className="flex w-full items-center justify-around cursor-pointer"> <ActiveLink href={"/"}>Home</ActiveLink> <ActiveLink href={"/products"}>Products</ActiveLink> <ActiveLink href={"/testimonials"}>What They Say ?</ActiveLink> <ActiveLink href={"/#about"}>About us</ActiveLink> <Link href={"/#footer"}><span className="py-1 px-2 border-yellow-600 border hover:bg-yellow-600 hover:text-gray-200 transition-all duration-500 ease-in-out rounded-xl text-yellow-500 custom-roboto font-medium text-base hover:opacity-80">Contact us</span></Link> </ul> </div> </nav> )} </> ) } export default Navbar; <file_sep>/components/About.jsx import Image from 'next/image' import React from 'react' function About({title, desc,logo}) { // const logoUrl =process.env.STRAPI_GRAPHQL_URL + logo return ( <section className="mainbg h-screen center w-full py-20 my-24"> <div className="w-9/12 center flex-col p-2 "> <div className="center w-full divide-x-2 divide-yellow-500"> <h1 className="txt-main md:text-6xl text-3xl custom-montserrat px-4">{title}</h1> <div className="w-max px-4"> <Image src={logo} height={150} width={150} className="rounded-xl shadow-xl scale-x-95 scale-y-95 transform transition duration-500 ease-in-out hover:scale-100" /> </div> </div> <div className="center w-11/12 md:w-4/5 flex-col pt-8"> <p className="txt-main text-base md:text-xl custom-montserrat font-medium md:px-1 py-2">{desc}</p> </div> </div> </section> ) } export default About <file_sep>/components/common/Testomonial.jsx import React from 'react' import { CgProfile } from 'react-icons/cg' import { m, useAnimation } from "framer-motion"; import { useInView } from "react-intersection-observer"; import { useEffect } from "react"; import { cardAnimation } from "../../animations"; function Testomonial({ date, name, review, feature }) { const controls = useAnimation() const { ref, inView } = useInView() useEffect(() => { if (inView) { controls.start('visible') } if (!inView) { controls.start('hidden') } }, [controls, inView]) return ( <m.div ref={ref} variants={cardAnimation} animate={controls} initial='hidden' className="bg-gray-100 bg-opacity-40 hover:bg-opacity-30 shadow-xl hover:shadow-2xl overflow-hidden my-10 mx-6 translate-y-0 transform transition duration-500 ease-in-out hover:translate-y-2 cursor-pointer md:w-2/6 w-5/6 flex flex-col items-start justify-between px-6 py-4 rounded-xl h-64 md:h-60"> <div className="w-full"> <div className="w-full flex items-center justify-start m-1"> <span><CgProfile size={25} /></span> <h2 className="px-2 txt-main custom-montserrat font-semibold text-base md:text-lg"> {name}</h2> </div> <p className="text-xs float-right m-1 text-gray-700 "> {date}</p> </div> <div className="justify-self-start h-full overflow-y-auto w-full"> <h3 className="custom-montserrat font-semibold text-sm my-2 mx-1 py-1 text-gray-700 border-b border-yellow-500 "> {feature}</h3> <p className="custom-roboto text-sm my-2 mx-1 py-1 text-gray-700 "> {review}</p> </div> </m.div> ) } export default Testomonial <file_sep>/pages/products/index.jsx import { client } from "../../lib/apollo"; import { GET_ALL_PRODUCTS } from "../../lib/queries"; import Head from "next/head"; import DisplayProduct from "../../components/common/DisplayProduct"; import { m } from "framer-motion"; import { container, item } from "../../animations"; import { useQuery } from '@apollo/client' import LogoLoader from "../../components/common/LogoLoader"; import DropDown from "../../components/common/Dropdown"; export default function allProducts({ products,categories }) { const { data, loading, error } = useQuery(GET_ALL_PRODUCTS) if (loading) return <LogoLoader /> if (error || !data) return <>error occured</> return ( <> <Head> <title>Products - <NAME></title> <meta property="og:title" content="Products by <NAME>" key="ogtitle" /> + <meta property="og:site_name" content="Products by <NAME>" key="ogsitename" /> + </Head> <main className="md:pt-14 pt-10 w-full min-h-screen center flex-wrap"> <div className="md:m-5 m-2 flex w-full items-center justify-between" id="category"> <h1 className="md:text-5xl underline text-2xl p-5 w-full font-medium custom-montserrat txt-main">Products</h1> <DropDown names={categories}/> </div> <m.section variants={container} initial="hidden" animate="visible" className="min-h-screen w-full center flex-col " > <div className="flex flex-wrap items-start justify-between md:justify-start" variants={item}> {products.map( ({ title, id, description, price, inStock, heroImg, slug, meta_description, new:isNew, productLink, }) => ( < DisplayProduct key={id} path={heroImg.url} alt={meta_description} title={title} description={description} price={price.toFixed(2)} link={productLink} new={isNew} inStock={inStock} slug={slug} /> ) )} </div> </m.section> </main> </> ); } export async function getStaticProps() { const { data } = await client.query({ query: GET_ALL_PRODUCTS, }); return { props: { products: data?.products, categories:data?.categories }, revalidate:10 }; } <file_sep>/animations/viewAnimate.js import { m, useAnimation } from "framer-motion"; import { useInView } from "react-intersection-observer"; import { useEffect } from "react"; function viewAnimate() { const controls = useAnimation() const { ref, inView } = useInView() useEffect(() => { if (inView) { controls.start('visible') } if (!inView) { controls.start('hidden') } }, [controls, inView]) } export default viewAnimate <file_sep>/lib/queries.js import { gql } from "@apollo/client"; const GET_PRODUCT_SLUGS = gql` query ProductSlugs{ products{ slug } } ` const GET_VIDEO = gql` query Video{ playbackvideo{ video{ url } thumbnail{ url } } }` const GET_ALL_REVIEWS = gql` query AllReviews{ reviews{ name testimonial feature date } }` const GET_ONE_CATEGORY = gql` query Category{ categories{ name id } }` const GET_PRODUCT_DETAILS = gql` query ProductDetail($slug: String!){ products(where: {slug: $slug}){ slug title hot new price description inStock productDescription image{ url } meta_title meta_description productLink perks reviews{ id name date testimonial feature } } }` const GET_ABOUT_US = gql` query About { aboutUs { title about logo{ url } } } `; const GET_ALL_PRODUCTS = gql` query { products{ id title description price inStock slug productLink new hot heroImg{ url } } categories{ name id } } `; const GET_CATEGORY = gql` query Categories($name: String!){ categories(where: {name: $name}){ name products{ title description price inStock heroImg{ url } productLink slug new meta_description } } }` const GET_LANDING_PAGE = gql` query Landing { landingPage{ title tagline } playbackvideo{ video{ url } thumbnail{ url } } products{ id title description price inStock slug productLink new hot heroImg{ url } } gallery{ imageOne{ url } captionOne imageTwo{ url } captionTwo } } `; export { GET_LANDING_PAGE, GET_ALL_PRODUCTS, GET_ABOUT_US, GET_PRODUCT_SLUGS, GET_CATEGORY, GET_PRODUCT_DETAILS, GET_ALL_REVIEWS, GET_ONE_CATEGORY }; <file_sep>/lib/apollo.js import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client"; const client = new ApolloClient({ cache: new InMemoryCache(), link: new HttpLink({ uri: process.env.STRAPI_GRAPHQL_URL, // uri:"http://localhost:1337/graphql", }) }); export { client }; <file_sep>/components/Footer.jsx import Link from 'next/link' import React from 'react' import { FaInstagram, FaFacebook, FaPinterest } from 'react-icons/fa' import CfTwo from './CfTwo' function Footer() { return ( <footer className='min-h-screen mainbg mt-64 center flex-wrap h-full w-full' id="footer"> <section className="center h-full w-full my-20"> <div> <CfTwo/> </div> </section> <div className="flex md:justify-between justify-center flex-wrap items-start h-full w-5/6"> {/* <div> <img src="./static/brandLogo.jepg" height={200} /> </div> */} <div className=" flex flex-col items-center justify-start h-full md:w-1/3 w-3/4 my-4"> <div className="center flex-col"> <h2 className="custom-montserrat txt-main font-semibold text-lg md:text-xl pb-2 md:pb-4">Contact us</h2> <p className="custom-roboto font-semibold cursor-pointer scale-100 transform transition duration-500 ease-in-out hover:scale-105 text-gray-400 hover:text-yellow-400 text-sm px-8 py-4 rounded-2xl border border-yellow-600"> <EMAIL></p> </div> </div> <div className="flex flex-col items-center justify-start h-full md:w-1/3 w-1/2 px-4 py-6"> <h1 className="custom-montserrat txt-main font-semibold text-lg md:text-xl">Follow us at</h1> <div className="container flex justify-around items-center"> <ul className="px-6 center"> <li className="px-4 py-6 rounded-full "> <a href="https://m.facebook.com/LuciaSophiaInternational/" target="_blank"> <FaFacebook size={30} className="text-blue-500 rounded-full " /> </a> </li> <li className="px-4 py-6 rounded-full "> <a href="https://www.instagram.com/luciasophia_natural_lifestyle/" target="_blank"> <FaInstagram size={30} className="text-purple-500 rounded-full " /> </a> </li> <li className="px-4 py-6 rounded-full "> <a href="https://www.pinterest.com/LuciaSophiaInternational/" target="_blank"> <FaPinterest size={30} className="text-red-600 rounded-full " /> </a> </li> </ul> </div> </div> <div className="flex-col center h-full md:w-1/3 w-1/2 px-4 py-6"> <h4 className="text-lg md:text-xl txt-main font-semibold custom-montserrat pb-2">Quick links</h4> <ul> <li><Link href="/products/#category"><a className="text-sm custom-roboto text-gray-400 hover:text-gray-600">Categories</a></Link></li> <li><Link href="/#hot"><a className="text-sm custom-roboto text-gray-400 hover:text-gray-600">Top products</a></Link></li> <li><Link href="/testimonials"><a className="text-sm custom-roboto text-gray-400 hover:text-gray-600">Testimonials</a></Link></li> </ul> </div> </div> <p className="custom-montserrat p-2 md:text-sm text-xs self-end justify-start min-w-full text-gray-500">© 2021 <NAME>. All Rights Reserved.</p> </footer> ) } export default Footer <file_sep>/components/common/DisplayProduct.jsx import React from "react"; import Image from "next/image"; import Button from "./Button"; import Link from "next/link"; import { m, useAnimation } from "framer-motion"; import { useInView } from "react-intersection-observer"; import { useEffect } from "react"; import { cardAnimation} from "../../animations"; import { AiFillTags } from 'react-icons/ai' import { BiShoppingBag } from 'react-icons/bi' function DisplayProduct({ path, alt, title, description, price, link, inStock, hot, slug, new: pNew, }) { const controls = useAnimation() const { ref, inView } = useInView() useEffect(() => { if (inView) { controls.start('visible') } if (!inView) { controls.start('hidden') } }, [controls, inView]) // let imgUrl = `"https://rocky-ocean-85600.herokuapp.com${path}`; let show = hot ? '' : 'hidden' let stockCol = inStock ? 'text-green-600' : "text-red-600" let stockTxt = inStock ? 'In stock' : "Out of stock" return ( <m.div ref={ref} variants={cardAnimation} animate={controls} initial='hidden' className="md:w-1/4 w-5/12 md:m-5 lg:m-10 m-2 rounded-xl center flex-col bg-gray-100 bg-opacity-40 hover:bg-opacity-30 shadow-xl hover:shadow-2xl overflow-hidden translate-y-0 transform transition duration-500 ease-in-out hover:translate-y-2" > <div className="overflow-hidden min-h-full"> {" "} <Image src={path || "/def.jpg"} alt={alt} width={500} height={330} className="rounded-xl shadow-xl min-h-full object-fill scale-100 transform transition duration-500 ease-in-out hover:scale-110" /> </div> <div className="flex flex-col items-start justify-center md:justify-between p-1 md:px-2 px-1 md:pl-2 divide-y divide-solid divide-red-600 min-w-full"> <div className="w-full flex justify-between items-center"> <div className="flex flex-col items-start md:m-0 cursor-pointer"> <h3 className="md:m-0 my-1 txt-main custom-montserrat font-semibold text-base md:text-xl lg:text-2xl md:py-2 align-self-baseline ">{title}</h3> <p className={` custom-montserrat md:text-xs text-xs md:font-bold ${stockCol}`}>{stockTxt}</p> <p className=" lg:text-base md:text-xs py-1 text-xs font-semibold transpara txt-gradient bg-gradient-to-r from-gray-700 to-gray-900 center"><AiFillTags/> ${price}</p> </div> {pNew && <span className="mx-2 px-2 py-1 rounded-xl text-gray-700 shadow-md custom-montserrat md:font-bold font-semibold text-xs animate-bounce bg-gradient-to-br from-yellow-300 to-yellow-600 cursor-pointer"> New </span>} </div> <div className="md:m-0 my-1 align-self-center cursor-pointer overflow-ellipsis"> <p className="lg:text-sm text-xs text-gray-900 custom-montserrat overflow-ellipsis align-top font-medium min-w-full py-2">{description}</p> <div className=" py-1 flex flex-wrap items-center md:h-20 justify-start cursor-pointer"> <Button><a rel="noopener noreferrer" target="_blank" className="lg:text-base text-xs w-full lg:w-max center" href={link}> <BiShoppingBag/> Buy Now </a></Button> <Button><Link passHref={true} href={`/products/${slug}`}><a rel="noopener noreferrer " className="lg:text-base text-xs w-full lg:w-max ">View Product</a></Link></Button> </div> </div> </div> </m.div> ); } export default DisplayProduct; <file_sep>/pages/_app.js import { ApolloProvider } from "@apollo/client"; import Layout from "../components/Layout"; import { client } from "../lib/apollo"; import { AnimateSharedLayout } from "framer-motion"; import "../styles/globals.css"; import "../styles/loader.css"; import "../styles/overlayEffect.css"; import "../styles/slider.css"; import "../styles/backgroundEffect.css" // The handler to smoothly scroll the element into view const handExitComplete = () => { if (typeof window !== 'undefined') { // Get the hash from the url const hashId = window.location.hash; if (hashId) { // Use the hash to find the first element with that id const element = document.querySelector(hashId); if (element) { // Smooth scroll to that elment element.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest', }); } } } }; function MyApp({ Component, pageProps }) { return ( <ApolloProvider client={client}> <section className="min-h-full min-w-full Sbg bg-fixed overflow-hidden"> <AnimateSharedLayout exitBeforeEnter onExitComplete={handExitComplete}> <Layout> <Component {...pageProps} /> </Layout> </AnimateSharedLayout> </section> </ApolloProvider> ); } export default MyApp;
1a2a5d2c9458ca95667095e5bb40afc931294144
[ "JavaScript" ]
19
JavaScript
alwaz-shahid/lucia-sophia
9402414eebbf2db98f9382b750c59375d5f3deea
9c9bd4e7f5228783d47e1628dfc7e2adebe1c8aa
refs/heads/master
<repo_name>armdev/micro-network<file_sep>/frontendnode/pom.xml <?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>com.project</groupId> <artifactId>frontend-node</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>frontendnode</name> <description>frontendnode</description> <parent> <groupId>org.joinfaces</groupId> <artifactId>jsf-spring-boot-parent</artifactId> <version>2.4.1</version> <relativePath/> </parent> <!--<parent>--> <!--<groupId>org.springframework.boot</groupId>--> <!--<artifactId>spring-boot-starter-parent</artifactId>--> <!--<version>1.4.1.RELEASE</version>--> <!--<relativePath/> &lt;!&ndash; lookup parent from repository &ndash;&gt;--> <!--</parent>--> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast-client</artifactId> <version>3.8.6</version> </dependency> <dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast-spring</artifactId> <version>3.8.6</version> </dependency> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>org.primefaces.themes</groupId> <artifactId>all-themes</artifactId> <version>1.0.10</version> </dependency> <dependency> <groupId>org.joinfaces</groupId> <artifactId>jsf-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-core</artifactId> <version>1.5.11</version> <scope/> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>com.netflix.rxjava</groupId> <artifactId>rxjava-core</artifactId> <version>0.20.7</version> </dependency> <dependency> <groupId>io.reactivex</groupId> <artifactId>rxjava</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.2</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>frontendnode</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> <version>1.2.8.RELEASE</version> </dependency> </dependencies> </plugin> </plugins> </build> <repositories> <repository> <url>http://repository.primefaces.org/</url> <id>primefaces</id> <layout>default</layout> <name>Repository for library PrimeFaces 3.2</name> </repository> <repository> <id>spring-releases</id> <url>https://repo.spring.io/libs-release</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-releases</id> <url>https://repo.spring.io/libs-release</url> </pluginRepository> </pluginRepositories> </project> <file_sep>/frontendnode/src/main/resources/i18n.properties nouser=Did not find any user mandatory=Fill mandatory fields signin=Sign In signup=Sign Up signout=Sign Out email=E-mail password=<PASSWORD> emailbusy=E-mail already is used wrongFormat=E-mail format is wrong firstname=First name lastname=Last name profile=Profile updatesuccess=Profile update was success updatefail=Profile update fail, please try later. update=Update save=Save back=Back cancel=Cancel profilePhoto=Profile Photo uploadProfilePhoto=Upload Profile Photo forgot=Forgot password? mainpage=Main page changepass=Change password actsuccess=Activization success mainpage=Main page getactlink=Get Activization link entervalid=Enter valid email sendRequest=Send request checkyourEmailForpass=Check your e-mail for password setnewpass=Set new password confirm=Confirm cancel=Cancel failact=Activization failed notactivated=You account is not active passchanged=<PASSWORD> passwordreminder=<PASSWORD> remindme=Remind me lostactivationlink=Lost activation link registersuccess=Registration was Success: Check your e-mail and confirm registration and Sign In mobileno=Mobile No: country=Country<file_sep>/airlinenode/src/main/java/io/project/services/FlightServiceImpl.java package io.project.services; import io.project.model.Flight; import io.project.repositories.FlightRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Component; @Service @Component public class FlightServiceImpl implements FlightService { @Autowired private FlightRepository flightRepository; // public FlightServiceImpl(FlightRepository flightRepository) { // this.flightRepository = flightRepository; // } @Override public List<Flight> findAll() { List<Flight> products = new ArrayList<>(); // flightRepository.findAll().forEach(products::add); //fun with Java 8 products = flightRepository.findAll(); return products; } @Override public Flight getById(Long id) { return flightRepository.findOne(id); } @Override public Flight saveOrUpdate(Flight product) { flightRepository.save(product); return product; } @Override public void delete(Long id) { flightRepository.delete(id); } } <file_sep>/corenode/Dockerfile #FROM openjdk:8-jdk-alpine FROM airhacks/java COPY target/corenode.jar /opt/corenode.jar ENTRYPOINT ["java","-Xmx512m", "-jar","/opt/corenode.jar"] EXPOSE 8585<file_sep>/airlinenode/src/main/java/io/project/application/AirlinesApplication.java package io.project.application; import io.project.model.Flight; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.cloud.sleuth.sampler.AlwaysSampler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableEurekaClient @EnableAsync @EnableFeignClients @EnableJpaRepositories("io.project.repositories") @EnableTransactionManagement(proxyTargetClass = true) @EnableScheduling @EnableHystrix @EnableCircuitBreaker @EnableDiscoveryClient @EnableCaching @Import(SpringConfig.class) @ComponentScan(basePackages = {"io"}, excludeFilters = { @ComponentScan.Filter(Configuration.class)}) @EntityScan(basePackageClasses=Flight.class) public class AirlinesApplication { public static void main(String[] args) { SpringApplication.run(AirlinesApplication.class, args); } @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @Bean public AlwaysSampler defaultSampler() { return new AlwaysSampler(); } } <file_sep>/docker-compose.yml version: '3' services: mysqlnode: image: mysqlnode build: ./mysqlnode container_name: mysqlnode environment: - MYSQL_ROOT_PASSWORD=<PASSWORD> - MYSQL_USER=admin - MYSQL_PASSWORD=<PASSWORD> - MYSQL_DATABASE=airlines ports: - 3306:3306 mongonode: image: mongo:latest container_name: mongonode environment: - MONGO_DATA_DIR=/data/db - MONGO_LOG_DIR=/dev/null volumes: - ./data/db:/data/db ports: - 27017:27017 command: mongod --smallfiles --logpath=/dev/null eurekanode: image: eurekanode build: ./eurekanode container_name: eurekanode ports: - "8761:8761" confignode: image: confignode build: ./confignode container_name: confignode links: - eurekanode ports: - "8888:8888" turbinenode: image: turbinenode build: ./turbinenode container_name: turbinenode links: - eurekanode ports: - "8082:8082" hystrixnode: image: hystrixnode build: ./hystrixnode container_name: hystrixnode links: - eurekanode - confignode - turbinenode ports: - "8081:8081" zipkinnode: image: zipkinnode build: ./zipkinnode container_name: zipkinnode links: - eurekanode ports: - "9411:9411" fullnode: image: fullnode build: ./fullnode container_name: fullnode links: - mongonode - eurekanode - confignode ports: - "8686:8686" corenode: image: corenode build: ./corenode container_name: corenode links: - eurekanode - confignode ports: - "8585:8585" airlinenode: image: airlinenode build: ./airlinenode container_name: airlinenode links: - eurekanode - confignode - mysqlnode ports: - "9090:9090" adminnode: image: adminnode build: ./adminnode container_name: adminnode links: - eurekanode - confignode - zipkinnode - turbinenode ports: - "1111:1111" frontend-node: image: frontendnode build: ./frontendnode container_name: frontendnode ports: - "9999:9999" <file_sep>/corenode/src/main/java/io/project/core/dao/BlockDAO.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package io.project.core.dao; import io.project.core.blockmodel.Block; import java.util.Date; import org.apache.commons.codec.digest.DigestUtils; /** * * @author armdev */ public class BlockDAO { public Block generateNextBlock(String blockData) { Block previousBlock = this.getLatestBlock(); String previousBlockIndex = previousBlock.getIndex(); String nextIndex = previousBlockIndex + 1; Long nextTimestamp = new Date().getTime() / 1000; String nextHash = this.calculateHash(nextIndex, previousBlock.getHash(), nextTimestamp.toString(), blockData); return new Block(nextIndex, previousBlock.getHash(), nextTimestamp.toString(), blockData, nextHash); } public Block getLatestBlock() { Block block = new Block(null); return block; } public Block saveBlock(Block block) { //create genesis block //do some checks return block; } public String calculateHash(String index, String previousHash, String timestamp, String data) { String sha256hex = DigestUtils.sha256Hex(index + previousHash + timestamp + data); return sha256hex; } } <file_sep>/frontendnode/src/main/java/com/project/web/handlers/UserBean.java package com.project.web.handlers; import javax.inject.Named; import javax.enterprise.context.RequestScoped; import lombok.Data; /** * * @author armdev */ @Named(value = "userBean") @RequestScoped @Data public class UserBean { private String email ="<EMAIL>"; private String password; public UserBean() { //// System.out.println("Generate date " + System.currentTimeMillis()); // System.out.println("Generate date " + System.currentTimeMillis()); // System.out.println("Generate date " + System.currentTimeMillis()); // System.out.println("Generate date " + System.currentTimeMillis()); // System.out.println("Generate date " + System.currentTimeMillis()); } public String doLogin() { /// System.out.println("Email is " + email); // System.out.println("Password is " + <PASSWORD>); return "profile"; } } <file_sep>/remoteserver/src/main/java/io/project/remote/RemoteServerApplication.java package io.project.remote; import io.project.remote.facades.PingMessagesFacade; import io.project.remote.interfaces.ExternalAccess; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.remoting.rmi.RmiServiceExporter; @SpringBootApplication public class RemoteServerApplication { public static void main(String[] args) { SpringApplication.run(RemoteServerApplication.class, args); } @Bean public ExternalAccess pingService() { return new PingMessagesFacade(); } @Bean public RmiServiceExporter exporter(ExternalAccess implementation) { Class<ExternalAccess> serviceInterface = ExternalAccess.class; RmiServiceExporter exporter = new RmiServiceExporter(); exporter.setServiceInterface(serviceInterface); exporter.setService(implementation); exporter.setServiceName(serviceInterface.getSimpleName()); exporter.setRegistryPort(1099); return exporter; } } <file_sep>/fullnode/src/main/java/io/project/services/WorkLogService.java package io.project.services; import com.mongodb.WriteResult; import io.project.models.WorkLog; import io.project.repositories.WorkLogRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; /** * * @author armenar */ @Service @Scope("singleton") @Component public class WorkLogService implements WorkLogRepository<WorkLog> { @Autowired private MongoTemplate mongoTemplate; @Override public List<WorkLog> getAllObjects() { return mongoTemplate.findAll(WorkLog.class); } @Override public void saveObject(WorkLog entity) { mongoTemplate.insert(entity); } @Override public WorkLog getObject(String id) { return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)), WorkLog.class); } @Override public WriteResult updateObject(String id, String worklog) { return mongoTemplate.updateFirst( new Query(Criteria.where("id").is(id)), Update.update("worklog", worklog), WorkLog.class); } @Override public void deleteObject(String id) { mongoTemplate .remove(new Query(Criteria.where("id").is(id)), WorkLog.class); } @Override public void createCollection() { if (!mongoTemplate.collectionExists(WorkLog.class)) { mongoTemplate.createCollection(WorkLog.class); } } @Override public void dropCollection() { if (mongoTemplate.collectionExists(WorkLog.class)) { mongoTemplate.dropCollection(WorkLog.class); } } } <file_sep>/run.sh #!/usr/bin/env bash set -e echo "Build the project and docker images" #mvn clean install echo "Clean and install all maven projects" mvn clean package -U -Dmaven.test.skip=true # Export the active docker machine IP export DOCKER_IP=$(docker-machine ip $(docker-machine active)) echo "DOCKER_IP is " echo $DOCKER_IP #docker rmi $(docker images | grep "^<none>" | awk "{print $3}") # docker-machine doesn't exist in Linux, assign default ip if it's not set #DOCKER_IP=${DOCKER_IP:-0.0.0.0} # Remove existing containers docker-compose down #docker-compose rm -f echo "Start the config service first and wait for it to become available" docker-compose up -d --build #docker-compose up -d --build --scale frontend-node=2 #docker exec -i mysql-node mysql -uroot -proot airlines < /mysql-node/db/airlines.sql #docker-compose exec mysql-node /bin/bash -c 'mysql -uroot -proot < ./mysql-node/db/airlines.sql' echo "Attach to the log output of the cluster" docker-compose logs <file_sep>/corenode/src/main/java/io/project/core/dao/GreetingController.java package io.project.core.dao; import org.springframework.web.bind.annotation.RequestMapping; public interface GreetingController { // @RequestMapping("/api/logs/healthcheck") String greeting(); } <file_sep>/frontendnode/src/main/java/com/project/web/handlers/FlightClient.java package com.project.web.handlers; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IList; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.SessionScoped; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import javax.faces.view.ViewScoped; import javax.inject.Named; import lombok.Data; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @Named @SessionScoped @Data public class FlightClient implements Serializable { private static final long serialVersionUID = 1L; private final String SERVICE_PATH = "http://192.168.99.100:9090/api/"; private static final Logger log = LoggerFactory.getLogger(FlightClient.class); @Autowired private HazelcastInstance hazelcastInstance; private List<FlightModel> finalList = new ArrayList<>(); private FlightModel flightModel = new FlightModel(); @PostConstruct public void init() { log.info("Post Construct started"); // List<FlightModel> fetchList = this.getAllList(); // this.addAll(fetchList); // finalList = this.getListOfFlights(); } public List<FlightModel> getFinalDataList() { // if (!FacesContext.getCurrentInstance().getRenderResponse()) { // return null; // } log.info("Get final list"); finalList = this.getListOfFlights(); return finalList; } public List<FlightModel> getListOfFlights() { log.info("Get all flights from cache"); IList<FlightModel> dataStore = hazelcastInstance.getList("flightList"); if (dataStore == null || dataStore.isEmpty()) { log.info("Cache is emty: fill cache"); List<FlightModel> fetchList = this.getAllList(); this.addAll(fetchList); dataStore = hazelcastInstance.getList("flightList"); } return dataStore; } public void addAll(List<FlightModel> list) { log.info("Add all flights to cache"); IList<FlightModel> dataStore = hazelcastInstance.getList("flightList"); dataStore.addAll(list); } public void removeAll() { log.info("clear cache "); IList<FlightModel> dataStore = hazelcastInstance.getList("flightList"); dataStore.clear(); } public List<FlightModel> getAllList() { List<FlightModel> model = null; CloseableHttpClient CLIENT = HttpClients.createDefault(); try { System.out.println("start"); HttpGet request = new HttpGet("http://192.168.99.100:9090/api/flights"); request.addHeader("charset", "UTF-8"); HttpResponse response = CLIENT.execute(request); System.out.println("start1"); response.addHeader("content-type", "application/json;charset=UTF-8"); HttpEntity entity = response.getEntity(); ObjectMapper mapper = new ObjectMapper(); log.info("get all data from backend"); model = mapper.readValue((EntityUtils.toString(entity)), new TypeReference<List<FlightModel>>() { }); } catch (IOException | ParseException ex) { ex.printStackTrace(); } return model; } public FlightModel getById(Long id) { FlightModel model = null; CloseableHttpClient CLIENT = HttpClients.createDefault(); try { System.out.println("start"); HttpGet request = new HttpGet("http://192.168.99.100:9090/api/flight/" + id); request.addHeader("charset", "UTF-8"); HttpResponse response = CLIENT.execute(request); System.out.println("start1"); response.addHeader("content-type", "application/json;charset=UTF-8"); HttpEntity entity = response.getEntity(); //System.out.println("start2 " +EntityUtils.toString(entity)); ObjectMapper mapper = new ObjectMapper(); model = mapper.readValue((EntityUtils.toString(entity)), new TypeReference<FlightModel>() { }); // model = mapper.readValue((EntityUtils.toString(entity)), FlightModel.class); System.out.println("start4"); System.out.println(model.toString()); } catch (IOException | ParseException ex) { ex.printStackTrace(); } return model; } } <file_sep>/frontendnode/Dockerfile FROM airhacks/java COPY target/frontendnode.jar /opt/frontendnode.jar ENTRYPOINT ["java","-Xmx1024m", "-jar","/opt/frontendnode.jar"] EXPOSE 9999 #FROM airhacks/java #VOLUME /tmp #ADD target/frontend-node.jar /frontend-node.jar #RUN bash -c 'touch /frontend-node.jar' #ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/frontend-node.jar"] #EXPOSE 9999<file_sep>/frontendnode/src/main/java/com/project/start/LocalListConfig.java package com.project.start; import com.hazelcast.config.ListConfig; import static com.hazelcast.config.MapConfig.DEFAULT_TTL_SECONDS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author armenar */ public class LocalListConfig extends ListConfig { private static final Logger log = LoggerFactory.getLogger(LocalListConfig.class); private int timeToLiveSeconds = DEFAULT_TTL_SECONDS; public LocalListConfig() { } public LocalListConfig(LocalListConfig config) { this.timeToLiveSeconds = config.getTimeToLiveSeconds(); } public int getTimeToLiveSeconds() { log.info("time to live in seconds is " + timeToLiveSeconds); return timeToLiveSeconds; } public LocalListConfig setTimeToLiveSeconds(int timeToLiveSeconds) { this.timeToLiveSeconds = timeToLiveSeconds; return this; } } <file_sep>/airlinenode/src/main/java/io/project/resources/FlightController.java package io.project.resources; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.shared.Applications; import com.netflix.eureka.EurekaServerContextHolder; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import io.project.model.Flight; import io.project.repositories.FlightRepository; import io.project.services.FlightService; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class FlightController { private static final Logger log = LoggerFactory.getLogger(FlightController.class); @Autowired @Lazy private EurekaClient eurekaClient; @Autowired private FlightService flightService; @Autowired private FlightRepository flightRepository; @GetMapping(path = "/flight/{id}", produces = "application/json;charset=UTF-8") public ResponseEntity<Flight> getFlight(@PathVariable Long id) { log.debug("REST request to get Blog : {}", id); Flight flight = flightService.getById(id); printAvailableServices(); return ResponseUtil.wrapOrNotFound(Optional.ofNullable(flight)); } @GetMapping(path = "/flights", produces = "application/json;charset=UTF-8") public List<Flight> findAll() { log.debug("REST request to get all Blogs"); PageRequest pageable = new PageRequest(0, 10); List<Flight> flightList = new ArrayList<>(); Page<Flight> page = flightRepository.findAll(new PageRequest(1, 100)); flightList.addAll(page.getContent()); printAvailableServices(); return flightList; } //https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc public void printAvailableServices() { try { //PeerAwareInstanceRegistry registry = EurekaServerContextHolder.getInstance().getServerContext().getRegistry(); Applications applications = eurekaClient.getApplications(); applications.getRegisteredApplications().forEach((registeredApplication) -> { registeredApplication.getInstances().forEach((instance) -> { log.info("*******************start************************"); log.info("App Name " + instance.getAppName()); log.info("Instance Id " + instance.getInstanceId()); log.info("HealthCheckUrl " + instance.getHealthCheckUrl()); log.info("getHomePageUrl " + instance.getHomePageUrl()); log.info("getSecureVipAddress " + instance.getSecureVipAddress()); log.info("getASGName " + instance.getASGName()); log.info("getStatusPageUrl " + instance.getStatusPageUrl()); log.info("getActionType " + instance.getActionType().toString()); log.info("getLastDirtyTimestamp " + instance.getLastDirtyTimestamp()); log.info("getVIPAddress " + instance.getVIPAddress()); log.info("getPort " + instance.getPort()); log.info("getLeaseInfo " + instance.getLeaseInfo().toString()); log.info("*******************stop************************"); }); }); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/fullnode/Dockerfile #FROM openjdk:8-jdk-alpine FROM airhacks/java COPY target/fullnode.jar /opt/fullnode.jar ENTRYPOINT ["java","-Xmx512m", "-jar","/opt/fullnode.jar"] EXPOSE 8686<file_sep>/airlinenode/Dockerfile #FROM openjdk:8-jdk-alpine FROM airhacks/java COPY target/airlinenode.jar /opt/airlinenode.jar ENTRYPOINT ["java","-Xmx512m", "-jar","/opt/airlinenode.jar"] EXPOSE 9090<file_sep>/README.md # Spring cloud Micro Network ## Acknowledgement Tested on Windows 10 using DockerToolbox ## RUN ```shell ./run.sh ``` Stop all containers: ```shell docker stop $(docker ps -a -q) ``` Remove all containers : ```shell docker rm $(docker ps -a -q) ``` Remove all images ```shell docker rmi $(docker images -q) ``` Remove all images which has name none ```shell docker rmi $(docker images | grep "^<none>" | awk "{print $3}") ``` Monitoring containers ```shell docker run \ --volume=/:/rootfs:ro \ --volume=/var/run:/var/run:rw \ --volume=/sys:/sys:ro \ --volume=/var/lib/docker/:/var/lib/docker:ro \ --volume=/dev/disk/:/dev/disk:ro \ --publish=9999:9999 \ --detach=true \ --name=cadvisor \ google/cadvisor:latest ``` Services ## Eureka node http://192.168.99.100:8761/ ## core-node http://192.168.99.100:8585/swagger-ui.html ## full-node http://192.168.99.100:8686/swagger-ui.html ## airline-node http://192.168.99.100:9090/swagger-ui.html ## frontend-node http://192.168.99.100:9999/frontendnode/index.jsf ## turbine-node http://192.168.99.100:8082/turbine.stream ## hystrix-node http://192.168.99.100:8081/hystrix/ ## Hystrix monitor turbine http://1192.168.127.12:8081/hystrix/monitor?stream=http%3A%2F%2F192.168.99.100%3A8082%2Fturbine.stream For see hystrix monitor please do some clicks in http://192.168.99.100:8686/swagger-ui.html dummy API methods and switch to link ## http://192.168.99.100:8081/hystrix/monitor?stream=http%3A%2F%2F192.168.99.100%3A8082%2Fturbine.stream ## Zipkin node This node will show logs from other nodes after you click core-node http://192.168.99.100:8585/swagger-ui.html API methods. http://192.168.99.100:9411/ ## Admin Node http://192.168.99.100:1111/login.html User admin Password <PASSWORD> docker-compose up -d --no-deps --build airline-node ## Restart all nodes ./restart.sh ## Benchmark docker-compose -f apache-benchmark/docker-compose.yml up ## Scale 1. docker service create --name frontend frontend-node 2. docker service scale frontend=2 3. docker ps -a 4. not tested fully https://docs.docker.com/engine/reference/commandline/service_create/#parent-command https://docs.docker.com/engine/swarm/swarm-tutorial/scale-service/ <file_sep>/apache-benchmark/docker-compose.yml version: '2' services: apache-benchmark-0: image: russmckendrick/ab command: ab -n 1000 -c 10000 -l -r http://192.168.99.100:5000/api/v2/mathload <file_sep>/corenode/src/main/java/io/project/core/application/FeignClientApplication.java package io.project.core.application; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.cloud.sleuth.sampler.AlwaysSampler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.mongodb.config.EnableMongoAuditing; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableAutoConfiguration @EnableEurekaClient @EnableAsync @EnableFeignClients @EnableMongoAuditing @EnableMongoRepositories @EnableScheduling @EnableHystrix @EnableCircuitBreaker @EnableDiscoveryClient @Import(SpringConfig.class) @ComponentScan(basePackages = {"io"}, excludeFilters = { @ComponentScan.Filter(Configuration.class)}) public class FeignClientApplication { public static void main(String[] args) { SpringApplication.run(FeignClientApplication.class, args); } @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @Bean public AlwaysSampler defaultSampler() { return new AlwaysSampler(); } }
eea0a5d85bfeecfa239d1b9bf996fd8546783be9
[ "YAML", "Markdown", "Maven POM", "INI", "Java", "Dockerfile", "Shell" ]
21
Maven POM
armdev/micro-network
ec809c84c48786644824e2a814c26b762d8adbe2
e155058bd21aa11db8f93c418a3f67d9816caaed
refs/heads/master
<repo_name>moekaddour/Serverless-Architecture-on-AWS-Nodejs-BackEnd<file_sep>/README.md # Serverless Architecture on AWS + Nodejs BackEnd This is a serverless app connected to amazon web services specifically Lambda and DynamoDB. This app is connected tho twitter API where fetches the latest tweets of <NAME> and <NAME> and saves them in the DynamoDB. ## Installation Git clone the link in a folder then run ```bash npm install ``` ## Usage There are four endpoints described as following: ``` GET Method : Get all the latest tweets by <NAME> 'https://qsiv7oaly0.execute-api.us-east-1.amazonaws.com/dev/getTweets' ``` ``` POST Method : Add a chosen tweets to the favorite table in the dataBase "dynamoDb" The body of the request should contain: { id: ...., text: ......, createdAt: ......, tweetedBy: ...... } 'https://qsiv7oaly0.execute-api.us-east-1.amazonaws.com/dev/add' ``` ``` DELETE Method : Remove a chosen tweet from the favorite table in the dataBase replace the {id} by the id of the tweet you intend to delete from the dataBase 'https://qsiv7oaly0.execute-api.us-east-1.amazonaws.com/dev/deleteFavorite/{id}' ``` ``` GET Method : Get all the favorite tweets from the favorite table in the data base 'https://qsiv7oaly0.execute-api.us-east-1.amazonaws.com/dev/getAllFavorite' ``` ## <file_sep>/add.js "use strict"; const AWS = require("aws-sdk"); const dynamoDb = new AWS.DynamoDB.DocumentClient(); module.exports.addFavorite = (event, context, callback) => { const data = JSON.parse(event.body); const params = { TableName: "favorite", Item: { tweetId: data.id, text: data.text, createdAt: data.createdAt, tweetedBy: data.tweetedBy } }; dynamoDb.put(params, (error, result) => { if (error) { console.error(error); callback(new Error("can not add it to favorites")); return; } const response = { statusCode: 200, body: JSON.stringify(result) }; callback(null, response); }); }; <file_sep>/handler.js "use strict"; const Twit = require("twit"); const config = require("./config"); const T = new Twit(config); module.exports.fetchTweets = (event, context, callback) => { T.get("statuses/user_timeline", { screen_name: "realDonaldTrump" }, function( err, data, response ) { callback(null, { statusCode: 200, body: JSON.stringify(data) }); }); };
38bf8f399caae03dbd517ffba1c135875ba52d4f
[ "Markdown", "JavaScript" ]
3
Markdown
moekaddour/Serverless-Architecture-on-AWS-Nodejs-BackEnd
c8064ea227452f663b2595cf3cf0c8c2ae7fc267
24c3168510519a1e817e9cbc3bc574dd50294057
refs/heads/main
<file_sep>#include <simplecpp> #include <iomanip> main_program { int n,s1=0,s2=0,s3=0,a,b; cin >>n; repeat(n) { cin>>a>>b; s1+=a*a; s2+=b*b; s3+=a*b; } long double cos=s3/(sqrt(s1*s2)); cout<<setprecision(2)<<cos<<endl; }
e4c578710d62a264f77a842ebee32e425f52b2f9
[ "C++" ]
1
C++
SunandineeMehra/SOC-1
999e2c80369ac4e681f37891b647ee4819250700
caa0869524224a34d088c09456af39f7aeec05c3
refs/heads/master
<repo_name>LaurenTraum/PickerExample<file_sep>/PickerExample/ViewController.swift // // ViewController.swift // PickerExample // // Created by <NAME> on 10/25/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var mySegmentedController: UISegmentedControl! let colors = ["red", "yellow", "green", "blue"] let shapes = ["circle", "square", "triangle"] @IBOutlet weak var pickerThingy: UIPickerView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. pickerThingy.delegate = self pickerThingy.dataSource = self mySegmentedController.setTitle("light", forSegmentAt: 0) mySegmentedController.setTitle("dark", forSegmentAt: 1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if component == 0{ return colors.count }else{ return shapes.count } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == 0{ return colors[row] }else{ return shapes[row] } } @IBAction func sillyButton(_ sender: UIButton) { let choice = mySegmentedController.selectedSegmentIndex sender.setTitle(mySegmentedController.titleForSegment(at:choice), for: UIControlState.normal) //sender.setTitle(colors[pickerThingy.selectedRow(inComponent:0)], for: UIControlState.normal) } }
c3ce8b13df44d492f86b9c98c4f0b9df7eca10df
[ "Swift" ]
1
Swift
LaurenTraum/PickerExample
69282cdd555f08401817eb24efc7bd29e08108bc
c5904e0ed3cc2537081eb78bb5d7ef433b53299d
refs/heads/main
<repo_name>victordaga/taskmanager<file_sep>/js/taskboard.js //My OBJ var myObj= { //Select TextArea textSelect: function(){ document.getElementById('description').select(); }, //Hide form Method hide: function() { document.getElementById("form").style.display = "none"; document.getElementById("show").style.display = "inline-block"; document.getElementById('name').value=""; document.getElementById('description').value=""; document.getElementById('myDateBegin').value=""; document.getElementById('myDateEnd').value=""; }, //Show Form Method show:function(){ document.getElementById("form").style.display = "block"; document.getElementById("show").style.display = "none"; document.getElementById("editBtn").style.display = "none"; document.getElementById("submitBtn").style.display = "inline-block"; }, showEdit:function(){ } }; //Removing task method function removeTask(x){ var myTasks = returnToDo(); for (var i = 0; i < myTasks.length; i++){ if (x == parseInt(myTasks[i].id)) { var item=i } } myTasks.splice(item, 1); localStorage.setItem('myData', JSON.stringify(myTasks)); showMyTasks(); console.log('task'+ x + 'deleted'); } //Editing task method function editTask(x){ var myTasks = returnToDo(); for (var i = 0; i < myTasks.length; i++){ if (x == parseInt(myTasks[i].id)) { var item=i } } document.getElementById("form").style.display = "block"; document.getElementById("show").style.display = "none"; document.getElementById("submitBtn").style.display = "none"; document.getElementById("editBtn").style.display = "inline-block"; document.getElementById('name').value=myTasks[item].name; document.getElementById('myDateBegin').value=myTasks[item].dateBg; document.getElementById('myDateEnd').value=myTasks[item].dateEnd; document.getElementById('description').value= myTasks[item].describe; document.getElementById('valueID').value= myTasks[item].id; } //Checks if there is data in JSON function returnToDo(){ var myTasks = []; var myTasksTemp = localStorage.getItem('myData'); if(myTasksTemp != null){ myTasks = JSON.parse(myTasksTemp); } return myTasks; } //Tasks Constructor function Task(){ var myTasks = returnToDo(); var topValue=0 for (var k = 0; k < myTasks.length; k++){ if(topValue <myTasks[k].id){ topValue = myTasks[k].id } } this.id = topValue+1; this.name = document.getElementById('name').value; this.dateBg = document.getElementById('myDateBegin').value; this.dateEnd = document.getElementById('myDateEnd').value; this.describe = document.getElementById('description').value; } //Random Number generator function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; } //InnerHTML tasks inserter function newTask(x,y,z,k,j){ document.getElementById('myTasks').innerHTML += '<div class="col l3 m4 s12 animated zoomIn taskForm postit"> <h4>'+x+'</h1>'+ '<p class="describeArea">'+y+'</p>' + '<p><b>Start:</b> ' +z +' </p>'+ '<p><b>End:</b> ' +k+ '</p>'+ '<hr class="lineInside">'+ '<div hidden id=valueID>'+j+'</div>'+ '<p><div class="delBtn red " id=red'+j+'" onclick="removeTask('+j+')"" ><i class="fas fa-trash-alt icon"></i></div>'+ '<div class="editBtn yellow id=yellow'+j+'" onclick="editTask('+j+')"" ><i class="far fa-edit"></i>Edit</div></p>'+ '</div>' } //Gets all the objects from the array. function showMyTasks(){ var myTasks = returnToDo(); document.getElementById('myTasks').innerHTML = ''; for(var i=0;i<myTasks.length;i++){ newTask( myTasks[i].name, myTasks[i].describe, myTasks[i].dateBg, myTasks[i].dateEnd, myTasks[i].id ); } } //Push Information to Array/DB function submitInfo(){ var myTasks = returnToDo(); myTasks.push(new Task); console.log(myTasks); localStorage.setItem('myData',JSON.stringify(myTasks)); showMyTasks(); myObj.hide(); } function submitEdit(){ var myTasks = returnToDo(); console.log(myTasks); for (var i = 0; i < myTasks.length; i++){ if (document.getElementById('valueID').value == myTasks[i].id) { var index=i } } myTasks[index].name = document.getElementById('name').value; myTasks[index].dateBg = document.getElementById('myDateBegin').value; myTasks[index].dateEnd = document.getElementById('myDateEnd').value; myTasks[index].describe = document.getElementById('description').value; localStorage.setItem('myData',JSON.stringify(myTasks)); showMyTasks(); myObj.hide(); } showMyTasks();<file_sep>/README.md # taskmanager Welcome to TaskMe - Your personal task manager This is a task manager made entirely in HTML CSS and JavaScript. With functions to add, remove and edit tasks. see the demo at: https://victordaga.github.io/taskmanager For this demo the files are being saved locally, so that even if the page is closed the data is saved. This way it is possible to see and test the experience of using the WebApp, even without the BackEnd. For the BackEnd a structure with the Flask Framework and a database in SQL or MongoDB was designed. Unfortunately, GItPages works statically and doesn't allow you to structure a database itself. The BackEnd project was designed as follows: -The frontEnd communicates via GET/POST requests with the flask server(Which can easily be in GCP, AWS or AZURE); -The flask Server will receive the requests and make a data validation (even for security reasons) and the data processing, and then it will make the queries to the database -The Database will initially have 2 tables: -loginTable: for Login purposes where hash and user data will be stored -dataTable: Where the id's and jsons containing the tasks and preferences of each user will be stored The Database will then return the values requested by the query to the flask server and it will direct to the corresponding route and return the request. Unfortunately, due to the deadline, I wasn't able to properly develop and deploy the backEnd on the Cloud.
396cefd6cad52d07919b3d8ccccec1f535bd4a1e
[ "JavaScript", "Markdown" ]
2
JavaScript
victordaga/taskmanager
76f6c803b66f293dbd6012c64467b65346abc761
2a8c9bf12dda513504f490da27210d4f40e91b2d
refs/heads/master
<repo_name>VCTLabs/meta-raspberrypi<file_sep>/conf/machine/include/rpi-default-providers.inc # RaspberryPi BSP default providers PREFERRED_PROVIDER_virtual/kernel ?= "linux-raspberrypi" PREFERRED_PROVIDER_u-boot ?= "u-boot-rpi" PREFERRED_PROVIDER_virtual/egl ?= "vc-graphics-hardfp" PREFERRED_PROVIDER_virtual/libgles2 ?= "vc-graphics-hardfp" PREFERRED_PROVIDER_virtual/libgl ?= "mesa-gl" PREFERRED_PROVIDER_virtual/mesa ?= "mesa-gl" PREFERRED_PROVIDER_jpeg ?= "libjpeg-turbo" PREFERRED_PROVIDER_jpeg-native ?= "libjpeg-turbo-native" PREFERRED_PROVIDER_virtual/xserver ?= "xserver-xorg" PREFERRED_PROVIDER_xserver_common ?= "x11-common" PREFERRED_PROVIDER_xserver-nodm-init ?= "lxdm" <file_sep>/conf/machine/include/tune-arm1176jzfs.inc DEFAULTTUNE ?= "armv6" require conf/machine/include/arm/arch-armv6.inc TUNEVALID[arm1176jzfs] = "Enable arm1176jzfs specific processor optimizations" TUNE_CCARGS += "${<EMAIL>.contains("TUNE_FEATURES", "arm1176jzfs", "-mtune=arm1176jzf-s -mfpu=vfp", "-march=armv6", d)}" AVAILTUNES += "arm1176jzfs" ARMPKGARCH_tune-arm1176jzfs = "arm1176jzfs" TUNE_FEATURES_tune-arm1176jzfs = "${TUNE_FEATURES_tune-armv6hf} arm1176jzfs callconvention-hard" PACKAGE_EXTRA_ARCHS_tune-arm1176jzfs = "${PACKAGE_EXTRA_ARCHS_tune-armv6hf} arm1176jzfshf-vfp" <file_sep>/recipes-multimedia/alsa/alsa-lib.inc do_compile_prepend() { sed -i -e "s|pcm.front cards.pcm.front|pcm.front cards.pcm.default|" \ ${S}/src/conf/alsa.conf } do_install_append_class-target() { install -d ${D}${sysconfdir}/modprobe.d install -m 0644 ${WORKDIR}/alsa.conf ${D}${sysconfdir}/modprobe.d/ } FILES_alsa-conf-base += "${sysconfdir}/modprobe.d/*"
25444e8c97c9640493020384ee84d67c8bef3310
[ "HTML", "PHP" ]
3
PHP
VCTLabs/meta-raspberrypi
c3e3e4fc2764fd351080354e19aec994bf46f0b9
862714b8a0777a017a1f564a164df87c0ab61545
refs/heads/main
<repo_name>leonardfreitas/mystore<file_sep>/models/sale.py class Sale: def __init__(self, customer, products): self.customer = customer self.products = products def total(self): t = 0 for product in self.products: t += product.price return t <file_sep>/features/products.md - [x] Cadastrar um produto - [x] Listar os produtos <file_sep>/services/fakes.py from faker import Faker from random import randint, choice from database import customers, products, sales from models.customer import Customer from models.product import Product from models.sale import Sale fake = Faker('pt_BR') quantity = 100 def seeder(): for _ in range(quantity): customer = Customer( fake.name(), randint(8, 99), fake.email() ) customers.append(customer) product = Product( fake.company(), randint(1, 100) ) products.append(product) for _ in range(quantity): products_data = [] quantity_products = randint(1,10) for _ in range(quantity_products): index = randint(0, 10) p = products[index] products_data.append(p) sale = Sale( choice(customers), products_data ) sales.append(sale)<file_sep>/features/sales.md - [x] cadastrar uma venda - [x] listar uma venda - [ ] visualizar o caixa<file_sep>/services/sales.py from database import sales, customers, products from models.sale import Sale def create_sale(customer_index, product_indexs): customer = customers[customer_index] products_data = [products[i] for i in product_indexs] sale = Sale(customer, products_data) sales.append(sale) def list_sales(): for sale in sales: print('------') print(sale.customer.name) for product in sale.products: print(product.name) print('------') def financial(): total = 0 for sale in sales: total += sale.total() print('Total: ', total) <file_sep>/commands.py CMD_CREATE_PRODUCT = 'add -p' CMD_LIST_PRODUCT = 'list -p' CMD_CREATE_CUSTOMER = 'add -c' CMD_LIST_CUSTOMER = 'list -c' CMD_CREATE_SALE = 'add -s' CMD_LIST_SALE = 'list -s' CMD_VIEW_SALE = 'view -s' CMD_EXIT = 'exit'<file_sep>/database.py customers = [] products = [] sales = []<file_sep>/features/customers.md - [x] cadastrar um cliente - [x] listar clientes - [ ] um cliente vai poder comprar um produto<file_sep>/app.py import commands as cmd from services.customers import create_customer, list_customers from services.fakes import seeder from services.products import create_product, list_products from services.sales import create_sale, financial, list_sales run = True while run: command = input('>> ') if command == cmd.CMD_EXIT: run = False if command == cmd.CMD_CREATE_CUSTOMER: name = input('Nome: ') age = int(input('Idade: ')) email = input('Email: ') create_customer(name, age, email) if command == cmd.CMD_LIST_CUSTOMER: list_customers() if command == cmd.CMD_CREATE_PRODUCT: name = input('Nome: ') price = float(input('Preço: ')) create_product(name, price) if command == cmd.CMD_LIST_PRODUCT: list_products() if command == cmd.CMD_CREATE_SALE: customer_index = int(input('Cliente: ')) product_indexs = input('Produtos: ').split(',') product_data = [int(i) for i in product_indexs] create_sale(customer_index, product_data) if command == cmd.CMD_LIST_SALE: list_sales() if command == cmd.CMD_VIEW_SALE: financial() if command == 'seed': seeder()<file_sep>/services/customers.py from database import customers from models.customer import Customer def create_customer(name, age, email): customer = Customer(name, age, email) customers.append(customer) def list_customers(): for customer in customers: print(customer) <file_sep>/services/products.py from database import products from models.product import Product def create_product(name, price): product = Product(name, price) products.append(product) def list_products(): for product in products: print(product)
78bdead4f11be3507d0c91f9e25891016c94f3f2
[ "Markdown", "Python" ]
11
Python
leonardfreitas/mystore
0f8540aa990d65a35cba8f11a32d7aca02260f70
df242dee29b37f23f8774070d7b1f03775a6763f
refs/heads/master
<file_sep>package cyber.auto; import org.testng.Assert; import org.testng.annotations.Test; /** * Unit test for simple App. */ public class PrinterTests { @Test public void emptyInputNotificationTest() { PrinterDriver.sendToPrint(""); Assert.assertTrue(PrinterDriver.isEmptyInputNotificationDisplayed()); } @Test public void correctInputTest() { String letter = "A"; PrinterDriver.sendToPrint(letter); Assert.assertTrue(PrinterDriver.isPrintingPatternDisplayed(letter)); } @Test public void correctInputInFileTest() { String letter = "A"; PrinterDriver.sendToPrint(letter); Assert.assertTrue(PrinterDriver.isPrintingPatternSavedToFile(letter)); } @Test public void incorrectInputTest() { PrinterDriver.sendToPrint("q"); Assert.assertTrue(PrinterDriver.hasNoOutput()); } }
6a5ce29e1285e53e4add9e312406689321516c48
[ "Java" ]
1
Java
evghub/printerapp
4153e7de941157b7bc26830abd5bbe7c5d45e135
1d9b0b88ab04a8d3bac8a8e61f9bde2507873cd5
refs/heads/master
<file_sep><?php /** * JS Post * Plugin Name: Dieg UTM URL Builder * Plugin URI: * Description: Generates UTM links. * Version: 0.0.1 * Author: <NAME> * License: GPL-3.0+ * License URI: http://www.gnu.org/licenses/gpl-3.0.txt * Text Domain: utm */ ?> <div> URL страницы записи : <p class="howto"><?php echo $fullval ?></p> <p class="howto">Наш Сервис : <a href="https://dieg.info" class="" target="_blank">Engine IP SEO</a></p> <input id="dieg_utm_source" class="dieg-hide dieg-input" type="text" name="" value="<?php echo $fullval ?>"> <ul class="tabs"> <li class="tab-link current" data-tab="tab-1">Facebook</li> <li class="tab-link" data-tab="tab-2">Google</li> </ul> <div id="tab-1" class="tab-content current"> <label style="width: 85px;display: inline-block;"> <?php if (array_key_exists('fb_tolstelka', $metas) ) { echo "The 'first' element is in the array"; } if (array_key_exists('fb_tolstelka', $metas) !== 'fb_tolstelka') { $arr=array('fb_tolstelka'=>'fb_tolstelka'); print_r($metas['fb_tolstelka']); print_r($arr['fb_tolstelka']); } if (array_key_exists('google', $metas) !== 'google') { $arr=array('google'=>'google'); print_r($metas['google']); print_r($arr['google']); } ?> </label> <label style="width: 85px;display: inline-block;">utm_source</label> <input id="dieg_utm_source_fb" class="dieg-input" type="text" name="?utm_source=" value="<?php echo $meta_key_fb ?>"> <label style="width: 85px;display: inline-block;">utm_medium</label> <input id="dieg_utm_medium_fb" class="dieg-input" type="text" name="&utm_medium=" value="<?php echo $val ?>"> <label style="width: 85px;display: inline-block;">utm_campaign</label> <input id="dieg_utm_campaign_fb" class="dieg-input" type="text" name="&utm_campaign=" value="<?php echo $val ?>"> <label style="width: 85px;display: inline-block;">utm_term</label> <input id="dieg_utm_term_fb" class="dieg-input" type="text" name="&utm_term=" value="<?php echo $meta_value_term_fb; if ( ! empty( $meta_value_term_fb ) ) { echo $meta_value_term_fb; } ?>"> <label style="width: 85px;display: inline-block;">utm_content</label> <input id="dieg_utm_content_fb" class="dieg-input" type="text" name="&utm_content=" value="<?php echo $meta_value_content_fb ?>"> <input type="submit" name="submit" value="submit" class="btn btn-primary"/><br/> </div> <div id="tab-2" class="tab-content"> <label style="width: 85px;display: inline-block;">utm_source</label> <input id="dieg_utm_source_go" class="" type="text" name="?utm_source=" value="<?php echo $meta_key_google ?>"> <label style="width: 85px;display: inline-block;">utm_medium</label> <input id="dieg_utm_medium_go" class="" type="text" name="&utm_medium=" value="<?php echo $val ?>"> <label style="width: 85px;display: inline-block;">utm_campaign</label> <input id="dieg_utm_campaign_go" class="" type="text" name="&utm_campaign=" value="<?php echo $val ?>"> <label style="width: 85px;display: inline-block;">utm_term</label> <input id="dieg_utm_term_go" class="" type="text" name="&utm_term_go=" value="<?php echo $meta_value_term_go ?>"> <label style="width: 85px;display: inline-block;">utm_content</label> <input id="dieg_utm_content_go" class="" type="text" name="&utm_content=" value="<?php echo $meta_value_content_go ?>"> </div> <span id="dieg_utm_block" style="display: block;padding-top: 20px;width:100%;word-wrap: break-word;"></span> <div style="display:block;margin-top:20px;"><a id="dieg_copy" onclick="copyToClipboard('#dieg_utm_block')" style="cursor:pointer;display:none;padding-top:10px;">Копировать ссылку</a></div> <a id="dieg_utm" class="dieg-btn" style="display: block; margin-top: 20px; text-align: center;">Сгенерировать ссылку</a> </div> <?php session_start(); if(isset($_POST["submit"])) { $utm_term = $_POST['&utm_term=']; update_post_meta($post->ID, 'utm_term', $utm_term); } ?> <script type="text/javascript"> /** * JS Post * Plugin Name: Dieg UTM URL Builder * Plugin URI: * Description: Generates UTM links. * Version: 0.0.1 * Author: <NAME> * License: GPL-3.0+ * License URI: http://www.gnu.org/licenses/gpl-3.0.txt * Text Domain: utm */ console.log("load") jQuery(document).ready(function(){ jQuery("#dieg_utm").click(function(){ jQuery("#dieg_copy").show(); var fnuma = []; jQuery(".dieg-input").each(function(i, field) { var input = jQuery(this); var name = jQuery(this).attr("name"); if(input.val()) { fnuma.push(name + input.val()); } }) console.log(fnuma, "fnuma") var fnumb = jQuery("#dieg_utm_source").val(); fnuma = fnuma.join(""); jQuery("#dieg_utm_block").text(fnuma); /*jQuery.post(window.location.href + fnumb, {a:fnumb}, function(data){ jQuery("#dieg_utm_block").text(window.location.href + fnumb); });*/ }); }); // tabs jQuery(document).ready(function(){ jQuery('ul.tabs li').click(function(){ var tab_id = jQuery(this).attr('data-tab'); jQuery('ul.tabs li').removeClass('current'); jQuery('.tab-content').removeClass('current'); jQuery('.tab-content input').removeClass('dieg-input'); jQuery(this).addClass('current'); jQuery("#"+tab_id).addClass('current'); jQuery("#"+tab_id).find("input").addClass('dieg-input'); }) }) function copyToClipboard(element) { var element = "#dieg_utm_block"; var $temp = jQuery("<input>"); jQuery("#dieg_utm_block").append($temp); $temp.val(jQuery(element).text()).select(); document.execCommand("copy"); $temp.remove(); }; </script><file_sep><?php /** * JS Post * Plugin Name: Dieg UTM URL Builder * Plugin URI: * Description: Generates UTM links. * Version: 0.0.1 * Author: <NAME> * License: GPL-3.0+ * License URI: http://www.gnu.org/licenses/gpl-3.0.txt * Text Domain: utm */ ?> <div class="load"></div> <script type="text/javascript"> /** * JS Post * Plugin Name: Dieg UTM URL Builder * Plugin URI: * Description: Generates UTM links. * Version: 0.0.1 * Author: <NAME> * License: GPL-3.0+ * License URI: http://www.gnu.org/licenses/gpl-3.0.txt * Text Domain: utm */ console.log("load") jQuery(document).ready(function(){ jQuery("#dieg_utm").click(function(){ jQuery("#dieg_copy").show(); var fnuma = []; jQuery(".dieg-input").each(function(i, field) { var input = jQuery(this); var name = jQuery(this).attr("name"); if(input.val()) { fnuma.push(name + input.val()); } }) console.log(fnuma, "fnuma") var fnumb = jQuery("#dieg_utm_source").val(); fnuma = fnuma.join(""); jQuery("#dieg_utm_block").text(fnuma); /*jQuery.post(window.location.href + fnumb, {a:fnumb}, function(data){ jQuery("#dieg_utm_block").text(window.location.href + fnumb); });*/ }); }); // tabs jQuery(document).ready(function(){ jQuery('ul.tabs li').click(function(){ var tab_id = jQuery(this).attr('data-tab'); jQuery('ul.tabs li').removeClass('current'); jQuery('.tab-content').removeClass('current'); jQuery('.tab-content input').removeClass('dieg-input'); jQuery(this).addClass('current'); jQuery("#"+tab_id).addClass('current'); jQuery("#"+tab_id).find("input").addClass('dieg-input'); }) }) function copyToClipboard(element) { var element = "#dieg_utm_block"; var $temp = jQuery("<input>"); jQuery("#dieg_utm_block").append($temp); $temp.val(jQuery(element).text()).select(); document.execCommand("copy"); $temp.remove(); }; </script><file_sep>/** * JS Post * Plugin Name: Dieg UTM URL Builder * Plugin URI: * Description: Generates UTM links. * Version: 0.0.1 * Author: <NAME> * License: GPL-3.0+ * License URI: http://www.gnu.org/licenses/gpl-3.0.txt * Text Domain: utm */ console.log("load") jQuery(document).ready(function(){ jQuery("#dieg_utm").click(function(){ console.log(jQuery(".tab-content.current a[id^='dieg_copy_']"), "fnuma") jQuery(".tab-content.current a[id^='dieg_copy_']").show(); var fnuma = []; jQuery(".tab-content.current .dieg-input").each(function(i, field) { var input = jQuery(this); var name = jQuery(this).attr("name"); if(input.val()) { fnuma.push(name + input.val()); } }); var fnumb = jQuery("#dieg_utm_source").val(); fnuma = fnuma.join(""); jQuery(".tab-content.current span[id^='dieg_utm_block_']").text(fnumb + fnuma); /*jQuery.post(window.location.href + fnumb, {a:fnumb}, function(data){ jQuery("#dieg_utm_block").text(window.location.href + fnumb); });*/ }); }); // tabs jQuery(document).ready(function(){ jQuery('ul.tabs li').click(function(){ var tab_id = jQuery(this).attr('data-tab'); jQuery('ul.tabs li').removeClass('current'); jQuery('.tab-content').removeClass('current'); jQuery('.tab-content input').removeClass('dieg-input'); jQuery(this).addClass('current'); jQuery("#"+tab_id).addClass('current'); jQuery("#"+tab_id).find("input").addClass('dieg-input'); }) }) function copyToClipboard(element) { /*var element = "#dieg_utm_block";*/ var $temp = jQuery("<input>"); jQuery("#dieg_utm_block").append($temp); $temp.val(jQuery(element).text()).select(); document.execCommand("copy"); $temp.remove(); }; <file_sep><?php /** * JS Post * Plugin Name: Dieg UTM URL Builder * Plugin URI: * Description: Generates UTM links. * Version: 0.0.1 * Author: <NAME> * License: GPL-3.0+ * License URI: http://www.gnu.org/licenses/gpl-3.0.txt * Text Domain: utm */ $dieg = 'dieg'; $diegtitle = 'UTM-метки поста'; $diegcallback = 'dieg_showup'; $version = '0.0.1'; $plugin_name = 'dieg_utm'; $plugin_real_name = 'dieg-utm-url-builder'; $custom_fields = get_post_custom($post->ID); print "$custom_fields"; print $custom_fields; function dieg_showup() { global $post; $fullval = get_permalink($post_id); $val = str_replace(home_url(), '', get_permalink()); $val = str_replace("/", "", $val); // хранить дефолтные значения как в произвольных полях $metas = get_post_meta( $post->ID ); // все мета поля $meta_value_term_fb = get_post_meta($post->ID,'utm_term_fb', true); $meta_key_fb = get_post_meta($post->ID,'fb_tolstelka', true); $meta_key_google = get_post_meta($post->ID,'google', true); //echo '<string>' . $meta_key_fb . '</string>'; //echo '<string>' . $meta_key_google . '</string>'; //echo '<string>' . $metas['fb_tolstelka'] . '</string>'; if( array_key_exists('fb_tolstelka', $metas) !== 0 ) { update_post_meta($post->ID, 'fb_tolstelka', 'fb_tolstelka'); //echo '<string>1</string>'; //print_r(get_post_meta($post->ID,'fb_tolstelka', false)); //print array_key_exists('fb_tolstelka', $metas); } else if( array_key_exists('fb_tolstelka', $metas) === 0 ) { add_post_meta( $post->ID, 'fb_tolstelka', 'fb_tolstelka', false ); //echo '<string>2</string>'; } else { update_post_meta($post->ID, 'fb_tolstelka', $meta_key_fb); //echo '<string>3</string>'; } if( array_key_exists('google', $metas !== 0) ) { update_post_meta($post->ID, 'google', $meta_key_google); //echo '<string>1g</string>'; //print_r(get_post_meta($post->ID,'google', false)); print array_key_exists('google', $metas); } else if( array_key_exists('google', $metas) === 0 ) { //echo '<string>2g</string>'; add_post_meta( $post->ID, 'google', 'google', false ); } else { //echo '<string>3g</string>'; update_post_meta($post->ID, 'google', 'google'); } if( array_key_exists('utm_term_fb', $metas !== 0) ) { update_post_meta($post->ID, 'utm_term_fb', $meta_value_term_fb); echo '<string>1f</string>'; print_r(get_post_meta($post->ID,'utm_term_fb', false)); print array_key_exists('utm_term_fb', $metas); } else if( array_key_exists('utm_term_fb', $metas) === 0 ) { echo '<string>2f</string>'; add_post_meta( $post->ID, 'utm_term_fb', '', false ); } else { echo '<string>3f -- '.$meta_value_term_fb. '</string>'; print array_key_exists('utm_term_fb', $metas); //update_post_meta($post->ID, 'utm_term_fb', $meta_value_term_fb); } // include_once('includes/dieg-sidebar-form.php'); include_once('includes/dieg-call-class.php'); include_once('includes/dieg-call-class-js.php'); } wp_enqueue_style($plugin_name, plugin_dir_url( __FILE__ ) . 'css/dieg.css?v=' . rand(), array(), $version, 'all'); function dieg_init($dieg, $diegtitle, $diegcallback) { print $diegtitle; $post_id = get_the_ID(); $post_type = get_post_type( $post->ID ); add_meta_box( $dieg, 'UTM-метки поста', 'dieg_showup', $post_type, 'side', 'default'); } add_action('add_meta_boxes', 'dieg_init'); ?> <file_sep><?php /** * JS Post * Plugin Name: Dieg UTM URL Builder * Plugin URI: * Description: Generates UTM links. * Version: 0.0.1 * Author: <NAME> * License: GPL-3.0+ * License URI: http://www.gnu.org/licenses/gpl-3.0.txt * Text Domain: utm */ ?> <?php $custom_fields = get_post_custom($post->ID); $my_custom_field = $custom_fields['utm_term']; foreach ( $my_custom_field as $key => $value ) { echo $key . " => " . $value . "<br />"; } ?>
ad0136084c36aed88949c74b65aa467b2919d9b0
[ "JavaScript", "PHP" ]
5
PHP
amushtaev/dieg-url-builder
c937d3396ee73b937e57494c150af4ef164ee0f7
f17395495dcb64220d6ff6475a0e143037c0353a
refs/heads/master
<file_sep>import * as React from "react" import { Link, graphql } from "gatsby" import Layout from "../components/layout" import Seo from "../components/seo" const Index = ({ data }) => { const posts = data?.allCosmicjsPosts?.edges; return ( <Layout> <Seo title="Home" /> <h3>Posts from Cosmic:</h3> { posts.map(({ node }) => <div key={node.slug}> <h4>{node.title}</h4> <p>{node.metadata?.description}</p> <hr /> </div> ) } </Layout> ) } export const pageQuery = graphql` query IndexQuery { allCosmicjsPosts(sort: { fields: [created], order: DESC }, limit: 1000) { edges { node { metadata { description } slug title created(formatString: "DD MMMM, YYYY") } } } } ` export default Index;
a07c0dcfc2b598f7e38bb92e7ced934fbe7c6fd2
[ "JavaScript" ]
1
JavaScript
Bitaru/test-gatsby
66632865eec6331a63d563c88aedbe2ebd15575d
2685bda3ae380e48d19f37acded781e13f62fb6a
refs/heads/master
<repo_name>CarolYedra/consola<file_sep>/Consola/src/main/java/es/avalon/jpa/consola/Principal6.java package es.avalon.jpa.consola; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import es.avalon.jpa.negocio.Capitulo; public class Principal6 { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("UnidadLibros"); EntityManager em = emf.createEntityManager(); TypedQuery<Capitulo> consulta=em.createQuery("select c from Capitulo c",Capitulo.class); List<Capitulo> lista=consulta.getResultList(); for (Capitulo c:lista) { System.out.println(c.getTitulo()); } } }
375a5b18b0c7efb264c8c5028ab78349b9d5b2c0
[ "Java" ]
1
Java
CarolYedra/consola
840048c4da4a7bd3db9fe735b05ce4f7e5d5104f
a0dd11466912b1a2da05f5ff133ee782d195b2b8
refs/heads/master
<file_sep>using System; // Upologismos evmvadou trigwnou me tin tupo tou Heron namespace Emvadon { class Program { static void Main(string[] args) { //INPUT Console.WriteLine("Type a side :"); double a = double.Parse(Console.ReadLine()); Console.WriteLine("Type b side :"); double b = double.Parse(Console.ReadLine()); Console.WriteLine("Type c side :"); double c = double.Parse(Console.ReadLine()); //PROCESSING double area = CalculationArea(a, b, c); //OUTPUT Console.WriteLine("The Area of the Triangle is {0}", area); } static double CalculationArea(double a, double b, double c) { double p = (a + b + c) / 2; double area = Math.Sqrt(p * (p - a) * (p - b) * (p - c)); return area; } } } <file_sep># HeronMethod Triangle Area Calculation
12f74d27c8293856c83c9118a8b70316d43cf726
[ "Markdown", "C#" ]
2
C#
theoant/HeronMethod
19f880a14facbe58a443ba9a14921e1f6eda0f6b
68e10603ca91fd1d0d28a3ddb24c1b77e7191ebb
refs/heads/master
<file_sep> let test = dom.find('#test')[0] let t1 = dom.find('#t2',test)[0] console.log(t1) console.log(dom.index(t1))
b6ebd630798cc5b26e2196a00075bdb3168fb618
[ "JavaScript" ]
1
JavaScript
alex54216/domApi
b5f7a396ed283d7d6fb81d2a813117a82d32b3f0
511917b98a45b0d7bd92b1c01474a69c19325cf6
refs/heads/main
<repo_name>tloyzelle/budget-tracker<file_sep>/seeders/seed.js var mongoose = require("mongoose"); var db = require("../models"); mongoose.connect("mongodb://localhost/transaction", {useNewUrlParser: true, useFindandModify: false, useUnifiedTopology: true} ); var transactionSeed = [ { name: "Food", value: 200, date: new Date(Date.now()) }, { name: "<NAME>", value: 800, date: new Date(Date.now()) }, { name: "<NAME>", value: 60, date: new Date(Date.now()) } ]; db.Transaction.deleteMany({}) .then(() => db.Transaction.collection.insertMany(transactionSeed)) .then(data => { console.log(data.result.n + " updated"); process.exit(0); }) .catch(err => { console.error(err); process.exit(1); });<file_sep>/README.md # budget-tracker ## Table of Contents * [Overview](#overview) * [To Install](#installation) * [Use](#use) * [License](#license) * [Questions](#questions) ## Overview This application allows for users to easily track their spending and access it at anytime, with offline functionality as well! [Github Repo](https://github.com/tloyzelle/Budget_Tracker) [Deployed Application](https://budget-tracker-tloyzelle.herokuapp.com) ## Installation Run npm i in terminal to install all needed dependencies. Then npm run seed to populate the database from CLI Last npm start to begin your port. ## Use https://user-images.githubusercontent.com/82417321/133891698-312b0365-5b9c-43f3-a85e-0452a4d68fe5.mov ## License This application is under the MIT license. ## Questions If there are any questions I can be contacted through my [email](<EMAIL>).
90a131593a1f34e4ddd64afa0919ee71220b50ff
[ "JavaScript", "Markdown" ]
2
JavaScript
tloyzelle/budget-tracker
aa59a414b9a4f71fa07fce69e294c013ff69d49c
ca617fbd49e14043977b9e2ed7977ac69d43cfdf
refs/heads/master
<repo_name>WestlakeFTC/PhiLobots<file_sep>/prototype/htsuperpro_task.c #ifndef HTSUPERPRO_TASK_INCLUDE #define HTSUPERPRO_TASK_INCLUDE //#define SUPERPRO_TEST #ifdef SUPERPRO_TEST //This is very important. Otherwise the communication with HTSPB will be very slow #pragma config(Sensor, S3, HTSPB, sensorI2CCustomFastSkipStates9V) #endif #include "htspb_drv.h" #define BYTES_PER_FRAME 6 short getShort(ubyte byte1, ubyte byte2) { short ret=(byte2<<8); ret |=byte1; return ret; } typedef struct orientation { short yaw; short pitch; short roll; } TOrientation; typedef struct htsupersensors { short yaw; short pitch; short roll; tSensors sPort; }TSuperSensors; volatile TSuperSensors superSensors; void SuperSensors_getOrientation(TOrientation& o) { hogCPU(); o.yaw=superSensors.yaw; o.roll=superSensors.roll; o.pitch=superSensors.pitch; releaseCPU(); } short SuperSensors_getYaw() { static bool insync=false; static unsigned long timeUsed= 0; static const int BYTES_TO_READ = 2; ubyte inputdata[BYTES_TO_READ]={0,0}; ubyte parity=0; ubyte myparity=0; unsigned long lasttime=nSysTime; long dt=0; static int numOfDataBytes=0; do{ lasttime=nSysTime; if(!insync){ //this sets S0 to 0, serving as synchronizing bit for beginning of transfer HTSPBSetStrobe(superSensors.sPort,0x0);//3ms //this is the data request to ask remote to get ready for next frame //of data // remote could return some useful header byte // for now just alternate at odd/even bits to confirm it is in sync ubyte header=HTSPBreadIO(superSensors.sPort, 0xFF);//4ms //writeDebugStreamLine("got header byte %d", header); while(header !=0x55){ header=HTSPBreadIO(superSensors.sPort, 0xFF); //writeDebugStreamLine("got header byte %d", header); } HTSPBSetStrobe(superSensors.sPort,0x01);//3ms while (header==0x55) header=HTSPBreadIO(superSensors.sPort, 0xFF);//4ms inputdata[0]=header; insync=true; }else{ inputdata[0] = HTSPBreadIO(superSensors.sPort, 0xFF);//4ms } for (int i=1;i<BYTES_TO_READ;i++) { inputdata[i] = HTSPBreadIO(superSensors.sPort, 0xFF);//4ms //writeDebugStreamLine("got byte %d: %d", i, inputdata[i]); } //HTSPBSetStrobe(superSensors.sPort,0x00);//3ms parity = HTSPBreadIO(superSensors.sPort, 0xFF);//4ms //writeDebugStream("got parity byte %d", parity); myparity=inputdata[0]; for (int i=1;i<BYTES_TO_READ;i++) { myparity^=inputdata[i]; } insync = (parity==myparity); //writeDebugStreamLine("Parity got:expected %d:%d", myparity, parity); }while(!insync); short yaw = getShort(inputdata[0],inputdata[1]); dt=nSysTime-lasttime; if(dt>0){ numOfDataBytes++; timeUsed += dt; } writeDebugStreamLine("got %d cycles in %lu ms", numOfDataBytes,timeUsed ); return yaw; } ////////////////////////////////////////////////////////////// // This loop only gets gyro readings from superpro // It's designed for cases fast gyro yaw reading is needed, e.g. control robot // heading in autonomous period. // Reading from superpro using I2C with fastest configuration (sensorI2CCustomFastSkipStates9V), // each call to drive API HTSPBreadIO takes about 2ms. // We need 2 bytes for yaw and 1 byte parity, so 6 ms delay. Fortunately // MPU is fast. so 6ms delay might be the bottleneck of the chain and total delay is about 6ms // this should be good for controlling robot. But if we read all 3 components of the MPU measurements: // pitch, roll, yaw, each 2 bytes, plus parity byte, then we will have 14ms delay, which is // boderline for robot control. ////////////////////////////////////////////////////////////// task htsuperpro_loop_yaw() { static const int BYTES_TO_READ = 2; ubyte inputdata[BYTES_TO_READ]={0,0}; long lasttime=nSysTime; int numOfDataBytes=0; bool insync =false; while(true) { if(!insync){ //this sets S0 to 0, serving as synchronizing bit for beginning of transfer HTSPBSetStrobe(superSensors.sPort,0x0);//3ms //this is the data request to ask remote to get ready for next frame //of data // remote could return some useful header byte // for now just alternate at odd/even bits to confirm it is in sync ubyte header=HTSPBreadIO(superSensors.sPort, 0xFF); //writeDebugStreamLine("got header byte %d", header); while(header !=0x55){ header=HTSPBreadIO(superSensors.sPort, 0xFF); //writeDebugStreamLine("got header byte %d", header); } HTSPBSetStrobe(superSensors.sPort,0x01); while (header==0x55) header=HTSPBreadIO(superSensors.sPort, 0xFF); insync=true; inputdata[0]=header; }else { inputdata[0]=HTSPBreadIO(superSensors.sPort, 0xFF);//4ms } for (int i=1;i<BYTES_TO_READ;i++) { //sleep(1); inputdata[i] = HTSPBreadIO(superSensors.sPort, 0xFF);//4ms //writeDebugStreamLine("got byte %d: %d", i, inputdata[i]); } //sleep(1); ubyte parity = HTSPBreadIO(superSensors.sPort, 0xFF);//4ms //writeDebugStream("got parity byte %d", parity); ubyte myparity=inputdata[0]; for (int i=1;i<BYTES_TO_READ;i++) { myparity^=inputdata[i]; } //writeDebugStreamLine(" my parity byte %d", myparity); insync= (parity==myparity); if(!insync) continue; hogCPU(); superSensors.yaw = getShort(inputdata[0],inputdata[1]); releaseCPU(); //writeDebugStreamLine("yaw:%d",superSensors.yaw); numOfDataBytes+=3; //writeDebugStreamLine("got %d bytes in %lu ms", numOfDataBytes, nSysTime-lasttime); sleep(20); } } task htsuperpro_loop() { ubyte inputdata[BYTES_PER_FRAME]; long lasttime=nSysTime; int numOfDataBytes=0; bool insync =false; while(true) { if(!insync){ //this sets S0 to 0, serving as synchronizing bit for beginning of transfer HTSPBSetStrobe(superSensors.sPort,0x0); //this is the data request to ask remote to get ready for next frame //of data // remote could return some useful header byte // for now just alternate at odd/even bits to confirm it is in sync ubyte header=HTSPBreadIO(superSensors.sPort, 0xFF); //writeDebugStreamLine("got header byte %d", header); while(header !=0x55){ header=HTSPBreadIO(superSensors.sPort, 0xFF); //writeDebugStreamLine("got header byte %d", header); } HTSPBSetStrobe(superSensors.sPort,0x01); while (header==0x55) header=HTSPBreadIO(superSensors.sPort, 0xFF); insync=true; inputdata[0]=header; }else { inputdata[0]=HTSPBreadIO(superSensors.sPort, 0xFF); } for (int i=1;i<BYTES_PER_FRAME;i++) { inputdata[i] = HTSPBreadIO(superSensors.sPort, 0xFF); //writeDebugStreamLine("got byte %d: %d", i, inputdata[i]); } ubyte parity = HTSPBreadIO(superSensors.sPort, 0xFF); //writeDebugStream("got parity byte %d", parity); ubyte myparity=inputdata[0]; for (int i=1;i<BYTES_PER_FRAME;i++) { myparity^=inputdata[i]; } writeDebugStreamLine(" my parity byte %d", myparity); if(parity!=myparity) //data error, discard { // writeDebugStreamLine("data error"); insync=false; continue; } hogCPU(); superSensors.yaw = getShort(inputdata[0],inputdata[1]); superSensors.pitch = getShort(inputdata[2], inputdata[3]); superSensors.roll = getShort(inputdata[4],inputdata[5]); releaseCPU(); numOfDataBytes+=6; writeDebugStreamLine("got %d bytes in %ld ms", numOfDataBytes, nSysTime-lasttime); sleep(2); } } void SuperSensors_init(tSensors sport) { superSensors.sPort=sport; // Set B0-7 for input HTSPBsetupIO(sport, 0x0); } void SuperSensors_init_task_yaw(tSensors sport) { superSensors.sPort=sport; // Set B0-7 for input HTSPBsetupIO(sport, 0x0); startTask(htsuperpro_loop_yaw); } void SuperSensors_init_task(tSensors sport) { superSensors.sPort=sport; // Set B0-7 for input HTSPBsetupIO(sport, 0x0); startTask(htsuperpro_loop); } #ifdef SUPERPRO_TEST #define SUPERPRO_TEST_TASK task main() { #ifdef SUPERPRO_TEST_TASK SuperSensors_init_task_yaw(S3); TOrientation orient; while(true) { SuperSensors_getOrientation(orient); displayTextLine(1, "y: %f", 0.01*orient.yaw); displayTextLine(2, "p: %f", 0.01*orient.pitch); displayTextLine(3, "r: %f", 0.01*orient.roll); writeDebugStreamLine("yaw in main:%d",orient.yaw); sleep(20); } #else SuperSensors_init(S3); while(true) { short yaw=SuperSensors_getYaw(); displayTextLine(1, "y: %f", 0.01*yaw); writeDebugStreamLine("yaw in main:%d",yaw); sleep(20); } #endif } #endif #endif <file_sep>/prototype/data/goalDetectorTest.c #pragma config(Hubs, S1, HTMotor, HTMotor, none, none) #pragma config(Hubs, S2, HTMotor, HTMotor, none, none) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S2, , sensorI2CMuxController) #pragma config(Sensor, S3, Gyro, sensorI2CCustom) #pragma config(Motor, mtr_S1_C1_1, FrontL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C1_2, BackL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C2_1, motorF, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C2_2, motorG, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_1, FrontR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_2, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C2_1, motorJ, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C2_2, motorK, tmotorTetrix, openLoop) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #define GYRO_PRECISION 2 //we do auto calibrate now, //but will use encoders to turn on/off calibration #include "hitechnic-gyro-task.c" #include "ultraSoundTest.c" const int TURN_POWER=100; const int easing_zone =70;//to be tuned const int TOLERANCE=1; const float kp = 1.0/easing_zone; const float kd = 0.0;//not needed const float ki = 0.00;//to be tuned to eliminate offset /** * Turn left for given degrees, negative means turn right */ void turn(int degrees) { hogCPU(); int heading= (gHeading+0.5); float dedt = -gRot; releaseCPU(); int target_heading = heading+degrees; //turn left if degrees to turn is positive int full_power =degrees>0? -TURN_POWER:TURN_POWER; float pid_output=0; int err=degrees; float err_integral=0; long last_action_time; long prev_meas_time=nSysTime; while(true) { int power =0; //calculate power based on err. if(abs(err)>TOLERANCE||abs(dedt)>5.0) { pid_output =err*kp+err_integral*ki; if(abs(dedt)>2)//sensor noise when rotation below 2 degrees/sec pid_output += kd*dedt; last_action_time=nSysTime; if(pid_output<-1) pid_output=-1; if(pid_output>1) pid_output=1; } power=full_power*pid_output+0.5; writeDebugStreamLine("targ: %d, head: %d, power: %d, dedt: %f, int:%f", target_heading, heading,power,dedt,err_integral); motor[FrontR] = power; motor[FrontL] = power; motor[BackR] = power; motor[BackL] = power; if(nSysTime-last_action_time>100) { //robot has been stable for 100 ms //we are done turning break; }else { //keep measuring just to see if it will be stable } sleep(5); //measuring hogCPU(); heading = (gHeading+0.5); dedt=-gRot; releaseCPU(); err=target_heading-heading; //TODO: we need timestamp measurement in gyro task err_integral += err*(nSysTime-prev_meas_time)/1000.0; prev_meas_time=nSysTime; } } faceObject(){ int min = 255; for(int i = 0; i < 46; i++){ turn(2); sleep(10); hogCPU(); heading = (gHeading + 0.5); // change to sonar reaading releaseCPU(); if(heading < min){ min = heading; } } sleep(500); for(int i = 0; i < 91; i++){ turn(-2); sleep(10); hogCPU(); heading = (gHeading + 0.5); releaseCPU(); if(heading < min){ min = heading; } } } task main() { startTask(gyro_loop); startTask(sonar_loop); while(gyro_loop_state!=READING) sleep(5); faceObject(); sleep(1000); turn(); } <file_sep>/competition/6710_test.c #pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, none) #pragma config(Sensor, S2, HTSPB, sensorI2CCustomFastSkipStates9V) #pragma config(Sensor, S4, HTMUX, sensorSONAR) #pragma config(Motor, mtr_S1_C1_1, FrontL, tmotorTetrix, openLoop, reversed) #pragma config(Motor, mtr_S1_C1_2, BackL, tmotorTetrix, openLoop, reversed, encoder) #pragma config(Motor, mtr_S1_C2_1, BackR, tmotorTetrix, openLoop, reversed, encoder) #pragma config(Motor, mtr_S1_C2_2, FrontR, tmotorTetrix, openLoop, reversed) #pragma config(Motor, mtr_S1_C3_1, MidR, tmotorTetrix, openLoop, reversed) #pragma config(Motor, mtr_S1_C3_2, MidL, tmotorTetrix, openLoop, reversed) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "SigmaDefs.h" #include "WestCoaster.h" #include "CenterGoalUs.h" #include "JoystickDriver.c" #include "hitechnic-gyro-task.h" WestCoaster g_wcDrive; #define DEBUG // number of encoder ticks per revolution of the motor #define TICKS_PER_REVOLUTION (280 * 4) // number of revolutions of the wheel per revolution of the motor #define GEAR_RATIO 1 #define WHEEL_CIRCUMFERENCE (4 * 3.14159) // number of encoder ticks per inch of travel #define TICKS_PER_INCH (TICKS_PER_REVOLUTION / WHEEL_CIRCUMFERENCE / GEAR_RATIO) // distance the middle wheel travels during one full pivot #define PIVOT_CIRCUMFERENCE (16.5 * 3.14159) // number of encoder ticks per degree of pivot #define TICKS_PER_DEGREE (TICKS_PER_INCH * PIVOT_CIRCUMFERENCE / 360) #define INCHES_PER_DEGREE (TICKS_PER_DEGREE / TICKS_PER_INCH) // tunable parameters #define RAMP_UP_STEPS 10 // number of steps to go from 0 to full power #define LINEAR_SCALING (0.05) // ratio of power difference to encoder difference #define INTEGRAL_SCALING (0.001) #define STRAIGHT_SLOWDOWN_INCHES 6 // number of inches before the end at which to start slowing down #define PIVOT_SLOWDOWN_INCHES 6 // number of inches before the end at which to start slowing down #define MIN_POWER 20 #define TIME_STEP 20 void setLeftPower(int power) { writeDebugStreamLine("setting left power: %d", power); motor[FrontL] = power; motor[MidL] = power; motor[BackL] = power; } void setRightPower(int power) { motor[FrontR] = motor[MidR] = motor[BackR] = power; } /* * Move the motors for the given number of inches at the given power. * The robot will pivot or move straight depending on the left and right * directions. leftDir and rightDir should only be 1 or -1 since they are * used to scale the absolute power. The wheel rotations are aligned by * proportionally varying the power with the encoder difference. */ void moveTank(int leftDir, int rightDir, float inches, int power, float slowdown) { float scaledPower, delta, leftPower, rightPower; int timeStart = nSysTime; float displacement = 0; // how far from the center we have deviated int count =0; // reset encoders nMotorEncoder[BackL] = 0; nMotorEncoder[BackR] = 0; // calculate encoder target float target = inches * TICKS_PER_INCH; #ifdef DEBUG writeDebugStreamLine("target is %d inches, %d ticks", inches, target); // sleep(100); #endif //DEBUG // slowly ramp up the motors int leftCount=0; int rightCount=0; for (int i = 0 ; (i < RAMP_UP_STEPS) && (leftCount + rightCount < target); i++) { leftCount = abs(nMotorEncoder[BackL]); rightCount = abs(nMotorEncoder[BackR]); displacement += (rightCount - leftCount); float currentPower = power / RAMP_UP_STEPS * i; delta = (rightCount-leftCount) * LINEAR_SCALING + displacement * INTEGRAL_SCALING; leftPower=currentPower+delta; rightPower=currentPower-delta; setLeftPower(leftDir * leftPower); setRightPower(rightDir * rightPower); sleep(TIME_STEP); } /* * Loop until both motors reach target, slowing down as they get closer * to the target. */ bool done = false; while (!done) { leftCount = abs(nMotorEncoder[BackL]); rightCount = abs(nMotorEncoder[BackR]); displacement += (rightCount - leftCount); const float averageCount = (rightCount + leftCount) * 0.5; const float slowDownDistance = (slowdown * TICKS_PER_INCH); scaledPower = power; if(averageCount > target - slowDownDistance) { float ratio = (target - averageCount) / slowDownDistance; if (ratio<0.5) { ratio=0.5; } scaledPower=scaledPower*ratio; } // keep scaled power above MIN_POWER so robot always moves if (scaledPower < MIN_POWER) scaledPower = MIN_POWER; delta = (rightCount-leftCount) * LINEAR_SCALING + displacement * INTEGRAL_SCALING; leftPower=scaledPower+delta; rightPower=scaledPower-delta; // if (leftPower < MIN_POWER) leftPower = MIN_POWER; // if (rightPower < MIN_POWER) rightPower = MIN_POWER; done = true; if (leftCount > target) { setLeftPower(0); } else { setLeftPower(leftDir *leftPower); done = false; } if (rightCount > target) { setRightPower(0); } else { setRightPower(rightDir *rightPower); done = false; } #ifdef DEBUG writeDebugStreamLine("time= %d\t\tleft= %d\t\tright=%d\t\tdelta=%d\t\tlp=%f\t\trp=%f\t\tdisp=%f", nSysTime - timeStart, leftCount, rightCount,rightCount-leftCount, leftPower, rightPower, displacement); #endif //DEBUG sleep(TIME_STEP); } } void moveForward(float inches, int power) { moveTank(1, -1, inches, power, STRAIGHT_SLOWDOWN_INCHES); } void moveBackward(float inches, int power) { moveTank(-1, 1, inches, power, STRAIGHT_SLOWDOWN_INCHES); } void pivotLeft(float degrees, int power) { moveTank(-1, -1, degrees * INCHES_PER_DEGREE, power, PIVOT_SLOWDOWN_INCHES); } void pivotRight(float degrees, int power) { moveTank(1, 1, degrees * INCHES_PER_DEGREE, power, PIVOT_SLOWDOWN_INCHES); } void moveLeft(int dir, float inches, int power) { // reset encoders nMotorEncoder[FrontL] = 0; // calculate encoder target float target = inches * TICKS_PER_INCH; #ifdef DEBUG writeDebugStreamLine("target is %d inches, %d ticks", inches, target); // sleep(100); #endif //DEBUG setLeftPower(dir * power); int leftCount= abs(nMotorEncoder[FrontL]); while (leftCount<target){ writeDebugStreamLine("%d ticks", leftCount); leftCount= abs(nMotorEncoder[FrontL]); } setLeftPower(0); } void moveRight(int dir, float inches, int power) { // reset encoders nMotorEncoder[FrontR] = 0; // calculate encoder target float target = inches * TICKS_PER_INCH; #ifdef DEBUG writeDebugStreamLine("target is %d inches, %d ticks", inches, target); // sleep(100); #endif //DEBUG setRightPower(dir * power); int rightCount= abs(nMotorEncoder[FrontR]); while (rightCount<target){ rightCount= abs(nMotorEncoder[FrontR]); } setRightPower(0); } void wiggle() { moveLeft(-1,2,30); moveRight(1,4,30); moveLeft(-1,4,30); moveRight(1,4,30); moveLeft(-1,2,30); setLeftPower(-30); setRightPower(30); sleep(300); setLeftPower(0); setRightPower(0); // moveBackward(5,30); } void wiggleMove() { /* WestCoaster_controlledEncoderObservedTurn(g_wcDrive,-15,35); WestCoaster_controlledStraightMove(g_wcDrive, -7,20); WestCoaster_controlledEncoderObservedTurn(g_wcDrive,30,35); WestCoaster_controlledStraightMove(g_wcDrive, -7,20); WestCoaster_controlledEncoderObservedTurn(g_wcDrive,-15,35); WestCoaster_controlledStraightMove(g_wcDrive, -7,20); */ WestCoaster_turnWithMPU(g_wcDrive,-5,30); WestCoaster_controlledStraightMove(g_wcDrive, -7,25); WestCoaster_turnWithMPU(g_wcDrive,10,30); WestCoaster_controlledStraightMove(g_wcDrive, -7,25); WestCoaster_turnWithMPU(g_wcDrive,-5,30); WestCoaster_controlledStraightMove(g_wcDrive, -7,20); } void grabGoal() { //you know what, we could re-use the center goal method // that is so cool! //moveForward(150,40); //WestCoaster_moveStraightWithMPU(g_wcDrive, -70, 40); // WestCoaster_controlledStraightMove(g_wcDrive,-70, 40); alignToGoal(g_wcDrive, CENTER_GOAL_SONAR, 5, 15); //wiggleMove(); sleep(5000); } void initializeRobot() { WestCoaster_init(g_wcDrive,FrontL, FrontR, BackL, BackR, BackL, BackR); WestCoaster_initMPU(S2); /*startTask(gyro_loop); while(gyro_loop_state!=GYRO_READING) { sleep(20); }*/ //set to true during competition to keep the grabber engaged bSystemLeaveServosEnabledOnProgramStop=false; } #define ALIGN_FAUCET_TO_CENTER 50 //milliseconds to align faucet #define OFF_RAMP_DIST 58 //platform and ramp measure 58 inches long #define GOAL_CENTER_TO_EDGE 11.6/2 #define FAUCET_EXTEND_BACK_CENTER GOAL_CENTER_TO_EDGE+0.5 //measure from the center of the drop to the edge of robot task main(){ initializeRobot(); // waitForStart(); /* sleep(1000); servo[foldRoller] = ROLLER_FOLDER_DOWN; sleep(1000); servo[foldRoller] = ROLLER_FOLDER_UP; sleep(1000); */ //=============== // TESTS // //wiggle(); /** * ***Turn and move with MPU with speed ramp up*** ** WestCoaster_turnWithMPU(g_wcDrive, -15,40); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, -15,40); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, 15,40); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, 15,40); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, 15,40); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, 15,40); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, -15,40); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, -15,40); //*/ // WestCoaster_moveStraightWithMPU(g_wcDrive, 20*6*6/5*6/5.5,20); // WestCoaster_moveWithMPU(g_wcDrive, -5*6*6/5*6/5.5,70, 60, 6); //sleep(2000); //WestCoaster_moveStraightWithMPU(g_wcDrive, -160,50); /*sleep(2000); WestCoaster_moveStraightWithMPU(g_wcDrive, -20,50); sleep(2000); WestCoaster_moveStraightWithMPU(g_wcDrive, 60,50); */ // WestCoaster_controlledEncoderObservedTurn(g_wcDrive,90,35); //sleep(1500); /* WestCoaster_controlledEncoderObservedTurn(g_wcDrive,-90,75); sleep(1500); WestCoaster_controlledEncoderObservedTurn(g_wcDrive,180,75); sleep(1500); WestCoaster_controlledEncoderObservedTurn(g_wcDrive,-180,75); */ // WestCoaster_controlledEncoderObservedTurn(g_wcDrive,60,35); //======================================================================= //back off the ramp, 56.9 inches from edge of field to front of bot //back of bot is 56.9+18=74.9 inches from edge of field // center of 60cm goal is 4.5*24=108 inches from edge //so need to move 108-74.9 to the center // then subtract the goal and robot faucet extents // and half-inch safety margin*/ /*OFF_RAMP_DIST +108 - 74.9 -FAUCET_EXTEND_BACK_CENTER -0.5;*/ float distance_to_60cm =-72; //go down the ramp //sleep(1000); // WestCoaster_controlledStraightMove(g_wcDrive, distance_to_60cm, 35); // sleep(1000); grabGoal(); sleep(1000); /*sleep(1000); //drop the little one readyFaucet(); sleep(1000); servo[hingeFaucet] = HINGE_FAUCET_FLIP; sleep(3000); WestCoaster_pidMPUTurn(g_wcDrive,30); sleep(1000); //deadReck sleep(1000); servo[spout] = SPOUT_OUT; //go grab another on // //fansOn(3000); */ } <file_sep>/competition/Ramp.c #pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, none) #pragma config(Hubs, S3, HTMotor, HTServo, HTServo, none) #pragma config(Hubs, S4, HTServo, none, none, none) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S2, HTSPB, sensorI2CCustomFastSkipStates9V) #pragma config(Sensor, S3, , sensorI2CMuxController) #pragma config(Sensor, S4, HTMUX, sensorI2CMuxController) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, Lift, tmotorTetrix, PIDControl, encoder) #pragma config(Motor, mtr_S1_C2_2, Flapper, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C3_1, BackR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C3_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, servo3, tServoNone) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, servo5, tServoNone) #pragma config(Servo, srvo_S3_C2_6, servo12, tServoStandard) #pragma config(Servo, srvo_S3_C3_1, servo13, tServoStandard) #pragma config(Servo, srvo_S3_C3_2, spout, tServoStandard) #pragma config(Servo, srvo_S3_C3_3, faucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_4, servo16, tServoStandard) #pragma config(Servo, srvo_S3_C3_5, servo17, tServoStandard) #pragma config(Servo, srvo_S3_C3_6, servo18, tServoStandard) #pragma config(Servo, srvo_S4_C1_1, foldRoller, tServoStandard) #pragma config(Servo, srvo_S4_C1_2, roller, tServoStandard) #pragma config(Servo, srvo_S4_C1_3, roller2, tServoStandard) #pragma config(Servo, srvo_S4_C1_4, servo22, tServoStandard) #pragma config(Servo, srvo_S4_C1_5, servo23, tServoNone) #pragma config(Servo, srvo_S4_C1_6, servo24, tServoNone) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "PhiloDefs.h" #include "WestCoaster.h" #include "CenterGoalUs.h" #include "PhiloUtils.h" #include "JoystickDriver.c" WestCoaster g_wcDrive; int initHeading; void wiggleMove() { /*WestCoaster_turnWithMPU(g_wcDrive,-2,60); WestCoaster_controlledStraightMove(g_wcDrive, -7,25); WestCoaster_turnWithMPU(g_wcDrive,10,60); WestCoaster_controlledStraightMove(g_wcDrive, -7,25); WestCoaster_turnWithMPU(g_wcDrive,-2,60);*/ WestCoaster_controlledStraightMove(g_wcDrive, -10,20); } void grabGoal() { wiggleMove(); goalGrabberDown(); sleep(200); } void doTests(); void initializeRobot() { WestCoaster_init(g_wcDrive, FrontL, FrontR, BackL, BackR, FrontL, FrontR); WestCoaster_initMPU(S2); goalGrabberUp(); //=============== // TESTS, comment it out for real // doTests(); motor [Flapper] = 0; pinClosed(); servo[foldRoller] = ROLLER_FOLDER_UP; servo[roller] = ROLLER_STOP; faucetInitial(); //move servos at maximium speed servoChangeRate[trailerL]=0; servoChangeRate[trailerR]=0; initHeading = SuperSensors_getHeading(); //set to true during competition to keep the grabber engaged bSystemLeaveServosEnabledOnProgramStop=false; } void doTests() { //alignToGoal(g_wcDrive, CENTER_GOAL_SONAR, 5, 15); //grabGoal(); /* while(true) { WestCoaster_turnWithMPU(g_wcDrive,15,80); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive,15,80); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, -15,80); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, -15,80); sleep(2000); }*/ /** * ***Turn and move with MPU with speed ramp up*** ***/ /* while(true){ WestCoaster_moveStraightWithMPU(g_wcDrive,-30, 80); sleep(5000); WestCoaster_moveStraightWithMPU(g_wcDrive,30, 80); sleep(5000); }*/ while(true){ WestCoaster_moveStraightWithMPUX(g_wcDrive,-70, 80); sleep(5000); WestCoaster_moveStraightWithMPUX(g_wcDrive,70, 80); sleep(5000); } /* while(true) { WestCoaster_controlledStraightMoveX(g_wcDrive,-30,80); sleep(5000); WestCoaster_controlledStraightMoveX(g_wcDrive,30,80); sleep(5000); }*/ } task main(){ initializeRobot(); waitForStart(); pinClosed(); sleep(1000); servo[foldRoller] = ROLLER_FOLDER_DOWN; sleep(1000); servo[foldRoller] = ROLLER_FOLDER_UP; sleep(1000); pinClosed(); //go down the ramp WestCoaster_moveStraightWithMPU(g_wcDrive, -71, 30); pinClosed(); faucetDeployed(); sleep(1000); //must be flipped before lift pinClosed(); liftGoUp(LIFT_60CM_HEIGHT); //from ramp while(!checkLiftDone()){}; WestCoaster_encoderObservedTurn(g_wcDrive,-3, 80); grabGoal(); WestCoaster_turnWithMPU(g_wcDrive, -125, 60); WestCoaster_moveStraightWithMPU(g_wcDrive, -15, 80); pinOpen(); //sleep (3000); goalGrabberUp(); ////// //WestCoaster_moveStraightWithMPU(g_wcDrive, 16, 40); ////// sleep(500); liftGoUp(LIFT_90CM_HEIGHT); //WestCoaster_turnWithMPU(g_wcDrive, 140, 40); float current_heading = SuperSensors_getHeading(); float delta=angleTurned(initHeading,current_heading); writeDebugStreamLine("delta: %d", delta); WestCoaster_turnWithMPU(g_wcDrive,(abs(delta)-22) ,60);//10 WestCoaster_moveStraightWithMPU(g_wcDrive,-28, 80, 4000);//-12 while(!checkLiftDone()){}; grabGoal(); // fansOn(4000); WestCoaster_turnWithMPU(g_wcDrive,6,80); motor[FanL] = -100; motor[FanR] = 100; motor[Flapper]=-100; //WestCoaster_moveStraightWithMPU(g_wcDrive, 3, 40); WestCoaster_moveStraightWithMPU(g_wcDrive,107, 80); motor[FanL] = 0; motor[FanR] = 0; motor[Flapper]=0; WestCoaster_turnWithMPU(g_wcDrive, 60, 70); WestCoaster_moveStraightWithMPU(g_wcDrive, 20, 80); //WestCoaster_turnWithMPU(g_wcDrive, 90, 70) //sleep(500); //WestCoaster_turnWithMPU(g_wcDrive, -90, 70); //WestCoaster_turnWithMPU(g_wcDrive,-90,70); /*sleep(500); //zalignToGoal(g_wcDrive, CENTER_GOAL_SONAR, 5, 15); while(true){}; WestCoaster_turnWithMPU(g_wcDrive,2,40); grabGoal(); sleep(500); //drop the little one //liftGoUp(LIFT_FOR_60CM,5000); servo[faucet] = HINGE_FAUCET_FLIP; sleep(1000); pinOpen(); sleep(500); //release 60cm goal WestCoaster_moveStraightWithMPU(g_wcDrive,4,40); WestCoaster_turnWithMPU(g_wcDrive,-90,40); WestCoaster_moveStraightWithMPU(g_wcDrive,-5,40); goalGrabberUp(); //grab the 90 cm goal sleep(500); servo[lift]=LIFT_FOR_90CM; WestCoaster_moveStraightWithMPU(g_wcDrive,2,40); sleep(500); /** alternative //we check and adjust the heading WestCoaster_measureMPU(g_wcDrive); int messed = angleDifference(initHeading, g_wcDrive.global_heading); WestCoaster_turnWithMPU(g_wcDrive,-messed,40); */ /*WestCoaster_turnWithMPU(g_wcDrive,90,40); sleep(500); //liftGoUp(LIFT_FOR_90CM, 4000); sleep(500); WestCoaster_controlledStraightMove(g_wcDrive,-10,50); grabGoal(); sleep(500); //drop the big one fansOn(5000); sleep(1000); //move all goals to parking /* //try to turn right a little if(!WestCoaster_turnWithMPU(g_wcDrive,5,40, false, 1000)){ //did not finish turn, backout more WestCoaster_moveStraightWithMPU(g_wcDrive,5,40); //then turn again; WestCoaster_turnWithMPU(g_wcDrive,5,40, false, 1000); } WestCoaster_moveStraightWithMPU(g_wcDrive,5,40); sleep(500); //now we check and adjust the heading WestCoaster_measureMPU(g_wcDrive); int messed = angleDifference(initHeading, g_wcDrive.global_heading); #ifdef TRACE_ENABLED if(abs(messed)>60){ //we messaged up the angle too much playSound(soundBeepBeep); } #endif int degrees_to_park = 20-messed; WestCoaster_turnWithMPU(g_wcDrive,degrees_to_park,40); sleep(1000); WestCoaster_moveStraightWithMPU(g_wcDrive,120,70); WestCoaster_turnWithMPU(g_wcDrive,-105,40); WestCoaster_moveStraightWithMPU(g_wcDrive,-10,70); WestCoaster_turnWithMPU(g_wcDrive,-70,40); WestCoaster_moveStraightWithMPU(g_wcDrive,-10,70);*/ } <file_sep>/prototype/bouncy-button.c #define DEBOUNCE_TIME 500 //debouncing period in ms #ifndef JOYSTICK_DRIVER_INCLDUDED #define JOYSTICK_DRIVER_INCLDUDED #include "JoystickDriver.c" #endif /************************************************ * * A java class like structure to handle buttons used * as toggle buttons. Excessive spurious button presses * are filtered out in the debounce method. */ typedef struct BJoyButtons { bool onJoy1; //on joy stick 1 or 2? int button; //index of the button on joy stick long lastTime; //last time pressed volatile bool pressed; //pressed or not } TBouncyBtn; void BouncyBtn_init(TBouncyBtn& btn, bool on_joy1, int btn_index) { btn.onJoy1=on_joy1; btn.button=btn_index; btn.lastTime=0; btn.pressed=false; } void BouncyBtn_debounce(TBouncyBtn& btn) { short isBtnOn; if (btn.onJoy1) isBtnOn=joy1Btn(btn.button); else isBtnOn=joy2Btn(btn.button); if(isBtnOn && !(btn.pressed) && ( (nSysTime - btn.lastTime )>DEBOUNCE_TIME) ) { hogCPU(); btn.pressed=true; btn.lastTime=nSysTime; releaseCPU(); } } bool BouncyBtn_checkAndClear(TBouncyBtn& btn) { bool res=false; hogCPU(); res=btn.pressed; if(res) btn.pressed=false; releaseCPU(); return res; } <file_sep>/prototype/gyro-encoder_fused.c ///////////////////////////////////////////////////////////////////////////////// // gyro_enocoder_fused is the file where we keep all miscellaneous methods // we need for our main programs(library) ///////////////////////////////////////////////////////////////////////////////// /** * Robot characteristics. these are constant, only change when robot *is re-designed */ // half-width of robot in inches measured from center-plane // of left wheels to // center plane of right side wheels const int robotHalfWidth = 8.25; // wheel radius in inches const int wheelRad = 2; // encoder counts per revolution of the motor output shaft const int cpr = 1120; // gear ratio of the drive train, turns of wheels // for each revolution of motor output shaft const float gear_ratio = 1.0; // full power level for moving forward const int FULL_POWER_FORWARD = 80; // full power level for turning left const int FULL_POWER_LEFT_TURN = 80; //dont let the motors stall too long! Max millis for motors to stall const int maxStallTime = 300; int inchesToCounts(float inches) { return abs((int)((cpr*inches)/(PI*wheelRad*2.0)/gear_ratio+0.5)); } /** * converts rotation degrees to encoder counts */ int degreesToCounts(int degrees) { return abs((int)((degrees * robotHalfWidth *cpr) /(360.0*wheelRad)/gear_ratio +0.5)); } /** * Turn left for given degrees, negative means turn right */ void allMotorsPowerRot(int power){ //set power to the Motors during turning motor[FrontR] = power; motor[FrontL] = power; motor[BackR] = power; motor[BackL] = power; motor[MidR] = power; motor[MidL] = power; } void allMotorsPowerStraight(int power){ // set power for motors while moving straight motor[FrontR] = -power; motor[FrontL] = power; motor[BackR] = -power; motor[BackL] = power; motor[MidR] = -power; motor[MidL] = power; } unsigned long stallTime =0 ; bool isStalling(int lastEncoderL, int lastEncoderR, unsigned int dt) { if(lastEncoderL == nMotorEncoder[FrontL] && lastEncoderR == nMotorEncoder[FrontR]) { stallTime += dt; if(stallTime > maxStallTime){ playImmediateTone(1000, 100); writeDebugStreamLine("Drive stalled"); return true; } }else{ stallTime = 0; } return false; } int observedBrakingOffSetL=180; int observedBrakingOffSetR=180; //move straight with set power void controlledStraightMove(float inches, int power){ nMotorEncoder[FrontL] = 0; nMotorEncoder[FrontR] = 0; int countToTurn = inchesToCounts(inches); if(countToTurn==0) return; if(inches < 0){ power = -power; } allMotorsPowerStraight(power); int lastEncoderL = 0; int lastEncoderR = 0; while(abs(nMotorEncoder[FrontL]) < countToTurn && abs(nMotorEncoder[FrontR])< countToTurn){ writeDebugStreamLine(" %d,%d,%d", nMotorEncoder[FrontL],nMotorEncoder[FrontR], nSysTime); sleep(20); if(isStalling(lastEncoderL,lastEncoderR, 20)){ break; } lastEncoderL = nMotorEncoder[FrontL]; lastEncoderR = nMotorEncoder[FrontR]; } allMotorsPowerStraight(0); do{ lastEncoderL=nMotorEncoder[FrontL]; lastEncoderR=nMotorEncoder[FrontR]; writeDebugStreamLine("counts:%d-off:%d/%d, encoderL: %d, encoderR: %d, power: %d, time: %d", countToTurn, observedBrakingOffSetL, observedBrakingOffSetR, lastEncoderL, lastEncoderR, 0, nSysTime); sleep(20); }while(nMotorEncoder[FrontL]!=lastEncoderL || nMotorEncoder[FrontR]!=lastEncoderR); writeDebugStreamLine("counts:%d-off:%d/%d, encoderL: %d, encoderR: %d, power: %d, time: %d", countToTurn, observedBrakingOffSetL, observedBrakingOffSetR, lastEncoderL, lastEncoderR, 0, nSysTime); } void straightMove(float inches){ //move straight with full power controlledStraightMove(inches, FULL_POWER_FORWARD); } void controlledEncoderObservedTurn(int target, int powerDesired){ nMotorEncoder[FrontR] = 0; nMotorEncoder[FrontL] = 0; int countToTurn = degreesToCounts(target); int lastEncoderR=0; int lastEncoderL=0; int power=target<0? -powerDesired:powerDesired; allMotorsPowerRot(power); while(abs(lastEncoderR)< countToTurn-observedBrakingOffSetR && abs(lastEncoderL) < countToTurn-observedBrakingOffSetL) { sleep(20); if(isStalling(lastEncoderL,lastEncoderR, 20)){ break; } lastEncoderR = nMotorEncoder[FrontR]; lastEncoderL = nMotorEncoder[FrontL]; writeDebugStreamLine("counts:%d-off:%d/%d, encoderL: %d, encoderR: %d, power: %d, time: %d", countToTurn, observedBrakingOffSetL,observedBrakingOffSetR, lastEncoderL, lastEncoderR, power, nSysTime); } allMotorsPowerRot(0); do{ lastEncoderL=nMotorEncoder[FrontL]; lastEncoderR=nMotorEncoder[FrontR]; writeDebugStreamLine("counts:%d-off:%d/%d, encoderL: %d, encoderR: %d, power: %d, time: %d", countToTurn, observedBrakingOffSetL, observedBrakingOffSetR, lastEncoderL, lastEncoderR, 0, nSysTime); sleep(20); }while(nMotorEncoder[FrontL]!=lastEncoderL || nMotorEncoder[FrontR]!=lastEncoderR); // observedBrakingOffSetL=abs(last_encoderL-beginningEncoderL); // observedBrakingOffSetR=abs(last_encoderR-beginningEncoderR); //observedGyroOffSet=gHeading-target; } void encoderObservedTurn(int target){ controlledEncoderObservedTurn(target, FULL_POWER_LEFT_TURN); } <file_sep>/prototype/data/test11-28-01.c counts:1119-off:0/0, encoderL: 0, encoderR: 0, power: 100,heading:0 time: 971509 counts:1119-off:0/0, encoderL: 12, encoderR: 7, power: 100,heading:0 time: 971530 counts:1119-off:0/0, encoderL: 41, encoderR: 33, power: 100,heading:0 time: 971551 counts:1119-off:0/0, encoderL: 58, encoderR: 68, power: 100,heading:0 time: 971572 counts:1119-off:0/0, encoderL: 102, encoderR: 88, power: 100,heading:0 time: 971593 counts:1119-off:0/0, encoderL: 146, encoderR: 128, power: 100,heading:2 time: 971614 counts:1119-off:0/0, encoderL: 165, encoderR: 172, power: 100,heading:4 time: 971634 counts:1119-off:0/0, encoderL: 213, encoderR: 204, power: 100,heading:8 time: 971655 counts:1119-off:0/0, encoderL: 231, encoderR: 260, power: 100,heading:12 time: 971677 counts:1119-off:0/0, encoderL: 272, encoderR: 289, power: 100,heading:15 time: 971698 counts:1119-off:0/0, encoderL: 319, encoderR: 348, power: 100,heading:19 time: 971719 counts:1119-off:0/0, encoderL: 370, encoderR: 411, power: 100,heading:23 time: 971740 counts:1119-off:0/0, encoderL: 402, encoderR: 470, power: 100,heading:26 time: 971761 counts:1119-off:0/0, encoderL: 424, encoderR: 500, power: 100,heading:30 time: 971781 counts:1119-off:0/0, encoderL: 478, encoderR: 570, power: 100,heading:33 time: 971802 counts:1119-off:0/0, encoderL: 530, encoderR: 600, power: 100,heading:37 time: 971822 counts:1119-off:0/0, encoderL: 554, encoderR: 659, power: 100,heading:41 time: 971843 counts:1119-off:0/0, encoderL: 601, encoderR: 718, power: 100,heading:45 time: 971864 counts:1119-off:0/0, encoderL: 651, encoderR: 748, power: 100,heading:49 time: 971884 counts:1119-off:0/0, encoderL: 692, encoderR: 813, power: 100,heading:56 time: 971908 counts:1119-off:0/0, encoderL: 755, encoderR: 882, power: 100,heading:60 time: 971931 counts:1119-off:0/0, encoderL: 805, encoderR: 942, power: 100,heading:64 time: 971952 counts:1119-off:0/0, encoderL: 831, encoderR: 972, power: 100,heading:68 time: 971973 counts:1119-off:0/0, encoderL: 888, encoderR: 1034, power: 100,heading:72 time: 971995 counts:1119-off:0/0, encoderL: 941, encoderR: 1098, power: 100,heading:75 time: 972016 counts:1119-off:0/0, encoderL: 967, encoderR: 1161, power: 100,heading:81 time: 972038 counts:1119-off:0/0, encoderL: 0, encoderR: 0, power: 100,heading:102 time: 977060 counts:1119-off:0/0, encoderL: 6, encoderR: 0, power: 100,heading:102 time: 977081 counts:1119-off:0/0, encoderL: 18, encoderR: 12, power: 100,heading:102 time: 977102 counts:1119-off:0/0, encoderL: 49, encoderR: 41, power: 100,heading:102 time: 977123 counts:1119-off:0/0, encoderL: 70, encoderR: 61, power: 100,heading:102 time: 977143 counts:1119-off:0/0, encoderL: 123, encoderR: 104, power: 100,heading:103 time: 977165 counts:1119-off:0/0, encoderL: 173, encoderR: 149, power: 100,heading:104 time: 977186 counts:1119-off:0/0, encoderL: 198, encoderR: 180, power: 100,heading:105 time: 977206 counts:1119-off:0/0, encoderL: 218, encoderR: 228, power: 100,heading:108 time: 977226 counts:1119-off:0/0, encoderL: 268, encoderR: 253, power: 100,heading:112 time: 977247 counts:1119-off:0/0, encoderL: 290, encoderR: 309, power: 100,heading:115 time: 977268 counts:1119-off:0/0, encoderL: 333, encoderR: 367, power: 100,heading:119 time: 977289 counts:1119-off:0/0, encoderL: 380, encoderR: 395, power: 100,heading:123 time: 977309 counts:1119-off:0/0, encoderL: 404, encoderR: 457, power: 100,heading:126 time: 977332 counts:1119-off:0/0, encoderL: 460, encoderR: 527, power: 100,heading:130 time: 977354 counts:1119-off:0/0, encoderL: 506, encoderR: 557, power: 100,heading:133 time: 977375 counts:1119-off:0/0, encoderL: 535, encoderR: 619, power: 100,heading:137 time: 977396 counts:1119-off:0/0, encoderL: 590, encoderR: 677, power: 100,heading:142 time: 977417 counts:1119-off:0/0, encoderL: 614, encoderR: 709, power: 100,heading:146 time: 977438 counts:1119-off:0/0, encoderL: 666, encoderR: 768, power: 100,heading:150 time: 977460 counts:1119-off:0/0, encoderL: 716, encoderR: 837, power: 100,heading:154 time: 977481 counts:1119-off:0/0, encoderL: 749, encoderR: 867, power: 100,heading:158 time: 977502 counts:1119-off:0/0, encoderL: 802, encoderR: 929, power: 100,heading:162 time: 977523 counts:1119-off:0/0, encoderL: 835, encoderR: 989, power: 100,heading:166 time: 977543 counts:1119-off:0/0, encoderL: 889, encoderR: 1019, power: 100,heading:170 time: 977563 counts:1119-off:0/0, encoderL: 913, encoderR: 1079, power: 100,heading:174 time: 977584 counts:1119-off:0/0, encoderL: 965, encoderR: 1145, power: 100,heading:177 time: 977605 counts:1119-off:0/0, encoderL: 0, encoderR: 0, power: 100,heading:200 time: 982626 counts:1119-off:0/0, encoderL: 2, encoderR: 0, power: 100,heading:200 time: 982646 counts:1119-off:0/0, encoderL: 21, encoderR: 17, power: 100,heading:200 time: 982668 counts:1119-off:0/0, encoderL: 35, encoderR: 30, power: 100,heading:200 time: 982689 counts:1119-off:0/0, encoderL: 76, encoderR: 69, power: 100,heading:200 time: 982712 counts:1119-off:0/0, encoderL: 121, encoderR: 110, power: 100,heading:200 time: 982735 counts:1119-off:0/0, encoderL: 150, encoderR: 132, power: 100,heading:201 time: 982756 counts:1119-off:0/0, encoderL: 202, encoderR: 186, power: 100,heading:204 time: 982778 counts:1119-off:0/0, encoderL: 244, encoderR: 234, power: 100,heading:207 time: 982799 counts:1119-off:0/0, encoderL: 265, encoderR: 285, power: 100,heading:210 time: 982820 counts:1119-off:0/0, encoderL: 309, encoderR: 311, power: 100,heading:213 time: 982841 counts:1119-off:0/0, encoderL: 354, encoderR: 368, power: 100,heading:217 time: 982862 counts:1119-off:0/0, encoderL: 374, encoderR: 430, power: 100,heading:221 time: 982883 counts:1119-off:0/0, encoderL: 430, encoderR: 472, power: 100,heading:224 time: 982904 counts:1119-off:0/0, encoderL: 457, encoderR: 534, power: 100,heading:228 time: 982925 counts:1119-off:0/0, encoderL: 508, encoderR: 564, power: 100,heading:231 time: 982946 counts:1119-off:0/0, encoderL: 554, encoderR: 625, power: 100,heading:235 time: 982968 counts:1119-off:0/0, encoderL: 600, encoderR: 683, power: 100,heading:241 time: 982989 counts:1119-off:0/0, encoderL: 628, encoderR: 745, power: 100,heading:245 time: 983010 counts:1119-off:0/0, encoderL: 691, encoderR: 777, power: 100,heading:249 time: 983031 counts:1119-off:0/0, encoderL: 730, encoderR: 848, power: 100,heading:253 time: 983052 counts:1119-off:0/0, encoderL: 787, encoderR: 880, power: 100,heading:257 time: 983073 counts:1119-off:0/0, encoderL: 844, encoderR: 943, power: 100,heading:261 time: 983094 counts:1119-off:0/0, encoderL: 867, encoderR: 1004, power: 100,heading:265 time: 983115 counts:1119-off:0/0, encoderL: 917, encoderR: 1036, power: 100,heading:269 time: 983135 counts:1119-off:0/0, encoderL: 972, encoderR: 1096, power: 100,heading:273 time: 983156 counts:1119-off:0/0, encoderL: 1007, encoderR: 1129, power: 100,heading:277 time: 983177 counts:1119-off:0/0, encoderL: 1007, encoderR: 1129, power: 0,heading:277 time: 983179 counts:1119-off:0/0, encoderL: 1007, encoderR: 1129, power: 0,heading:283 time: 983201 counts:1119-off:0/0, encoderL: 1007, encoderR: 1129, power: 0,heading:287 time: 983222 counts:1119-off:0/0, encoderL: 1007, encoderR: 1129, power: 0,heading:291 time: 983243 counts:1119-off:0/0, encoderL: 1007, encoderR: 1129, power: 0,heading:294 time: 983264 counts:1119-off:0/0, encoderL: 1007, encoderR: 1129, power: 0,heading:297 time: 983285 counts:1119-off:0/0, encoderL: 1007, encoderR: 1129, power: 0,heading:299 time: 983306 counts:1119-off:0/0, encoderL: 1007, encoderR: 1129, power: 0,heading:300 time: 983327 counts:1119-off:0/0, encoderL: 1007, encoderR: 1129, power: 0,heading:301 time: 983349 counts:1119-off:0/0, encoderL: 1007, encoderR: 1129, power: 0,heading:300 time: 983370 <file_sep>/competition/UltraSoundTest.c #pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, HTServo) #pragma config(Hubs, S3, HTMotor, HTServo, HTServo, HTServo) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S2, HTSPB, sensorI2CCustomFastSkipStates9V) #pragma config(Sensor, S3, , sensorI2CMuxController) #pragma config(Sensor, S4, HTMUX, sensorI2CCustomFastSkipStates9V) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, motorF, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C2_2, Flapper, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C3_1, BackR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C3_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S1_C4_1, servo1, tServoNone) #pragma config(Servo, srvo_S1_C4_2, servo2, tServoNone) #pragma config(Servo, srvo_S1_C4_3, servo3, tServoNone) #pragma config(Servo, srvo_S1_C4_4, servo4, tServoNone) #pragma config(Servo, srvo_S1_C4_5, servo5, tServoNone) #pragma config(Servo, srvo_S1_C4_6, servo6, tServoNone) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, lift, tServoStandard) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_6, servo12, tServoNone) #pragma config(Servo, srvo_S3_C3_1, servo13, tServoNone) #pragma config(Servo, srvo_S3_C3_2, spout, tServoStandard) #pragma config(Servo, srvo_S3_C3_3, faucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_4, servo16, tServoNone) #pragma config(Servo, srvo_S3_C3_5, servo17, tServoNone) #pragma config(Servo, srvo_S3_C3_6, servo18, tServoNone) #pragma config(Servo, srvo_S3_C4_1, foldRoller, tServoStandard) #pragma config(Servo, srvo_S3_C4_2, roller, tServoStandard) #pragma config(Servo, srvo_S3_C4_3, servo21, tServoNone) #pragma config(Servo, srvo_S3_C4_4, servo22, tServoNone) #pragma config(Servo, srvo_S3_C4_5, servo23, tServoNone) #pragma config(Servo, srvo_S3_C4_6, servo24, tServoNone) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "PhiloDefs.h" #include "CenterGoalUs.h" task main() { while(true){ sleep(200); #ifdef USE_HT_SENSOR_MUX int distL= readDist(CENTER_GOAL_SONAR); int distR = USreadDist (msensor_S4_2); #else int distL=SensorValue[sonarSensorL]; int distR=SensorValue[sonarSensorR]; #endif writeDebugStreamLine("left: %d, right: %d",distL, distR); int position=determineGoalPosition(CENTER_GOAL_SONAR, 50); writeDebugStreamLine("goalPosition: %d",position); } } <file_sep>/prototype/Ramp.c #pragma config(Hubs, S1, HTMotor, HTMotor, none, none) #pragma config(Hubs, S2, HTMotor, HTServo, none, none) #pragma config(Hubs, S3, HTMotor, HTServo, none, none) #pragma config(Sensor, S4, sonarSensor, sensorSONAR) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, MidR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C2_2, MidL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_1, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S2_C2_1, flapper1, tServoStandard) #pragma config(Servo, srvo_S2_C2_2, flapper2, tServoStandard) #pragma config(Servo, srvo_S2_C2_3, servo3, tServoNone) #pragma config(Servo, srvo_S2_C2_4, servo4, tServoNone) #pragma config(Servo, srvo_S2_C2_5, servo5, tServoNone) #pragma config(Servo, srvo_S2_C2_6, servo6, tServoNone) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, lift, tServoStandard) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_6, faucet, tServoStandard) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "gyro-encoder_fused.c" #include "ultraSoundAutonomous.c" #include "JoystickDriver.c" void readyFaucet() { } void fansOn(unsigned long time) { unsigned long targetTime = nSysTime + time; while(nSysTime < targetTime) { motor[FanL] = -100; motor[FanR] = 100; } motor[FanL] = 0; motor[FanR] = 0; } void liftGoUp(int height) { int position = ((height-18*2.54)/(122-18*2.54)*(32-224))+224; servo[lift]=position; } void swagger(bool right, int time, int domPower){ if(right){ motor[FrontR] = domPower; motor[BackR] = domPower; motor[FrontL] = -(domPower-20); motor[BackL] = -(domPower-20); } else{ motor[FrontL] = -domPower; motor[BackL] = -domPower; motor[FrontR] = (domPower-25); motor[BackR] = (domPower-25); } long timeStart =nSysTime; while(nSysTime < timeStart + time){} allMotorsPowerStraight(0); } #define GRABBER_UP 100 #define GRABBER_DOWN 20 void wiggleMove() { controlledEncoderObservedTurn(-30,25); controlledStraightMove(-5,20); controlledEncoderObservedTurn(30,25); controlledStraightMove(-8,20); } void grabGoal() { wiggleMove(); servo[trailerR] = GRABBER_DOWN; servo[trailerL] = 255-GRABBER_DOWN; sleep(200); writeDebugStreamLine("Grabber Position:%d", ServoValue[trailerR]); } void initializeRobot() { //servo[lift] = 224; //servo[flap] = 0; servo[trailerR] = GRABBER_UP; servo[trailerL] = 255-GRABBER_UP; //move servos at maximium speed servoChangeRate[trailerL]=0; servoChangeRate[trailerR]=0; //set to true during competition to keep the grabber engaged bSystemLeaveServosEnabledOnProgramStop=true; } task main() { initializeRobot(); sleep(700); // waitForStart(); //liftGoUp(90); //sleep(10000); // straightMove(24); controlledStraightMove(-66,25); controlledEncoderObservedTurn(25,40); liftGoUp(70); sleep(5000); controlledStraightMove(-15,30); grabGoal(); sleep(2000); encoderObservedTurn(-180); straightMove(-100); //encoderObservedTurn(90); // sleep(5000); //controlledStraightMove(20,20); //sleep(1000); //straightMove(10); //sleep(1000); //controlledEncoderObservedTurn(-180, 80); //sleep(1000); //controlledEncoderObservedTurn(90, 80); //we only need 100ms or less to determine the center goal //orientation. /*controlledStraightMove(-12, 25); sleep(1000); wiggleMove(); sleep(500); grabGoal(); sleep(1000); encoderObservedTurn(-40); straightMove(5); sleep(1000); encoderObservedTurn(180); straightMove(-95); sleep(3000); controlledStraightMove(-15,10); //readyFaucet(); sleep(1000); //fansOn(4000); sleep(1000); encoderObservedTurn(-40); sleep(1000); controlledStraightMove(110, 100); sleep(1000); encoderObservedTurn(-130); */} <file_sep>/prototype/encoder_test.c #pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, HTServo) #pragma config(Hubs, S3, HTMotor, HTServo, HTServo, HTServo) #pragma config(Sensor, S2, HTSPB, sensorI2CCustomFastSkipStates9V) #pragma config(Sensor, S4, HTMUX, sensorSONAR) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, MidR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_2, MidL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C3_1, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C3_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S1_C4_1, flapper1, tServoStandard) #pragma config(Servo, srvo_S1_C4_2, flapper2, tServoStandard) #pragma config(Servo, srvo_S1_C4_3, servo3, tServoNone) #pragma config(Servo, srvo_S1_C4_4, servo4, tServoNone) #pragma config(Servo, srvo_S1_C4_5, servo5, tServoNone) #pragma config(Servo, srvo_S1_C4_6, servo6, tServoNone) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, lift, tServoStandard) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_6, faucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_1, flapper3, tServoStandard) #pragma config(Servo, srvo_S3_C3_2, spout, tServoStandard) #pragma config(Servo, srvo_S3_C3_3, hingeFaucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_4, servo16, tServoNone) #pragma config(Servo, srvo_S3_C3_5, servo17, tServoNone) #pragma config(Servo, srvo_S3_C3_6, servo18, tServoNone) #pragma config(Servo, srvo_S3_C4_1, foldRoller, tServoStandard) #pragma config(Servo, srvo_S3_C4_2, roller, tServoStandard) #pragma config(Servo, srvo_S3_C4_3, servo21, tServoNone) #pragma config(Servo, srvo_S3_C4_4, servo22, tServoNone) #pragma config(Servo, srvo_S3_C4_5, servo23, tServoNone) #pragma config(Servo, srvo_S3_C4_6, servo24, tServoNone) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// /*#pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, HTServo) #pragma config(Hubs, S3, HTMotor, HTServo, HTServo, HTServo) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S3, , sensorI2CMuxController) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, MidR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_2, MidL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C3_1, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C3_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, motorJ, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, motorK, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S1_C4_1, servo1, tServoNone) #pragma config(Servo, srvo_S1_C4_2, servo2, tServoNone) #pragma config(Servo, srvo_S1_C4_3, servo3, tServoNone) #pragma config(Servo, srvo_S1_C4_4, servo4, tServoNone) #pragma config(Servo, srvo_S1_C4_5, servo5, tServoNone) #pragma config(Servo, srvo_S1_C4_6, servo6, tServoNone) #pragma config(Servo, srvo_S3_C2_1, servo7, tServoNone) #pragma config(Servo, srvo_S3_C2_2, servo8, tServoNone) #pragma config(Servo, srvo_S3_C2_3, servo9, tServoNone) #pragma config(Servo, srvo_S3_C2_4, servo10, tServoNone) #pragma config(Servo, srvo_S3_C2_5, servo11, tServoNone) #pragma config(Servo, srvo_S3_C2_6, servo12, tServoNone) #pragma config(Servo, srvo_S3_C3_1, servo13, tServoNone) #pragma config(Servo, srvo_S3_C3_2, servo14, tServoNone) #pragma config(Servo, srvo_S3_C3_3, servo15, tServoNone) #pragma config(Servo, srvo_S3_C3_4, servo16, tServoNone) #pragma config(Servo, srvo_S3_C3_5, servo17, tServoNone) #pragma config(Servo, srvo_S3_C3_6, servo18, tServoNone) #pragma config(Servo, srvo_S3_C4_1, servo19, tServoNone) #pragma config(Servo, srvo_S3_C4_2, servo20, tServoNone) #pragma config(Servo, srvo_S3_C4_3, servo21, tServoNone) #pragma config(Servo, srvo_S3_C4_4, servo22, tServoNone) #pragma config(Servo, srvo_S3_C4_5, servo23, tServoNone) #pragma config(Servo, srvo_S3_C4_6, servo24, tServoNone)*/ #include "../competition/HTSuperproSensors.h" void allPower(int power) { motor[BackL]=power; motor[FrontL]=power; motor[MidL]=power; motor[BackR]=-power; motor[FrontR]=-power; motor[MidR]=-power; } #define THRESH 800 task main() { SuperSensors_init_task_yaw(S2); while(!super_health) sleep(20); TOrientation orient; int leftCount=0; int rightCount=0; int lastRight=0; int lastLeft=0; allPower(75); do{ lastRight=rightCount; lastLeft=leftCount; leftCount=nMotorEncoder[FrontL]; rightCount=nMotorEncoder[FrontR]; writeDebugStreamLine("encoders L/R: %d/%d", leftCount, rightCount); if(abs(lastLeft-leftCount)>THRESH || abs(lastLeft)-abs(leftCount)>0) { writeDebugStreamLine("****Left encoder bogus"); } if(abs(lastRight-rightCount)>THRESH || abs(lastRight)-abs(rightCount)>0) { writeDebugStreamLine("****Right encoder bogus"); } SuperSensors_getOrientation(orient); writeDebugStreamLine("yaw in main:%d",0.01*orient.yaw); sleep(20); }while(abs(rightCount)<20000||abs(leftCount)<20000); allPower(0); sleep(3000); } <file_sep>/competition/hitechnic-gyro-drv2.h /*!@addtogroup HiTechnic * @{ * @defgroup htgyro Gyroscopic Sensor * HiTechnic Gyroscopic Sensor * @{ */ #ifndef __HTGYRO_H__ #define __HTGYRO_H__ /** \file hitechnic-gyro-drv2.h * \brief customized HiTechnic Gyroscopic Sensor driver based on * \author <NAME> (xander_at_botbench.com) * \date 20 February 2011 * \version 0.4 * * Modifications: * 1) Changed calibration to use 100 readings every 5 ms (200HZ) * HT Gyro sampling os 300HZ per http://www.ev-3.net/en/archives/849 * 2) add auto calibration to compensate drifting if the ratotion speed is low * 3) add deadband calculation */ #pragma systemFile #include "hitechnic-sensormux.h" #ifndef __COMMON_H__ #include "common.h" #endif #define CAL_SAMPLE_SIZE 100 typedef struct { tI2CData I2CData; float rotation; float offset; float deadband; bool smux; tMUXSensor smuxport; } tHTGYRO, *tHTGYROPtr; bool initSensor(tHTGYROPtr htgyroPtr, tSensors port); bool initSensor(tHTGYROPtr htgyroPtr, tMUXSensor muxsensor); bool readSensor(tHTGYROPtr htgyroPtr); bool sensorCalibrate(tHTGYROPtr htgyroPtr); float HTGYROreadRot(tSensors link); float HTGYROstartCal(tSensors link); float HTGYROreadCal(tSensors link); // void HTGYROsetCal(tSensors link, short offset); #ifdef __HTSMUX_SUPPORT__ float HTGYROreadRot(tMUXSensor muxsensor); float HTGYROstartCal(tMUXSensor muxsensor); float HTGYROreadCal(tMUXSensor muxsensor); void HTGYROsetCal(tMUXSensor muxsensor, short offset); #endif // __HTSMUX_SUPPORT__ float HTGYRO_offsets[][] = {{620.0, 620.0, 620.0, 620.0}, /*!< Array for offset values. Default is 620 */ {620.0, 620.0, 620.0, 620.0}, {620.0, 620.0, 620.0, 620.0}, {620.0, 620.0, 620.0, 620.0}}; /** * Read the value of the gyro * @param link the HTGYRO port number * @return the value of the gyro */ float HTGYROreadRot(tSensors link) { // Make sure the sensor is configured as type sensorRawValue if (SensorType[link] != sensorAnalogInactive) { SensorType[link] = sensorAnalogInactive; sleep(100); } return (SensorValue[link] - HTGYRO_offsets[link][0]); } /** * Read the value of the gyro * @param muxsensor the SMUX sensor port number * @return the value of the gyro */ #ifdef __HTSMUX_SUPPORT__ float HTGYROreadRot(tMUXSensor muxsensor) { return HTSMUXreadAnalogue(muxsensor) - HTGYRO_offsets[SPORT(muxsensor)][MPORT(muxsensor)]; } #endif // __HTSMUX_SUPPORT__ /** * Calibrate the gyro by calculating the average offset of 100 raw readings. * @param link the HTGYRO port number * @return the new offset value for the gyro */ float HTGYROstartCal(tSensors link) { long _avgdata = 0; // Make sure the sensor is configured as type sensorRawValue if (SensorType[link] != sensorAnalogInactive) { SensorType[link] = sensorAnalogInactive; sleep(100); } // Take 50 readings and average them out for (short i = 0; i < CAL_SAMPLE_SIZE; i++) { _avgdata += SensorValue[link]; sleep(5); } // Store new offset HTGYRO_offsets[link][0] = (_avgdata / CAL_SAMPLE_SIZE); // Return new offset value return HTGYRO_offsets[link][0]; } /** * Calibrate the gyro by calculating the average offset of 100 raw readings. * @param muxsensor the SMUX sensor port number * @return the new offset value for the gyro */ #ifdef __HTSMUX_SUPPORT__ float HTGYROstartCal(tMUXSensor muxsensor) { long _avgdata = 0; // Take 100 readings and average them out for (short i = 0; i < CAL_SAMPLE_SIZE; i++) { _avgdata += HTSMUXreadAnalogue(muxsensor); sleep(5); } // Store new offset HTGYRO_offsets[SPORT(muxsensor)][MPORT(muxsensor)] = (_avgdata / CAL_SAMPLE_SIZE); // Return new offset value return HTGYRO_offsets[SPORT(muxsensor)][MPORT(muxsensor)]; } #endif // __HTSMUX_SUPPORT__ /** * Override the current offset for the gyro manually * @param link the HTGYRO port number * @param offset the new offset to be used */ //#define HTGYROsetCal(link, offset) HTGYRO_offsets[link][0] = offset void HTGYROsetCal(tSensors link, short offset) { HTGYRO_offsets[link][0] = offset; } /** * Override the current offset for the gyro manually * @param muxsensor the SMUX sensor port number * @param offset the new offset to be used */ #ifdef __HTSMUX_SUPPORT__ //#define HTGYROsetCal(muxsensor, offset) HTGYRO_offsets[SPORT(muxsensor)][MPORT(muxsensor)] = offset void HTGYROsetCal(tMUXSensor muxsensor, short offset) { HTGYRO_offsets[SPORT(muxsensor)][MPORT(muxsensor)] = offset; } #endif // __HTSMUX_SUPPORT__ /** * Retrieve the current offset for the gyro * @param link the HTGYRO port number * @return the offset value for the gyro */ float HTGYROreadCal(tSensors link) { return HTGYRO_offsets[link][0]; } /** * Retrieve the current offset for the gyro * @param muxsensor the SMUX sensor port number * @return the offset value for the gyro */ #ifdef __HTSMUX_SUPPORT__ float HTGYROreadCal(tMUXSensor muxsensor) { return HTGYRO_offsets[SPORT(muxsensor)][MPORT(muxsensor)]; } #endif // __HTSMUX_SUPPORT__ /** * Initialise the sensor's data struct and port * * @param htgyroPtr pointer to the sensor's data struct * @param port the sensor port * @return true if no error occured, false if it did */ bool initSensor(tHTGYROPtr htgyroPtr, tSensors port) { memset(htgyroPtr, 0, sizeof(tHTGYROPtr)); htgyroPtr->I2CData.port = port; htgyroPtr->I2CData.type = sensorAnalogActive; htgyroPtr->smux = false; // Ensure the sensor is configured correctly if (SensorType[htgyroPtr->I2CData.port] != htgyroPtr->I2CData.type) SensorType[htgyroPtr->I2CData.port] = htgyroPtr->I2CData.type; return true; } /** * Initialise the sensor's data struct and MUX port * * @param htgyroPtr pointer to the sensor's data struct * @param muxsensor the sensor MUX port * @return true if no error occured, false if it did */ bool initSensor(tHTGYROPtr htgyroPtr, tMUXSensor muxsensor) { memset(htgyroPtr, 0, sizeof(tHTGYROPtr)); htgyroPtr->I2CData.type = sensorI2CCustom; htgyroPtr->smux = true; htgyroPtr->smuxport = muxsensor; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ///This is a bug because I2CData.port is not init'd //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Ensure the sensor is configured correctly /* if (SensorType[htgyroPtr->I2CData.port] != htgyroPtr->I2CData.type) SensorType[htgyroPtr->I2CData.port] = htgyroPtr->I2CData.type; */ return HTSMUXsetAnalogueActive(muxsensor); } /** * Read all the sensor's data * * @param htgyroPtr pointer to the sensor's data struct * @return true if no error occured, false if it did */ bool readSensor(tHTGYROPtr htgyroPtr) { memset(htgyroPtr->I2CData.request, 0, sizeof(htgyroPtr->I2CData.request)); float raw=0; if (htgyroPtr->smux) raw = HTSMUXreadAnalogue(htgyroPtr->smuxport); else raw = SensorValue[htgyroPtr->I2CData.port]; htgyroPtr->rotation = raw - htgyroPtr->offset; if(abs(htgyroPtr->rotation)<htgyroPtr->deadband) htgyroPtr->rotation = 0; #ifdef GYRO_PRECISION if(abs(htgyroPtr->rotation)<GYRO_PRECISION) { htgyroPtr->offset=((CAL_SAMPLE_SIZE-10)*htgyroPtr->offset +10*raw)/CAL_SAMPLE_SIZE; } #endif return true; } bool sensorCalibrate(tHTGYROPtr htgyroPtr) { long avgdata = 0; // Take 50 readings and average them out for (short i = 0; i < CAL_SAMPLE_SIZE; i++) { if (htgyroPtr->smux) avgdata += HTSMUXreadAnalogue(htgyroPtr->smuxport); else avgdata += SensorValue[htgyroPtr->I2CData.port]; sleep(5); } htgyroPtr->offset = (avgdata*1.0) / CAL_SAMPLE_SIZE; //find deadband float raw_gyro=0; float min_raw=1023; float max_raw=0; for (short i = 0; i < CAL_SAMPLE_SIZE; i++) { if (htgyroPtr->smux) raw_gyro= HTSMUXreadAnalogue(htgyroPtr->smuxport)-htgyroPtr->offset; else raw_gyro= SensorValue[htgyroPtr->I2CData.port]-htgyroPtr->offset; if(raw_gyro>max_raw) { max_raw=raw_gyro; } if(raw_gyro<min_raw) { min_raw=raw_gyro; } sleep(5); } htgyroPtr->deadband=max_raw-min_raw; return true; } #endif // __HTGYRO_H__ /* @} */ /* @} */ <file_sep>/prototype/data/test11-28-03-no-update.c counts to turn: 1241, encoderLCount: 0, encoderRCount: 0, power: 100 counts to turn: 1241, encoderLCount: 0, encoderRCount: 0, power: 100, time: 1947575 counts to turn: 1241, encoderLCount: 0, encoderRCount: 0, power: 100, time: 1947596 counts to turn: 1241, encoderLCount: 15, encoderRCount: 13, power: 100, time: 1947616 counts to turn: 1241, encoderLCount: 27, encoderRCount: 26, power: 100, time: 1947637 counts to turn: 1241, encoderLCount: 72, encoderRCount: 62, power: 100, time: 1947660 counts to turn: 1241, encoderLCount: 122, encoderRCount: 109, power: 100, time: 1947681 counts to turn: 1241, encoderLCount: 148, encoderRCount: 154, power: 100, time: 1947702 counts to turn: 1241, encoderLCount: 195, encoderRCount: 177, power: 100, time: 1947723 counts to turn: 1241, encoderLCount: 219, encoderRCount: 231, power: 100, time: 1947743 counts to turn: 1241, encoderLCount: 260, encoderRCount: 253, power: 100, time: 1947764 counts to turn: 1241, encoderLCount: 281, encoderRCount: 303, power: 100, time: 1947785 counts to turn: 1241, encoderLCount: 329, encoderRCount: 356, power: 100, time: 1947805 counts to turn: 1241, encoderLCount: 373, encoderRCount: 384, power: 100, time: 1947826 counts to turn: 1241, encoderLCount: 418, encoderRCount: 441, power: 100, time: 1947847 counts to turn: 1241, encoderLCount: 442, encoderRCount: 510, power: 100, time: 1947871 counts to turn: 1241, encoderLCount: 493, encoderRCount: 569, power: 100, time: 1947892 counts to turn: 1241, encoderLCount: 541, encoderRCount: 598, power: 100, time: 1947913 counts to turn: 1241, encoderLCount: 572, encoderRCount: 658, power: 100, time: 1947934 counts to turn: 1241, encoderLCount: 620, encoderRCount: 718, power: 100, time: 1947954 counts to turn: 1241, encoderLCount: 645, encoderRCount: 746, power: 100, time: 1947975 counts to turn: 1241, encoderLCount: 695, encoderRCount: 810, power: 100, time: 1947998 counts to turn: 1241, encoderLCount: 721, encoderRCount: 882, power: 100, time: 1948019 counts to turn: 1241, encoderLCount: 782, encoderRCount: 912, power: 100, time: 1948041 counts to turn: 1241, encoderLCount: 836, encoderRCount: 973, power: 100, time: 1948062 counts to turn: 1241, encoderLCount: 864, encoderRCount: 1037, power: 100, time: 1948083 counts to turn: 1241, encoderLCount: 915, encoderRCount: 1069, power: 100, time: 1948104 counts to turn: 1241, encoderLCount: 963, encoderRCount: 1131, power: 100, time: 1948125 counts to turn: 1241, encoderLCount: 987, encoderRCount: 1161, power: 100, time: 1948146 counts to turn: 1241, encoderLCount: 1044, encoderRCount: 1235, power: 100, time: 1948167 counts to turn: 1241, encoderLCount: 1071, encoderRCount: 1297, power: 100, time: 1948188 counts to turn: 1241, encoderLCount: 1130, encoderRCount: 1338, power: 100, time: 1948209 counts to turn: 1241, encoderLCount: 1160, encoderRCount: 1376, power: 100, time: 1948229 counts to turn: 1241, encoderLCount: 1191, encoderRCount: 1381, power: 100, time: 1948250 counts to turn: 1241, encoderLCount: 1198, encoderRCount: 1383, power: 100, time: 1948271 counts to turn: 1241, encoderLCount: 1199, encoderRCount: 1383, power: 100, time: 1948291 counts to turn: 1241, encoderLCount: 1200, encoderRCount: 1385, power: 100, time: 1948312 counts to turn: 1241, encoderLCount: 1200, encoderRCount: 1388, power: 100, time: 1948333 counts to turn: 1241, encoderLCount: 1200, encoderRCount: 1391, power: 100, time: 1948353 counts to turn: 1241, encoderLCount: 1200, encoderRCount: 1392, power: 100, time: 1948373 counts to turn: 1241, encoderLCount: 1200, encoderRCount: 1392, power: 100, time: 1948394 counts to turn: 1241, encoderLCount: 1200, encoderRCount: 1392, power: 100, time: 1948415 counts to turn: 1241, encoderLCount: 1200, encoderRCount: 1392, power: 100, time: 1948436 counts to turn: 1241, encoderLCount: 1200, encoderRCount: 1392, power: 100, time: 1948457 counts to turn: 1241, encoderLCount: 1200, encoderRCount: 1392, power: 100, time: 1948478 counts to turn: 1241, encoderLCount: 1200, encoderRCount: 1392, power: 100, time: 1948501 counts to turn: 1241, encoderLCount: 1200, encoderRCount: 1392, power: 100, time: 1948522 counts to turn: 1241, encoderLCount: 0, encoderRCount: 0, power: 100 counts to turn: 1241, encoderLCount: 0, encoderRCount: 0, power: 100, time: 1953544 counts to turn: 1241, encoderLCount: 0, encoderRCount: 0, power: 100, time: 1953565 counts to turn: 1241, encoderLCount: 8, encoderRCount: 1, power: 100, time: 1953585 counts to turn: 1241, encoderLCount: 32, encoderRCount: 19, power: 100, time: 1953606 counts to turn: 1241, encoderLCount: 49, encoderRCount: 49, power: 100, time: 1953627 counts to turn: 1241, encoderLCount: 95, encoderRCount: 67, power: 100, time: 1953647 counts to turn: 1241, encoderLCount: 125, encoderRCount: 109, power: 100, time: 1953670 counts to turn: 1241, encoderLCount: 176, encoderRCount: 153, power: 100, time: 1953691 counts to turn: 1241, encoderLCount: 203, encoderRCount: 181, power: 100, time: 1953712 counts to turn: 1241, encoderLCount: 241, encoderRCount: 232, power: 100, time: 1953733 counts to turn: 1241, encoderLCount: 279, encoderRCount: 282, power: 100, time: 1953754 counts to turn: 1241, encoderLCount: 322, encoderRCount: 311, power: 100, time: 1953775 counts to turn: 1241, encoderLCount: 344, encoderRCount: 366, power: 100, time: 1953796 counts to turn: 1241, encoderLCount: 397, encoderRCount: 421, power: 100, time: 1953817 counts to turn: 1241, encoderLCount: 421, encoderRCount: 450, power: 100, time: 1953838 counts to turn: 1241, encoderLCount: 471, encoderRCount: 521, power: 100, time: 1953859 counts to turn: 1241, encoderLCount: 493, encoderRCount: 578, power: 100, time: 1953880 counts to turn: 1241, encoderLCount: 539, encoderRCount: 606, power: 100, time: 1953900 counts to turn: 1241, encoderLCount: 587, encoderRCount: 664, power: 100, time: 1953922 counts to turn: 1241, encoderLCount: 613, encoderRCount: 723, power: 100, time: 1953943 counts to turn: 1241, encoderLCount: 671, encoderRCount: 781, power: 100, time: 1953964 counts to turn: 1241, encoderLCount: 697, encoderRCount: 820, power: 100, time: 1953984 counts to turn: 1241, encoderLCount: 758, encoderRCount: 883, power: 100, time: 1954005 counts to turn: 1241, encoderLCount: 784, encoderRCount: 912, power: 100, time: 1954026 counts to turn: 1241, encoderLCount: 837, encoderRCount: 973, power: 100, time: 1954047 counts to turn: 1241, encoderLCount: 885, encoderRCount: 1034, power: 100, time: 1954068 counts to turn: 1241, encoderLCount: 910, encoderRCount: 1066, power: 100, time: 1954089 counts to turn: 1241, encoderLCount: 964, encoderRCount: 1128, power: 100, time: 1954113 counts to turn: 1241, encoderLCount: 1017, encoderRCount: 1170, power: 100, time: 1954134 counts to turn: 1241, encoderLCount: 1041, encoderRCount: 1232, power: 100, time: 1954155 counts to turn: 1241, encoderLCount: 1089, encoderRCount: 1296, power: 100, time: 1954176 counts to turn: 1241, encoderLCount: 1113, encoderRCount: 1335, power: 100, time: 1954197 counts to turn: 1241, encoderLCount: 1170, encoderRCount: 1395, power: 100, time: 1954218 counts to turn: 1241, encoderLCount: 1179, encoderRCount: 1407, power: 100, time: 1954238 counts to turn: 1241, encoderLCount: 1186, encoderRCount: 1415, power: 100, time: 1954261 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1417, power: 100, time: 1954285 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1417, power: 100, time: 1954306 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1419, power: 100, time: 1954326 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1423, power: 100, time: 1954347 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1425, power: 100, time: 1954367 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1426, power: 100, time: 1954390 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1428, power: 100, time: 1954411 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1428, power: 100, time: 1954432 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1428, power: 100, time: 1954453 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1428, power: 100, time: 1954474 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1428, power: 100, time: 1954495 counts to turn: 1241, encoderLCount: 1187, encoderRCount: 1428, power: 100, time: 1954516 counts:1119-off:118/100, encoderL: 0, encoderR: 0, power: 100,heading:0 time: 2029307 counts:1119-off:118/100, encoderL: 1, encoderR: 0, power: 100,heading:0 time: 2029328 counts:1119-off:118/100, encoderL: 15, encoderR: 16, power: 100,heading:0 time: 2029351 counts:1119-off:118/100, encoderL: 38, encoderR: 46, power: 100,heading:0 time: 2029371 counts:1119-off:118/100, encoderL: 55, encoderR: 84, power: 100,heading:0 time: 2029392 counts:1119-off:118/100, encoderL: 87, encoderR: 102, power: 100,heading:2 time: 2029414 counts:1119-off:118/100, encoderL: 108, encoderR: 151, power: 100,heading:4 time: 2029436 counts:1119-off:118/100, encoderL: 152, encoderR: 174, power: 100,heading:7 time: 2029457 counts:1119-off:118/100, encoderL: 191, encoderR: 222, power: 100,heading:11 time: 2029478 counts:1119-off:118/100, encoderL: 213, encoderR: 274, power: 100,heading:15 time: 2029499 counts:1119-off:118/100, encoderL: 257, encoderR: 304, power: 100,heading:18 time: 2029520 counts:1119-off:118/100, encoderL: 307, encoderR: 361, power: 100,heading:22 time: 2029542 counts:1119-off:118/100, encoderL: 336, encoderR: 420, power: 100,heading:27 time: 2029563 counts:1119-off:118/100, encoderL: 399, encoderR: 459, power: 100,heading:31 time: 2029585 counts:1119-off:118/100, encoderL: 425, encoderR: 519, power: 100,heading:35 time: 2029607 counts:1119-off:118/100, encoderL: 473, encoderR: 579, power: 100,heading:39 time: 2029629 counts:1119-off:118/100, encoderL: 522, encoderR: 641, power: 100,heading:43 time: 2029650 counts:1119-off:118/100, encoderL: 574, encoderR: 670, power: 100,heading:47 time: 2029671 counts:1119-off:118/100, encoderL: 598, encoderR: 733, power: 100,heading:53 time: 2029694 counts:1119-off:118/100, encoderL: 660, encoderR: 765, power: 100,heading:57 time: 2029715 counts:1119-off:118/100, encoderL: 692, encoderR: 837, power: 100,heading:61 time: 2029736 counts:1119-off:118/100, encoderL: 741, encoderR: 896, power: 100,heading:65 time: 2029758 counts:1119-off:118/100, encoderL: 791, encoderR: 956, power: 100,heading:69 time: 2029778 counts:1119-off:118/100, encoderL: 815, encoderR: 985, power: 100,heading:73 time: 2029799 counts:1119-off:118/100, encoderL: 863, encoderR: 1045, power: 100,heading:77 time: 2029820 counts:1119-off:118/100, encoderL: 916, encoderR: 1113, power: 0,heading:80 time: 2029843 counts:1119-off:118/100, encoderL: 973, encoderR: 1176, power: 0,heading:88 time: 2029883 counts:1119-off:118/100, encoderL: 979, encoderR: 1184, power: 0,heading:97 time: 2029924 counts:1119-off:118/100, encoderL: 981, encoderR: 1187, power: 0,heading:102 time: 2029965 counts:1119-off:118/100, encoderL: 981, encoderR: 1193, power: 0,heading:103 time: 2030006 counts:1119-off:118/100, encoderL: 0, encoderR: 0, power: 100,heading:99 time: 2035048 counts:1119-off:118/100, encoderL: 1, encoderR: 0, power: 100,heading:99 time: 2035069 counts:1119-off:118/100, encoderL: 7, encoderR: 11, power: 100,heading:99 time: 2035090 counts:1119-off:118/100, encoderL: 31, encoderR: 39, power: 100,heading:99 time: 2035111 counts:1119-off:118/100, encoderL: 46, encoderR: 76, power: 100,heading:99 time: 2035132 counts:1119-off:118/100, encoderL: 98, encoderR: 96, power: 100,heading:100 time: 2035153 counts:1119-off:118/100, encoderL: 144, encoderR: 140, power: 100,heading:101 time: 2035174 counts:1119-off:118/100, encoderL: 170, encoderR: 167, power: 100,heading:103 time: 2035196 counts:1119-off:118/100, encoderL: 210, encoderR: 214, power: 100,heading:105 time: 2035218 counts:1119-off:118/100, encoderL: 253, encoderR: 264, power: 100,heading:107 time: 2035241 counts:1119-off:118/100, encoderL: 274, encoderR: 315, power: 100,heading:110 time: 2035262 counts:1119-off:118/100, encoderL: 320, encoderR: 341, power: 100,heading:114 time: 2035283 counts:1119-off:118/100, encoderL: 342, encoderR: 396, power: 100,heading:119 time: 2035305 counts:1119-off:118/100, encoderL: 387, encoderR: 426, power: 100,heading:122 time: 2035326 counts:1119-off:118/100, encoderL: 422, encoderR: 498, power: 100,heading:126 time: 2035346 counts:1119-off:118/100, encoderL: 468, encoderR: 558, power: 100,heading:129 time: 2035367 counts:1119-off:118/100, encoderL: 512, encoderR: 587, power: 100,heading:133 time: 2035388 counts:1119-off:118/100, encoderL: 536, encoderR: 645, power: 100,heading:136 time: 2035409 counts:1119-off:118/100, encoderL: 589, encoderR: 708, power: 100,heading:140 time: 2035430 counts:1119-off:118/100, encoderL: 632, encoderR: 738, power: 100,heading:144 time: 2035451 counts:1119-off:118/100, encoderL: 655, encoderR: 808, power: 100,heading:150 time: 2035474 counts:1119-off:118/100, encoderL: 718, encoderR: 869, power: 100,heading:153 time: 2035496 counts:1119-off:118/100, encoderL: 768, encoderR: 897, power: 100,heading:157 time: 2035516 counts:1119-off:118/100, encoderL: 792, encoderR: 959, power: 100,heading:161 time: 2035539 counts:1119-off:118/100, encoderL: 843, encoderR: 1024, power: 100,heading:165 time: 2035560 counts:1119-off:118/100, encoderL: 884, encoderR: 1065, power: 0,heading:169 time: 2035582 counts:1119-off:118/100, encoderL: 919, encoderR: 1098, power: 0,heading:176 time: 2035623 counts:1119-off:118/100, encoderL: 922, encoderR: 1101, power: 0,heading:184 time: 2035665 counts:1119-off:118/100, encoderL: 921, encoderR: 1106, power: 0,heading:187 time: 2035705 counts:1119-off:118/100, encoderL: 921, encoderR: 1110, power: 0,heading:187 time: 2035746 counts:1119-off:118/100, encoderL: 0, encoderR: 0, power: 100,heading:184 time: 2040787 counts:1119-off:118/100, encoderL: 6, encoderR: 14, power: 100,heading:184 time: 2040808 counts:1119-off:118/100, encoderL: 27, encoderR: 26, power: 100,heading:184 time: 2040829 counts:1119-off:118/100, encoderL: 45, encoderR: 66, power: 100,heading:184 time: 2040850 counts:1119-off:118/100, encoderL: 95, encoderR: 107, power: 100,heading:184 time: 2040871 counts:1119-off:118/100, encoderL: 140, encoderR: 130, power: 100,heading:185 time: 2040891 counts:1119-off:118/100, encoderL: 161, encoderR: 176, power: 100,heading:186 time: 2040912 counts:1119-off:118/100, encoderL: 210, encoderR: 208, power: 100,heading:188 time: 2040933 counts:1119-off:118/100, encoderL: 252, encoderR: 258, power: 100,heading:192 time: 2040954 counts:1119-off:118/100, encoderL: 272, encoderR: 309, power: 100,heading:195 time: 2040975 counts:1119-off:118/100, encoderL: 320, encoderR: 334, power: 100,heading:198 time: 2040996 counts:1119-off:118/100, encoderL: 340, encoderR: 389, power: 100,heading:202 time: 2041017 counts:1119-off:118/100, encoderL: 383, encoderR: 448, power: 100,heading:205 time: 2041038 counts:1119-off:118/100, encoderL: 427, encoderR: 479, power: 100,heading:208 time: 2041059 counts:1119-off:118/100, encoderL: 455, encoderR: 547, power: 100,heading:211 time: 2041080 counts:1119-off:118/100, encoderL: 502, encoderR: 577, power: 100,heading:215 time: 2041100 counts:1119-off:118/100, encoderL: 526, encoderR: 637, power: 100,heading:218 time: 2041121 counts:1119-off:118/100, encoderL: 579, encoderR: 696, power: 100,heading:222 time: 2041142 counts:1119-off:118/100, encoderL: 605, encoderR: 725, power: 100,heading:226 time: 2041163 counts:1119-off:118/100, encoderL: 651, encoderR: 782, power: 100,heading:233 time: 2041187 counts:1119-off:118/100, encoderL: 698, encoderR: 851, power: 100,heading:236 time: 2041209 counts:1119-off:118/100, encoderL: 756, encoderR: 911, power: 100,heading:240 time: 2041230 counts:1119-off:118/100, encoderL: 779, encoderR: 940, power: 100,heading:244 time: 2041251 counts:1119-off:118/100, encoderL: 829, encoderR: 998, power: 100,heading:248 time: 2041274 counts:1119-off:118/100, encoderL: 861, encoderR: 1061, power: 100,heading:252 time: 2041295 counts:1119-off:118/100, encoderL: 916, encoderR: 1102, power: 0,heading:257 time: 2041316 counts:1119-off:118/100, encoderL: 964, encoderR: 1158, power: 0,heading:265 time: 2041357 counts:1119-off:118/100, encoderL: 970, encoderR: 1162, power: 0,heading:271 time: 2041398 counts:1119-off:118/100, encoderL: 970, encoderR: 1166, power: 0,heading:276 time: 2041439 counts:1119-off:118/100, encoderL: 970, encoderR: 1171, power: 0,heading:276 time: 2041480 <file_sep>/prototype/PhiloTeleOP.c #pragma config(Hubs, S1, HTMotor, HTMotor, none, none) #pragma config(Hubs, S2, HTMotor, HTServo, none, none) #pragma config(Hubs, S3, HTMotor, HTServo, HTServo, none) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S2, , sensorI2CMuxController) #pragma config(Sensor, S3, , sensorI2CMuxController) #pragma config(Sensor, S4, sonarSensor, sensorSONAR) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, MidR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C2_2, MidL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_1, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S2_C2_1, flapper1, tServoStandard) #pragma config(Servo, srvo_S2_C2_2, flapper2, tServoStandard) #pragma config(Servo, srvo_S2_C2_3, servo3, tServoNone) #pragma config(Servo, srvo_S2_C2_4, servo4, tServoNone) #pragma config(Servo, srvo_S2_C2_5, servo5, tServoNone) #pragma config(Servo, srvo_S2_C2_6, servo6, tServoNone) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, lift, tServoStandard) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_6, faucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_1, flapper3, tServoStandard) #pragma config(Servo, srvo_S3_C3_2, servo14, tServoNone) #pragma config(Servo, srvo_S3_C3_3, servo15, tServoNone) #pragma config(Servo, srvo_S3_C3_4, servo16, tServoNone) #pragma config(Servo, srvo_S3_C3_5, servo17, tServoNone) #pragma config(Servo, srvo_S3_C3_6, servo18, tServoNone) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #ifndef JOYSTICK_DRIVER_INCLDUDED #define JOYSTICK_DRIVER_INCLDUDED #include "JoystickDriver.c" #endif #include "bouncy-button.c" // These are the toggle buttons to control different // subsystems as their names suggested // TBouncyBtn flapBtn, rakeBtn, fanBtn, flapperBtn, nitro, flapRevBtn; bool flapDown = false; int motorScale = 70; bool forwardFlap = true; bool revFlap = false; //************************************************************* // Tank Drive Control for the west coast drive // // Parameters: // @rawLeftJoy raw reading from the left joystick // @rawRightJoy raw reading from the right joystick //************************************************************* void controlDrive(int rawLeftJoy, int rawRightJoy){ int leftJoy=0; int rightJoy=0; if(abs(rawLeftJoy/128.0*motorScale) > 5) leftJoy=rawLeftJoy/128.0*motorScale; else leftJoy = 0; if(abs(rawRightJoy/128.0*motorScale) > 5) rightJoy=rawRightJoy/128.0*motorScale; else rightJoy = 0; motor[FrontR] =-rightJoy; motor[FrontL] = leftJoy; motor[BackR] = -rightJoy; motor[BackL] = leftJoy; motor[MidR] = -rightJoy; motor[MidL] = leftJoy; } //************************************************************** // Control the lift servo using a joystick // Parameters // @rawJoy raw reading of the joystick that controls the lift // //*******************q******************************************* #define MAX_LIFT 249 //highest position for lift servo #define MIN_LIFT 12 //lowest position for lift servo void controlLift( int rawJoy){ rawJoy = -rawJoy; //80 full joystick pushes to move lift from 0 to max position //this control the sensitivity and the less sensitive the joystick is // the more accurate control can be, but the slower the lift const int lift_per_step=(MAX_LIFT)/80; if(abs(rawJoy)<5){ //this might be needed for continuous rotation servo //but we did not have it last time servo[lift]=127; return; } // fraction of the joystick movement float raw=rawJoy/128.0; // convert joystick movement to steps of the servo int steps_to_move = raw * lift_per_step; int current_lift = ServoValue[lift]; current_lift += steps_to_move; if(current_lift<MIN_LIFT) current_lift=MIN_LIFT; if(current_lift>MAX_LIFT) current_lift=MAX_LIFT; servo[lift] = current_lift; writeDebugStreamLine("steps:%d, raw: %d, current lift: %d", steps_to_move, rawJoy, current_lift); } void controlFans(){ if(!BouncyBtn_checkAndClear(fanBtn)){ return; } writeDebugStreamLine("fan pressed"); static bool wasOnLastTime = false; if(!wasOnLastTime){ motor[FanL] = -100; motor[FanR] = 100; wasOnLastTime = true; } else{ motor[FanL] = 0; motor[FanR] = 0; wasOnLastTime = false; } } void controlRakes() { if (!BouncyBtn_checkAndClear(rakeBtn)) return; writeDebugStreamLine("rake pressed"); static bool wasOnLastTime = false; if (wasOnLastTime) { servo[rakes] = 128; wasOnLastTime = false; } else { servo [rakes] = 255; wasOnLastTime = true; } } void controlFlap() { if (!BouncyBtn_checkAndClear(flapBtn)) return; writeDebugStreamLine("flap pressed"); static bool wasOnLastTime = false; if (wasOnLastTime) { servo[flap] = 0; flapDown = false; wasOnLastTime = false; } else { servo [flap] = 250; flapDown = true; wasOnLastTime = true; } } void nitroCheck(){ if(!BouncyBtn_checkAndClear(nitro)){ return; } writeDebugStreamLine("boost pressed"); static bool wasOnLastTime = false; if(!wasOnLastTime){ motorScale = 100; wasOnLastTime = true; } else{ motorScale = 30; wasOnLastTime = false; } } void controlFaucet(bool faucetLeft, bool faucetRight) { if (!faucetRight && !faucetLeft){ servo [faucet] = 127; } else if(faucetRight){ servo [faucet] = 255; }else if(faucetLeft){ servo [faucet] = 0; } } #define GRABBER_UP 100 #define GRABBER_DOWN 20 void controlGoalGrabber() { switch(joystick.joy1_TopHat) { case 0: //up servo[trailerR] = GRABBER_UP; servo[trailerL] = 255-GRABBER_UP; writeDebugStreamLine("Grabber Position for up:%d", ServoValue[trailerR]); break; case 4://down servo[trailerR] = GRABBER_DOWN; servo[trailerL] = 255-GRABBER_DOWN; writeDebugStreamLine("Grabber Position for down:%d", ServoValue[trailerR]); break; default: //do nothing for other cases } } //////////////////////////////////////////////////////////////////// // // initializeRobot // // Prior to the start of tele-op mode, you may want to perform some // initialization on your robot // and the variables within your program. // // In most cases, you may not have to add any code to this function // and it will remain "empty". // //////////////////////////////////////////////////////////////////// void initializeRobot() { // Place code here to sinitialize servos to starting positions. // Sensors are automatically configured and setup by ROBOTC. // They may need a brief time to stabilize. BouncyBtn_init(fanBtn,false, 2); //on joy2, btn#2 BouncyBtn_init(flapBtn,false,1); //on joy2, btn#4 // and so on ... BouncyBtn_init(flapperBtn,true,7); BouncyBtn_init(nitro, true, 6); BouncyBtn_init(flapRevBtn, false, 8); //BouncyBtn_init(rakeBtn,true,6); //on joy1, btn#6 servo[lift] = MIN_LIFT; servo[flap] = 0; servo[trailerR] = GRABBER_UP; servo[trailerL] = 255-GRABBER_UP; //keep goal servoChangeRate[trailerL]=0; servoChangeRate[trailerR]=0; return; } void flappersTurn() { if(!BouncyBtn_checkAndClear(flapperBtn)){ return; } writeDebugStreamLine("flapper pressed"); static bool wasOnLastTime = false; if(forwardFlap){ if(!wasOnLastTime){ servo[flapper1] =255; servo[flapper2] = 255; servo[flapper3] = 255; wasOnLastTime = true; forwardFlap =true; } else{ servo[flapper1] =128; servo[flapper2] = 128; servo[flapper3] = 128; wasOnLastTime = false; forwardFlap =true; } }else { servo[flapper1] =128; servo[flapper2] = 128; servo[flapper3] = 128; wasOnLastTime = false; forwardFlap = false; } } void flappersTurnRev() { if(!BouncyBtn_checkAndClear(flapRevBtn)){ return; } writeDebugStreamLine("flapper pressed"); static bool wasOnLastTime = false; if(!forwardFlap){ if(!wasOnLastTime){ servo[flapper1] =0; servo[flapper2] = 0; servo[flapper3] = 0; wasOnLastTime = true; forwardFlap =false;} else{ servo[flapper1] =128; servo[flapper2] = 128; servo[flapper3] = 128; wasOnLastTime = false; forwardFlap =false; } }else{ servo[flapper1] =128; servo[flapper2] = 128; servo[flapper3] = 128; wasOnLastTime = false; forwardFlap =true; } } task main() { initializeRobot(); //Uncomment this for real competition waitForStart(); // wait for start of tele-op phase //set everything while (true) { getJoystickSettings(joystick); BouncyBtn_debounce(flapBtn); BouncyBtn_debounce(fanBtn); BouncyBtn_debounce(flapperBtn); //BouncyBtn_debounce(rakeBtn); BouncyBtn_debounce(nitro); BouncyBtn_debounce(flapRevBtn); int rawLeftJoy=joystick.joy1_y1; int rawRightJoy=joystick.joy1_y2; int rawRightJoy2 = joystick.joy2_y2; controlDrive(rawLeftJoy, rawRightJoy); controlFans(); controlFlap(); flappersTurn(); nitroCheck(); //controlRakes(); controlFaucet(joy2Btn(5), joy2Btn(6)); controlLift(rawRightJoy2); controlGoalGrabber(); sleep(10); } } <file_sep>/competition/Ramp_test.c #pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, HTServo) #pragma config(Hubs, S3, HTMotor, HTServo, HTServo, HTServo) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S2, HTSPB, sensorI2CCustomFastSkipStates9V) #pragma config(Sensor, S3, , sensorI2CMuxController) #pragma config(Sensor, S4, HTMUX, sensorI2CCustomFastSkipStates9V) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, MidR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_2, MidL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C3_1, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C3_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S1_C4_1, flapper1, tServoStandard) #pragma config(Servo, srvo_S1_C4_2, flapper2, tServoStandard) #pragma config(Servo, srvo_S1_C4_3, servo3, tServoNone) #pragma config(Servo, srvo_S1_C4_4, servo4, tServoNone) #pragma config(Servo, srvo_S1_C4_5, servo5, tServoNone) #pragma config(Servo, srvo_S1_C4_6, servo6, tServoNone) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, lift, tServoStandard) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_6, faucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_1, flapper3, tServoStandard) #pragma config(Servo, srvo_S3_C3_2, spout, tServoStandard) #pragma config(Servo, srvo_S3_C3_3, hingeFaucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_4, servo16, tServoNone) #pragma config(Servo, srvo_S3_C3_5, servo17, tServoNone) #pragma config(Servo, srvo_S3_C3_6, servo18, tServoNone) #pragma config(Servo, srvo_S3_C4_1, foldRoller, tServoStandard) #pragma config(Servo, srvo_S3_C4_2, roller, tServoStandard) #pragma config(Servo, srvo_S3_C4_3, servo21, tServoNone) #pragma config(Servo, srvo_S3_C4_4, servo22, tServoNone) #pragma config(Servo, srvo_S3_C4_5, servo23, tServoNone) #pragma config(Servo, srvo_S3_C4_6, servo24, tServoNone) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "PhiloDefs.h" #include "WestCoaster.h" #include "CenterGoalUs.h" #include "PhiloUtils.h" #include "JoystickDriver.c" #include "hitechnic-gyro-task.h" WestCoaster g_wcDrive; void swagger(bool right, unsigned int time, int domPower){ if(right){ motor[FrontR] = domPower; motor[BackR] = domPower; motor[FrontL] = -(domPower-20); motor[BackL] = -(domPower-20); } else{ motor[FrontL] = -domPower; motor[BackL] = -domPower; motor[FrontR] = (domPower-25); motor[BackR] = (domPower-25); } unsigned long timeStart =nSysTime; while(nSysTime < timeStart + time){}; WestCoaster_allMotorsPowerStraight(g_wcDrive, 0); } void wiggleMove() { WestCoaster_controlledEncoderObservedTurn(g_wcDrive,-15,35); WestCoaster_controlledStraightMove(g_wcDrive, -7,20); WestCoaster_controlledEncoderObservedTurn(g_wcDrive,30,35); WestCoaster_controlledStraightMove(g_wcDrive, -7,20); WestCoaster_controlledEncoderObservedTurn(g_wcDrive,-15,35); WestCoaster_controlledStraightMove(g_wcDrive, -7,20); } void grabGoal() { //you know what, we could re-use the center goal method // that is so cool! //driveToGoal(g_wcDrive, CENTER_GOAL_SONAR, 25/2.54, 30); wiggleMove(); servo[trailerR] = GRABBER_DOWN; servo[trailerL] = 255-GRABBER_DOWN; sleep(200); writeDebugStreamLine("Grabber Position:%d", ServoValue[trailerR]); } void initializeRobot() { servo[lift] = LIFT_BOTTOM; WestCoaster_init(g_wcDrive,BackL, FrontL, MidL, MidR, BackL, BackR, BackL, FrontL); WestCoaster_initMPUPID(S2); /*startTask(gyro_loop); while(gyro_loop_state!=GYRO_READING) { sleep(20); }*/ servo[trailerR] = GRABBER_UP; servo[trailerL] = 255-GRABBER_UP; servo[flapper1] =FLAPPER_STOP; servo[flapper2] = FLAPPER_STOP; servo[flapper3] = FLAPPER_STOP; servo[spout]= SPOUT_IN; servo[foldRoller] = 70;//14 servo[roller] = 127; servo[hingeFaucet] = 0; //move servos at maximium speed servoChangeRate[trailerL]=0; servoChangeRate[trailerR]=0; //set to true during competition to keep the grabber engaged bSystemLeaveServosEnabledOnProgramStop=false; } #define ALIGN_FAUCET_TO_CENTER 50 //milliseconds to align faucet #define OFF_RAMP_DIST 58 //platform and ramp measure 58 inches long #define GOAL_CENTER_TO_EDGE 11.6/2 #define FAUCET_EXTEND_BACK_CENTER GOAL_CENTER_TO_EDGE+0.5 //measure from the center of the drop to the edge of robot task main(){ initializeRobot(); // waitForStart(); /* sleep(1000); servo[foldRoller] = ROLLER_FOLDER_DOWN; sleep(1000); servo[foldRoller] = ROLLER_FOLDER_UP; sleep(1000); */ //=============== // TESTS // /** * ***Turn and move with MPU with speed ramp up*** ** WestCoaster_turnWithMPU(g_wcDrive, -90,20); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, 90,20); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, -20,20); sleep(2000); WestCoaster_turnWithMPU(g_wcDrive, 20,20); */ WestCoaster_moveStraightWithMPU(g_wcDrive, -160,50); sleep(2000); WestCoaster_moveStraightWithMPU(g_wcDrive, 160,50); sleep(2000); WestCoaster_moveStraightWithMPU(g_wcDrive, -20,50); sleep(2000); WestCoaster_moveStraightWithMPU(g_wcDrive, 60,50); // WestCoaster_controlledEncoderObservedTurn(g_wcDrive,90,35); //sleep(1500); /* WestCoaster_controlledEncoderObservedTurn(g_wcDrive,-90,75); sleep(1500); WestCoaster_controlledEncoderObservedTurn(g_wcDrive,180,75); sleep(1500); WestCoaster_controlledEncoderObservedTurn(g_wcDrive,-180,75); */ // WestCoaster_controlledEncoderObservedTurn(g_wcDrive,60,35); //======================================================================= //back off the ramp, 56.9 inches from edge of field to front of bot //back of bot is 56.9+18=74.9 inches from edge of field // center of 60cm goal is 4.5*24=108 inches from edge //so need to move 108-74.9 to the center // then subtract the goal and robot faucet extents // and half-inch safety margin*/ /*OFF_RAMP_DIST +108 - 74.9 -FAUCET_EXTEND_BACK_CENTER -0.5;*/ float distance_to_60cm =-72; //go down the ramp //sleep(1000); // WestCoaster_controlledStraightMove(g_wcDrive, distance_to_60cm, 35); sleep(1000); //grabGoal(); sleep(1000); /*sleep(1000); //drop the little one readyFaucet(); sleep(1000); servo[hingeFaucet] = HINGE_FAUCET_FLIP; sleep(3000); WestCoaster_pidMPUTurn(g_wcDrive,30); sleep(1000); //deadReck sleep(1000); servo[spout] = SPOUT_OUT; //go grab another on // //fansOn(3000); */ } <file_sep>/competition/dbgtrace.h #if 0 /// Copyright (c) Titan Robotics Club. All rights reserved. /// /// <module name="dbgtrace.h" /> /// /// <summary> /// This module contains the tracing functions and definitions. /// </summary> /// /// <remarks> /// Environment: RobotC for Lego Mindstorms NXT. /// </remarks> #endif #ifndef _DBGTRACE_H #define _DBGTRACE_H #pragma systemFile // // Constants. // #ifndef TRACE_MODULES #define TRACE_MODULES 0 #endif #ifndef TRACE_LEVEL #define TRACE_LEVEL TASK #endif #ifndef MSG_LEVEL #define MSG_LEVEL INFO #endif // // Module ID. // #define MOD_LIB 0xfffffff0 #define MOD_GEN_MASK 0x0000000f #define MOD_BATT 0x00000010 #define MOD_MENU 0x00000020 #define MOD_NXTBTN 0x00000040 #define MOD_JOYSTICK 0x00000080 #define MOD_TIMER 0x00000100 #define MOD_SM 0x00000200 #define MOD_KALMAN 0x00000400 #define MOD_ANALOG 0x00000800 #define MOD_SENSOR 0x00001000 #define MOD_ENCODER 0x00002000 #define MOD_ACCEL 0x00004000 #define MOD_GYRO 0x00008000 #define MOD_COMPASS 0x00010000 #define MOD_TOUCH 0x00020000 #define MOD_IRSEEKER 0x00040000 #define MOD_RADAR 0x00080000 #define MOD_SERVO 0x00100000 #define MOD_PIDCTRL 0x00200000 #define MOD_DRIVE 0x00400000 #define MOD_PIDDRIVE 0x00800000 #define MOD_PIDMOTOR 0x01000000 #define MOD_LNFOLLOW 0x02000000 #define MOD_WALLFOLLOW 0x04000000 #define MOD_MAIN 0x00000001 #define TGenModId(n) ((MOD_MAIN << (n)) && MOD_GEN_MASK) #define INIT 0 #define API 1 #define CALLBK 2 #define EVENT 3 #define FUNC 4 #define TASK 5 #define UTIL 6 #define HIFREQ 7 #define FATAL 0 #define ERR 1 #define WARN 2 #define INFO 3 #define VERBOSE 4 #ifndef TRACE_PERIOD #define TRACE_PERIOD 500 //in msec #endif #ifndef SAMPLING_PERIOD #define SAMPLING_PERIOD 500 //in msec #endif #define TPrintf writeDebugStream #define TPrintfLine writeDebugStreamLine // // Trace macros. // #ifdef _DEBUG_TRACE #define TModEnterMsg(m,p) if (g_TraceEnabled && \ ((g_TraceModules & (m)) != 0) && \ (_levelTrace <= g_TraceLevel)) \ { \ TracePrefix(_pszFuncName, true, false); \ TPrintf p; \ TPrintf(")\n"); \ } #define TModEnter(m) if (g_TraceEnabled && \ ((g_TraceModules & (m)) != 0) && \ (_levelTrace <= g_TraceLevel)) \ { \ TracePrefix(_pszFuncName, true, true); \ } #define TModExitMsg(m,p) if (g_TraceEnabled && \ ((g_TraceModules & (m)) != 0) && \ (_levelTrace <= g_TraceLevel)) \ { \ TracePrefix(_pszFuncName, false, false); \ TPrintfLine p; \ } #define TModExit(m) if (g_TraceEnabled && \ ((g_TraceModules & (m)) != 0) && \ (_levelTrace <= g_TraceLevel)) \ { \ TracePrefix(_pszFuncName, false, true); \ } #define TModMsg(m,e,p) if (g_TraceEnabled && \ ((g_TraceModules & (m)) != 0) && \ ((e) <= g_MsgLevel)) \ { \ MsgPrefix(_pszFuncName, e); \ TPrintfLine p; \ } #define TraceInit(m,l,e) { \ g_TraceModules = (m); \ g_TraceLevel = (l); \ g_MsgLevel = (e); \ g_TraceEnabled = false; \ g_TraceTime = nPgmTime; \ } #define TEnable(b) g_TraceEnabled = b #define TFuncName(s) char *_pszFuncName = s #define TLevel(l) int _levelTrace = l #define TEnterMsg(p) TModEnterMsg(MOD_ID, p) #define TEnter() TModEnter(MOD_ID) #define TExitMsg(p) TModExitMsg(MOD_ID, p) #define TExit() TModExit(MOD_ID) #define TMsg(e,p) TModMsg(MOD_ID, e, p) #define TFatal(p) TModMsg(MOD_ID, FATAL, p) #define TErr(p) TModMsg(MOD_ID, ERR, p) #define TWarn(p) TModMsg(MOD_ID, WARN, p) #define TInfo(p) TModMsg(MOD_ID, INFO, p) #define TVerbose(p) TModMsg(MOD_ID, VERBOSE, p) #define TMsgPeriod(t,p) { \ static unsigned long _nextTime = nPgmTime; \ if (nPgmTime >= _nextTime) \ { \ _nextTime = nPgmTime + (t); \ TModMsg(MOD_ID, INFO, p); \ } \ } #define TSampling(p) TMsgPeriod(SAMPLING_PERIOD, p) #define TAssertPeriod(t,p,r) { \ unsigned long _currTime = nPgmTime; \ unsigned long _period = _currTime - (t); \ t = _currTime; \ if (abs(_period - (p)) > (r)) \ { \ TWarn(("AssertPeriod=%f", _period)); \ } \ } #define TPeriodStart() if (nPgmTime >= g_TraceTime) \ { \ g_TraceTime = nPgmTime + TRACE_PERIOD; \ TEnable(true); \ } #define TPeriodEnd() TEnable(false) #else #define TraceInit(m,l,e) #define TEnable(b) #define TFuncName(s) #define TLevel(l) #define TEnterMsg(p) #define TEnter() #define TExitMsg(p) #define TExit() #define TMsg(e,p) #define TFatal(p) #define TErr(p) #define TWarn(p) #define TInfo(p) #define TVerbose(p) #define TMsgPeriod(t,p) #define TSampling(p) #define TAssertPeriod(t,p,r) #define TPeriodStart() #define TPeriodEnd() #endif //ifdef _DEBUG_TRACE #ifdef _DEBUG_TRACE unsigned long g_TraceModules = 0; int g_TraceLevel = 0; int g_MsgLevel = 0; int g_IndentLevel = 0; bool g_TraceEnabled = false; unsigned long g_TraceTime = 0; /** * This function prints the trace prefix string to the debug stream. * * @param pszFuncName Specifies the function name. * @param fEnter Specifies whether this is a TEnter or TExit. * @param fNewLine Specifies whether it should print a newline. */ void TracePrefix( char *pszFuncName, bool fEnter, bool fNewLine ) { if (fEnter) { g_IndentLevel++; } for (int i = 0; i < g_IndentLevel; ++i) { TPrintf("| "); } TPrintf(pszFuncName); if (fEnter) { TPrintf(fNewLine? "()\n": "("); } else { TPrintf(fNewLine? "!\n": "!"); g_IndentLevel--; } return; } //TracePrefix /** * This function prints the message prefix string to the debug stream. * * @param pszFuncName Specifies the function name. * @param msgLevel Specifies the message level. */ void MsgPrefix( char *pszFuncName, int msgLevel ) { char *pszPrefix; switch (msgLevel) { case FATAL: pszPrefix = "_Fatal:"; break; case ERR: pszPrefix = "_Err:"; break; case WARN: pszPrefix = "_Warn:"; break; case INFO: pszPrefix = "_Info:"; break; case VERBOSE: pszPrefix = "_Verbose:"; break; default: pszPrefix = "_Unk:"; break; } TPrintf("%s%s", pszFuncName, pszPrefix); return; } //MsgPrefix #endif //ifdef _DEBUG_TRACE #endif //ifndef _DBGTRACE_H <file_sep>/competition/PhiloTeleOP.c #pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, none) #pragma config(Hubs, S3, HTMotor, HTServo, HTServo, none) #pragma config(Hubs, S4, HTServo, none, none, none) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S2, HTSPB, sensorI2CCustomFastSkipStates9V) #pragma config(Sensor, S3, , sensorI2CMuxController) #pragma config(Sensor, S4, HTMUX, sensorI2CMuxController) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, Lift, tmotorTetrix, PIDControl, encoder) #pragma config(Motor, mtr_S1_C2_2, Flapper, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C3_1, BackR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C3_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, servo3, tServoNone) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, servo5, tServoNone) #pragma config(Servo, srvo_S3_C2_6, servo12, tServoStandard) #pragma config(Servo, srvo_S3_C3_1, servo13, tServoStandard) #pragma config(Servo, srvo_S3_C3_2, spout, tServoStandard) #pragma config(Servo, srvo_S3_C3_3, faucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_4, servo16, tServoStandard) #pragma config(Servo, srvo_S3_C3_5, servo17, tServoStandard) #pragma config(Servo, srvo_S3_C3_6, servo18, tServoStandard) #pragma config(Servo, srvo_S4_C1_1, foldRoller, tServoStandard) #pragma config(Servo, srvo_S4_C1_2, roller, tServoStandard) #pragma config(Servo, srvo_S4_C1_3, roller2, tServoStandard) #pragma config(Servo, srvo_S4_C1_4, servo22, tServoStandard) #pragma config(Servo, srvo_S4_C1_5, servo23, tServoNone) #pragma config(Servo, srvo_S4_C1_6, servo24, tServoNone) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "PhiloDefs.h" #include "PhiloUtils.h" #ifndef JOYSTICK_DRIVER_INCLDUDED #define JOYSTICK_DRIVER_INCLDUDED #include "JoystickDriver.c" #endif #include "BouncyButton.h" // These are the toggle buttons to control different // subsystems as their names suggested // TBouncyBtn fanBtn, flapperBtn, nitro, flapRevBtn, hingeFaucetBtn, foldRollBtn, rollerBtn, rollRevBtn, spoutBtn, thirtyBtn, sixtyBtn, ninetyBtn, oneTwentyBtn; int motorScale = 70; //************************************************************* // Tank Drive Control for the west coast drive // // Parameters: // @rawLeftJoy raw reading from the left joystick // @rawRightJoy raw reading from the right joystick //************************************************************* void controlDrive(int rawLeftJoy, int rawRightJoy){ int leftJoy=0; int rightJoy=0; if(abs(rawLeftJoy/128.0*motorScale) > 5) leftJoy=rawLeftJoy/128.0*motorScale; else leftJoy = 0; if(abs(rawRightJoy/128.0*motorScale) > 5) rightJoy=rawRightJoy/128.0*motorScale; else rightJoy = 0; motor[FrontR] =-rightJoy; motor[FrontL] = leftJoy; motor[BackR] = -rightJoy; motor[BackL] = leftJoy; } //************************************************************** // Control the lift servo using a joystick // Parameters // @rawJoy raw reading of the joystick that controls the lift // //*******************q******************************************* void controlLift( int rawJoy){ //TODO int cm=rawJoy/30; moveLift(cm); } void controlFans(){ if(!BouncyBtn_checkAndClear(fanBtn)){ return; } writeDebugStreamLine("fan pressed"); static bool wasOnLastTime = false; if(!wasOnLastTime){ motor[FanL] = -100; motor[FanR] = 100; wasOnLastTime = true; } else{ motor[FanL] = 0; motor[FanR] = 0; wasOnLastTime = false; } } void nitroCheck(){ if(!BouncyBtn_checkAndClear(nitro)){ return; } writeDebugStreamLine("boost pressed"); static bool wasOnLastTime = false; if(!wasOnLastTime){ motorScale = 100; wasOnLastTime = true; } else{ motorScale = 30; wasOnLastTime = false; } } void liftToThirty() { if(!BouncyBtn_checkAndClear(thirtyBtn)){ return; } writeDebugStreamLine("thirty engaged"); liftGoUp(LIFT_BOTTOM_HEIGHT); } void liftToSixty() { if(!BouncyBtn_checkAndClear(sixtyBtn)){ return; } writeDebugStreamLine("sixty engaged"); liftGoUp(LIFT_60CM_HEIGHT); } void liftToNinety () { if(!BouncyBtn_checkAndClear(ninetyBtn)){ return; } writeDebugStreamLine("ninety engaged"); liftGoUp(LIFT_90CM_HEIGHT); } void liftToOneTwenty () { if(!BouncyBtn_checkAndClear(oneTwentyBtn)){ return; } writeDebugStreamLine("onetwenty engaged"); liftGoUp(LIFT_TOP_HEIGHT); } void controlGoalGrabber() { switch(joystick.joy1_TopHat) { case 0: //up goalGrabberUp(); writeDebugStreamLine("Grabber Position for up:%d", ServoValue[trailerR]); break; case 4://down goalGrabberDown(); writeDebugStreamLine("Grabber Position for down:%d", ServoValue[trailerR]); break; default: //do nothing for other cases } } void hingeFaucetOn(){ if(!BouncyBtn_checkAndClear(hingeFaucetBtn)){ return; } writeDebugStreamLine("faucet engaged"); static bool wasOnLastTime = false; if(!wasOnLastTime){ faucetDeployed(); wasOnLastTime = true; } else{ faucetInitial(); wasOnLastTime = false; } } /* void rollerOn(){ if(!BouncyBtn_checkAndClear(rollerBtn)){ return; } writeDebugStreamLine("roller rolling"); static bool wasOnLastTime = false; if(!wasOnLastTime){ servo[roller] = 250; servo[roller2]=0 wasOnLastTime = true; } else{ servo[roller] = 126; servo[roller2]=127; wasOnLastTime = false; } } */ void foldRollerOn(){ if(!BouncyBtn_checkAndClear(foldRollBtn)){ return; } writeDebugStreamLine("roller engaged"); static bool wasRollerOnLastTime = false; if(!wasRollerOnLastTime){ servo[foldRoller] = ROLLER_FOLDER_UP; wasRollerOnLastTime = true; } else{ servo[foldRoller] = ROLLER_FOLDER_DOWN; wasRollerOnLastTime = false; } } void spoutOn(){ if(!BouncyBtn_checkAndClear(spoutBtn)){ return; } writeDebugStreamLine("spout engaged"); static bool wasSpoutOnLastTime = false; if(!wasSpoutOnLastTime){ pinOpen(); wasSpoutOnLastTime = true; } else{ pinClosed(); wasSpoutOnLastTime = false; } writeDebugStreamLine("pin value:%d", ServoValue[spout]); } //////////////////////////////////////////////////////////////////// // // initializeRobot // // Prior to the start of tele-op mode, you may want to perform some // initialization on your robot // and the variables within your program. // // In most cases, you may not have to add any code to this function // and it will remain "empty". // //////////////////////////////////////////////////////////////////// void initializeRobot() { // Place code here to sinitialize servos to starting positions. // Sensors are automatically configured and setup by ROBOTC. // They may need a brief time to stabilize. BouncyBtn_init(fanBtn,false, 2); //on joy2, btn#2 BouncyBtn_init(flapperBtn,true,7);//on joy1, btn#7 BouncyBtn_init(nitro, true, 6); //on joy1, btn#6 BouncyBtn_init(flapRevBtn, true, 8);//on joy1, btn#8 BouncyBtn_init(hingeFaucetBtn, true, 9); // true, 9 BouncyBtn_init(foldRollBtn, true, 4); // true, 4 BouncyBtn_init(rollerBtn, true, 2); // true, 2 BouncyBtn_init(rollRevBtn, true, 1); //true, 1 BouncyBtn_init(spoutBtn, false, 3); //true, 3 BouncyBtn_init(thirtyBtn, false, 5); //false , 5 BouncyBtn_init(sixtyBtn, false, 6); //false, 6 BouncyBtn_init(ninetyBtn, false,8); //false, 7 BouncyBtn_init(oneTwentyBtn, false, 7); //false 8 goalGrabberDown(); //keep goal faucetDeployed(); servo[roller] = 126; servo[roller2] = 127; motor[Flapper]=0; servo[foldRoller] = ROLLER_FOLDER_UP; servo[spout]=160; servoChangeRate[trailerL]=0; servoChangeRate[trailerR]=0; return; } int flapper_state = FLAPPER_STOP; void flapperForward() { flapper_state = FLAPPER_FORWARD; motor[Flapper]= 100; } void flapperStop() { flapper_state = FLAPPER_STOP; motor[Flapper] = 0; } void flapperReverse() { flapper_state = FLAPPER_REV; motor[Flapper] = -100; } void flapperPressed() { writeDebugStreamLine("flapper pressed"); switch (flapper_state) { case FLAPPER_REV: case FLAPPER_STOP: flapperForward(); break; case FLAPPER_FORWARD: flapperStop(); break; } } void flapperRevPressed() { writeDebugStreamLine("flapper rev pressed"); switch (flapper_state) { case FLAPPER_FORWARD: case FLAPPER_STOP: flapperReverse(); break; case FLAPPER_REV: flapperStop(); break; } } void controlFlappers() { if(BouncyBtn_checkAndClear(flapperBtn)){ flapperPressed(); return; } if(BouncyBtn_checkAndClear(flapRevBtn)){ flapperRevPressed(); return; } } int roller_state = ROLLER_STOP; void rollerForward() { roller_state = ROLLER_FORWARD; servo[roller] = ROLLER_FORWARD; servo[roller2] = ROLLER_REV; } void rollerStop() { roller_state = ROLLER_STOP; servo [roller] = ROLLER_STOP; servo [roller2] = ROLLER_STOP; } void rollerReverse() { roller_state = ROLLER_REV; servo [roller] = ROLLER_REV; servo [roller2] = ROLLER_FORWARD; } void rollerPressed() { writeDebugStreamLine("roller pressed"); switch (roller_state) { case ROLLER_REV: case ROLLER_STOP: rollerForward(); break; case ROLLER_FORWARD: rollerStop(); break; } } void rollerRevPressed() { writeDebugStreamLine("roller rev pressed"); switch (roller_state) { case ROLLER_FORWARD: case ROLLER_STOP: rollerReverse(); break; case ROLLER_REV: rollerStop(); break; } } void controlRollers() { if(BouncyBtn_checkAndClear(rollerBtn)){ rollerPressed(); return; } if(BouncyBtn_checkAndClear(rollRevBtn)){ rollerRevPressed(); return; } } task main() { initializeRobot(); //Uncomment this for real competition waitForStart(); // wait for start of tele-op phase //set everything while (true) { getJoystickSettings(joystick); BouncyBtn_debounce(fanBtn); BouncyBtn_debounce(flapperBtn); BouncyBtn_debounce(nitro); BouncyBtn_debounce(flapRevBtn); BouncyBtn_debounce(hingeFaucetBtn); BouncyBtn_debounce(foldRollBtn); BouncyBtn_debounce(spoutBtn); BouncyBtn_debounce(thirtyBtn); BouncyBtn_debounce(sixtyBtn); BouncyBtn_debounce(ninetyBtn); BouncyBtn_debounce(oneTwentyBtn); BouncyBtn_debounce(rollerBtn); BouncyBtn_debounce(rollRevBtn); int rawLeftJoy=joystick.joy1_y1; int rawRightJoy=joystick.joy1_y2; int rawRightJoy2 = joystick.joy2_y2; controlDrive(rawLeftJoy, rawRightJoy); controlFans(); controlFlappers(); nitroCheck(); hingeFaucetOn(); controlRollers(); foldRollerOn(); spoutOn(); liftToNinety(); liftToThirty(); liftToSixty(); liftToOneTwenty(); //controlRakes(); controlLift(rawRightJoy2); checkLiftDone(); controlGoalGrabber(); sleep(10); } } <file_sep>/competition/PhiloDefs.h #ifndef _PHILO_DEFS_H_ #define _PHILO_DEFS_H_ //uncomment to turn off debug stream #define TRACE_ENABLED //lift servo positions #define LIFT_BOTTOM_HEIGHT 18*2.54 #define LIFT_60CM_HEIGHT 58 #define LIFT_90CM_HEIGHT 88 #define LIFT_TOP_HEIGHT 115 #define LIFT_RATIO (2* PI*2.54) //highest position for lift servo #define MAX_LIFT LIFT_BOTTOM //lowest position for lift servo #define MIN_LIFT LIFT_TOP //lift top and bottom height in cm measured from floor //flapper servo positions #define FLAPPER_FORWARD 255 #define FLAPPER_STOP 126 #define FLAPPER_REV 0 #define ROLLER_FORWARD 255 #define ROLLER_STOP 126 #define ROLLER_REV 0 ///sensors #define USE_HT_SENSOR_MUX #define CENTER_GOAL_SONAR msensor_S4_1 #define GYRO_SENSOR msensor_S4_2 #define HEADING_TOLERANCE 0.5 #define DISTANCE_TOLERANCE 0.5 #define POWER_ADJUST_FACTOR 1.4 #define SPEED_TARGET 40 //inches per second #define MOTOR_DEADBAND 20 #define MIN_STALL_POWER 40 //servos #define ROLLER_FOLDER_DOWN 245 #define HINGE_FAUCET_FLIP 153 #define ROLLER_FOLDER_UP 128 #define FAUCET_INITIAL 0 #define FAUCET_DEPLOYED 160 #define PIN_CLOSED 161 #define PIN_OPEN 50 #endif//_PHILO_DEFS_H_ <file_sep>/competition/MollysRamp_test.c #pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, HTServo) #pragma config(Hubs, S3, HTMotor, HTServo, HTServo, HTServo) #pragma config(Sensor, S1, TXMC1, sensorI2CMuxController) #pragma config(Sensor, S2, HTSPB, sensorI2CCustomFastSkipStates9V) #pragma config(Sensor, S3, TXMC3, sensorI2CMuxController) #pragma config(Sensor, S4, HTMUX, sensorI2CCustomFastSkipStates9V) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, MidR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_2, MidL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C3_1, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C3_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S1_C4_1, flapper1, tServoStandard) #pragma config(Servo, srvo_S1_C4_2, flapper2, tServoStandard) #pragma config(Servo, srvo_S1_C4_3, servo3, tServoNone) #pragma config(Servo, srvo_S1_C4_4, servo4, tServoNone) #pragma config(Servo, srvo_S1_C4_5, servo5, tServoNone) #pragma config(Servo, srvo_S1_C4_6, servo6, tServoNone) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, lift, tServoStandard) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_6, faucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_1, flapper3, tServoStandard) #pragma config(Servo, srvo_S3_C3_2, spout, tServoStandard) #pragma config(Servo, srvo_S3_C3_3, hingeFaucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_4, servo16, tServoNone) #pragma config(Servo, srvo_S3_C3_5, servo17, tServoNone) #pragma config(Servo, srvo_S3_C3_6, servo18, tServoNone) #pragma config(Servo, srvo_S3_C4_1, foldRoller, tServoStandard) #pragma config(Servo, srvo_S3_C4_2, roller, tServoStandard) #pragma config(Servo, srvo_S3_C4_3, servo21, tServoNone) #pragma config(Servo, srvo_S3_C4_4, servo22, tServoNone) #pragma config(Servo, srvo_S3_C4_5, servo23, tServoNone) #pragma config(Servo, srvo_S3_C4_6, servo24, tServoNone) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #define DEBUG // number of encoder ticks per revolution of the motor #define TICKS_PER_REVOLUTION (280 * 4) // number of revolutions of the wheel per revolution of the motor #define GEAR_RATIO 1 #define WHEEL_CIRCUMFERENCE (4 * 3.14159) // number of encoder ticks per inch of travel #define TICKS_PER_INCH (TICKS_PER_REVOLUTION / WHEEL_CIRCUMFERENCE / GEAR_RATIO) // distance the middle wheel travels during one full pivot #define PIVOT_CIRCUMFERENCE (16.5 * 3.14159) // number of encoder ticks per degree of pivot #define TICKS_PER_DEGREE (TICKS_PER_INCH * PIVOT_CIRCUMFERENCE / 360) #define INCHES_PER_DEGREE (TICKS_PER_DEGREE / TICKS_PER_INCH) // tunable parameters #define RAMP_UP_STEPS 10 // number of steps to go from 0 to full power #define LINEAR_SCALING (0.05) // ratio of power difference to encoder difference #define INTEGRAL_SCALING (0.001) #define STRAIGHT_SLOWDOWN_INCHES 6 // number of inches before the end at which to start slowing down #define PIVOT_SLOWDOWN_INCHES 6 // number of inches before the end at which to start slowing down #define MIN_POWER 20 #define TIME_STEP 20 void setLeftPower(int power) { motor[FrontL] = motor[MidL] = motor[BackL] = power; } void setRightPower(int power) { motor[FrontR] = motor[MidR] = motor[BackR] = power; } /* * Move the motors for the given number of inches at the given power. * The robot will pivot or move straight depending on the left and right * directions. leftDir and rightDir should only be 1 or -1 since they are * used to scale the absolute power. The wheel rotations are aligned by * proportionally varying the power with the encoder difference. */ void moveTank(int leftDir, int rightDir, float inches, int power, float slowdown) { float scaledPower, delta, leftPower, rightPower; int timeStart = nSysTime; float displacement = 0; // how far from the center we have deviated int count =0; // reset encoders nMotorEncoder[FrontL] = 0; nMotorEncoder[FrontR] = 0; // calculate encoder target float target = inches * TICKS_PER_INCH; #ifdef DEBUG writeDebugStreamLine("target is %d inches, %d ticks", inches, target); // sleep(100); #endif //DEBUG // slowly ramp up the motors int leftCount=0; int rightCount=0; for (int i = 0 ; (i < RAMP_UP_STEPS) && (leftCount + rightCount < target); i++) { leftCount = abs(nMotorEncoder[FrontL]); rightCount = abs(nMotorEncoder[FrontR]); displacement += (rightCount - leftCount); float currentPower = power / RAMP_UP_STEPS * i; delta = (rightCount-leftCount) * LINEAR_SCALING + displacement * INTEGRAL_SCALING; leftPower=currentPower+delta; rightPower=currentPower-delta; setLeftPower(leftDir * leftPower); setRightPower(rightDir * rightPower); sleep(TIME_STEP); } /* * Loop until both motors reach target, slowing down as they get closer * to the target. */ bool done = false; while (!done) { leftCount = abs(nMotorEncoder[FrontL]); rightCount = abs(nMotorEncoder[FrontR]); displacement += (rightCount - leftCount); const float averageCount = (rightCount + leftCount) * 0.5; const float slowDownDistance = (slowdown * TICKS_PER_INCH); scaledPower = power; if(averageCount > target - slowDownDistance) { float ratio = (target - averageCount) / slowDownDistance; if (ratio<0.5) { ratio=0.5; } scaledPower=scaledPower*ratio; } // keep scaled power above MIN_POWER so robot always moves if (scaledPower < MIN_POWER) scaledPower = MIN_POWER; delta = (rightCount-leftCount) * LINEAR_SCALING + displacement * INTEGRAL_SCALING; leftPower=scaledPower+delta; rightPower=scaledPower-delta; // if (leftPower < MIN_POWER) leftPower = MIN_POWER; // if (rightPower < MIN_POWER) rightPower = MIN_POWER; done = true; if (leftCount > target) { setLeftPower(0); } else { setLeftPower(leftDir *leftPower); done = false; } if (rightCount > target) { setRightPower(0); } else { setRightPower(rightDir *rightPower); done = false; } #ifdef DEBUG writeDebugStreamLine("time= %d\t\tleft= %d\t\tright=%d\t\tdelta=%d\t\tlp=%f\t\trp=%f\t\tdisp=%f", nSysTime - timeStart, leftCount, rightCount,rightCount-leftCount, leftPower, rightPower, displacement); #endif //DEBUG sleep(TIME_STEP); } } void moveForward(float inches, int power) { moveTank(1, -1, inches, power, STRAIGHT_SLOWDOWN_INCHES); } void moveBackward(float inches, int power) { moveTank(-1, 1, inches, power, STRAIGHT_SLOWDOWN_INCHES); } void pivotLeft(float degrees, int power) { moveTank(-1, -1, degrees * INCHES_PER_DEGREE, power, PIVOT_SLOWDOWN_INCHES); } void pivotRight(float degrees, int power) { moveTank(1, 1, degrees * INCHES_PER_DEGREE, power, PIVOT_SLOWDOWN_INCHES); } void moveLeft(int dir, float inches, int power) { // reset encoders nMotorEncoder[FrontL] = 0; // calculate encoder target float target = inches * TICKS_PER_INCH; #ifdef DEBUG writeDebugStreamLine("target is %d inches, %d ticks", inches, target); // sleep(100); #endif //DEBUG setLeftPower(dir * power); int leftCount= abs(nMotorEncoder[FrontL]); while (leftCount<target){ leftCount= abs(nMotorEncoder[FrontL]); } setLeftPower(0); } void moveRight(int dir, float inches, int power) { // reset encoders nMotorEncoder[FrontR] = 0; // calculate encoder target float target = inches * TICKS_PER_INCH; #ifdef DEBUG writeDebugStreamLine("target is %d inches, %d ticks", inches, target); // sleep(100); #endif //DEBUG setRightPower(dir * power); int rightCount= abs(nMotorEncoder[FrontR]); while (rightCount<target){ rightCount= abs(nMotorEncoder[FrontR]); } setRightPower(0); } void wiggle() { moveLeft(-1,2,30); moveRight(1,4,30); moveLeft(-1,4,30); moveRight(1,4,30); moveLeft(-1,2,30); setLeftPower(-30); setRightPower(30); sleep(300); setLeftPower(0); setRightPower(0); // moveBackward(5,30); } #define LIFT_DOWN 198 #define LIFT_60CM 165 #define LIFT_90CM 100 #define LIFT_120CM 35 void setLiftDown(){ servo[lift]=LIFT_DOWN; } void setLift60cm(){ servo[lift]=LIFT_60CM; } void setLift90cm(){ servo[lift]=LIFT_90CM; } void setLift120cm(){ servo[lift]=LIFT_120CM; } #define GRABBER_UP 100 #define GRABBER_DOWN 20 void goalGrabberUp() { servo[trailerR] = 200; servo[trailerL] = 75; } void goalGrabberDown() { servo[trailerR] = 75; servo[trailerL] = 150; } #define PIN_CLOSED 150 #define PIN_OPEN 50 void pinOpen(){ servo[spout]=PIN_OPEN; } void pinClosed(){ servo[spout]=PIN_CLOSED; } //flapper servo positions #define FLAPPER_FORWARD 255 #define FLAPPER_STOP 127 #define FLAPPER_REV 0 int flapper_state = FLAPPER_STOP; void flapperForward() { flapper_state = FLAPPER_FORWARD; servo[flapper1] =FLAPPER_FORWARD; servo[flapper2] = FLAPPER_FORWARD; servo[flapper3] = FLAPPER_FORWARD; } void flapperStop() { flapper_state = FLAPPER_STOP; servo[flapper1] =FLAPPER_STOP; servo[flapper2] = FLAPPER_STOP; servo[flapper3] = FLAPPER_STOP; } void flapperReverse() { flapper_state = FLAPPER_REV; servo[flapper1] =FLAPPER_REV; servo[flapper2] = FLAPPER_REV; servo[flapper3] = FLAPPER_REV; } #define FAUCET_INITIAL 0 #define FAUCET_DEPLOYED 160 void faucetInitial() { servo[faucet] = FAUCET_INITIAL; } void faucetDeployed() { servo[faucet] = FAUCET_DEPLOYED; } task main() { // moveForward(72,40); // while(true) {} sleep(3000); /* pivotLeft(90,40); sleep(3000); pivotRight(90,40); sleep(3000); pivotLeft(20,40); sleep(3000); pivotRight(20,40); sleep(3000); */ moveBackward(64, 50); //moveForward(100,35); } <file_sep>/competition/ParkingLot.c #pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, none) #pragma config(Hubs, S3, HTMotor, HTServo, HTServo, none) #pragma config(Hubs, S4, HTServo, none, none, none) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S2, HTSPB, sensorI2CCustomFastSkipStates9V) #pragma config(Sensor, S3, , sensorI2CMuxController) #pragma config(Sensor, S4, HTMUX, sensorI2CMuxController) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, motorF, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C2_2, Flapper, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C3_1, BackR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C3_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, lift, tServoStandard) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_6, servo12, tServoStandard) #pragma config(Servo, srvo_S3_C3_1, servo13, tServoStandard) #pragma config(Servo, srvo_S3_C3_2, spout, tServoStandard) #pragma config(Servo, srvo_S3_C3_3, faucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_4, servo16, tServoStandard) #pragma config(Servo, srvo_S3_C3_5, servo17, tServoStandard) #pragma config(Servo, srvo_S3_C3_6, servo18, tServoStandard) #pragma config(Servo, srvo_S4_C1_1, foldRoller, tServoNone) #pragma config(Servo, srvo_S4_C1_2, roller, tServoNone) #pragma config(Servo, srvo_S4_C1_3, servo21, tServoNone) #pragma config(Servo, srvo_S4_C1_4, servo22, tServoNone) #pragma config(Servo, srvo_S4_C1_5, servo23, tServoNone) #pragma config(Servo, srvo_S4_C1_6, servo24, tServoNone) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #define KICK_AND_GOAL #include "PhiloDefs.h" #include "WestCoaster.h" #include "CenterGoalUs.h" #include "JoystickDriver.c" #include "PhiloUtils.h" WestCoaster g_wcDrive; int initHeading; void initializeRobot() { // Place code here to sinitialize servos to starting positions. // Sensors are automatically configured and setup by ROBOTC. They may need a brief time to stabilize. servo[lift]= LIFT_BOTTOM; // while(true){}; WestCoaster_init(g_wcDrive,FrontL, FrontR, BackL, BackR, FrontL, FrontR); WestCoaster_initMPU(S2); initHeading = SuperSensors_getHeading(); servo[foldRoller] = ROLLER_FOLDER_UP; goalGrabberUp(); motor[Flapper] = 0; pinClosed(); servo[faucet]=0; //move servos at maximium speed servoChangeRate[trailerL]=0; servoChangeRate[trailerR]=0; servoChangeRate[lift]=0; //set to true during competition to keep the grabber engaged bSystemLeaveServosEnabledOnProgramStop=false; return; } void kickFromParking(int goalPosition) { if(goalPosition == 1){ WestCoaster_moveStraightWithMPU(g_wcDrive,-28, 70); //sleep(100); WestCoaster_turnWithMPU(g_wcDrive,50, 100); //MPU turn //sleep(100); WestCoaster_moveStraightWithMPU(g_wcDrive,-10, 70); //sleep(100); WestCoaster_turnWithMPU(g_wcDrive,-100, 100); //MPU turn //sleep(100); WestCoaster_forwardFullSpeed(g_wcDrive,-24); WestCoaster_forwardFullSpeed(g_wcDrive,10); WestCoaster_forwardFullSpeed(g_wcDrive,-15); } else if(goalPosition == 2){ WestCoaster_moveStraightWithMPU(g_wcDrive,-29,70); //sleep(100); WestCoaster_turnWithMPU(g_wcDrive,-70, 70);// //sleep(100); WestCoaster_forwardFullSpeed(g_wcDrive,-48); WestCoaster_forwardFullSpeed(g_wcDrive,10); WestCoaster_forwardFullSpeed(g_wcDrive,-15); } else if(goalPosition ==3){ WestCoaster_moveStraightWithMPU(g_wcDrive,-28,70); //sleep(500); WestCoaster_turnWithMPU(g_wcDrive,-90, 70);// //sleep(-100); WestCoaster_moveStraightWithMPU(g_wcDrive,-15, 70); //sleep(200); WestCoaster_turnWithMPU(g_wcDrive,100, 70);// //sleep(100); WestCoaster_forwardFullSpeed(g_wcDrive,-48); WestCoaster_forwardFullSpeed(g_wcDrive,10); WestCoaster_forwardFullSpeed(g_wcDrive,-15); } } void kickFromGoal() { WestCoaster_moveStraightWithMPU(g_wcDrive,10,70); float current_heading=SuperSensors_getHeading(); int messed = angleDifference(initHeading, current_heading); //sleep(600); WestCoaster_turnWithMPU(g_wcDrive,70-messed, 70, false); //sleep(600); WestCoaster_moveStraightWithMPU(g_wcDrive,-15,70); //sleep(600); WestCoaster_turnWithMPU(g_wcDrive,-65,70); //sleep(600); WestCoaster_forwardFullSpeed(g_wcDrive, -40); //lower down the lift liftGoUp(LIFT_FOR_90CM, 7000); //going back and forth one more time WestCoaster_forwardFullSpeed(g_wcDrive, 20); WestCoaster_forwardFullSpeed(g_wcDrive, -30); //sleep(1000); } //get very close to the center goal using encoders void closeToCenterGoal(int goalPosition) { //assume robot edge lined up with edge of first tile // and center lined up with the center line of field if(goalPosition == 1){ WestCoaster_moveStraightWithMPU(g_wcDrive,-15, 70); WestCoaster_turnWithMPU(g_wcDrive, -70, 70); WestCoaster_moveStraightWithMPU(g_wcDrive, -26,70); WestCoaster_turnWithMPU(g_wcDrive, 90, 70); WestCoaster_moveStraightWithMPU(g_wcDrive,-45,70); WestCoaster_turnWithMPU(g_wcDrive, 90, 70); WestCoaster_moveStraightWithMPU(g_wcDrive,-6,70); } else if(goalPosition == 2){ WestCoaster_turnWithMPU(g_wcDrive,-45, 70); WestCoaster_moveStraightWithMPU(g_wcDrive,-1.414*24, 70); WestCoaster_turnWithMPU(g_wcDrive,90,70); WestCoaster_moveStraightWithMPU(g_wcDrive,-10, 70); } else if(goalPosition ==3){ WestCoaster_moveStraightWithMPU(g_wcDrive,-25, 70); } } //drop ball to void deposit() { faucetDeployed(); sleep(500); pinOpen(); sleep(200); fansOn(4000); } const int headingToGoal[3] ={90, 45, 0}; task main() { initializeRobot(); waitForStart(); servo[foldRoller] = ROLLER_FOLDER_DOWN; sleep(500); servo[foldRoller] = ROLLER_FOLDER_UP; servo[faucet] = FAUCET_DEPLOYED; servo[lift] = LIFT_FOR_90CM; sleep(10000); /* WestCoaster_moveStraightWithMPU(g_wcDrive,7,30); WestCoaster_turnWithMPU(g_wcDrive, -45, 40); WestCoaster_moveStraightWithMPU(g_wcDrive,75,50); WestCoaster_turnWithMPU(g_wcDrive, -120, 40); WestCoaster_turnWithMPU(g_wcDrive, 70, 40); WestCoaster_turnWithMPU(g_wcDrive, -140, 40); WestCoaster_moveStraightWithMPU(g_wcDrive,20,50); *? /* WestCoaster_moveStraightWithMPU(g_wcDrive,-4,30); //we only need 100ms or less to determine the center goal //orientation. int goalPosition = determineGoalPosition(CENTER_GOAL_SONAR, 100); // // correct initHeading based on goal position // initHeading +=headingToGoal[goalPosition-1]; //make sure it is -180 to 180, consistent with MPU if(initHeading>180){ initHeading -=360; } if(initHeading<-180) { initHeading+=360; } #ifndef KICK_AND_GOAL kickFromParking(goalPosition); #else closeToCenterGoal(goalPosition); sleep(600); //fine alignment using sonar driveToGoal(g_wcDrive, CENTER_GOAL_SONAR, 15, 15); deposit(); //go to kickstand kickFromGoal(); #endif*/ } <file_sep>/competition/PhiloUtils.h #ifndef _PHILO_UTILS_H_ #define _PHILO_UTILS_H_ /** * Common utilities used for autonomous and teleop */ void goalGrabberUp() { servo[trailerR] = 200; servo[trailerL] = 75; } void goalGrabberDown() { servo[trailerR] = 75; servo[trailerL] = 150; } void faucetInitial() { servo[faucet] = FAUCET_INITIAL; } void faucetDeployed() { servo[faucet] = FAUCET_DEPLOYED; } void pinOpen(){ servo[spout]=PIN_OPEN; } void pinClosed(){ servo[spout]=PIN_CLOSED; } void fansOn(unsigned long time) { unsigned long targetTime = nSysTime + 500; while(nSysTime < targetTime) { motor[FanL] = -100; motor[FanR] = 100; } motor[Flapper]=-100; targetTime=nSysTime+time; while(nSysTime < targetTime) { motor[FanL] = -100; motor[FanR] = 100; } motor[FanL] = 0; motor[FanR] = 0; motor[Flapper]=0; sleep(100); } static float lastLiftPosition = LIFT_BOTTOM_HEIGHT; bool liftMoving = false; int cmToCounts(float cm){ int counts = (cm) * 1440.0/(LIFT_RATIO); return counts; } float countsToCm(int counts){ float cm = counts/1440.0*(LIFT_RATIO); return cm; } unsigned long lastTimeSetLift =0; const unsigned int LIFT_TIME_OUT = 3000; void liftGoUp(float cm){ //consider when moving another button pushed if(nMotorRunState[Lift] != runStateIdle) return; int countsToTurn = cmToCounts(cm-lastLiftPosition); if(countsToTurn == 0) return; writeDebugStreamLine("lastPosition: %d countsToTurn: %d", lastLiftPosition, countsToTurn); nMotorEncoder[Lift] = 0; //consider negative case nMotorEncoderTarget[Lift]=countsToTurn; if(countsToTurn < 0){ motor[Lift] = -50;//tune }else if(countsToTurn>0) { motor[Lift] = 50; } lastTimeSetLift=nSysTime; liftMoving=true; } void moveLift( int cm){ liftGoUp(cm + lastLiftPosition); } bool checkLiftDone() { if(nMotorRunState[Lift] != runStateIdle && nSysTime-lastTimeSetLift<LIFT_TIME_OUT) return false; if(!liftMoving) return true; liftMoving=false; writeDebugStreamLine("LiftEncoder: %d", nMotorEncoder[Lift]); lastLiftPosition = countsToCm(nMotorEncoder[Lift])+lastLiftPosition; writeDebugStreamLine("LiftEncoder: %d lastLiftPosition: %d", nMotorEncoder[Lift], lastLiftPosition); motor[Lift] = 0; return true; } float angleTurned(float fromHeading, float toHeading) { float delta=toHeading-fromHeading; //normalize it to (-180,180) if(delta>180) { delta-=360; } if(delta<-180) { delta+=360; } return delta; } #endif <file_sep>/competition/SigmaDefs.h #ifndef _PHILO_DEFS_H_ #define _PHILO_DEFS_H_ //We use MPU6050 for gyro PID #define MPU_PID //grabber servo positions #define GRABBER_UP 180 #define GRABBER_DOWN 60 //lift servo positions #define LIFT_TOP 80 #define LIFT_BOTTOM 200 //highest position for lift servo #define MAX_LIFT LIFT_BOTTOM //lowest position for lift servo #define MIN_LIFT LIFT_TOP //lift top and bottom height in cm measured from floor #define LIFT_TOP_HEIGHT 122 #define LIFT_BOTTOM_HEIGHT (18*2.54) //lift position for 60CM goal. //This should be close to 60 #define LIFT_FOR_60CM 64 #define LIFT_FOR_90CM 94 #define LIFT_FOR_120CM 124 //flapper servo positions #define FLAPPER_FORWARD 255 #define FLAPPER_STOP 127 #define FLAPPER_REV 0 //Sprout #define SPOUT_OUT 45 #define SPOUT_IN 160 //sensors //#define USE_HT_SENSOR_MUX #define TRACE_ENABLED #define CENTER_GOAL_SONAR S4//msensor_S4_1 #define GYRO_SENSOR msensor_S4_2 #define HEADING_TOLERANCE 1 #define DISTANCE_TOLERANCE (0.5) #define POWER_ADJUST_FACTOR 3 #define SPEED_TARGET 20 //inches per second #define MOTOR_DEADBAND 20 #define MIN_STALL_POWER 40 #define ROLLER_FOLDER_DOWN 245 #define HINGE_FAUCET_FLIP 153 #define ROLLER_FOLDER_UP 70 #endif//_PHILO_DEFS_H_ <file_sep>/competition/WestCoaster.h /** * This file defines a west-coast drive with six motors. * And methods to control the drive. */ #ifndef __WEST_COASTER_H__ #define __WEST_COASTER_H__ #include "HTSuperproSensors.h" /** * Robot characteristics. these are constant, only change when robot is re-designed */ // half-width of robot in inches measured from center-plane of left wheels to // center plane of right side wheels const int robotHalfWidth = 8.25; // wheel radius in inches const int wheelRad = 2; // encoder counts per revolution of the motor output shaft const int cpr = 1120; // gear ratio of the drive train, turns of wheels // for each revolution of motor output shaft const float gear_ratio = 1.95; //We use ratio of power applied to left to that applied to right // to synchronize left and right motors, that is, minimize encoder // difference (value returned from WestCoaster_getRotPos). // Applying higher ratio when left is slower than right, i.e., offset is positive. //Limit power offset to -50% to 50% const float max_power_ratio_offset = 0.5; const float min_power_ratio_offset = -0.5; // The real ratio of power_left/power_right=1+ratio_offset. // Because the highest power applied to right side will be // totalpower/(2+min_power_ratio_offset), and the highest // power applied to left will be totalpower*(1+max_power_ratio_offset) // /(2+max_power_ratio_offset) // so the total power should // be less than 100*(2+min_power_ratio_offset), or 100*(2+max_power_ratio_offset) // /(1+max_power_ratio_offset) // which-ever is less. For +/-50% limit, this is const float MAX_TOTAL_POWER = 150; // full power level for moving forward const int FULL_POWER_FORWARD = MAX_TOTAL_POWER/2; // full power level for turning left const int FULL_POWER_LEFT = MAX_TOTAL_POWER/2; //Position and rotation control interval. //We do not need control at very high frequency. const unsigned long pos_control_interval = 200; //ms const unsigned long rot_control_interval = 200; //ms //AndyMark Neverest motors can tolerate more than 2 min stalling //we will check every other position control loop const unsigned int stall_check_interval=2*pos_control_interval; //We need sync motors faster than position control const unsigned int motor_sync_interval = pos_control_interval/2; //outermost control loop interval. This should be the smallest. const unsigned int control_loop_interval = motor_sync_interval/5; //interval to gradually ramping up power const unsigned int ramp_up_interval = pos_control_interval/2; const float clicks_per_inch = cpr/(PI*wheelRad*2.0*gear_ratio); /** * converts inches in straight distance to encoder counts. */ int inchesToCounts(float inches) { return abs((int)(clicks_per_inch*inches+0.5)); } /** * converts rotation degrees to encoder counts */ int degreesToCounts(int degrees) { return abs((int)((degrees * robotHalfWidth *cpr) /(360.0*wheelRad)/gear_ratio +0.5)); } typedef struct wc { tMotor frontL; tMotor frontR; tMotor backL; tMotor backR; tMotor encoderL; tMotor encoderR; unsigned long nextStallCheckTick; unsigned long nextMotorSyncTick; int last_encoderLeft; int last_encoderRight; int last_deltaL_f;//filtered left encoder change int last_deltaL;//unfiltered left encoder change int last_deltaR_f; int last_deltaR; float mpuTheta; float global_heading; int last_powerLeft; int last_powerRight; } WestCoaster; bool usePID=true; void WestCoaster_initPID(); void WestCoaster_resetSyncPID(); bool WestCoaster_isStalling(WestCoaster& wc); void WestCoaster_init(WestCoaster& wc, tMotor fl, tMotor fr, tMotor bl, tMotor br, tMotor el, tMotor er ) { if(usePID) WestCoaster_initPID(); wc.frontL=fl; wc.frontR=fr; wc.backL=bl; wc.backR=br; wc.encoderL=el; wc.encoderR=er; wc.nextStallCheckTick=nSysTime+stall_check_interval; wc.nextMotorSyncTick=nSysTime+motor_sync_interval; } /** * Moves forward/backward with different power assigned to left and right */ void WestCoaster_distributePower(WestCoaster& wc, int powerLeft, int powerRight, bool rotation) { wc.last_powerLeft = powerLeft; wc.last_powerRight = powerRight; if(rotation) powerRight=-powerRight; //just to make sure firmware to use these values together //We still don't know exact timing of sending them to // motor controller by the firmware. hogCPU(); motor[wc.frontR] = -powerRight; motor[wc.backR] = -powerRight; motor[wc.frontL] = powerLeft; motor[wc.backL] = powerLeft; releaseCPU(); } void WestCoaster_allMotorsPowerStraight(WestCoaster& wc,int power){ WestCoaster_distributePower(wc,power, power, false); } /** * Turn left for given power, negative means turn right */ void WestCoaster_allMotorsPowerRot(WestCoaster& wc, int power){ WestCoaster_distributePower(wc,power, power, true); } void WestCoaster_resetStates(WestCoaster& wc) { nMotorEncoder[wc.encoderL] = 0; nMotorEncoder[wc.encoderR] = 0; //let encoders settle. sleep(250); wc.nextStallCheckTick=nSysTime+stall_check_interval; wc.last_encoderLeft=0; wc.last_encoderRight=0; wc.last_deltaL_f = 0; wc.last_deltaR_f = 0; wc.last_deltaL = 0; wc.last_deltaR = 0; wc.mpuTheta = 0; wc.global_heading = SuperSensors_getHeading(); // writeDebugStreamLine("WC reset, currentHeading: %f", wc.global_heading); } void WestCoaster_pidMotorSync(WestCoaster& wc, int total_power, bool rotation); #define ENCODER_THRESH 300 #define ENCODER_FILRER 0.1 int bad_countinous_left=0; int bad_countinous_right=0; void WestCoaster_measureEncoders(WestCoaster& wc, bool allowDrop) { int current_encoder=nMotorEncoder[wc.encoderR]; if(abs(wc.last_encoderRight-current_encoder)>ENCODER_THRESH && abs(wc.last_encoderLeft-current_encoder)>(ENCODER_THRESH/2)) { #ifdef TRACE_ENABLED writeDebugStreamLine("*****Bogus encoder right jump, assume average speed"); #endif bad_countinous_right++; wc.last_encoderRight+=wc.last_deltaR_f; wc.last_deltaR=wc.last_deltaR_f; if(bad_countinous_right==5){ playSound(soundLowBuzzShort); } }else if (!allowDrop && abs(wc.last_encoderRight)>abs(current_encoder) && abs(wc.last_powerRight)>MIN_STALL_POWER && abs(wc.last_encoderLeft-current_encoder)>(ENCODER_THRESH/2)) { #ifdef TRACE_ENABLED writeDebugStreamLine("*****Bogus encoder right drop, reset encoderR filter"); #endif wc.last_encoderRight = current_encoder;//use this as new starting point wc.last_deltaR = 0; wc.last_deltaR_f = 0; bad_countinous_right = 0; } else { bad_countinous_right = 0; wc.last_deltaR = (current_encoder-wc.last_encoderRight); wc.last_deltaR_f = ENCODER_FILRER*wc.last_deltaR + (1.0 - ENCODER_FILRER)*wc.last_deltaR_f; //moving average for speed wc.last_encoderRight = current_encoder;//resync the filtered encoder with raw } int rawRight=current_encoder; current_encoder = nMotorEncoder[wc.encoderL]; if(abs(wc.last_encoderLeft-current_encoder)>ENCODER_THRESH && abs(wc.last_encoderRight-current_encoder)>(ENCODER_THRESH/2)) { #ifdef TRACE_ENABLED writeDebugStreamLine("*****Bogus encoder left jump, assume average speed"); #endif bad_countinous_left++; if(bad_countinous_left==5) playSound(soundLowBuzzShort); wc.last_encoderLeft += wc.last_deltaL_f; wc.last_deltaL=wc.last_deltaL_f; }else if (!allowDrop && abs(wc.last_encoderLeft)>abs(current_encoder) && abs(wc.last_powerLeft)>MIN_STALL_POWER && abs(wc.last_encoderRight-current_encoder)>(ENCODER_THRESH/2)) { #ifdef TRACE_ENABLED writeDebugStreamLine("*****Bogus encoder left drop, reset EncoderL filter"); #endif wc.last_encoderLeft=current_encoder;//use this as new starting point wc.last_deltaL=0; wc.last_deltaL_f=0; bad_countinous_left=0; } else { bad_countinous_left = 0; wc.last_deltaL = (current_encoder-wc.last_encoderLeft); wc.last_deltaL_f = ENCODER_FILRER*wc.last_deltaL + (1.0 - ENCODER_FILRER)*wc.last_deltaL_f; wc.last_encoderLeft=current_encoder;//resync the filtered with raw } #ifdef TRACE_ENABLED writeDebugStreamLine("Left/Right RawEncoder %d/%d, filtered: %d/%d", current_encoder, rawRight,wc.last_encoderLeft, wc.last_encoderRight ); #endif } void WestCoaster_waitForEncoderCounts(WestCoaster& wc, int leftTarget, int rightTarget, bool rotation, bool sync, unsigned long timeout) { if(sync)WestCoaster_resetSyncPID(); int total_power=(wc.last_powerRight+wc.last_powerRight); #ifdef TRACE_ENABLED writeDebugStreamLine("**targets (L/R):%d/%d, encoderL: %d, encoderR: %d, total_powe:%d time: %d", leftTarget,rightTarget, wc.last_encoderLeft, wc.last_encoderRight, total_power, nSysTime); #endif unsigned long timeEnd = nSysTime + timeout; while(abs(wc.last_encoderRight) < rightTarget && abs(wc.last_encoderLeft) < leftTarget && nSysTime < timeEnd) { sleep(control_loop_interval);//must be smaller than sync interval WestCoaster_measureEncoders(wc, false); if(WestCoaster_isStalling(wc)) break; if(sync)WestCoaster_pidMotorSync(wc, total_power, rotation); #ifdef TRACE_ENABLED writeDebugStreamLine("targets (L/R):%d/%d, encoder: %d/%d, total_powe:%d time: %d", leftTarget,rightTarget, wc.last_encoderLeft, wc.last_encoderRight, total_power, nSysTime); #endif } return ; } /** * Stops all motors and checks encoders untill no movement detected. * This is usually called after commands to move the drive so * that we know it's stopped for sure before proceeding with next steps. */ void WestCoaster_fullStop(WestCoaster& wc) { WestCoaster_allMotorsPowerRot(wc,0); int last_encoderL=0; int last_encoderR=0; do{ last_encoderL=nMotorEncoder[wc.encoderL]; last_encoderR=nMotorEncoder[wc.encoderR]; /** * These debug messages can be used to tune offsets observedBrakingOffSetL * and observedBrakingOffSetR */ #ifdef TRACE_ENABLED writeDebugStreamLine("encoderL: %d, encoderR: %d, time: %d", last_encoderL, last_encoderR, nSysTime); #endif sleep(20); }while(nMotorEncoder[wc.encoderL]!=last_encoderL || nMotorEncoder[wc.encoderR]!=last_encoderR); } void WestCoaster_rampUpSpeed(WestCoaster& wc, int counts, int power){ int current_power=0; int power_step=5; if(power<0) power_step=-5; while(abs(wc.last_encoderLeft)< counts && abs(wc.last_encoderRight) < counts && abs(current_power)<abs(power)) { current_power+=power_step; WestCoaster_allMotorsPowerStraight(wc, current_power); sleep(control_loop_interval); WestCoaster_measureEncoders(wc, false); if(WestCoaster_isStalling(wc)) break; #ifdef TRACE_ENABLED writeDebugStreamLine("**targets (L/R):%d/%d, encoderL: %d, encoderR: %d, total_powe:%d time: %d", counts,counts, wc.last_encoderLeft, wc.last_encoderRight, current_power, nSysTime); #endif } return ; } void WestCoaster_controlledStraightMove(WestCoaster& wc, float inches, int power, unsigned long timeout=5000){ WestCoaster_resetStates(wc); int countToMove = inchesToCounts(inches); if(countToMove==0) return; if(inches < 0){ power = -power; } int ramp_up_counts=inchesToCounts(24); if(ramp_up_counts<countToMove/2) WestCoaster_rampUpSpeed(wc, ramp_up_counts, power); WestCoaster_allMotorsPowerStraight(wc, power); WestCoaster_waitForEncoderCounts(wc, countToMove, countToMove, false, true, timeout); WestCoaster_fullStop(wc); } void WestCoaster_straightMove(WestCoaster& wc, float inches, unsigned long timeout=5000){ WestCoaster_controlledStraightMove(wc, inches, FULL_POWER_FORWARD, timeout); } /** * Just move forward as fast as possible, no need to sync left/right motors * This can be used for cases where speed/force is more * important than straightness, e.g. to get the kickstand in cascade effect */ void WestCoaster_forwardFullSpeed(WestCoaster& wc, float inches, unsigned long timeout=5000){ WestCoaster_resetStates(wc); int countToMove = inchesToCounts(inches); if(countToMove==0) return; int power=100; if(inches < 0){ power = -100; } WestCoaster_allMotorsPowerStraight(wc, power); WestCoaster_waitForEncoderCounts(wc, countToMove, countToMove, false, false, timeout); WestCoaster_fullStop(wc); } /** * This is a predictive controller based on observed offset of encoders after powering * off motors. The observed offsets are due to inertia of the robot so they are roughly * constant for a specific robot on similar field surfaces and with fully charged battery. * Therefore, these constants should be tuned for each robot design. * To tune them, just run the robot and use debug messge output from WestCoaster_fullStop * to calculate the braking offset. */ int observedBrakingOffSetL=0; int observedBrakingOffSetR=0; void WestCoaster_observedStraightMove(WestCoaster& wc, float inches, unsigned long timeout=5000){ WestCoaster_resetStates(wc); int countToMove = inchesToCounts(inches); if(countToMove==0)return; int power = FULL_POWER_FORWARD; // writeDebugStreamLine("counts to move: %d, encoderLCount: %d, encoderRCount: %d, time: %d",countToTurn, //nMotorEncoder[wc.encoderL],nMotorEncoder[wc.encoderR], nSysTime); if(inches < 0){ power = -power; } WestCoaster_allMotorsPowerStraight(wc, power); //TODO: also sync motors for rotation? WestCoaster_waitForEncoderCounts(wc, countToMove-observedBrakingOffSetL, countToMove-observedBrakingOffSetR, false, false, timeout); WestCoaster_fullStop(wc); } void WestCoaster_controlledEncoderObservedTurn(WestCoaster& wc, int desired, int powerDesired, unsigned long timeout=2000){ if (desired < 0) { powerDesired = powerDesired * -1; } WestCoaster_resetStates(wc); int countToTurn = degreesToCounts(desired); WestCoaster_allMotorsPowerRot(wc, powerDesired); //TODO also sync motors WestCoaster_waitForEncoderCounts(wc, countToTurn-observedBrakingOffSetL, countToTurn-observedBrakingOffSetR, true, false, timeout); WestCoaster_fullStop(wc); } void WestCoaster_encoderObservedTurn(WestCoaster& wc, int target, unsigned long timeout=5000){ WestCoaster_controlledEncoderObservedTurn(wc, target, FULL_POWER_LEFT, timeout); return; } bool WestCoaster_isStalling(WestCoaster& wc) { static int prev_encoder_right=0; static int prev_encoder_left=0; if(wc.nextStallCheckTick>=nSysTime || (abs(wc.last_powerLeft)<=MIN_STALL_POWER && abs(wc.last_powerRight)<=MIN_STALL_POWER)) return false; //writeDebugStreamLine("time: %d, stall_check: %d", nSysTime, wc.nextStallCheckTick); wc.nextStallCheckTick = nSysTime+stall_check_interval; if(prev_encoder_left == wc.last_encoderLeft&& prev_encoder_right == wc.last_encoderRight) { writeDebugStreamLine("Drive stalled: power L/R: %d/%d", wc.last_powerLeft, wc.last_powerRight); WestCoaster_allMotorsPowerRot(wc,0); playImmediateTone(1000, 100); return true; } prev_encoder_right = wc.last_encoderRight; prev_encoder_left = wc.last_encoderLeft; return false; } // inches moved // since last reset float WestCoaster_getDistanceMoved(WestCoaster& wc) { return (-wc.last_encoderRight + wc.last_encoderLeft)/2.0/clicks_per_inch; } float WestCoaster_getRotPos(WestCoaster& wc) { return abs(wc.last_encoderRight)-abs(wc.last_encoderLeft); } //========================================================== // Experimental PID controllers // using adapted library code from team 118 //========================================================== #include "trcdefs.h" #include "dbgtrace.h" #include "pidctl.h" #define KP_TURN -0.002 //power ratio offset per encoder counter difference #define KI_TURN 0.0 #define KD_TURN 0.0 // encoder PID stablize direction to make sure // robot going straight, minimizing encoder counter differences // between left and right motors PIDCTRL g_encoder_turn_pid; void WestCoaster_initPID() { PIDCtrlInit(g_encoder_turn_pid, KP_TURN, KI_TURN, KD_TURN, 10.0, //Tolerance for encoder mismatch 400, //settling time for mismatch PIDCTRLO_ABS_SETPT, //setpoint will be absolute value (not relative to current measurement) 0.0 //initial ratio offset ); } void WestCoaster_pidMotorSync(WestCoaster& wc, int total_power, bool rotation) { if(wc.nextMotorSyncTick>nSysTime) return; //need clamp maxiumum total power so that the power on either side won't exceed // maximum specified if(total_power>MAX_TOTAL_POWER) { total_power=MAX_TOTAL_POWER; } if(total_power<-MAX_TOTAL_POWER) { total_power=-MAX_TOTAL_POWER; } wc.nextMotorSyncTick += motor_sync_interval; float ratio=1.0+PIDCtrlOutput(g_encoder_turn_pid, WestCoaster_getRotPos(wc)); // powerLeft+powerRight=(1+ratio)*powerRight=total_power // therefore: int powerRight =(int)(total_power/(1+ratio)); int powerLeft = (int) (ratio*powerRight); #ifdef TRACE_ENABLED writeDebugStreamLine("powerLeft: %d, powerRight: %d, mismatch: %d", powerLeft, powerRight, WestCoaster_getRotPos(wc)); #endif WestCoaster_distributePower(wc, powerLeft, powerRight, rotation); } void WestCoaster_resetSyncPID() { PIDCtrlReset(g_encoder_turn_pid); PIDCtrlSetPowerLimits(g_encoder_turn_pid, min_power_ratio_offset, max_power_ratio_offset); PIDCtrlSetTarget(g_encoder_turn_pid, 0, 0); } static bool mpu_inited =false; void WestCoaster_initMPU(tSensors superpro) { if(!mpu_inited) { mpu_inited=true; SuperSensors_init_task_yaw(superpro); unsigned int waited=0; while(!super_health) { sleep(20); waited+=20; if(waited>2000) { #ifdef TRACE_ENABLED writeDebugStreamLine("super sensors not running!"); #endif playSound(soundBeepBeep); break; } } float last_heading=0; waited=0; while(abs(last_heading-SuperSensors_getHeading())>1) { last_heading=SuperSensors_getHeading(); sleep(200); waited+=200; if(waited>3000) { #ifdef TRACE_ENABLED writeDebugStreamLine("super sensors not finished initialization!"); #endif playSound(soundBeepBeep); mpu_inited=false; break; } } } } float angleDifference(float angle1, float angle2) { float delta=angle2-angle1; //MPU yaw reading increase clockwise, not counter clockwise if(delta>180)//cross 180 from negative to positive) { delta-=360; } if(delta<-180)//crosee 180 from positive to negative { delta+=360; } return delta; } void WestCoaster_measureMPU(WestCoaster& wc) { float current_heading=SuperSensors_getHeading(); //writeDebugStreamLine("**current_heading: %f, global_heading: %f", current_heading, wc.global_heading); float delta=angleDifference(wc.global_heading, current_heading); wc.mpuTheta+=delta;//accumulated angle change since reset wc.global_heading=current_heading; } const float SLOWDOWN_DEGREES = 40.0; // usually we can make a full circle in less than 2 sec // specify timeout if caller thinks need more time (low power case) bool WestCoaster_turnWithMPU(WestCoaster& wc, int degrees, int power, bool ramping=true, int timeout=3000) { if(power<0){ playSound(soundLowBuzz); writeDebugStreamLine("do you mean positive power?"); power=-power; } WestCoaster_resetStates(wc); int powerAvg=0; //increase power 10% each step during ramp-up phase int power_ramp_step = ramping?power*0.1:power; if (degrees<0){ power_ramp_step= ramping? -power*0.1:-power; } ramping=true; clearTimer(T1); unsigned long ramping_tick=nSysTime; bool res=false; while(time1[T1]<timeout){ if( ramping && ( abs(powerAvg)>=abs(power) || abs(wc.last_deltaL_f/clicks_per_inch*1000/control_loop_interval)>SPEED_TARGET || abs(wc.last_deltaL_f/clicks_per_inch*1000/control_loop_interval)>SPEED_TARGET ) ) {//done with ramping up power ramping=false; } if( ramping && ramping_tick<=nSysTime ) { ramping_tick+=ramp_up_interval; powerAvg+=power_ramp_step; } WestCoaster_distributePower(wc, powerAvg, powerAvg, true); sleep(control_loop_interval); WestCoaster_measureMPU(wc); WestCoaster_measureEncoders(wc, false); int degrees_turned =wc.mpuTheta; #ifdef TRACE_ENABLED writeDebugStreamLine("current_heading: %f, turned: %f, power:%d", wc.global_heading, degrees_turned, powerAvg); #endif if(degrees_turned>degrees && degrees > 0){ //we are at target, stop res=true; break; } else if(degrees_turned<degrees&&degrees < 0){ res=true; break; } if(WestCoaster_isStalling(wc)) break; if( abs(degrees_turned-degrees) < SLOWDOWN_DEGREES) { float ratio = abs(degrees_turned-degrees) /(2* SLOWDOWN_DEGREES); if (ratio<0.5) { ratio=0.5; } powerAvg = powerAvg*ratio; if( abs(powerAvg)<MOTOR_DEADBAND ) { if( power_ramp_step>0 ) powerAvg = min(power,MOTOR_DEADBAND); else powerAvg = -min(power,MOTOR_DEADBAND); } //ramping=false; } } WestCoaster_fullStop(wc); return res; } int WestCoaster_getAverageCount(WestCoaster& wc) { if(bad_countinous_left>=5 && bad_countinous_right<5) return abs(wc.last_encoderRight); if(bad_countinous_left<5 && bad_countinous_right>=5) return abs(wc.last_encoderLeft); //both are bad or both are good return (abs(wc.last_encoderRight)+abs(wc.last_encoderLeft))/2.0; } const float SLOWDOWN_DISTANCE = 6.0; const float SLOWDOWN_COUNTS = SLOWDOWN_DISTANCE * clicks_per_inch; const float MIN_SPEED = 0.005; //inches per ms bool WestCoaster_moveStraightWithMPU(WestCoaster& wc, float distance, int power, int timeout=0) { if(power<0){ playSound(soundLowBuzz); writeDebugStreamLine("do you mean positive power?"); power=-power; } WestCoaster_resetStates(wc); int countToMove = inchesToCounts(distance); int powerAvg=0; //increase power 5% each step during ramp-up phase int power_ramp_step = 5; if ( distance<0 ){ power_ramp_step = -5; } bool ramping=true; unsigned long ramping_tick=nSysTime; int powerLeft, powerRight; powerRight=powerLeft=powerAvg; float leftAdjust=1; float rightAdjust=1; if(timeout==0) timeout=abs(distance)/MIN_SPEED; writeDebugStreamLine("timeout:%d",timeout); clearTimer(T1); bool res=false; unsigned long last_control_tick=nSysTime; while(time1[T1]<timeout){ if( ramping && ( ( abs(powerAvg)>=abs(power) || abs(wc.last_deltaL_f/clicks_per_inch*1000/control_loop_interval)>SPEED_TARGET || abs(wc.last_deltaL_f/clicks_per_inch*1000/control_loop_interval)>SPEED_TARGET) ) ) {//done with ramping up power ramping = false; } if( ramping && ramping_tick<=nSysTime ) { ramping_tick += ramp_up_interval; powerAvg += power_ramp_step; } powerLeft = powerAvg/leftAdjust; powerRight = powerAvg/rightAdjust; WestCoaster_distributePower(wc, powerLeft, powerRight, false); long freeTime=control_loop_interval-(nSysTime-last_control_tick); last_control_tick=nSysTime; sleep(control_loop_interval); //else //playSound(soundBeepBeep); WestCoaster_measureEncoders(wc, false); WestCoaster_measureMPU(wc); #ifdef TRACE_ENABLED writeDebugStream("freetime:%d encoders(L/R): %d/%d, enc_targ: %d, ",freeTime, wc.last_encoderLeft, wc.last_encoderRight, countToMove); writeDebugStreamLine("current_heading: %f, turned: %f, power L/R:%d/%d", wc.global_heading, wc.mpuTheta, powerLeft, powerRight); #endif //correct heading if(abs(wc.mpuTheta)>HEADING_TOLERANCE) { if( (wc.mpuTheta>0 && distance>0) || (wc.mpuTheta<0 && distance<0)) //drifting to the right moving forward //or drifting to the left moving backwards {//reducing left power #ifdef TRACE_ENABLED writeDebugStreamLine("reducing left power"); #endif leftAdjust = POWER_ADJUST_FACTOR; rightAdjust = 1; } else //drifting to the left moving forward or //drifting to the right moving backward { //reducing right power #ifdef TRACE_ENABLED writeDebugStreamLine("reducing right power"); #endif rightAdjust = POWER_ADJUST_FACTOR; leftAdjust = 1; } }else{ rightAdjust = 1; leftAdjust = 1; } int avg_counts=WestCoaster_getAverageCount(wc); if( countToMove <= avg_counts) { res=true; break; } if(WestCoaster_isStalling(wc)) break; if( countToMove-avg_counts < SLOWDOWN_COUNTS) { float ratio = (countToMove-avg_counts) /(2* SLOWDOWN_COUNTS); if (ratio<0.5) { ratio=0.5; } powerAvg = powerAvg*ratio; if( abs(powerAvg)<MOTOR_DEADBAND ) { if( power_ramp_step>0 ) powerAvg = min(MOTOR_DEADBAND,power); else powerAvg = -min(MOTOR_DEADBAND,power); } } } WestCoaster_fullStop(wc); return res; } void deadReck(WestCoaster& wc, unsigned int time){ unsigned long startTime = nSysTime; WestCoaster_allMotorsPowerStraight(wc, -75); while(nSysTime < startTime + time){sleep(10);} WestCoaster_allMotorsPowerStraight(wc, 0); sleep(500); } bool WestCoaster_controlledStraightMoveX(WestCoaster& wc, float inches, int power, unsigned long timeout=0){ if(power<0){ playSound(soundLowBuzz); writeDebugStreamLine("do you mean positive power?"); power=-power; } WestCoaster_resetStates(wc); int countToMove = inchesToCounts(inches); int powerAvg=0; //increase power 5% each step during ramp-up phase int power_ramp_step = 5; if ( inches<0 ){ power_ramp_step = -5; } bool ramping=true; unsigned long ramping_tick=nSysTime; if(timeout==0) timeout=abs(inches)/MIN_SPEED; writeDebugStreamLine("timeout:%d",timeout); clearTimer(T1); bool res=false; unsigned long last_control_tick=nSysTime; while(time1[T1]<timeout){ if( ramping && ( ( abs(powerAvg)>=abs(power) || abs(wc.last_deltaL_f/clicks_per_inch*1000/control_loop_interval)>SPEED_TARGET || abs(wc.last_deltaL_f/clicks_per_inch*1000/control_loop_interval)>SPEED_TARGET) ) ) {//done with ramping up power ramping = false; } if( ramping && ramping_tick<=nSysTime ) { ramping_tick += ramp_up_interval; powerAvg += power_ramp_step; } WestCoaster_pidMotorSync(wc, 2*powerAvg, false); long freeTime=control_loop_interval-(nSysTime-last_control_tick); last_control_tick=nSysTime; sleep(control_loop_interval); //else //playSound(soundBeepBeep); WestCoaster_measureEncoders(wc, false); #ifdef TRACE_ENABLED writeDebugStream("freetime:%d encoders(L/R): %d/%d, enc_targ: %d, ",freeTime, wc.last_encoderLeft, wc.last_encoderRight, countToMove); #endif int avg_counts=WestCoaster_getAverageCount(wc); if( countToMove <= avg_counts) { res=true; break; } if(WestCoaster_isStalling(wc)) break; if( countToMove-avg_counts < SLOWDOWN_COUNTS) { float ratio = (countToMove-avg_counts) /(2* SLOWDOWN_COUNTS); if (ratio<0.5) { ratio=0.5; } powerAvg = powerAvg*ratio; if( abs(powerAvg)<MOTOR_DEADBAND ) { if( power_ramp_step>0 ) powerAvg = min(MOTOR_DEADBAND,power); else powerAvg = -min(MOTOR_DEADBAND,power); } } } WestCoaster_fullStop(wc); return res; } bool WestCoaster_moveStraightWithMPUX(WestCoaster& wc, float distance, int power, int timeout=0) { if(power<0){ playSound(soundLowBuzz); writeDebugStreamLine("do you mean positive power?"); power=-power; } WestCoaster_resetStates(wc); int countToMove = inchesToCounts(distance); int powerAvg=0; //increase power 5% each step during ramp-up phase int power_ramp_step = 5; if ( distance<0 ){ power_ramp_step = -5; } bool ramping=true; unsigned long ramping_tick=nSysTime; int powerLeft, powerRight; powerRight=powerLeft=powerAvg; float leftAdjust=1; float rightAdjust=1; if(timeout==0) timeout=abs(distance)/MIN_SPEED; writeDebugStreamLine("timeout:%d",timeout); clearTimer(T1); bool res=false; bool useMPU=false; unsigned long last_control_tick=nSysTime; while(time1[T1]<timeout){ if( ramping && ( ( abs(powerAvg)>=abs(power) || abs(wc.last_deltaL_f/clicks_per_inch*1000/control_loop_interval)>SPEED_TARGET || abs(wc.last_deltaL_f/clicks_per_inch*1000/control_loop_interval)>SPEED_TARGET) ) ) {//done with ramping up power ramping = false; } if( ramping && ramping_tick<=nSysTime ) { ramping_tick += ramp_up_interval; powerAvg += power_ramp_step; } //correct heading when encoders are not good enough if(abs(wc.mpuTheta)>HEADING_TOLERANCE ||bad_countinous_right>=3 ||bad_countinous_left>=3 ||useMPU) { powerLeft = powerAvg/leftAdjust; powerRight = powerAvg/rightAdjust; WestCoaster_distributePower(wc, powerLeft, powerRight, false); useMPU=true;//continue to use MPU once we started }else { WestCoaster_pidMotorSync(wc, 2*powerAvg, false); } long freeTime=control_loop_interval-(nSysTime-last_control_tick); last_control_tick=nSysTime; sleep(control_loop_interval); //else //playSound(soundBeepBeep); WestCoaster_measureEncoders(wc, false); WestCoaster_measureMPU(wc); #ifdef TRACE_ENABLED writeDebugStream("freetime:%d encoders(L/R): %d/%d, enc_targ: %d, ",freeTime, wc.last_encoderLeft, wc.last_encoderRight, countToMove); writeDebugStreamLine("current_heading: %f, turned: %f, power L/R:%d/%d", wc.global_heading, wc.mpuTheta, powerLeft, powerRight); #endif //correct heading if(abs(wc.mpuTheta)>HEADING_TOLERANCE) { if( (wc.mpuTheta>0 && distance>0) || (wc.mpuTheta<0 && distance<0)) //drifting to the right moving forward //or drifting to the left moving backwards {//reducing left power #ifdef TRACE_ENABLED writeDebugStreamLine("reducing left power"); #endif leftAdjust = POWER_ADJUST_FACTOR; rightAdjust = 1; } else //drifting to the left moving forward or //drifting to the right moving backward { //reducing right power #ifdef TRACE_ENABLED writeDebugStreamLine("reducing right power"); #endif rightAdjust = POWER_ADJUST_FACTOR; leftAdjust = 1; } }else{ rightAdjust = 1; leftAdjust = 1; } int avg_counts=WestCoaster_getAverageCount(wc); if( countToMove <= avg_counts) { res=true; break; } if(WestCoaster_isStalling(wc)) break; if( countToMove-avg_counts < SLOWDOWN_COUNTS) { float ratio = (countToMove-avg_counts) /(2* SLOWDOWN_COUNTS); if (ratio<0.5) { ratio=0.5; } powerAvg = powerAvg*ratio; if( abs(powerAvg)<MOTOR_DEADBAND ) { if( power_ramp_step>0 ) powerAvg = min(MOTOR_DEADBAND,power); else powerAvg = -min(MOTOR_DEADBAND,power); } } } WestCoaster_fullStop(wc); return res; } #endif //WEST_COASTER_H <file_sep>/prototype/motor_superpro_test.c #pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, HTServo) #pragma config(Hubs, S3, HTMotor, HTServo, HTServo, HTServo) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S2, HTSPB, sensorI2CCustomFastSkipStates9V) #pragma config(Sensor, S3, , sensorI2CMuxController) #pragma config(Sensor, S4, HTMUX, sensorSONAR) #pragma config(Motor, mtr_S1_C1_1, motorD, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C1_2, motorE, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, MidR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_2, MidL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C3_1, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C3_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S1_C4_1, flapper1, tServoStandard) #pragma config(Servo, srvo_S1_C4_2, flapper2, tServoStandard) #pragma config(Servo, srvo_S1_C4_3, servo3, tServoNone) #pragma config(Servo, srvo_S1_C4_4, servo4, tServoNone) #pragma config(Servo, srvo_S1_C4_5, servo5, tServoNone) #pragma config(Servo, srvo_S1_C4_6, servo6, tServoNone) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, lift, tServoStandard) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_6, faucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_1, flapper3, tServoStandard) #pragma config(Servo, srvo_S3_C3_2, spout, tServoStandard) #pragma config(Servo, srvo_S3_C3_3, hingeFaucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_4, servo16, tServoNone) #pragma config(Servo, srvo_S3_C3_5, servo17, tServoNone) #pragma config(Servo, srvo_S3_C3_6, servo18, tServoNone) #pragma config(Servo, srvo_S3_C4_1, foldRoller, tServoStandard) #pragma config(Servo, srvo_S3_C4_2, roller, tServoStandard) #pragma config(Servo, srvo_S3_C4_3, servo21, tServoNone) #pragma config(Servo, srvo_S3_C4_4, servo22, tServoNone) #pragma config(Servo, srvo_S3_C4_5, servo23, tServoNone) #pragma config(Servo, srvo_S3_C4_6, servo24, tServoNone) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// /*#pragma config(Hubs, S1, HTMotor, none, none, none) #pragma config(Sensor, S2, SPB, sensorI2CCustomFastSkipStates9V) #pragma config(Motor, mtr_S1_C1_1, motorD, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C1_2, motorE, tmotorTetrix, openLoop) */ ///////////////////////////////////////////////////////////////////////////////////////////////////// // // Tele-Operation Mode Code Template // // This file contains a template for simplified creation of an tele-op program for an FTC // competition. // // You need to customize two functions with code unique to your specific robot. // ///////////////////////////////////////////////////////////////////////////////////////////////////// //#include "JoystickDriver.c" //Include file to "handle" the Bluetooth messages. #include "../competition/HTSuperproSensors.h" ///////////////////////////////////////////////////////////////////////////////////////////////////// // // initializeRobot // // Prior to the start of tele-op mode, you may want to perform some initialization on your robot // and the variables within your program. // // In most cases, you may not have to add any code to this function and it will remain "empty". // ///////////////////////////////////////////////////////////////////////////////////////////////////// void initializeRobot() { SuperSensors_init_task_yaw(S2); while(!super_health) sleep(20); // Place code here to sinitialize servos to starting positions. // Sensors are automatically configured and setup by ROBOTC. They may need a brief time to stabilize. return; } ///////////////////////////////////////////////////////////////////////////////////////////////////// // // Main Task // // The following is the main code for the tele-op robot operation. Customize as appropriate for // your specific robot. // // Game controller / joystick information is sent periodically (about every 50 milliseconds) from // the FMS (Field Management System) to the robot. Most tele-op programs will follow the following // logic: // 1. Loop forever repeating the following actions: // 2. Get the latest game controller / joystick settings that have been received from the PC. // 3. Perform appropriate actions based on the joystick + buttons settings. This is usually a // simple action: // * Joystick values are usually directly translated into power levels for a motor or // position of a servo. // * Buttons are usually used to start/stop a motor or cause a servo to move to a specific // position. // 4. Repeat the loop. // // Your program needs to continuously loop because you need to continuously respond to changes in // the game controller settings. // // At the end of the tele-op period, the FMS will autonmatically abort (stop) execution of the program. // ///////////////////////////////////////////////////////////////////////////////////////////////////// TOrientation orient; void showHeading() { SuperSensors_getOrientation(orient); displayTextLine(1, "y: %f", 0.01*orient.yaw); displayTextLine(2, "p: %f", 0.01*orient.pitch); displayTextLine(3, "r: %f", 0.01*orient.roll); writeDebugStreamLine("yaw in main:%d",0.01*orient.yaw); } task main() { initializeRobot(); //waitForStart(); // wait for start of tele-op phase while (true) { // Insert code to have servos and motors respond to joystick and button values. // Look in the ROBOTC samples folder for programs that may be similar to what you want to perform. // You may be able to find "snippets" of code that are similar to the functions that you want to // perform. nMotorEncoder[motorD]=0; nMotorEncoder[motorE]=0; sleep(20); int target=1120*20; // nMotorEncoderTarget[motorD]=target; // nMotorEncoderTarget[motorE]=target; int lastCountD=nMotorEncoder[motorD]; int newCountD=lastCountD; int lastCountE=nMotorEncoder[motorE]; int newCountE=lastCountE; ; motor[motorD]=100; motor[motorE]=100; // while(nMotorRunState[motorD] != runStateIdle ){ while(newCountD<target&&newCountE<target){ lastCountD=newCountD; lastCountE=newCountE; //sleep(10); newCountD=nMotorEncoder[motorD]; newCountE=nMotorEncoder[motorE]; writeDebugStreamLine("encoder d/e: %d/%d", newCountD, newCountE); if(lastCountD>newCountD||abs(newCountD-lastCountD)>800) { writeDebugStreamLine("********bogus encoderD"); playImmediateTone(1000,500); } if(lastCountE>newCountE||abs(newCountE-lastCountE)>800) { writeDebugStreamLine("********bogus encoderE"); playImmediateTone(1000,500); } showHeading(); } motor[motorE]=0; motor[motorD] = 0; // motor D is stopped at a power level of 0 do{ lastCountD=newCountD; lastCountE=newCountE; sleep(10); newCountD=nMotorEncoder[motorD]; newCountE=nMotorEncoder[motorE]; writeDebugStreamLine("**idle encoder: %d/%d", newCountD, newCountE); showHeading(); }while (lastCountD!=newCountD||lastCountE!=newCountE); sleep(2000); } } <file_sep>/prototype/Ramp2goal.c #pragma config(Hubs, S1, HTMotor, HTServo, none, none) #pragma config(Hubs, S2, HTMotor, none, none, none) #pragma config(Hubs, S3, HTMotor, HTServo, none, none) #pragma config(Sensor, S4, sonarSensor, sensorSONAR) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_1, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_2, FrontR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S1_C2_1, servo1, tServoContinuousRotation) #pragma config(Servo, srvo_S1_C2_2, servo2, tServoStandard) #pragma config(Servo, srvo_S1_C2_3, trailer, tServoStandard) #pragma config(Servo, srvo_S1_C2_4, faucet, tServoStandard) #pragma config(Servo, srvo_S1_C2_5, rakes, tServoStandard) #pragma config(Servo, srvo_S1_C2_6, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_1, belt, tServoNone) #pragma config(Servo, srvo_S3_C2_2, lift, tServoNone) #pragma config(Servo, srvo_S3_C2_3, servo9, tServoNone) #pragma config(Servo, srvo_S3_C2_4, servo10, tServoNone) #pragma config(Servo, srvo_S3_C2_5, servo11, tServoNone) #pragma config(Servo, srvo_S3_C2_6, servo12, tServoNone) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "gyro-encoder_fused.c" #include "ultraSoundAutonomous.c" #include "JoystickDriver.c" void turnFaucet(bool left, long duration ) { long start_time = nSysTime; if(left){ servo [faucet] = 0; }else{ servo [faucet] = 255; } while(nSysTime-start_time < duration){ } servo [faucet] = 127; } void turnOnFan(long duration) { long start_time = nSysTime; motor[FanL] = -100; motor[FanR] = 100; while (nSysTime-start_time<duration){}; motor[FanL]=0; motor[FanR]=0; } #define MAX_LIFT 249 //highest position for lift servo #define MIN_LIFT 12 //lowest position for lift servo #define MAX_TUBE_POSITION 90 #define MIN_TUBE_POSITION 30 void liftTube(int height) { servo[lift] = (height-MIN_TUBE_POSITION)*(MAX_LIFT-MIN_LIFT) /(MAX_TUBE_POSITION-MIN_TUBE_POSITION); } ///////////////////////////////////////////////////////////////////////////////////////////////////// // // initializeRobot // // Prior to the start of autonomous mode, you may want to perform some initialization on your robot. // Things that might be performed during initialization include: // 1. Move motors and servos to a preset position. // 2. Some sensor types take a short while to reach stable values during which time it is best that // robot is not moving. For example, gyro sensor needs a few seconds to obtain the background // "bias" value. // // In many cases, you may not have to add any code to this function and it will remain "empty". // ///////////////////////////////////////////////////////////////////////////////////////////////////// void initializeRobot() { // Place code here to sinitialize servos to starting positions. // Sensors are automatically configured and setup by ROBOTC. They may need a brief time to stabilize. servo[flap]=255;//close flap return; } #define ALIGN_FAUCET_TO_CENTER 50 //milliseconds to align faucet #define OFF_RAMP_DIST 58 //platform and ramp measure 58 inches long #define GOAL_CENTER_TO_EDGE 11.6/2 #define FAUCET_EXTEND_BACK_CENTER GOAL_CENTER_TO_EDGE+0.5 //measure from the center of the drop to the edge of robot task main() { initializeRobot(); waitForStart(); //back off the ramp, 56.9 inches from edge of field to front of bot //back of bot is 56.9+18=74.9 inches from edge of field // center of 60cm goal is 4.5*24=108 inches from edge //so need to move 108-74.9 to the center // then subtract the goal and robot faucet extents // and half-inch safety margin float distance_to_60cm = OFF_RAMP_DIST +108 - 74.9 -FAUCET_EXTEND_BACK_CENTER -0.5; //distance to align center of robot with center of field float distance_to_center = OFF_RAMP_DIST + (72-56.9-9); straightMove(-distance_to_60cm); sleep(500); liftTube(60); //let tube lifted sleep(1000); turnFaucet(true, ALIGN_FAUCET_TO_CENTER); sleep(500); turnOnFan(1000); //move robot forward straightMove(distance_to_60cm-distance_to_center); //turn right facing center structure encoderObservedTurn(-90); int goalPosition = determineGoalPosition(sonarSensor, 500); displayCenteredTextLine(0, "Goal: %d", goalPosition);/* Display Sonar Sensor values */ if(goalPosition == 1){ //is position 3 but detected as position 1, and // handled same as position 1 started from parking lot straightMove(38); sleep(100); encoderObservedTurn(-135); sleep(100); straightMove(24); } else if(goalPosition == 2){ //turn opposite direction as we did for parking lot straightMove(29); sleep(100); encoderObservedTurn(44); sleep(100); straightMove(48); } else if(goalPosition ==3){ // is position 1 but detected as position 3, //similar to position 3 started from parking lot, but oppsite turns straightMove(28); sleep(500); encoderObservedTurn(90); sleep(100); straightMove(15); sleep(200); encoderObservedTurn(-100); sleep(100); straightMove(48); } } <file_sep>/prototype/data/test11-28-04-no-update.c #pragma config(Hubs, S1, HTMotor, HTMotor, none, none) #pragma config(Hubs, S2, HTMotor, HTMotor, none, none) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S2, , sensorI2CMuxController) #pragma config(Sensor, S3, Gyro, sensorI2CCustom) #pragma config(Sensor, S4, sonarSensor, sensorSONAR) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, motorF, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C2_2, motorG, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_1, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S2_C2_1, motorJ, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C2_2, motorK, tmotorTetrix, openLoop) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "gyro-encoder_fused.c" #include "ultraSoundAutonomous.c" task main() { //waitForStart(); // straightMove(63); startTask(gyro_loop); while(gyro_loop_state!=READING) sleep(5); sleep(50); encoderObservedTurn(180); sleep(5000); encoderObservedTurn(-90); sleep(5000); encoderObservedTurn(-90); //encoderPredictionTurn(-90); /*sleep(2000); int goalPosition = determineGoalPosition(); displayCenteredTextLine(0, "Goal Position"); /* Display Sonar Sensor values */ /*displayCenteredBigTextLine(2, "%d", goalPosition); displayCenteredTextLine(4, "dist:%d", distance); sleep(5000); if(goalPosition == 1){ straightMove(30); sleep(100); gyroTurn(-90); sleep(100); straightMove(23); sleep(100); gyroTurn(-90); sleep(100); straightMove(48); sleep(100); } else if(goalPosition == 2){ straightMove(180); gyroTurn(90); } else{ encoderTurn(45); sleep(50); straightMove(85); sleep(50); encoderTurn(-100); sleep(50); straightMove(36); }*/ } <file_sep>/competition/CenterGoalTest.c #pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, none) #pragma config(Hubs, S3, HTMotor, HTServo, HTServo, none) #pragma config(Hubs, S4, HTServo, none, none, none) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S2, HTSPB, sensorI2CCustomFastSkipStates9V) #pragma config(Sensor, S3, , sensorI2CMuxController) #pragma config(Sensor, S4, HTMUX, sensorI2CMuxController) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, motorF, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C2_2, Flapper, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C3_1, BackR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C3_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, lift, tServoStandard) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_6, servo12, tServoStandard) #pragma config(Servo, srvo_S3_C3_1, servo13, tServoStandard) #pragma config(Servo, srvo_S3_C3_2, spout, tServoStandard) #pragma config(Servo, srvo_S3_C3_3, faucet, tServoStandard) #pragma config(Servo, srvo_S3_C3_4, servo16, tServoStandard) #pragma config(Servo, srvo_S3_C3_5, servo17, tServoStandard) #pragma config(Servo, srvo_S3_C3_6, servo18, tServoStandard) #pragma config(Servo, srvo_S4_C1_1, foldRoller, tServoNone) #pragma config(Servo, srvo_S4_C1_2, roller, tServoNone) #pragma config(Servo, srvo_S4_C1_3, servo21, tServoNone) #pragma config(Servo, srvo_S4_C1_4, servo22, tServoNone) #pragma config(Servo, srvo_S4_C1_5, servo23, tServoNone) #pragma config(Servo, srvo_S4_C1_6, servo24, tServoNone) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "PhiloDefs.h" #include "PhiloUtils.h" #include "CenterGoalUs.h" WestCoaster g_wcDrive; void initializeRobot() { WestCoaster_init(g_wcDrive,FrontL, FrontR, BackL, BackR, FrontL, FrontR); WestCoaster_initMPU(S2); servo[lift] = LIFT_BOTTOM; motor [Flapper] = 0; pinClosed(); servo[foldRoller] = ROLLER_FOLDER_UP; servo[roller] = 126; faucetInitial(); //move servos at maximium speed servoChangeRate[trailerL]=0; servoChangeRate[trailerR]=0; servoChangeRate[lift]=0; //set to true during competition to keep the grabber engaged bSystemLeaveServosEnabledOnProgramStop=true; } task main() { initializeRobot(); driveToGoal(g_wcDrive, CENTER_GOAL_SONAR, 20, 30); //did we find the center goal? } <file_sep>/prototype/data/test11-28-02.c counts:1119-off:0/0, encoderL: 0, encoderR: 0, power: 100,heading:0 time: 1358886 counts:1119-off:0/0, encoderL: 6, encoderR: 15, power: 100,heading:0 time: 1358906 counts:1119-off:0/0, encoderL: 15, encoderR: 27, power: 100,heading:0 time: 1358927 counts:1119-off:0/0, encoderL: 45, encoderR: 56, power: 100,heading:0 time: 1358950 counts:1119-off:0/0, encoderL: 61, encoderR: 92, power: 100,heading:1 time: 1358970 counts:1119-off:0/0, encoderL: 99, encoderR: 112, power: 100,heading:3 time: 1358991 counts:1119-off:0/0, encoderL: 135, encoderR: 160, power: 100,heading:8 time: 1359014 counts:1119-off:0/0, encoderL: 157, encoderR: 215, power: 100,heading:11 time: 1359035 counts:1119-off:0/0, encoderL: 195, encoderR: 240, power: 100,heading:14 time: 1359056 counts:1119-off:0/0, encoderL: 217, encoderR: 297, power: 100,heading:18 time: 1359077 counts:1119-off:0/0, encoderL: 272, encoderR: 352, power: 100,heading:22 time: 1359098 counts:1119-off:0/0, encoderL: 322, encoderR: 411, power: 100,heading:25 time: 1359119 counts:1119-off:0/0, encoderL: 370, encoderR: 441, power: 100,heading:29 time: 1359140 counts:1119-off:0/0, encoderL: 394, encoderR: 512, power: 100,heading:32 time: 1359163 counts:1119-off:0/0, encoderL: 442, encoderR: 573, power: 100,heading:38 time: 1359185 counts:1119-off:0/0, encoderL: 486, encoderR: 603, power: 100,heading:42 time: 1359205 counts:1119-off:0/0, encoderL: 521, encoderR: 661, power: 100,heading:46 time: 1359227 counts:1119-off:0/0, encoderL: 569, encoderR: 723, power: 100,heading:50 time: 1359248 counts:1119-off:0/0, encoderL: 616, encoderR: 753, power: 100,heading:53 time: 1359268 counts:1119-off:0/0, encoderL: 641, encoderR: 818, power: 100,heading:57 time: 1359291 counts:1119-off:0/0, encoderL: 698, encoderR: 857, power: 100,heading:62 time: 1359312 counts:1119-off:0/0, encoderL: 729, encoderR: 922, power: 100,heading:66 time: 1359333 counts:1119-off:0/0, encoderL: 781, encoderR: 984, power: 100,heading:72 time: 1359354 counts:1119-off:0/0, encoderL: 847, encoderR: 1017, power: 100,heading:76 time: 1359375 counts:1119-off:0/0, encoderL: 873, encoderR: 1081, power: 100,heading:79 time: 1359397 counts:1119-off:0/0, encoderL: 921, encoderR: 1141, power: 100,heading:83 time: 1359419 counts:1119-off:0/0, encoderL: 980, encoderR: 1173, power: 0,heading:87 time: 1359440 counts:1119-off:0/0, encoderL: 1039, encoderR: 1248, power: 0,heading:95 time: 1359481 counts:1119-off:0/0, encoderL: 1048, encoderR: 1249, power: 0,heading:102 time: 1359521 counts:1119-off:0/0, encoderL: 1049, encoderR: 1254, power: 0,heading:106 time: 1359562 counts:1119-off:0/0, encoderL: 1049, encoderR: 1261, power: 0,heading:107 time: 1359603 counts:1119-off:0/0, encoderL: 1049, encoderR: 1262, power: 0,heading:106 time: 1359645 counts:1119-off:128/121, encoderL: 0, encoderR: 0, power: 100,heading:104 time: 1364686 counts:1119-off:128/121, encoderL: 8, encoderR: 16, power: 100,heading:104 time: 1364707 counts:1119-off:128/121, encoderL: 20, encoderR: 31, power: 100,heading:104 time: 1364728 counts:1119-off:128/121, encoderL: 50, encoderR: 70, power: 100,heading:104 time: 1364749 counts:1119-off:128/121, encoderL: 90, encoderR: 114, power: 100,heading:105 time: 1364771 counts:1119-off:128/121, encoderL: 110, encoderR: 135, power: 100,heading:106 time: 1364791 counts:1119-off:128/121, encoderL: 158, encoderR: 182, power: 100,heading:108 time: 1364813 counts:1119-off:128/121, encoderL: 184, encoderR: 237, power: 100,heading:110 time: 1364834 counts:1119-off:128/121, encoderL: 234, encoderR: 262, power: 100,heading:113 time: 1364855 counts:1119-off:128/121, encoderL: 264, encoderR: 314, power: 100,heading:116 time: 1364877 counts:1119-off:128/121, encoderL: 308, encoderR: 367, power: 100,heading:119 time: 1364899 counts:1119-off:128/121, encoderL: 350, encoderR: 424, power: 100,heading:123 time: 1364920 counts:1119-off:128/121, encoderL: 396, encoderR: 456, power: 100,heading:126 time: 1364940 counts:1119-off:128/121, encoderL: 418, encoderR: 527, power: 100,heading:129 time: 1364961 counts:1119-off:128/121, encoderL: 471, encoderR: 560, power: 100,heading:133 time: 1364982 counts:1119-off:128/121, encoderL: 493, encoderR: 621, power: 100,heading:138 time: 1365005 counts:1119-off:128/121, encoderL: 546, encoderR: 679, power: 100,heading:142 time: 1365026 counts:1119-off:128/121, encoderL: 572, encoderR: 736, power: 100,heading:146 time: 1365047 counts:1119-off:128/121, encoderL: 622, encoderR: 765, power: 100,heading:150 time: 1365068 counts:1119-off:128/121, encoderL: 678, encoderR: 826, power: 100,heading:154 time: 1365091 counts:1119-off:128/121, encoderL: 701, encoderR: 894, power: 100,heading:158 time: 1365112 counts:1119-off:128/121, encoderL: 754, encoderR: 926, power: 100,heading:161 time: 1365132 counts:1119-off:128/121, encoderL: 780, encoderR: 985, power: 100,heading:165 time: 1365153 counts:1119-off:128/121, encoderL: 836, encoderR: 1046, power: 100,heading:171 time: 1365174 counts:1119-off:128/121, encoderL: 865, encoderR: 1085, power: 0,heading:175 time: 1365195 counts:1119-off:128/121, encoderL: 937, encoderR: 1120, power: 0,heading:182 time: 1365236 counts:1119-off:128/121, encoderL: 943, encoderR: 1122, power: 0,heading:188 time: 1365279 counts:1119-off:128/121, encoderL: 944, encoderR: 1126, power: 0,heading:191 time: 1365319 counts:1119-off:128/121, encoderL: 944, encoderR: 1130, power: 0,heading:191 time: 1365359 counts:1119-off:108/84, encoderL: 0, encoderR: 0, power: 100,heading:189 time: 1370400 counts:1119-off:108/84, encoderL: 0, encoderR: 6, power: 100,heading:189 time: 1370421 counts:1119-off:108/84, encoderL: 12, encoderR: 30, power: 100,heading:189 time: 1370443 counts:1119-off:108/84, encoderL: 40, encoderR: 72, power: 100,heading:189 time: 1370464 counts:1119-off:108/84, encoderL: 79, encoderR: 97, power: 100,heading:190 time: 1370485 counts:1119-off:108/84, encoderL: 103, encoderR: 141, power: 100,heading:190 time: 1370508 counts:1119-off:108/84, encoderL: 151, encoderR: 184, power: 100,heading:192 time: 1370530 counts:1119-off:108/84, encoderL: 193, encoderR: 235, power: 100,heading:194 time: 1370550 counts:1119-off:108/84, encoderL: 217, encoderR: 259, power: 100,heading:197 time: 1370571 counts:1119-off:108/84, encoderL: 259, encoderR: 311, power: 100,heading:202 time: 1370594 counts:1119-off:108/84, encoderL: 301, encoderR: 365, power: 100,heading:205 time: 1370615 counts:1119-off:108/84, encoderL: 323, encoderR: 421, power: 100,heading:209 time: 1370636 counts:1119-off:108/84, encoderL: 377, encoderR: 449, power: 100,heading:212 time: 1370657 counts:1119-off:108/84, encoderL: 402, encoderR: 520, power: 100,heading:216 time: 1370679 counts:1119-off:108/84, encoderL: 451, encoderR: 582, power: 100,heading:219 time: 1370700 counts:1119-off:108/84, encoderL: 497, encoderR: 611, power: 100,heading:223 time: 1370721 counts:1119-off:108/84, encoderL: 543, encoderR: 671, power: 100,heading:226 time: 1370742 counts:1119-off:108/84, encoderL: 566, encoderR: 731, power: 100,heading:230 time: 1370763 counts:1119-off:108/84, encoderL: 616, encoderR: 763, power: 100,heading:236 time: 1370785 counts:1119-off:108/84, encoderL: 678, encoderR: 821, power: 100,heading:240 time: 1370806 counts:1119-off:108/84, encoderL: 708, encoderR: 864, power: 100,heading:244 time: 1370828 counts:1119-off:108/84, encoderL: 762, encoderR: 929, power: 100,heading:248 time: 1370849 counts:1119-off:108/84, encoderL: 786, encoderR: 994, power: 100,heading:252 time: 1370870 counts:1119-off:108/84, encoderL: 837, encoderR: 1024, power: 100,heading:256 time: 1370891 counts:1119-off:108/84, encoderL: 866, encoderR: 1092, power: 0,heading:260 time: 1370912 counts:1119-off:108/84, encoderL: 947, encoderR: 1129, power: 0,heading:267 time: 1370952 counts:1119-off:108/84, encoderL: 955, encoderR: 1132, power: 0,heading:274 time: 1370993 counts:1119-off:108/84, encoderL: 956, encoderR: 1138, power: 0,heading:279 time: 1371036 counts:1119-off:108/84, encoderL: 956, encoderR: 1141, power: 0,heading:280 time: 1371076 counts:1119-off:108/84, encoderL: 956, encoderR: 1142, power: 0,heading:279 time: 1371117 <file_sep>/competition/ramp2goal.c #pragma config(Hubs, S1, HTMotor, HTMotor, none, none) #pragma config(Hubs, S2, HTMotor, HTServo, none, none) #pragma config(Hubs, S3, HTMotor, HTServo, none, none) #pragma config(Sensor, S4, sonarSensor, sensorSONAR) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, MidR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C2_2, MidL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_1, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S2_C2_1, flapper1, tServoStandard) #pragma config(Servo, srvo_S2_C2_2, flapper2, tServoStandard) #pragma config(Servo, srvo_S2_C2_3, servo3, tServoNone) #pragma config(Servo, srvo_S2_C2_4, servo4, tServoNone) #pragma config(Servo, srvo_S2_C2_5, servo5, tServoNone) #pragma config(Servo, srvo_S2_C2_6, servo6, tServoNone) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, lift, tServoStandard) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_6, faucet, tServoStandard) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "WestCoaster.h" #include "CenterGoalUs.h" #include "JoystickDriver.c" void turnFaucet(bool left, long duration ) { long start_time = nSysTime; if(left){ servo [faucet] = 0; }else{ servo [faucet] = 255; } while(nSysTime-start_time < duration){ } servo [faucet] = 127; } void turnOnFan(long duration) { long start_time = nSysTime; motor[FanL] = -100; motor[FanR] = 100; while (nSysTime-start_time<duration){}; motor[FanL]=0; motor[FanR]=0; } #define MAX_LIFT 249 //highest position for lift servo #define MIN_LIFT 12 //lowest position for lift servo #define MAX_TUBE_POSITION 90 #define MIN_TUBE_POSITION 30 void liftTube(int height) { /*servo[lift] = (height-MIN_TUBE_POSITION)*(MAX_LIFT-MIN_LIFT) /(MAX_TUBE_POSITION-MIN_TUBE_POSITION);*/ } ///////////////////////////////////////////////////////////////////////////////////////////////////// // // initializeRobot // // Prior to the start of autonomous mode, you may want to perform some initialization on your robot. // Things that might be performed during initialization include: // 1. Move motors and servos to a preset position. // 2. Some sensor types take a short while to reach stable values during which time it is best that // robot is not moving. For example, gyro sensor needs a few seconds to obtain the background // "bias" value. // // In many cases, you may not have to add any code to this function and it will remain "empty". // ///////////////////////////////////////////////////////////////////////////////////////////////////// WestCoaster g_wcDrive; void initializeRobot() { // Place code here to sinitialize servos to starting positions. // Sensors are automatically configured and setup by ROBOTC. They may need a brief time to stabilize. //servo[flap]=255;//close flap WestCoaster_init(g_wcDrive,FrontL, FrontR, MidL, MidR, BackL, BackR, FrontL, FrontR); return; } #define ALIGN_FAUCET_TO_CENTER 50 //milliseconds to align faucet #define OFF_RAMP_DIST 58 //platform and ramp measure 58 inches long #define GOAL_CENTER_TO_EDGE 11.6/2 #define FAUCET_EXTEND_BACK_CENTER GOAL_CENTER_TO_EDGE+0.5 //measure from the center of the drop to the edge of robot task main() { initializeRobot(); waitForStart(); //back off the ramp, 56.9 inches from edge of field to front of bot //back of bot is 56.9+18=74.9 inches from edge of field // center of 60cm goal is 4.5*24=108 inches from edge //so need to move 108-74.9 to the center // then subtract the goal and robot faucet extents // and half-inch safety margin float distance_to_60cm = OFF_RAMP_DIST +108 - 74.9 -FAUCET_EXTEND_BACK_CENTER -0.5; //distance to align center of robot with center of field float distance_to_center = OFF_RAMP_DIST + (72-56.9-9); WestCoaster_pidStraightMove(g_wcDrive,-distance_to_60cm); sleep(500); liftTube(60); //let tube lifted sleep(1000); turnFaucet(true, ALIGN_FAUCET_TO_CENTER); sleep(500); turnOnFan(1000); //move robot forward WestCoaster_pidstraightMove(g_wcDrive, distance_to_60cm-distance_to_center); //turn right facing center structure WestCoaster_encoderObservedTurn(g_wcDrive, -90); int goalPosition = determineGoalPosition(sonarSensor, 500); displayCenteredTextLine(0, "Goal: %d", goalPosition);/* Display Sonar Sensor values */ if(goalPosition == 1){ //is position 3 but detected as position 1, and // handled same as position 1 started from parking lot WestCoaster_pidStraightMove(g_wcDrive,38); sleep(100); WestCoaster_encoderObservedTurn(g_wcDrive,-135); sleep(100); WestCoaster_pidStraightMove(g_wcDrive,24); } else if(goalPosition == 2){ //turn opposite direction as we did for parking lot WestCoaster_pidStraightMove(g_wcDrive,29); sleep(100); WestCoaster_encoderObservedTurn(g_wcDrive,44); sleep(100); WestCoaster_pidStraightMove(g_wcDrive,48); } else if(goalPosition ==3){ // is position 1 but detected as position 3, //similar to position 3 started from parking lot, but oppsite turns WestCoaster_pidStraightMove(g_wcDrive,28); sleep(500); WestCoaster_encoderObservedTurn(g_wcDrive,90); sleep(100); WestCoaster_pidStraightMove(g_wcDrive,15); sleep(200); WestCoaster_pidStraightMove(g_wcDrive,-100); sleep(100); WestCoaster_pidStraightMove(g_wcDrive,48); } } <file_sep>/competition/BouncyButton.h #define DEBOUNCE_TIME 500 //debouncing period in ms #ifndef JOYSTICK_DRIVER_INCLDUDED #define JOYSTICK_DRIVER_INCLDUDED #include "JoystickDriver.c" #endif /************************************************ * * A java class like structure to handle buttons used * as toggle buttons. Excessive spurious button presses * are filtered out in the debounce method. */ typedef struct BJoyButtons { bool onJoy1; //on joy stick 1 or 2? int button; //index of the button on joy stick long lastTime; //last time pressed volatile bool pressed; //pressed or not } TBouncyBtn; void BouncyBtn_init(TBouncyBtn& btn, bool on_joy1, int btn_index) { btn.onJoy1=on_joy1; btn.button=btn_index; btn.lastTime=0; btn.pressed=false; } void BouncyBtn_debounce(TBouncyBtn& btn) { short isBtnOn; if (btn.onJoy1) isBtnOn=joy1Btn(btn.button); else isBtnOn=joy2Btn(btn.button); if(isBtnOn && !(btn.pressed) && ( (nSysTime - btn.lastTime )>DEBOUNCE_TIME) ) { hogCPU(); btn.pressed=true; btn.lastTime=nSysTime; releaseCPU(); } } bool BouncyBtn_checkAndClear(TBouncyBtn& btn) { bool res=false; hogCPU(); res=btn.pressed; if(res) btn.pressed=false; releaseCPU(); return res; } <file_sep>/prototype/hitechnic-gyro-task.c /** * A wrapper on code from <NAME> (xander_at_botbench.com) * 20 February 2011 * version 0.3 * modifications: * 1)add heading calculation by integrating rate of rotation readings * 2)move the sensor handling to separate task * 3)use customized driver * 4)change sampling rate to 200 HZ */ //define this to zero if you don't want driver to auto-calibrate #ifndef GYRO_PRECISION #define GYRO_PRECISION 1//gyro noise level #endif #include "hitechnic-gyro-drv2.h" //#define TESTING volatile float gHeading = 0;//in degrees volatile float gRot = 0;//in degrees per second typedef enum x { INIT=0, CALIBRATION, READING, STOPPED }GYRO_LOOP_STATE; volatile GYRO_LOOP_STATE gyro_loop_state; task gyro_loop () { gyro_loop_state=INIT; int dt=10; unsigned long prevTime,currTime; // Create struct to hold sensor data tHTGYRO gyroSensor; while(gyro_loop_state!=STOPPED) { switch(gyro_loop_state) { case INIT: // Initialise and configure struct and port hogCPU(); initSensor(&gyroSensor, S3); gyro_loop_state=CALIBRATION; releaseCPU(); break; case CALIBRATION: sleep(1000);//let it settle down #ifdef TESTING eraseDisplay(); displayTextLine(1, "Resetting"); displayTextLine(2, "offset"); sleep(500); #endif hogCPU(); // Start the calibration sensorCalibrate(&gyroSensor); #ifdef TESTING //and display the offset in testing mode displayTextLine(2, "Offset: %f", gyroSensor.offset); clearDebugStream(); writeDebugStreamLine("Offset: %f deadband: %f",gyroSensor.offset,gyroSensor.deadband); playSound(soundBlip); while(bSoundActive) sleep(1); #endif gHeading=0.0; prevTime =nSysTime; gyro_loop_state=READING; releaseCPU(); break; case READING: while(gyro_loop_state==READING){ clearTimer(T2); hogCPU(); // Read the current rotational speed readSensor(&gyroSensor); currTime = nSysTime; gRot = gyroSensor.rotation; //There is a possibility that nSysTime would reach max value of 32 bit long integer //then wrapped around. But it would be NXT has run over 1000 hours gHeading += gRot* (currTime-prevTime)/1000.0; prevTime=currTime; releaseCPU(); #ifdef TESTING eraseDisplay(); displayTextLine(1, "Reading"); // Read the current calibration offset and display it displayTextLine(2, "Offset: %f", gyroSensor.offset); writeDebugStreamLine("Offset: %f deadband: %f", gyroSensor.offset, gyroSensor.deadband); displayClearTextLine(4); // Read the current rotational speed and display it displayTextLine(4, "Gyro: %f", gyroSensor.rotation); writeDebugStreamLine("Rotation: %f",gyroSensor.rotation); displayTextLine(5, "Degrees: %f", gHeading); writeDebugStreamLine("Heading: %f",gHeading); displayTextLine(6, "Press enter"); displayTextLine(7, "to recalibrate"); #endif while(time1[T2]<dt && gyro_loop_state==READING){ sleep(1); } } break; default: //should never happen break; } } } #ifdef TESTING task main() { bFloatConversionErrors=true; displayTextLine(0, "HT Gyro"); displayTextLine(1, "Test task"); displayTextLine(5, "Press enter"); displayTextLine(6, "to set relative"); displayTextLine(7, "heading"); sleep(2000); eraseDisplay(); startTask(gyro_loop); while(true) { if(getXbuttonValue(xButtonEnter)) { gyro_loop_state = CALIBRATION; sleep(2000); }else if(getXbuttonValue(xButtonLeft)) { gyro_loop_state = STOPPED; while(gyro_loop_state!=STOPPED) sleep(2000); stopTask(gyro_loop); }else if(getXbuttonValue(xButtonRight)) { startTask(gyro_loop); }else { sleep(1000); } } } #endif <file_sep>/competition/HTSuperproSensors.h #ifndef _HTSUPERPRO_SENSORS_H_ #define _HTSUPERPRO_SENSORS_H_ //modified superpro drive #include "htspb_drv.h" #define BYTES_PER_FRAME 6 short getShort(ubyte byte1, ubyte byte2) { short ret=(byte2<<8); ret |=byte1; return ret; } typedef struct htsupersensors { tSensors sPort; }TSuperSensors; TSuperSensors superSensors; volatile bool super_health=false; volatile short super_yaw; float SuperSensors_getHeading() { float heading=0; hogCPU(); heading=super_yaw; releaseCPU(); heading=heading*0.01; return heading; } ////////////////////////////////////////////////////////////// // This loop only gets gyro readings from superpro // It's designed for cases fast gyro yaw reading is needed, e.g. control robot // heading in autonomous period. // Reading from superpro using I2C with fastest configuration // (sensorI2CCustomFastSkipStates9V), // each call to drive API HTSPBreadIO takes about 2ms. // We need 2 bytes for yaw and 1 byte parity, so 6 ms delay. Fortunately // MPU is fast. so 6ms delay might be the bottleneck of the chain and total // delay is about 6ms. That should be good for controlling robot. // But if we read all 3 components of // the MPU measurements: pitch, roll, yaw, each 2 bytes, plus parity byte, // then we will have 14ms delay, which is boderline for robot control. ////////////////////////////////////////////////////////////// //needs be at leat 2 for Arduino DUE // at least 1 for NANO #define DELAY_READ 1 task htsuperpro_loop_yaw() { static const int BYTES_TO_READ = 2; static const int monitor_period = 1000; ubyte inputdata[BYTES_TO_READ]={0,0}; unsigned long lasttime=nSysTime; int numOfDataBytes=0; bool insync =false; while(true) { if(!insync){ super_health=false; //this sets S0 to 0, serving as synchronizing bit for beginning //of transfer HTSPBSetStrobe(superSensors.sPort,0x0);//3ms //this is the data request to ask remote to get ready for next frame //of data // remote could return some useful header byte // for now just alternate at odd/even bits to confirm it is in sync ubyte header=HTSPBreadIO(superSensors.sPort, 0xFF); sleep(DELAY_READ); //writeDebugStreamLine("got header byte %d", header); while(header !=0x55){ header=HTSPBreadIO(superSensors.sPort, 0xFF); //writeDebugStreamLine("got header byte %d", header); //sleep(DELAY_READ); } HTSPBSetStrobe(superSensors.sPort,0x01); while (header==0x55) header=HTSPBreadIO(superSensors.sPort, 0xFF); insync=true; inputdata[0]=header; }else { inputdata[0]=HTSPBreadIO(superSensors.sPort, 0xFF);//2ms sleep(DELAY_READ); } //writeDebugStreamLine("got byte %d: %d", 0, inputdata[0]); for (int i=1;i<BYTES_TO_READ;i++) { inputdata[i] = HTSPBreadIO(superSensors.sPort, 0xFF);//2ms sleep(DELAY_READ); //writeDebugStreamLine("got byte %d: %d", i, inputdata[i]); } ubyte parity = HTSPBreadIO(superSensors.sPort, 0xFF);//2ms sleep(DELAY_READ); ubyte myparity=inputdata[0]; for (int i=1;i<BYTES_TO_READ;i++) { myparity^=inputdata[i]; } //writeDebugStreamLine("parity: %d my parity byte %d", parity, myparity); insync = (parity==myparity); if(!insync) continue; hogCPU(); super_yaw = getShort(inputdata[0],inputdata[1]); releaseCPU(); //writeDebugStreamLine("yaw:%d",super_yaw); numOfDataBytes+=3; if(nSysTime-lasttime>monitor_period ) { if(numOfDataBytes<(monitor_period*3/50))//at most 50 ms cycle time { #ifdef TRACE_ENABLED writeDebugStreamLine("got %d bytes in %lu ms", numOfDataBytes, monitor_period); #endif super_health=false; }else { super_health=true; } lasttime=nSysTime; numOfDataBytes=0; }else if(nSysTime<lasttime) {//system time started over lasttime=nSysTime; numOfDataBytes=0; super_health=true; } sleep(10); } } void SuperSensors_init_task_yaw(tSensors sport) { superSensors.sPort=sport; // Set B0-7 for input HTSPBsetupIO(sport, 0x0); startTask(htsuperpro_loop_yaw); } #endif <file_sep>/competition/hitechnic-gyro-task.h /** * A wrapper on code from <NAME> (xander_at_botbench.com) * 20 February 2011 * version 0.3 * modifications: * 1)add heading calculation by integrating rate of rotation readings * 2)move the sensor handling to separate task * 3)use customized driver * 4)change sampling rate to 200 HZ */ //define this to zero if you don't want driver to auto-calibrate #ifndef GYRO_PRECISION #define GYRO_PRECISION 1//gyro noise level #endif #ifdef USE_HT_SENSOR_MUX #include "hitechnic-sensormux.h" #endif #include "hitechnic-gyro-drv2.h" //#define TESTING #define GYRO_INIT 0 #define GYRO_CALIBRATION 2 #define GYRO_READING 4 #define GYRO_STOPPED 8 volatile float gHeading = 0;//in degrees volatile float gRot = 0;//in degrees per second volatile int gyro_loop_state; float gyro_heading() { float heading=0; hogCPU(); heading=gHeading; releaseCPU(); return heading; } task gyro_loop () { gyro_loop_state=INIT; int dt=20; unsigned long prevTime,currTime; // Create struct to hold sensor data tHTGYRO gyroSensor; while(gyro_loop_state!=GYRO_STOPPED) { switch(gyro_loop_state) { case GYRO_INIT: // Initialise and configure struct and port hogCPU(); initSensor(&gyroSensor, GYRO_SENSOR); gyro_loop_state=GYRO_CALIBRATION; releaseCPU(); break; case GYRO_CALIBRATION: sleep(1000);//let it settle down hogCPU(); // Start the calibration sensorCalibrate(&gyroSensor); gHeading=0.0; prevTime =nSysTime; gyro_loop_state=GYRO_READING; releaseCPU(); break; case GYRO_READING: while(gyro_loop_state==GYRO_READING){ clearTimer(T2); hogCPU(); // Read the current rotational speed readSensor(&gyroSensor); currTime = nSysTime; gRot = gyroSensor.rotation; //There is a possibility that nSysTime would reach max value of 32 bit long integer //then wrapped around. But it would be NXT has run over 1000 hours gHeading += gRot* (currTime-prevTime)/1000.0; prevTime=currTime; releaseCPU(); while(time1[T2]<dt && gyro_loop_state==GYRO_READING){ sleep(5); } } break; default: //should never happen break; } } } <file_sep>/prototype/ParkingLot.c #pragma config(Hubs, S1, HTMotor, HTMotor, none, none) #pragma config(Hubs, S2, HTMotor, HTServo, none, none) #pragma config(Hubs, S3, HTMotor, HTServo, none, none) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Sensor, S2, , sensorI2CMuxController) #pragma config(Sensor, S3, , sensorI2CMuxController) #pragma config(Sensor, S4, sonarSensor, sensorSONAR) #pragma config(Motor, motorA, , tmotorNXT, openLoop) #pragma config(Motor, motorB, , tmotorNXT, openLoop) #pragma config(Motor, motorC, , tmotorNXT, openLoop) #pragma config(Motor, mtr_S1_C1_1, BackL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C1_2, FrontL, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_1, MidR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S1_C2_2, MidL, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_1, BackR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S2_C1_2, FrontR, tmotorTetrix, openLoop, encoder) #pragma config(Motor, mtr_S3_C1_1, FanR, tmotorTetrix, openLoop) #pragma config(Motor, mtr_S3_C1_2, FanL, tmotorTetrix, openLoop) #pragma config(Servo, srvo_S2_C2_1, flapper1, tServoStandard) #pragma config(Servo, srvo_S2_C2_2, flapper2, tServoStandard) #pragma config(Servo, srvo_S2_C2_3, servo3, tServoNone) #pragma config(Servo, srvo_S2_C2_4, servo4, tServoNone) #pragma config(Servo, srvo_S2_C2_5, servo5, tServoNone) #pragma config(Servo, srvo_S2_C2_6, servo6, tServoNone) #pragma config(Servo, srvo_S3_C2_1, trailerR, tServoStandard) #pragma config(Servo, srvo_S3_C2_2, trailerL, tServoStandard) #pragma config(Servo, srvo_S3_C2_3, lift, tServoStandard) #pragma config(Servo, srvo_S3_C2_4, rakes, tServoStandard) #pragma config(Servo, srvo_S3_C2_5, flap, tServoStandard) #pragma config(Servo, srvo_S3_C2_6, faucet, tServoStandard) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "ultraSoundAutonomous.c" #include "gyro-encoder_fused.c" #include "JoystickDriver.c" //fanon //grabgoal // task main() { waitForStart(); int distance=0; straightMove(-3); sleep(1000); //we only need 100ms or less to determine the center goal //orientation. int goalPosition = determineGoalPosition(sonarSensor, 100); /* Display Sonar Sensor values */ distance = SensorValue[sonarSensor]; displayCenteredTextLine(0, "Goal: %d", goalPosition); displayCenteredTextLine(1, "distance: %d", distance); if(goalPosition == 1){ straightMove(-38); sleep(100); encoderObservedTurn(-115); sleep(100); straightMove(-24); } else if(goalPosition == 2){ straightMove(-29); sleep(100); encoderObservedTurn(-70); sleep(100); straightMove(-48); } else if(goalPosition ==3){ straightMove(-28); sleep(500); encoderObservedTurn(-90); sleep(100); straightMove(-15); sleep(200); encoderObservedTurn(70); sleep(100); straightMove(-48); } }
c2a812eabbaeae5e3013f65ee668cd67536e2087
[ "C" ]
33
C
WestlakeFTC/PhiLobots
c40dfa79bb6adf03ba3ed0fa95493effe02e79fc
3f657f586a6ca649321828ba9ab8977dcef5efeb
refs/heads/master
<file_sep>import numpy as np # min(1/2*np.linalg.norm(w,ord=2)+c*np.sum(sai,axis=0) <file_sep>import numpy as np def sigmoid (x): return 1/(1+np.exp(-x)) def z_score(x): x_mean=np.mean(x,axis=0) x_norm=np.linalg.norm(x-x_mean,ord=2,axis=0)**0.5 x_z_score =(x-x_mean) /x_norm return x_z_score def initparams(): w1 = np.random.rand(3, 2)-0.5 w2 = np.random.rand(2, 3)-0.5 w3 = np.random.rand(3, 2)-0.5 b1 = np.zeros((1,2))+0.1 b2 =np.zeros((1,3))+0.1 b3 =np.zeros((1,2))+0.1 params = {"W1": w1, "W2": w2, "W3": w3,"B1":b1,"B2":b2,"B3":b3} return params def train_loop (X,Y,params,eta): W1=params['W1'] W2=params['W2'] W3=params['W3'] B1=params['B1'] B2=params['B2'] B3=params['B3'] m=X.shape[0] Y1 = np.dot(X,W1)+B1 #shape(M,2) A1 = sigmoid(Y1) #shape(M,2) Y2 = np.dot(A1, W2)+B2 #shape(M,3) A2 = sigmoid(Y2) #shape(M,3) Y3 = np.dot(A2, W3)+B3 #shape(M,2) Out = sigmoid(Y3) #shape(M,2) E= Out-Y loss =np.sum(E*E) dY3 = E * Out * (1-Out) #shape(m,2) dW3 = 1/m* np.dot(A2.T, dY3) #shape(3,2) dB3=1/m*np.sum(dY3, axis=0,keepdims=True)#shape(1,2) dA2 = np.dot(dY3, W3.T) #shape(m,3) dY2 = dA2 * A2 * (1-A2) #shape(m,3) dW2 = 1/m*np.dot(A1.T, dY2) #shape(2,3) dB2 = 1/m*np.sum(dY2,axis=0,keepdims=True)#shape(1,3) dA1 = np.dot(dY2, W2.T) #shape(m,2) dY1 = dA1 * A1 * (1-A1) #shape(m,2) dW1 = 1/m * np.dot(X.T,dY1) #shape (3,2) dB1 = 1/m*np.sum(dY1,axis=0,keepdims=True)#shape(1,2) W1=W1-eta*dW1 W2=W2-eta*dW2 W3=W3-eta*dW3 B1=B1-eta*dB1 B2 = B2 - eta * dB2 B3 = B3 - eta * dB3 params_out = {"W1":W1,"W2":W2,"W3":W3,"B1":B1,"B2":B2,"B3":B3} return params_out,loss <file_sep>import numpy as np import ch2_eg_lib data=np.load("ch2_data.npz") x_data=data["arr_0"] y_data=data["arr_1"] x_zs=ch2_eg_lib.z_score(x_data) #zscore归一化 y_zs=ch2_eg_lib.z_score(y_data) # print(x_zs,y_zs) np.random.seed(9) #随机种子 params=ch2_eg_lib.initparams() #初始化参数 eta =5 m= x_data.shape[0] for i in range(0,m): #循环100次 # xi=np.array([x_zs[i]]) # yi=np.array([y_zs[i]]) params,loss = ch2_eg_lib.train_loop(x_zs,y_zs,params,eta) #训练参数 print(loss) print(params['W1'], params['W2'], params['W3'], params['B1'], params['B2'], params['B3']) # result # [[-0.48962038 0.00175194] # [-0.00422788 -0.36618807] # [-0.35764881 -0.28145701]] # [[-0.08154142 -0.25174518 -0.41560398] # [-0.15437849 -0.33311583 0.37879221]] # [[ 0.4515835 -0.46074807] # [ 0.19954682 0.07311573] # [ 0.39870043 0.16729628]] <file_sep>import numpy as np #min (x.T A x + x.T b) def grad_method (A,b,x0,epsilon): x=x0 i=0 grad=2*(np.matmul(A,x)+b) while( np.linalg.norm(grad,ord=2) > epsilon ): i=i+1 t=np.linalg.norm(grad,ord=2)**2 /( 2 * np.matmul( np.matmul(grad.T,A), grad )) #最优步长值 x= x-t * grad grad = 2 * (np.matmul(A , x) + b) fun_val = np.matmul(np.matmul(x.T , A) , x) + np.matmul(b.T,x) print("%r grad:%r value:%r"%(i,np.linalg.norm(grad,ord=2),fun_val)) <file_sep>import numpy as np import tensorflow as tf import ch2_eg_lib as c2l import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # X_data =np.array( np.loadtxt("ch2data.csv",delimiter=',',usecols=(0,1),unpack=True)).T # Y_data =np.array( [np.loadtxt("ch2data.csv",delimiter=',',usecols=(3),unpack=True)]).T data=np.load("ch2_data.npz") X_data=data["arr_0"] Y_data=data["arr_1"] X_zs=c2l.z_score(X_data) Y_zs=c2l.z_score(Y_data) print(X_zs,Y_zs) # fig=plt.figure() # ax= Axes3D(fig) # ax.plot_surface(np.arange(-4, 4, 0.25), np.arange(-4, 4, 0.25), Y_data, rstride=1, cstride=1, cmap='rainbow') learning_rate = 0.5 X =tf.placeholder(tf.float32,[None,3]) Y =tf.placeholder(tf.float32,[None,2]) batch =256 steps = X_data.shape[0]//batch-1 def add_layer(inputs, in_size, out_size, activation_function=None): Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1, out_size]) + 0.1) Wx_plus_b = tf.matmul(inputs, Weights) + biases if activation_function is None: outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b) return outputs Layer1 = add_layer(X,3,1024,activation_function=tf.nn.relu) Layer2 = add_layer(Layer1,1024,512,activation_function=tf.nn.relu) Layer3 = add_layer(Layer2,512,256,activation_function=tf.nn.relu) Layer4 = add_layer(Layer3,256,128,activation_function=tf.nn.relu) Pred = add_layer(Layer4,128,2,activation_function=None) loss = tf.reduce_mean(tf.reduce_sum(tf.square(Y-Pred))) Optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for i in range(0, 1000): i_step =i%steps batch_X = X_zs[i_step * batch:((i_step + 1) * batch - 1), :] batch_Y = Y_zs[i_step * batch:((i_step + 1) * batch - 1), :] l,_=sess.run([loss,Optimizer],feed_dict= {X:batch_X,Y:batch_Y}) print("Epoch {0}: {1}".format(i, l))<file_sep>import numpy as np import ch1 A=np.array([[1,0],[0,2]]) b=np.array([[0],[0]]) x0=np.array([[1],[2]]) epsilon = 1e-5 ch1.grad_method(A, b, x0, epsilon)
370025423d3acf88080790da1ed609fa94beb6c0
[ "Python" ]
6
Python
tyrdom/study163
59bf2fca30c7f3995e8b7c72abe4faa323b9f2a7
ced5ea246e74696a640fd5185680b34905a81723